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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
#region License
// <copyright file="StringArrayEnumerator.cs" company="Giacomo Stelluti Scala">
// Copyright 2015-2013 Giacomo Stelluti Scala
// </copyright>
//
// 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
#region Using Directives
using System;
using Ssz.Utils.CommandLine.Infrastructure;
#endregion
namespace Ssz.Utils.CommandLine.Parsing
{
internal sealed class StringArrayEnumerator : IArgumentEnumerator
{
#region construction and destruction
public StringArrayEnumerator(string[] value)
{
Assumes.NotNull(value, "value");
_data = value;
_index = -1;
_endIndex = value.Length;
}
#endregion
#region public functions
public bool MoveNext()
{
if (_index < _endIndex)
{
_index++;
return _index < _endIndex;
}
return false;
}
public string GetRemainingFromNext()
{
throw new NotSupportedException();
}
public bool MovePrevious()
{
if (_index <= 0)
{
throw new InvalidOperationException();
}
if (_index <= _endIndex)
{
_index--;
return _index <= _endIndex;
}
return false;
}
public string Current
{
get
{
if (_index == -1)
{
throw new InvalidOperationException();
}
if (_index >= _endIndex)
{
throw new InvalidOperationException();
}
return _data[_index];
}
}
public string Next
{
get
{
if (_index == -1)
{
throw new InvalidOperationException();
}
if (_index > _endIndex)
{
throw new InvalidOperationException();
}
if (IsLast)
{
return null;
}
return _data[_index + 1];
}
}
public bool IsLast
{
get { return _index == _endIndex - 1; }
}
#endregion
#region private fields
private readonly int _endIndex;
private readonly string[] _data;
private int _index;
#endregion
}
} | 25.652482 | 80 | 0.544374 | [
"MIT"
] | ru-petrovi4/Ssz.Utils | Ssz.Utils.Net4/CommandLine/Parsing/StringArrayEnumerator.cs | 3,619 | 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/MDMRegistration.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.Versioning;
namespace TerraFX.Interop.Windows;
/// <include file='MANAGEMENT_SERVICE_INFO.xml' path='doc/member[@name="MANAGEMENT_SERVICE_INFO"]/*' />
[SupportedOSPlatform("windows8.1")]
public unsafe partial struct MANAGEMENT_SERVICE_INFO
{
/// <include file='MANAGEMENT_SERVICE_INFO.xml' path='doc/member[@name="MANAGEMENT_SERVICE_INFO.pszMDMServiceUri"]/*' />
[NativeTypeName("LPWSTR")]
public ushort* pszMDMServiceUri;
/// <include file='MANAGEMENT_SERVICE_INFO.xml' path='doc/member[@name="MANAGEMENT_SERVICE_INFO.pszAuthenticationUri"]/*' />
[NativeTypeName("LPWSTR")]
public ushort* pszAuthenticationUri;
}
| 43.454545 | 145 | 0.762552 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/MDMRegistration/MANAGEMENT_SERVICE_INFO.cs | 958 | C# |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon 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.Concurrent;
using System.Collections.Generic;
using NUnit.Framework;
using Remotion.Development.UnitTesting;
using Remotion.Development.UnitTesting.ObjectMothers;
using Remotion.Development.UnitTesting.Reflection;
using Remotion.TypePipe.Caching;
using Remotion.TypePipe.CodeGeneration;
using Remotion.TypePipe.TypeAssembly.Implementation;
using Moq;
namespace Remotion.TypePipe.UnitTests.Caching
{
[TestFixture]
public class ConstructorForAssembledTypeCacheTest
{
private Mock<ITypeAssembler> _typeAssemblerMock;
private Mock<IConstructorDelegateFactory> _constructorDelegateFactoryMock;
private ConstructorForAssembledTypeCache _cache;
private IDictionary<ConstructorForAssembledTypeCacheKey, Delegate> _constructorCalls;
private Type _assembledType;
private Type _delegateType;
private bool _allowNonPublic;
private Delegate _generatedCtorCall;
[SetUp]
public void SetUp ()
{
_typeAssemblerMock = new Mock<ITypeAssembler> (MockBehavior.Strict);
_constructorDelegateFactoryMock = new Mock<IConstructorDelegateFactory> (MockBehavior.Strict);
_cache = new ConstructorForAssembledTypeCache (_typeAssemblerMock.Object, _constructorDelegateFactoryMock.Object);
_constructorCalls = (ConcurrentDictionary<ConstructorForAssembledTypeCacheKey, Delegate>) PrivateInvoke.GetNonPublicField (_cache, "_constructorCalls");
_assembledType = ReflectionObjectMother.GetSomeType();
_delegateType = ReflectionObjectMother.GetSomeDelegateType();
_allowNonPublic = BooleanObjectMother.GetRandomBoolean();
_generatedCtorCall = new Func<int> (() => 7);
}
[Test]
public void GetOrCreateConstructorCall_CacheHit ()
{
_constructorCalls.Add (new ConstructorForAssembledTypeCacheKey (_assembledType, _delegateType, _allowNonPublic), _generatedCtorCall);
var result = _cache.GetOrCreateConstructorCall (_assembledType, _delegateType, _allowNonPublic);
Assert.That (result, Is.SameAs (_generatedCtorCall));
}
[Test]
public void GetOrCreateConstructorCall_CacheMiss ()
{
var requestedType = ReflectionObjectMother.GetSomeType();
_typeAssemblerMock.Setup (mock => mock.GetRequestedType (_assembledType)).Returns (requestedType).Verifiable();
_constructorDelegateFactoryMock
.Setup (mock => mock.CreateConstructorCall (requestedType, _assembledType, _delegateType, _allowNonPublic))
.Returns (_generatedCtorCall)
.Verifiable();
var result = _cache.GetOrCreateConstructorCall (_assembledType, _delegateType, _allowNonPublic);
_constructorDelegateFactoryMock.Verify();
Assert.That (result, Is.SameAs (_generatedCtorCall));
var reverseConstructionKey = new ConstructorForAssembledTypeCacheKey (_assembledType, _delegateType, _allowNonPublic);
Assert.That (_constructorCalls[reverseConstructionKey], Is.SameAs (_generatedCtorCall));
}
}
} | 40.815217 | 158 | 0.770706 | [
"ECL-2.0",
"Apache-2.0"
] | bubdm/TypePipe | Core.UnitTests/Caching/ConstructorForAssembledTypeCacheTest.cs | 3,757 | C# |
using System;
namespace SdkBased
{
public class Class1
{
public void GenerateCodeAnalysisWarning(string foo)
{
if (foo == null) throw new ArgumentNullException("foo");
}
}
}
| 17.230769 | 68 | 0.589286 | [
"MIT"
] | Styxxy/Issue-BuildPropsTargets | SdkBased/Class1.cs | 226 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// AgentOrganization Data Structure.
/// </summary>
public class AgentOrganization : AlipayObject
{
/// <summary>
/// 经代下面二级商户id
/// </summary>
[JsonPropertyName("agent_merchant_id")]
public string AgentMerchantId { get; set; }
/// <summary>
/// 代理机构(ISV)蚂蚁编码,组织入驻蚂蚁生成的cid
/// </summary>
[JsonPropertyName("cid")]
public string Cid { get; set; }
/// <summary>
/// 代理机构(ISV)蚂蚁全称,组织入驻蚂蚂蚁的全称
/// </summary>
[JsonPropertyName("cid_name")]
public string CidName { get; set; }
}
}
| 24.827586 | 51 | 0.561111 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/AgentOrganization.cs | 810 | C# |
namespace Borg.Framework.Storage.Contracts
{
public interface IMimeTypeSpec
{
string Extension { get; }
string MimeType { get; }
}
} | 20.125 | 43 | 0.627329 | [
"Apache-2.0"
] | mitsbits/Bor | src/Framework/Borg.Framework/Storage/Contracts/IMimeTypeSpec.cs | 163 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ThScoreFileConverter.Extensions;
using ThScoreFileConverter.Models;
using ThScoreFileConverter.Models.Th15;
using ThScoreFileConverterTests.UnitTesting;
using ISpellCard = ThScoreFileConverter.Models.Th13.ISpellCard<ThScoreFileConverter.Models.Level>;
namespace ThScoreFileConverterTests.Models.Th15
{
[TestClass]
public class SpellCardTests
{
internal static Mock<ISpellCard> MockSpellCard()
{
var mock = new Mock<ISpellCard>();
_ = mock.SetupGet(m => m.Name).Returns(TestUtils.MakeRandomArray<byte>(0x80));
_ = mock.SetupGet(m => m.ClearCount).Returns(1);
_ = mock.SetupGet(m => m.PracticeClearCount).Returns(2);
_ = mock.SetupGet(m => m.TrialCount).Returns(3);
_ = mock.SetupGet(m => m.PracticeTrialCount).Returns(4);
_ = mock.SetupGet(m => m.Id).Returns(5);
_ = mock.SetupGet(m => m.Level).Returns(Level.Normal);
_ = mock.SetupGet(m => m.PracticeScore).Returns(6789);
return mock;
}
internal static byte[] MakeByteArray(ISpellCard spellCard)
{
return TestUtils.MakeByteArray(
spellCard.Name,
spellCard.ClearCount,
spellCard.PracticeClearCount,
spellCard.TrialCount,
spellCard.PracticeTrialCount,
spellCard.Id - 1,
TestUtils.Cast<int>(spellCard.Level),
spellCard.PracticeScore);
}
internal static void Validate(ISpellCard expected, ISpellCard actual)
{
CollectionAssert.That.AreEqual(expected.Name, actual.Name);
Assert.AreEqual(expected.ClearCount, actual.ClearCount);
Assert.AreEqual(expected.PracticeClearCount, actual.PracticeClearCount);
Assert.AreEqual(expected.TrialCount, actual.TrialCount);
Assert.AreEqual(expected.PracticeTrialCount, actual.PracticeTrialCount);
Assert.AreEqual(expected.Id, actual.Id);
Assert.AreEqual(expected.Level, actual.Level);
Assert.AreEqual(expected.PracticeScore, actual.PracticeScore);
}
[TestMethod]
public void SpellCardTest()
{
var mock = new Mock<ISpellCard>();
var spellCard = new SpellCard();
Validate(mock.Object, spellCard);
Assert.IsFalse(spellCard.HasTried);
}
[TestMethod]
public void ReadFromTest()
{
var mock = MockSpellCard();
var spellCard = TestUtils.Create<SpellCard>(MakeByteArray(mock.Object));
Validate(mock.Object, spellCard);
Assert.IsTrue(spellCard.HasTried);
}
[TestMethod]
public void ReadFromTestShortenedName()
{
var mock = MockSpellCard();
var name = mock.Object.Name;
_ = mock.SetupGet(m => m.Name).Returns(name.SkipLast(1).ToArray());
_ = Assert.ThrowsException<InvalidCastException>(
() => TestUtils.Create<SpellCard>(MakeByteArray(mock.Object)));
}
[TestMethod]
public void ReadFromTestExceededName()
{
var mock = MockSpellCard();
var name = mock.Object.Name;
_ = mock.SetupGet(m => m.Name).Returns(name.Concat(TestUtils.MakeRandomArray<byte>(1)).ToArray());
_ = Assert.ThrowsException<InvalidCastException>(
() => TestUtils.Create<SpellCard>(MakeByteArray(mock.Object)));
}
public static IEnumerable<object[]> InvalidLevels
=> TestUtils.GetInvalidEnumerators(typeof(Level));
[DataTestMethod]
[DynamicData(nameof(InvalidLevels))]
public void ReadFromTestInvalidLevel(int level)
{
var mock = MockSpellCard();
_ = mock.SetupGet(m => m.Level).Returns(TestUtils.Cast<Level>(level));
_ = Assert.ThrowsException<InvalidCastException>(
() => TestUtils.Create<SpellCard>(MakeByteArray(mock.Object)));
}
}
}
| 37.122807 | 110 | 0.615076 | [
"BSD-2-Clause"
] | armadillo-winX/ThScoreFileConverter | ThScoreFileConverterTests/Models/Th15/SpellCardTests.cs | 4,234 | C# |
/*
* Copyright 2019 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : PlgTableCommon
* Summary : The phrases used by the table plugin and editor
*
* Author : Mikhail Shiryaev
* Created : 2016
* Modified : 2019
*/
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
namespace Scada.Table
{
/// <summary>
/// The phrases used by the table plugin and editor.
/// <para>Фразы, используемые плагином и редактором таблиц.</para>
/// </summary>
public static class TablePhrases
{
// Scada.Table.TableView
public static string LoadTableViewError { get; private set; }
public static string SaveTableViewError { get; private set; }
// Scada.Table.Editor.Forms.FrmMain
public static string EditorTitle { get; private set; }
public static string DefaultTableTitle { get; private set; }
public static string TableFileFilter { get; private set; }
public static string SaveTableConfirm { get; private set; }
public static string BaseNotFound { get; private set; }
public static string EmptyDeviceNode { get; private set; }
public static string LoadConfigBaseError { get; private set; }
public static string FillCnlTreeError { get; private set; }
public static string LoadFormStateError { get; private set; }
public static string SaveFormStateError { get; private set; }
// Scada.Web.Plugins.Table.EventsRepBuilder
public static string EventsWorksheet { get; private set; }
public static string AllEventsTitle { get; private set; }
public static string EventsByViewTitle { get; private set; }
public static string EventsGen { get; private set; }
public static string NumCol { get; private set; }
public static string TimeCol { get; private set; }
public static string ObjCol { get; private set; }
public static string DevCol { get; private set; }
public static string CnlCol { get; private set; }
public static string TextCol { get; private set; }
public static string AckCol { get; private set; }
// Scada.Web.Plugins.Table.HourDataRepBuilder
public static string HourDataWorksheet { get; private set; }
public static string HourDataTitle { get; private set; }
public static string HourDataGen { get; private set; }
// Scada.Web.Plugins.Table.EventsWndSpec
public static string EventsTitle { get; private set; }
// Scada.Web.Plugins.Table.WFrmTable
public static string SelectedDay { get; private set; }
public static string PreviousDay { get; private set; }
public static string PrevDayItem { get; private set; }
public static string ItemCol { get; private set; }
public static string CurCol { get; private set; }
public static string InCnlHint { get; private set; }
public static string CtrlCnlHint { get; private set; }
public static string ObjectHint { get; private set; }
public static string DeviceHint { get; private set; }
public static string QuantityHint { get; private set; }
public static string UnitHint { get; private set; }
public static void Init()
{
Localization.Dict dict = Localization.GetDictionary("Scada.Table.TableView");
LoadTableViewError = dict.GetPhrase("LoadTableViewError");
SaveTableViewError = dict.GetPhrase("SaveTableViewError");
dict = Localization.GetDictionary("Scada.Table.Editor.Forms.FrmMain");
EditorTitle = dict.GetPhrase("EditorTitle");
DefaultTableTitle = dict.GetPhrase("DefaultTableTitle");
TableFileFilter = dict.GetPhrase("TableFileFilter");
SaveTableConfirm = dict.GetPhrase("SaveTableConfirm");
BaseNotFound = dict.GetPhrase("BaseNotFound");
EmptyDeviceNode = dict.GetPhrase("EmptyDeviceNode");
LoadConfigBaseError = dict.GetPhrase("LoadConfigBaseError");
FillCnlTreeError = dict.GetPhrase("FillCnlTreeError");
LoadFormStateError = dict.GetPhrase("LoadFormStateError");
SaveFormStateError = dict.GetPhrase("SaveFormStateError");
dict = Localization.GetDictionary("Scada.Web.Plugins.Table.EventsRepBuilder");
EventsWorksheet = dict.GetPhrase("EventsWorksheet", "EventsWorksheet"); // the default phrase must comply with Excel restrictions
AllEventsTitle = dict.GetPhrase("AllEventsTitle");
EventsByViewTitle = dict.GetPhrase("EventsByViewTitle");
EventsGen = dict.GetPhrase("EventsGen");
NumCol = dict.GetPhrase("NumCol");
TimeCol = dict.GetPhrase("TimeCol");
ObjCol = dict.GetPhrase("ObjCol");
DevCol = dict.GetPhrase("DevCol");
CnlCol = dict.GetPhrase("CnlCol");
TextCol = dict.GetPhrase("TextCol");
AckCol = dict.GetPhrase("AckCol");
dict = Localization.GetDictionary("Scada.Web.Plugins.Table.HourDataRepBuilder");
HourDataWorksheet = dict.GetPhrase("HourDataWorksheet");
HourDataTitle = dict.GetPhrase("HourDataTitle");
HourDataGen = dict.GetPhrase("HourDataGen");
dict = Localization.GetDictionary("Scada.Web.Plugins.Table.EventsWndSpec");
EventsTitle = dict.GetPhrase("EventsTitle");
dict = Localization.GetDictionary("Scada.Web.Plugins.Table.WFrmTable");
SelectedDay = dict.GetPhrase("SelectedDay");
PreviousDay = dict.GetPhrase("PreviousDay");
PrevDayItem = dict.GetPhrase("PrevDayItem");
ItemCol = dict.GetPhrase("ItemCol");
CurCol = dict.GetPhrase("CurCol");
InCnlHint = dict.GetPhrase("InCnlHint");
CtrlCnlHint = dict.GetPhrase("CtrlCnlHint");
ObjectHint = dict.GetPhrase("ObjectHint");
DeviceHint = dict.GetPhrase("DeviceHint");
QuantityHint = dict.GetPhrase("QuantityHint");
UnitHint = dict.GetPhrase("UnitHint");
}
}
}
| 48.114286 | 141 | 0.661075 | [
"Apache-2.0"
] | Arvid-new/scada | ScadaWeb/ScadaTable/PlgTableCommon/TablePhrases.cs | 6,780 | C# |
//
// FastResume.cs
//
// Authors:
// Alan McGovern [email protected]
//
// Copyright (C) 2009 Alan McGovern
//
// 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.
//
using System;
using System.IO;
using MonoTorrent.BEncoding;
namespace MonoTorrent.Client
{
public class FastResume
{
// Version 1 stored the Bitfield and Infohash.
//
// Version 2 added the UnhashedPieces bitfield.
//
static readonly BEncodedNumber FastResumeVersion = 2;
internal static readonly BEncodedString BitfieldKey = "bitfield";
internal static readonly BEncodedString BitfieldLengthKey = "bitfield_length";
internal static readonly BEncodedString InfoHashKey = "infohash";
internal static readonly BEncodedString UnhashedPiecesKey = "unhashed_pieces";
internal static readonly BEncodedString VersionKey = "version";
public BitField Bitfield { get; }
public InfoHash Infohash { get; }
public BitField UnhashedPieces { get; }
[Obsolete ("This constructor should not be used")]
public FastResume ()
{
}
[Obsolete ("The constructor overload which takes an 'unhashedPieces' parameter should be used instead of this.")]
public FastResume (InfoHash infoHash, BitField bitfield)
{
Infohash = infoHash ?? throw new ArgumentNullException (nameof (infoHash));
Bitfield = bitfield ?? throw new ArgumentNullException (nameof (bitfield));
UnhashedPieces = new BitField (Bitfield.Length);
}
public FastResume (InfoHash infoHash, BitField bitfield, BitField unhashedPieces)
{
Infohash = infoHash ?? throw new ArgumentNullException (nameof (infoHash));
Bitfield = bitfield?.Clone () ?? throw new ArgumentNullException (nameof (bitfield));
UnhashedPieces = unhashedPieces?.Clone () ?? throw new ArgumentNullException (nameof (UnhashedPieces));
for (int i = 0; i < Bitfield.Length; i++) {
if (bitfield[i] && unhashedPieces[i])
throw new ArgumentException ($"The bitfield is set to true at index {i} but that piece is marked as unhashed.");
}
}
public FastResume (BEncodedDictionary dict)
{
CheckVersion (dict);
CheckContent (dict, InfoHashKey);
CheckContent (dict, BitfieldKey);
CheckContent (dict, BitfieldLengthKey);
Infohash = new InfoHash (((BEncodedString) dict[InfoHashKey]).TextBytes);
Bitfield = new BitField ((int) ((BEncodedNumber) dict[BitfieldLengthKey]).Number);
byte[] data = ((BEncodedString) dict[BitfieldKey]).TextBytes;
Bitfield.FromArray (data, 0);
UnhashedPieces = new BitField (Bitfield.Length);
// If we're loading up an older version of the FastResume data then we
if (dict.ContainsKey (UnhashedPiecesKey)) {
data = ((BEncodedString) dict[UnhashedPiecesKey]).TextBytes;
UnhashedPieces.FromArray (data, 0);
}
}
static void CheckContent (BEncodedDictionary dict, BEncodedString key)
{
if (!dict.ContainsKey (key))
throw new TorrentException ($"Invalid FastResume data. Key '{key}' was not present");
}
static void CheckVersion (BEncodedDictionary dict)
{
long? version = (dict[VersionKey] as BEncodedNumber)?.Number;
if (version.GetValueOrDefault () == 1 || version.GetValueOrDefault () == 2)
return;
throw new ArgumentException ($"This FastResume is version {version}, but only version '1' and '2' are supported");
}
public BEncodedDictionary Encode ()
{
return new BEncodedDictionary {
{ VersionKey, FastResumeVersion },
{ InfoHashKey, new BEncodedString(Infohash.Hash) },
{ BitfieldKey, new BEncodedString(Bitfield.ToByteArray()) },
{ BitfieldLengthKey, (BEncodedNumber)Bitfield.Length },
{ UnhashedPiecesKey, new BEncodedString (UnhashedPieces.ToByteArray ()) }
};
}
public void Encode (Stream s)
{
byte[] data = Encode ().Encode ();
s.Write (data, 0, data.Length);
}
}
}
| 40.073529 | 132 | 0.643853 | [
"MIT"
] | corsearch/monotorrent | src/MonoTorrent/MonoTorrent.Client/FastResume/FastResume.cs | 5,450 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2017. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to licence terms.
//
// Version 4.6.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
using ComponentFactory.Krypton.Navigator;
using ComponentFactory.Krypton.Workspace;
namespace ComponentFactory.Krypton.Docking
{
/// <summary>
/// Extends the KryptonWorkspace to work within the docking edge of a control.
/// </summary>
[ToolboxItem(false)]
[DesignerCategory("code")]
[DesignTimeVisible(false)]
public class KryptonDockspaceSlide : KryptonDockspace
{
#region Identity
/// <summary>
/// Initialize a new instance of the KryptonDockspaceSlide class.
/// </summary>
public KryptonDockspaceSlide()
{
// Cannot drag pages inside the sliding dockspace
AllowPageDrag = false;
}
#endregion
#region Protectect
/// <summary>
/// Initialize a new cell.
/// </summary>
/// <param name="cell">Cell being added to the control.</param>
protected override void NewCellInitialize(KryptonWorkspaceCell cell)
{
// Let base class perform event hooking and customizations
base.NewCellInitialize(cell);
// We only ever show a single page in the dockspace, so remove default
// tabbed appearance and instead use a header group mode instead
cell.NavigatorMode = NavigatorMode.HeaderGroup;
}
#endregion
}
}
| 33.796875 | 83 | 0.627369 | [
"BSD-3-Clause"
] | BMBH/Krypton | Source/Krypton Components/ComponentFactory.Krypton.Docking/Control Docking/KryptonDockspaceSlide.cs | 2,166 | C# |
namespace Antlr.Examples.LLStar
{
using System;
using System.IO;
using Antlr.Runtime;
public class LLStarApp
{
public static void Main(string[] args)
{
if (args.Length == 1)
{
string fullpath;
if ( Path.IsPathRooted(args[0]) )
fullpath = args[0];
else
fullpath = Path.Combine(Environment.CurrentDirectory, args[0]);
Console.Out.WriteLine("Processing file: {0}", fullpath);
ICharStream input = new ANTLRFileStream(fullpath);
SimpleCLexer lex = new SimpleCLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lex);
//System.out.println("tokens="+tokens);
SimpleCParser parser = new SimpleCParser(tokens);
parser.program();
Console.Out.WriteLine("Finished processing file: {0}", fullpath);
}
else
Console.Error.WriteLine("Usage: llstar <input-filename>");
}
}
} | 27.21875 | 69 | 0.669346 | [
"MIT"
] | JaDogg/__py_playground | reference/examples-v3/csharp/LL-star/Main.cs | 871 | C# |
namespace Discord
{
/// <summary> Specifies the state of the client's login status. </summary>
public enum LoginState : byte
{
/// <summary> The client is currently logged out. </summary>
LoggedOut,
/// <summary> The client is currently logging in. </summary>
LoggingIn,
/// <summary> The client is currently logged in. </summary>
LoggedIn,
/// <summary> The client is currently logging out. </summary>
LoggingOut
}
}
| 31.125 | 78 | 0.606426 | [
"MIT"
] | 230Daniel/Discord.Net | src/Discord.Net.Core/LoginState.cs | 498 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCar : BaseCar
{
private void Start()
{
CarName = GameController.m_instance.m_playerData.PlayerName;
m_rigidbody = GetComponent<Rigidbody>();
m_meshRenderer = GetComponent<MeshRenderer>();
IsAnAi = false;
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
GameController.m_instance.m_pauseMenu.PauseGame();
}
if (GameController.m_instance.m_raceHasStarted && m_isActive && !m_raceHasEnded && !GameController.m_instance.m_gameIsPaused)
{
if (m_hasBeenStopped)
m_hasBeenStopped = false;
UseItem();
m_raceTime += Time.deltaTime;
}
else if (!m_isActive && GameController.m_instance.m_raceHasStarted)
{
transform.Rotate(Vector3.up * 10f);
}
if (GameController.m_instance.m_gameIsPaused)
{
if (!m_hasBeenStopped)
{
m_idlePosition = transform.position;
m_hasBeenStopped = true;
}
else
{
transform.position = m_idlePosition;
}
}
}
private void FixedUpdate()
{
if (GameController.m_instance.m_raceHasStarted && !m_raceHasEnded && m_isActive && !GameController.m_instance.m_gameIsPaused)
{
CarMovement();
}
}
protected override void CarMovement()
{
if (Input.GetKey(KeyCode.Space))
{
if (m_wheel.motorTorque >= m_carSpeed)
m_wheel.motorTorque = m_carSpeed;
else
{ m_wheel.motorTorque += 500 * Time.deltaTime; }
}
else
{ m_wheel.motorTorque = 0; }
if (Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.W))
{
RotateCar(Vector3.left + Vector3.forward, transform, m_carTurnSpeed);
}
else if (Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.S))
{
RotateCar(Vector3.left + Vector3.back, transform, m_carTurnSpeed);
}
else if (Input.GetKey(KeyCode.RightArrow) && Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.D) && Input.GetKey(KeyCode.W))
{
RotateCar(Vector3.forward + Vector3.right, transform, m_carTurnSpeed);
}
else if (Input.GetKey(KeyCode.RightArrow) && Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.D) && Input.GetKey(KeyCode.S))
{
RotateCar(Vector3.back + Vector3.right, transform, m_carTurnSpeed);
}
else if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
RotateCar(Vector3.left, transform, m_carTurnSpeed);
}
else if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
RotateCar(Vector3.right, transform, m_carTurnSpeed);
}
else if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
{
RotateCar(Vector3.forward, transform, m_carTurnSpeed);
}
else if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
{
RotateCar(Vector3.back, transform, m_carTurnSpeed);
}
}
protected override void UseItem()
{
if (Input.GetKeyDown(KeyCode.B) && !GameController.m_instance.m_gameIsPaused)
{
if (m_hasTacos)
{
GameObject go = SpawnObject(m_weaponSlot.transform, GameController.m_instance.m_weapons[0]);
TacoScript t = go.GetComponent<TacoScript>();
t.m_owner = gameObject;
}
else if (m_hasBoost)
{
UseBoost(transform, m_rigidbody);
}
}
}
} | 33.571429 | 139 | 0.580476 | [
"MIT"
] | maksens/LocoRacers | Beta_0.2.1/Beta_0.2.1/Assets/Scripts/Cars/RaceScripts/PlayerCar.cs | 3,997 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="Options.cs">
// Copyright (c) 2003-2021 Aspose Pty Ltd
// </copyright>
// <summary>
// 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.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Merger.Cloud.Sdk.Model
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// Options
/// </summary>
public class Options
{
/// <summary>
/// File info
/// </summary>
public FileInfo FileInfo { get; set; }
/// <summary>
/// The output path.
/// </summary>
public string OutputPath { get; set; }
/// <summary>
/// Get 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 Options {\n");
sb.Append(" FileInfo: ").Append(this.FileInfo).Append("\n");
sb.Append(" OutputPath: ").Append(this.OutputPath).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
}
}
| 39.666667 | 119 | 0.584416 | [
"MIT"
] | groupdocs-merger-cloud/groupdocs-merger-cloud-dotnet | src/GroupDocs.Merger.Cloud.Sdk/Model/Options.cs | 2,618 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd, 2006 - 2016. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, PO Box 1504,
// Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms.
//
// Version 5.452.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Windows.Forms;
namespace KryptonPanelExamples
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 31.633333 | 81 | 0.539515 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.452 | Source/Demos/Non-NuGet/Krypton Toolkit Examples/KryptonPanel Examples/Program.cs | 952 | 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.Commands.Common.Authentication;
using Microsoft.Azure.Commands.ScenarioTest.Mocks;
using Microsoft.Azure.Graph.RBAC;
using Microsoft.Azure.Management.Authorization;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Test;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Microsoft.WindowsAzure.Management.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using RestTestFramework = Microsoft.Rest.ClientRuntime.Azure.TestFramework;
namespace Microsoft.Azure.Commands.ScenarioTest.SqlTests
{
using System.IO;
public class SqlTestsBase : RMTestBase
{
protected SqlEvnSetupHelper helper;
private const string TenantIdKey = "TenantId";
private const string DomainKey = "Domain";
public string UserDomain { get; private set; }
protected SqlTestsBase()
{
helper = new SqlEvnSetupHelper();
}
protected virtual void SetupManagementClients(RestTestFramework.MockContext context)
{
var sqlClient = GetSqlClient(context);
var sqlLegacyClient = GetLegacySqlClient();
var storageClient = GetStorageClient();
//TODO, Remove the MockDeploymentFactory call when the test is re-recorded
var resourcesClient = MockDeploymentClientFactory.GetResourceClient(GetResourcesClient());
var authorizationClient = GetAuthorizationManagementClient();
helper.SetupSomeOfManagementClients(sqlClient, sqlLegacyClient, storageClient, resourcesClient, authorizationClient);
}
protected void RunPowerShellTest(params string[] scripts)
{
var callingClassType = TestUtilities.GetCallingClass(2);
var mockName = TestUtilities.GetCurrentMethodName(2);
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Microsoft.Resources", null);
d.Add("Microsoft.Features", null);
d.Add("Microsoft.Authorization", null);
var providersToIgnore = new Dictionary<string, string>();
providersToIgnore.Add("Microsoft.Azure.Graph.RBAC.GraphRbacManagementClient", "1.42-previewInternal");
providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");
HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore);
HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");
// Enable undo functionality as well as mock recording
using (RestTestFramework.MockContext context = RestTestFramework.MockContext.Start(callingClassType, mockName))
{
SetupManagementClients(context);
helper.SetupEnvironment();
helper.SetupModules(AzureModule.AzureResourceManager,
"ScenarioTests\\Common.ps1",
"ScenarioTests\\" + this.GetType().Name + ".ps1",
helper.RMProfileModule,
helper.RMResourceModule,
helper.RMStorageDataPlaneModule,
helper.GetRMModulePath(@"AzureRM.Insights.psd1"),
helper.GetRMModulePath(@"AzureRM.Sql.psd1"),
"AzureRM.Storage.ps1",
"AzureRM.Resources.ps1");
helper.RunPowerShellTest(scripts);
}
}
protected Management.Sql.SqlManagementClient GetSqlClient(RestTestFramework.MockContext context)
{
Management.Sql.SqlManagementClient client =
context.GetServiceClient<Management.Sql.SqlManagementClient>(
RestTestFramework.TestEnvironmentFactory.GetTestEnvironment());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected Management.Sql.LegacySdk.SqlManagementClient GetLegacySqlClient()
{
Management.Sql.LegacySdk.SqlManagementClient client =
TestBase.GetServiceClient<Management.Sql.LegacySdk.SqlManagementClient>(
new CSMTestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected StorageManagementClient GetStorageClient()
{
StorageManagementClient client = TestBase.GetServiceClient<StorageManagementClient>(new RDFETestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected ResourceManagementClient GetResourcesClient()
{
ResourceManagementClient client = TestBase.GetServiceClient<ResourceManagementClient>(new CSMTestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected AuthorizationManagementClient GetAuthorizationManagementClient()
{
AuthorizationManagementClient client = TestBase.GetServiceClient<AuthorizationManagementClient>(new CSMTestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
protected GraphRbacManagementClient GetGraphClient(RestTestFramework.MockContext context)
{
var environment = RestTestFramework.TestEnvironmentFactory.GetTestEnvironment();
string tenantId = null;
if (HttpMockServer.Mode == HttpRecorderMode.Record)
{
tenantId = environment.Tenant;
UserDomain = environment.UserName.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries).Last();
HttpMockServer.Variables[TenantIdKey] = tenantId;
HttpMockServer.Variables[DomainKey] = UserDomain;
}
else if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
if (HttpMockServer.Variables.ContainsKey(TenantIdKey))
{
tenantId = HttpMockServer.Variables[TenantIdKey];
AzureRmProfileProvider.Instance.Profile.Context.Tenant.Id = new Guid(tenantId);
}
if (HttpMockServer.Variables.ContainsKey(DomainKey))
{
UserDomain = HttpMockServer.Variables[DomainKey];
AzureRmProfileProvider.Instance.Profile.Context.Tenant.Domain = UserDomain;
}
}
var client = context.GetGraphServiceClient<GraphRbacManagementClient>(environment);
client.TenantID = tenantId;
return client;
}
protected Management.Storage.StorageManagementClient GetStorageV2Client()
{
var client =
TestBase.GetServiceClient<Management.Storage.StorageManagementClient>(new CSMTestEnvironmentFactory());
if (HttpMockServer.Mode == HttpRecorderMode.Playback)
{
client.LongRunningOperationInitialTimeout = 0;
client.LongRunningOperationRetryTimeout = 0;
}
return client;
}
}
}
| 45.305 | 142 | 0.626973 | [
"MIT"
] | NonStatic2014/azure-powershell | src/ResourceManager/Sql/Commands.Sql.Test/ScenarioTests/SqlTestsBase.cs | 8,862 | C# |
using UnityEngine;
using UnityEditor;
public class PackageTool
{
[MenuItem("Package/Update Package")]
static void UpdatePackage()
{
AssetDatabase.ExportPackage("Assets/Kvant", "KvantSprayMV.unitypackage", ExportPackageOptions.Recurse);
}
}
| 22.083333 | 111 | 0.728302 | [
"Unlicense"
] | keijiro/KvantSprayMV | Assets/Editor/PackageTool.cs | 265 | C# |
using System;
using System.Collections.Generic;
namespace AdventOfCode.Y2021.Day03
{
class S02
{
public void Solve(List<string> puzzleInput)
{
int result = 0;
var binary = 0;
var oxygenList = new List<string>(puzzleInput);
var oxygenTempList = new List<string>();
var co2List = new List<string>(puzzleInput);
var co2TempList = new List<string>();
var co2oxyIndex = 0;
while(oxygenList.Count > 1)
{
binary = 0;
foreach(string line in oxygenList)
{
if(line[co2oxyIndex] == '1')
{
binary++;
}
else
{
binary--;
}
}
foreach(string line in oxygenList)
{
if((binary >= 0 && line[co2oxyIndex] == '1') || ((binary < 0 && line[co2oxyIndex] == '0')))
{
oxygenTempList.Add(line);
}
}
oxygenList = new List<string>(oxygenTempList);
oxygenTempList.Clear();
co2oxyIndex++;
}
OxygenGeneratorRating = oxygenList[0];
co2oxyIndex = 0;
while(co2List.Count > 1)
{
binary = 0;
foreach(string line in co2List)
{
if(line[co2oxyIndex] == '1')
{
binary++;
}
else
{
binary--;
}
}
foreach(string line in co2List)
{
if((binary >= 0 && line[co2oxyIndex] == '0') || ((binary < 0 && line[co2oxyIndex] == '1')))
{
co2TempList.Add(line);
}
}
co2List = new List<string>(co2TempList);
co2TempList.Clear();
co2oxyIndex++;
}
CO2ScrubberRating = co2List[0];
int oxygenDecimal = Convert.ToInt32(OxygenGeneratorRating,2);
int co2Decimal = Convert.ToInt32(CO2ScrubberRating,2);
result = oxygenDecimal * co2Decimal;
Console.WriteLine($"{result} is the result and {oxygenDecimal} is the OxygenRating and {co2Decimal} is the CO2Rating");
}
public string InputFile = "2021/day03/input.txt";
public string OxygenGeneratorRating = "";
public string CO2ScrubberRating = "";
}
} | 32.857143 | 131 | 0.419203 | [
"MIT"
] | huntpbrennan/AdventOfCode | 2021/day03/s02.cs | 2,760 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("khelechy")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.2.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.2")]
[assembly: System.Reflection.AssemblyProductAttribute("CSJsonDB")]
[assembly: System.Reflection.AssemblyTitleAttribute("CSJsonDB")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.2.0")]
[assembly: System.Reflection.AssemblyMetadataAttribute("RepositoryUrl", "https://github.com/Khelechy/CSJsonDB.git")]
// Generated by the MSBuild WriteCodeFragment class.
| 43.64 | 116 | 0.662695 | [
"MIT"
] | davidfowl/CSJsonDB | obj/Debug/net5.0/CSJsonDB.AssemblyInfo.cs | 1,091 | C# |
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Parser.Html;
using ComboRox.Core.Utilities.SimpleGuard;
using Html2Amp.Sanitization;
using Html2Amp.Sanitization.Implementation;
using System.Collections.Generic;
namespace Html2Amp
{
public class HtmlToAmpConverter
{
private HtmlParser parser;
private HashSet<ISanitizer> sanitizers;
private RunConfiguration configuration;
private RunContext runContext;
private volatile bool isInitialized = false;
private object initializationLock = new object();
public HtmlToAmpConverter()
{
// We should load the css engine of AngleSharp,
//otherwise it doesn't pasre the css.
// https://github.com/AngleSharp/AngleSharp/issues/90
this.parser = new HtmlParser(Configuration.Default.WithCss());
this.configuration = new RunConfiguration();
this.sanitizers = new HashSet<ISanitizer>();
// Initializing a default collection of sanitizers
// With high priority should be the sanitizers which remove and rewrite elements in order to
// eliminate redundant removing/rewriting of them itself or their attributes. After that
// they should be ordered by logical behaviour. E.g. the YouTubeVideoSanitizer should be
// before IFrameSanitizer, because YouTubeVideoSanitizer relies on iframe element.
// Removing elements
this.sanitizers.Add(new ScriptElementSanitizer());
// Rewriting elements
this.sanitizers.Add(new ImageSanitizer());
this.sanitizers.Add(new YouTubeVideoSanitizer());
this.sanitizers.Add(new IFrameSanitizer());
this.sanitizers.Add(new AudioSanitizer());
// Removing attributes
this.sanitizers.Add(new StyleAttributeSanitizer());
this.sanitizers.Add(new JavaScriptRelatedAttributeSanitizer());
this.sanitizers.Add(new XmlAttributeSanitizer());
// Changing attributes
this.sanitizers.Add(new HrefJavaScriptSanitizer());
this.sanitizers.Add(new TargetAttributeSanitizer());
}
/// <summary>
/// Sets the collection of <see cref="ISanitizer"/> which will be used for convertion.
/// </summary>
/// <param name="sanitizers">Collection of <see cref="ISanitizer"/></param>
/// <returns><see cref="HtmlToAmpConverter"/></returns>
public HtmlToAmpConverter WithSanitizers(HashSet<ISanitizer> sanitizers)
{
this.sanitizers = sanitizers;
return this;
}
/// <summary>
/// Sets the <see cref="RunConfiguration" /> which will be used for convertion.
/// </summary>
/// <param name="configuration">The <see cref="RunConfiguration"/></param>
/// <returns><see cref="HtmlToAmpConverter"/></returns>
public HtmlToAmpConverter WithConfiguration(RunConfiguration configuration)
{
this.configuration = configuration;
return this;
}
/// <summary>
/// Converts HTML to "AMP HTML".
/// </summary>
/// <param name="htmlSource">HTML source code to be converted.</param>
/// <exception cref="ArgumentNullException">When <paramref name="htmlSource"/> is null or empty string.</exception>
/// <returns>Returns <see cref="ConvertionResult"/> which contains the result of the convertion.</returns>
public ConvertionResult ConvertFromHtml(string htmlSource)
{
Guard.Requires(htmlSource, "htmlSource").IsNotNullOrEmpty();
IHtmlDocument document = parser.Parse(htmlSource);
IHtmlHtmlElement htmlElement = (IHtmlHtmlElement)document.DocumentElement;
this.EnsureInitilized();
ConvertFromHtmlElement(document, document.Body);
return new ConvertionResult {
AmpHtml = document.Body.InnerHtml
};
}
private void EnsureInitilized()
{
if (!isInitialized)
{
lock (this.initializationLock)
{
if (!isInitialized)
{
this.Initialize();
this.isInitialized = true;
}
}
}
}
private void Initialize()
{
this.runContext = new RunContext(this.configuration);
foreach (var sanitizer in this.sanitizers)
{
sanitizer.Configure(this.runContext);
}
}
private void ConvertFromHtmlElement(IDocument document, IElement htmlElement)
{
foreach (var sanitizer in sanitizers)
{
if (sanitizer.CanSanitize(htmlElement))
{
htmlElement = sanitizer.Sanitize(document, htmlElement);
if (htmlElement == null) // If the element is removed
{
break;
}
}
}
if (htmlElement != null)
{
foreach (var childElement in htmlElement.Children)
{
ConvertFromHtmlElement(document, childElement);
}
}
}
}
} | 29.228758 | 117 | 0.71847 | [
"Apache-2.0"
] | mustakimali/Html2Amp | Html2Amp/HtmlToAmpConverter.cs | 4,474 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Text.Analyzers
{
/// <summary>
/// CA1704: Identifiers should be spelled correctly
/// </summary>
public abstract class IdentifiersShouldBeSpelledCorrectlyAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1704";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyTitle), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageAssembly = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageAssembly), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNamespace = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageNamespace), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageType = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageType), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMember = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMember), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberParameter = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMemberParameter), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDelegateParameter = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageDelegateParameter), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageTypeTypeParameter = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageTypeTypeParameter), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMethodTypeParameter = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMethodTypeParameter), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageAssemblyMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageAssemblyMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNamespaceMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageNamespaceMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageTypeMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageTypeMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMemberMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMemberParameterMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMemberParameterMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDelegateParameterMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageDelegateParameterMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageTypeTypeParameterMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageTypeTypeParameterMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMethodTypeParameterMoreMeaningfulName = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyMessageMethodTypeParameterMoreMeaningfulName), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(TextAnalyzersResources.IdentifiersShouldBeSpelledCorrectlyDescription), TextAnalyzersResources.ResourceManager, typeof(TextAnalyzersResources));
internal static DiagnosticDescriptor AssemblyRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageAssembly,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor NamespaceRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNamespace,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor TypeRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageType,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor MemberRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMember,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor MemberParameterRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMemberParameter,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor DelegateParameterRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDelegateParameter,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor TypeTypeParameterRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageTypeTypeParameter,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor MethodTypeParameterRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMethodTypeParameter,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor AssemblyMoreMeaningfulNameRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageAssemblyMoreMeaningfulName,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor NamespaceMoreMeaningfulNameRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNamespaceMoreMeaningfulName,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor TypeMoreMeaningfulNameRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageTypeMoreMeaningfulName,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor MemberMoreMeaningfulNameRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMemberMoreMeaningfulName,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor MemberParameterMoreMeaningfulNameRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMemberParameterMoreMeaningfulName,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor DelegateParameterMoreMeaningfulNameRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDelegateParameterMoreMeaningfulName,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor TypeTypeParameterMoreMeaningfulNameRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageTypeTypeParameterMoreMeaningfulName,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
internal static DiagnosticDescriptor MethodTypeParameterMoreMeaningfulNameRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMethodTypeParameterMoreMeaningfulName,
DiagnosticCategory.Naming,
DiagnosticSeverity.Warning,
isEnabledByDefault: false,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1704",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray<DiagnosticDescriptor>.Empty;
//ImmutableArray.Create(AssemblyRule, NamespaceRule, TypeRule, MemberRule, MemberParameterRule, DelegateParameterRule, TypeTypeParameterRule, MethodTypeParameterRule, AssemblyMoreMeaningfulNameRule, NamespaceMoreMeaningfulNameRule, TypeMoreMeaningfulNameRule, MemberMoreMeaningfulNameRule, MemberParameterMoreMeaningfulNameRule, DelegateParameterMoreMeaningfulNameRule, TypeTypeParameterMoreMeaningfulNameRule, MethodTypeParameterMoreMeaningfulNameRule);
#pragma warning disable RS1025 // Configure generated code analysis
public override void Initialize(AnalysisContext analysisContext)
#pragma warning restore RS1025 // Configure generated code analysis
{
analysisContext.EnableConcurrentExecution();
// TODO: Configure generated code analysis.
//analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
}
}
} | 120.241026 | 462 | 0.503519 | [
"Apache-2.0"
] | LLLXXXCCC/roslyn-analyzers | src/Text.Analyzers/Core/IdentifiersShouldBeSpelledCorrectly.cs | 23,447 | C# |
using System.Xml;
using MetX.Standard.Generation.CSharp.Project;
using MetX.Standard.Library;
using MetX.Standard.Library.Extensions;
using MetX.Tests.Standard.Generation.CSharp.Project.Pieces;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MetX.Tests.Standard.Generation.CSharp.Project
{
public partial class ConsoleClientCsProjGeneratorTests
{
[TestMethod]
public void PackageReference_InsertOne_NotPresent()
{
var modifier = Piece.GetEmptyClient();
var element = modifier.ItemGroup.Common.InsertOrUpdate();
Assert.IsNotNull(element);
Assert.AreEqual(modifier.ItemGroup.Common.PackageName, element.Attributes["Include"]?.Value);
Assert.IsNotNull(modifier.ItemGroup.Common.Version, element.Attributes["Version"]?.Value);
}
[TestMethod]
public void PackageReference_InsertOneWithAssets_NotPresent()
{
var modifier = Piece.GetEmptyClient();
var element = modifier.ItemGroup.Analyzers.InsertOrUpdate();
Assert.IsNotNull(element);
Assert.AreEqual(modifier.ItemGroup.Analyzers.PackageName, element.Attributes["Include"]?.Value);
Assert.AreEqual(modifier.ItemGroup.Analyzers.Version, element.Attributes["Version"]?.Value);
Assert.AreEqual(2, element.ChildNodes.Count);
Assert.AreEqual("PrivateAssets", element.ChildNodes[0]?.Name);
Assert.AreEqual(modifier.ItemGroup.Analyzers.PrivateAssets, element.ChildNodes[0]?.InnerText);
Assert.AreEqual("IncludeAssets", element.ChildNodes[1]?.Name);
Assert.AreEqual(modifier.ItemGroup.Analyzers.IncludeAssets, element.ChildNodes[1]?.InnerText);
}
[TestMethod]
public void PackageReference_InsertOne_Present()
{
var modifier = Piece.GetFullClient();
var element = modifier.ItemGroup.Common.InsertOrUpdate();
AssertPackageReference(element, modifier.ItemGroup.Common);
}
[TestMethod]
public void PackageReference_InsertOneWithAssets_Present()
{
var modifier = Piece.GetFullClient();
var element = modifier.ItemGroup.Analyzers.InsertOrUpdate();
AssertPackageReference(element, modifier.ItemGroup.Analyzers);
}
[TestMethod]
public void InsertOrUpdateAllForGeneration_Simple()
{
var modifier = Piece.GetFullClient();
var element = modifier.ItemGroup.Analyzers.InsertOrUpdate();
AssertPackageReference(element, modifier.ItemGroup.Analyzers);
}
[TestMethod]
public void InsertOrUpdateAll_Simple()
{
var modifier = Piece.GetEmptyClient();
var analyzersPR = modifier.ItemGroup.Analyzers.InsertOrUpdate();
var commonPR = modifier.ItemGroup.Common.InsertOrUpdate();
var workspacesPR = modifier.ItemGroup.CSharpWorkspaces.InsertOrUpdate();
AssertPackageReference(analyzersPR, modifier.ItemGroup.Analyzers);
AssertPackageReference(commonPR, modifier.ItemGroup.Common);
AssertPackageReference(workspacesPR, modifier.ItemGroup.CSharpWorkspaces);
}
[TestMethod]
public void RemoveAll_AlreadyThere()
{
var modifier = Piece.GetFullClient();
var analyzersPR = modifier.ItemGroup.Analyzers.Remove();
var commonPR = modifier.ItemGroup.Common.Remove();
var workspacesPR = modifier.ItemGroup.CSharpWorkspaces.Remove();
Assert.IsNull(analyzersPR);
Assert.IsNull(commonPR);
Assert.IsNull(workspacesPR);
}
[TestMethod]
public void RemoveAll_NothingThere()
{
var modifier = Piece.GetEmptyClient();
var analyzersPR = modifier.ItemGroup.Analyzers.Remove();
var commonPR = modifier.ItemGroup.Common.Remove();
var workspacesPR = modifier.ItemGroup.CSharpWorkspaces.Remove();
Assert.IsNull(analyzersPR);
Assert.IsNull(commonPR);
Assert.IsNull(workspacesPR);
}
public static void AssertPackageReference(XmlElement element, PackageReference reference)
{
Assert.IsNotNull(element);
Assert.AreEqual(reference.PackageName, element.Attributes["Include"]?.Value);
Assert.AreEqual(reference.Version, element.Attributes["Version"]?.Value);
if(reference.PrivateAssets.IsNotEmpty())
{
Assert.IsTrue(element.ChildNodes.Count is > 0 and < 3);
Assert.AreEqual("PrivateAssets", element.ChildNodes[0]?.Name);
Assert.AreEqual(reference.PrivateAssets, element.ChildNodes[0]?.InnerText);
}
if(reference.IncludeAssets.IsNotEmpty())
{
Assert.IsTrue(element.ChildNodes.Count is > 0 and < 3);
Assert.AreEqual("IncludeAssets", element.ChildNodes[1]?.Name);
Assert.AreEqual(reference.IncludeAssets, element.ChildNodes[1]?.InnerText);
}
}
}
} | 40.992308 | 108 | 0.634078 | [
"ISC"
] | wrawlsqw/xlg | MetX/MetX.Tests/Standard/Generation/CSharp/Project/ConsoleClientCsProjGeneratorTests_PackageReference.cs | 5,331 | C# |
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace FrogScroller
{
public partial class ImageViewController : UIViewController
{
public ImageViewController (int pageIndex)
{
PageIndex = pageIndex;
}
public int PageIndex { get; private set; }
public static ImageViewController ImageViewControllerForPageIndex (int pageIndex)
{
return pageIndex >= 0 && pageIndex < ImageScrollView.ImageCount ?
new ImageViewController (pageIndex) : null;
}
public override void LoadView ()
{
ImageScrollView scrollView = new ImageScrollView () {
Index = PageIndex,
AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight,
};
this.View = scrollView;
}
}
} | 22.727273 | 92 | 0.737333 | [
"Apache-2.0"
] | Acidburn0zzz/monotouch-samples | FrogScroller/FrogScroller/ImageViewController.cs | 750 | C# |
using System;
using Norm.Responses;
using System.Collections.Generic;
namespace Norm
{
/// <summary>
/// <see cref="Norm.MongoAdmin"/>
/// </summary>
public interface IMongoAdmin : IDisposable
{
AssertInfoResponse AssertionInfo();
BuildInfoResponse BuildInfo();
IMongoDatabase Database { get; }
DroppedDatabaseResponse DropDatabase();
ForceSyncResponse ForceSync(bool async);
IEnumerable<DatabaseInfo> GetAllDatabases();
IEnumerable<CurrentOperationResponse> GetCurrentOperations();
int GetProfileLevel();
GenericCommandResponse KillOperation(double operationId);
PreviousErrorResponse PreviousErrors();
bool RepairDatabase(bool preserveClonedFilesOnFailure, bool backupOriginalFiles);
bool ResetLastError();
ServerStatusResponse ServerStatus();
bool SetProfileLevel(int value, out int previousLevel);
bool SetProfileLevel(int value);
}
}
| 35.142857 | 89 | 0.700203 | [
"BSD-3-Clause"
] | adzerk/NoRM | NoRM/IMongoAdmin.cs | 986 | C# |
using Gu.Roslyn.Asserts;
[assembly: TransitiveMetadataReferences(typeof(IDisposableAnalyzers.Test.ValidWithAllAnalyzers))]
[assembly: TransitiveMetadataReferences(typeof(Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute))]
[assembly: TransitiveMetadataReferences(typeof(System.Windows.Forms.Form))]
[assembly: TransitiveMetadataReferences(typeof(System.Windows.Controls.Control))]
[assembly: TransitiveMetadataReferences(typeof(System.Reactive.Linq.Observable))]
[assembly: MetadataReferences(
typeof(System.Net.WebClient),
typeof(System.Net.Mail.Attachment),
typeof(System.Data.Common.DbConnection),
typeof(System.Threading.Tasks.ValueTask),
typeof(System.Xml.Serialization.XmlSerializer),
typeof(Moq.Mock<>),
typeof(Ninject.KernelConfiguration))]
| 49.75 | 116 | 0.815327 | [
"MIT"
] | AraHaan/IDisposableAnalyzers | IDisposableAnalyzers.Test/AssemblyAttributes.cs | 798 | C# |
using System;
using System.Windows;
using System.Windows.Media;
namespace WpfExtendedWindow.Views.Controls
{
/// <summary>
/// Drawing restore icon
/// </summary>
public class DrawingRestoreIcon : IDrawingIcon
{
/// <summary>
/// Draws restore icon.
/// </summary>
/// <param name="drawingContext">DrawingContext of canvas</param>
/// <param name="factor">Factor from identity DPI</param>
/// <param name="foreground">Icon foreground Brush</param>
/// <remarks>This drawing assumes that canvas size is 16x16 by default.</remarks>
public void Draw(DrawingContext drawingContext, double factor, Brush foreground)
{
var pen = new Pen(foreground, Math.Round(1D * factor) / factor); // 1 is base path thickness.
var rect1Chrome = new Rect(3, 6, 7, 7);
var rect1Title = new Rect(3, 6, 7, 2); // 2 is base title height.
var rect2Chrome = new Rect(6, 3, 7, 7);
var rect2Title = new Rect(6, 3, 7, 2); // 2 is base title height.
var rect1ChromeActual = new Rect(
rect1Chrome.X + pen.Thickness / 2,
rect1Chrome.Y + pen.Thickness / 2,
rect1Chrome.Width - pen.Thickness,
rect1Chrome.Height - pen.Thickness);
var rect1TitleActual = new Rect(
rect1Title.X + pen.Thickness / 2,
rect1Title.Y + pen.Thickness / 2,
rect1Title.Width - pen.Thickness,
rect1Title.Height - pen.Thickness);
var rect2ChromeActual = new Rect(
rect2Chrome.X + pen.Thickness / 2,
rect2Chrome.Y + pen.Thickness / 2,
rect2Chrome.Width - pen.Thickness,
rect2Chrome.Height - pen.Thickness);
var rect2TitleActual = new Rect(
rect2Title.X + pen.Thickness / 2,
rect2Title.Y + pen.Thickness / 2,
rect2Title.Width - pen.Thickness,
rect2Title.Height - pen.Thickness);
// Create a guidelines set.
var guidelines = new GuidelineSet();
guidelines.GuidelinesX.Add(rect1Chrome.Left);
guidelines.GuidelinesX.Add(rect1Chrome.Right);
guidelines.GuidelinesY.Add(rect1Chrome.Top);
guidelines.GuidelinesY.Add(rect1Chrome.Bottom);
guidelines.GuidelinesY.Add(rect1Title.Bottom);
guidelines.GuidelinesX.Add(rect2Chrome.Left);
guidelines.GuidelinesX.Add(rect2Chrome.Right);
guidelines.GuidelinesY.Add(rect2Chrome.Top);
guidelines.GuidelinesY.Add(rect2Chrome.Bottom);
guidelines.GuidelinesY.Add(rect2Title.Bottom);
drawingContext.PushGuidelineSet(guidelines);
// Draw rectangles.
drawingContext.DrawRectangle(null, pen, rect1ChromeActual);
drawingContext.DrawRectangle(foreground, pen, rect1TitleActual);
var combined = new CombinedGeometry(
new RectangleGeometry(rect2ChromeActual),
new RectangleGeometry(rect1ChromeActual))
{
GeometryCombineMode = GeometryCombineMode.Exclude
};
drawingContext.DrawGeometry(null, pen, combined);
drawingContext.DrawRectangle(foreground, pen, rect2TitleActual);
drawingContext.Pop();
}
}
} | 33.534091 | 97 | 0.695358 | [
"MIT"
] | emoacht/WpfMonitorAware | Source/WpfExtendedWindow/Views/Controls/DrawingRestoreIcon.cs | 2,953 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ReservaSala.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ReservaSala.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
private readonly IEmployeeRepository employeeRepository;
public EmployeesController(IEmployeeRepository employeeRepository) => this.employeeRepository = employeeRepository;
[HttpGet]
public async Task<ActionResult> GetAllEmployees()
{
try
{
return Ok(await employeeRepository.GetAll());
}
catch (Exception exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
"Error retrieving data from the database : " + exception.Message);
}
}
[HttpGet("{id:int}")]
public async Task<ActionResult<Employee>> GetEmployee(int id)
{
try
{
var result = await employeeRepository.Get(id);
if (result == null)
{
return NotFound();
}
return result;
}
catch (Exception exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
"Error retrieving data from the database : " + exception.Message);
}
}
[HttpPost]
public async Task<ActionResult<Employee>> CreateEmployee([FromBody] Employee employee)
{
try
{
if (employee == null)
{
return BadRequest();
}
var emp = await employeeRepository.GetByEmail(employee.Email);
if (emp != null)
{
ModelState.AddModelError("Email", "Employee email already in use");
return BadRequest(ModelState);
}
var createdEmployee = await employeeRepository.Add(employee);
return CreatedAtAction(nameof(GetEmployee),
new { id = createdEmployee.EmployeeId }, createdEmployee);
}
catch (Exception exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
"Error creating new employee record : " + exception.Message);
}
}
[HttpPut]
public async Task<ActionResult<Employee>> UpdateEmployee(Employee employee)
{
try
{
var employeeToUpdate = await employeeRepository.Get(employee.EmployeeId);
if (employeeToUpdate == null)
{
return NotFound($"Employee with Id = {employee.EmployeeId} not found");
}
return await employeeRepository.Update(employee);
}
catch (Exception exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
"Error updating data : " + exception.Message);
}
}
[HttpDelete("{id:int}")]
public async Task<ActionResult<Employee>> DeleteEmployee(int id)
{
try
{
var employeeToDelete = await employeeRepository.Get(id);
if (employeeToDelete == null)
{
return NotFound($"Employee with Id = {id} not found");
}
return await employeeRepository.Delete(id);
}
catch (Exception exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
"Error deleting data : " + exception.Message);
}
}
[HttpGet("{search}")]
public async Task<ActionResult<IEnumerable<Employee>>> Search(string name, Gender? gender)
{
try
{
var result = await employeeRepository.Search(name, gender);
if (result.Any())
{
return Ok(result);
}
return NotFound();
}
catch (Exception exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
"Error retrieving data from the database : " + exception.Message);
}
}
}
}
| 29.75641 | 123 | 0.521758 | [
"MIT"
] | RondineleG/ReservaSala.Api | src/ReservaSala.Api/Controllers/EmployeesController.cs | 4,644 | C# |
using DBTools;
using RinnaiPortal.FactoryMethod;
using RinnaiPortal.Interface;
using RinnaiPortal.Repository.Sign;
using RinnaiPortal.Tools;
using RinnaiPortal.ViewModel.Sign;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RinnaiPortal.Repository
{
public class DailyRepository : ISignRepository
{
private DB _dc { get; set; }
private RootRepository _rootRepo { get; set; }
public DailyRepository(DB dc, RootRepository rootRepo)
{
_dc = dc;
_rootRepo = rootRepo;
}
//列表
public Pagination GetPagination(SignListParms slParms, PaggerParms pParms)
{
//string DataSource = RepositoryFactory.SmartManConn["DataSource"] + "." + RepositoryFactory.SmartManConn["Catelog"] ;
string strSQL = String.Format(
@"SELECT * from (SELECT AA.EMPLOYECD AS USERID, AA.DUTYDATE, MAX(AA.PAYYYYYMM) AS PAYYYYYMM, ISNULL(MAX(AA.BEGINTIME),'') AS BeginTime, ISNULL(MAX(AA.ENDTIME),'') AS EndTime,
SUM(AA.OverWorkHours) AS OverWorkHours, SUM(AA.RecreateDays) AS RecreateDays, SUM(AA.OffWork1) AS OffWork1, SUM(AA.OffWork2) AS OffWork2,
SUM(AA.OFFWORK3) AS OffWork3, SUM(AA.OffHours) AS OffHours, SUM(AA.OffWork5M) AS OffWork5M, SUM(AA.OffWork6M) AS OffWork6M, SUM(AA.OffWork8)
AS OffWork8, SUM(AA.OffWork9) AS OffWork9, SUM(AA.OffWorkHours) AS OffWorkHours, SUM(AA.OffWork14) AS OffWork14, SUM(AA.MEALDELAY) AS MealDelay,
SUM(AA.LOSTTIMES) AS LostTimes, SUM(AA.AddHours) AS AddHours, SUM(AA.OverWork1) AS OverWork1, SUM(AA.OverWork2) AS OverWork2, SUM(AA.OverWork3)
AS OverWork3, SUM(AA.OverWork4) AS OverWork4, MAX(Department.CODENAME) AS Department_ID,
ISNULL(MAX(AA.RemarkOff),'') AS RemarkOff
FROM (SELECT DO.EMPLOYECD, DO.DUTYDATE, DO.PAYYYYYMM, DO.BEGINTIME, DO.ENDTIME, 0 AS OverWorkHours, 0 AS RecreateDays, 0 AS OffWork1,
0 AS OffWork2, CASE WHEN DO.DUTYDATE = CAST(CONVERT(varchar, getdate(), 112) AS DECIMAL) THEN 0 ELSE F.OffWork3 END AS OFFWORK3,
0 AS OffHours, F.OffWork5M, F.OffWork6M, 0 AS OffWork8, 0 AS OffWork9, 0 AS OffWorkHours, 0 AS OffWork14, DO.MEALDELAY,
CASE WHEN DO.DUTYDATE = CAST(CONVERT(VARCHAR, GETDATE(), 112) AS DECIMAL) THEN 0 ELSE DO.LOSTTIMES END AS LOSTTIMES, 0 AS AddHours,
0 AS OverWork1, 0 AS OverWork2, 0 AS OverWork3, 0 AS OverWork4, DO.RemarkOff
FROM ITEIP.HRIS.dbo.DAILYONOFF AS DO INNER JOIN
ITEIP.HRIS.dbo.EMPLOYEE AS EM ON EM.EMPLOYECD = DO.EMPLOYECD AND DO.EMPLOYECD = EM.EMPLOYECD LEFT OUTER JOIN
ITEIP.HRIS.dbo.Dailyonoff_View AS F ON F.Employecd = DO.EMPLOYECD AND F.DutyDate = DO.DUTYDATE
WHERE (LEFT(DO.DUTYDATE, 4) BETWEEN CAST(YEAR(GETDATE()) - 1 AS DECIMAL) AND CAST(YEAR(GETDATE()) + 1 AS DECIMAL)) AND
(EM.EMPLOYECD IN
(SELECT EMPLOYECD
FROM ITEIP.HRIS.dbo.EMPLOYEE AS Sub
WHERE (1 = 1))) AND (DO.COMPANYCD = 'A') AND (EM.HIRETYPE IN ('A', 'B', 'C', 'D', 'E', 'F', ''))
UNION ALL
SELECT EMPLOYECD, DUTYDATE, '' AS PAYYYYYMM, '' AS BeginTime, '' AS EndTime, 0 AS OverWorkHours, ISNULL(SUM(RECREATEDAYS), 0) AS RecreateDays,
ISNULL(SUM(OFFWORK1), 0) AS OffWork1, ISNULL(SUM(OFFWORK2), 0) AS OffWork2, 0 AS OffWork3, ISNULL(SUM(OFFHOURS), 0) AS OffHours,
0 AS Offwork5M, 0 AS Offwork6M, ISNULL(SUM(OFFWORK8), 0) AS OffWork8, ISNULL(SUM(OFFWORK9), 0) AS OffWork9, ISNULL(SUM(OFFWORKHOURS), 0)
AS OffWorkHours, ISNULL(SUM(OffWork14), 0) AS OffWork14, 0 AS MealDelay, 0 AS LostTimes, 0 AS AddHours, 0 AS OverWork1, 0 AS OverWork2,
0 AS OverWork3, 0 AS OverWork4, '' AS REMARKOFF
FROM ITEIP.HRIS.dbo.DAILYOFF
WHERE (LEFT(DUTYDATE, 4) BETWEEN CAST(YEAR(GETDATE()) - 1 AS DECIMAL) AND CAST(YEAR(GETDATE()) + 1 AS DECIMAL))
GROUP BY EMPLOYECD, DUTYDATE
UNION ALL
SELECT EMPLOYECD, DUTYDATE, '' AS PAYYYYYMM, '' AS BeginTime, '' AS EndTime, ISNULL(SUM(OVERWORKHOURS), 0) AS OverWorkHours,
0 AS RecreateDays, 0 AS OffWork1, 0 AS OffWork2, 0 AS OffWork3, 0 AS OffHours, 0 AS Offwork5M, 0 AS Offwork6M, 0 AS OffWork8, 0 AS OffWork9,
0 AS OffWorkHours, 0 AS OffWork14, 0 AS MealDelay, 0 AS LostTimes, ISNULL(SUM(ADDHOURS), 0) AS AddHours, ISNULL(SUM(OVERWORK1), 0)
AS OverWork1, ISNULL(SUM(OVERWORK2), 0) AS OverWork2, ISNULL(SUM(OVERWORK3), 0) AS OverWork3, ISNULL(SUM(OVERWORK4), 0)
AS OverWork4, '' AS REMARKOFF
FROM ITEIP.HRIS.dbo.DAILYON
WHERE (LEFT(DUTYDATE, 4) BETWEEN CAST(YEAR(GETDATE()) - 1 AS DECIMAL) AND CAST(YEAR(GETDATE()) + 1 AS DECIMAL))
GROUP BY EMPLOYECD, DUTYDATE) AS AA
INNER JOIN ITEIP.HRIS.dbo.Employee AS EMPLOYEE ON AA.EMPLOYECD = Employee.EMPLOYECD
INNER JOIN ITEIP.HRIS.dbo.CODEDTL AS Department ON Employee.UNITCD = Department.CODECD and Department.TYPECD = 'UNIT'
WHERE (EMPLOYEE.QUITDATE='0') GROUP BY AA.EMPLOYECD, AA.DUTYDATE ) as Daily
where USERID=@USERID and PAYYYYYMM=@PAYYYYYMM");
var conditionsDic = new Conditions()
{
{ "@USERID", slParms.EmployeeID_FK},
{ "@PAYYYYYMM", slParms.payYYYYMM}
};
int PageCount=0;
if (slParms.PageName=="Default")
{
PageCount = 6;
}
else
{
PageCount = 40;
}
var paginationParms = new PaginationParms()
{
QueryString = strSQL,
QueryConditions = conditionsDic,
//PageIndex = pParms.PageIndex,
PageSize = PageCount
};
//pParms.OrderField = "CreateDate".Equals(pParms.OrderField) ? "PAYYYYYMM" : pParms.OrderField;
//string orderExpression = String.Format("{0}{1}", pParms.Descending ? "-" : "", pParms.OrderField);
string orderExpression = String.Format("{0}{1}", "-", "PAYYYYYMM");
var allowColumns = new List<string>
{
"USERID", "DUTYDATE", "PAYYYYYMM", "BeginTime", "EndTime", "OverWorkHours", "RecreateDays", "OffWork1", "OffWork2", "OffWork3", "OffHours", "OffWork5M", "OffWork6M", "OffWork8", "OffWork9", "OffWorkHours", "OffWork14", "MealDelay", "LostTimes", "AddHours", "OverWork1", "OverWork2", "OverWork3", "OverWork4", "Department_ID", "RemarkOff"
};
//根據 SQL取得 Pagination
return _dc.QueryForPagination(paginationParms, orderExpression, allowColumns);
}
}
} | 84.962617 | 341 | 0.471125 | [
"MIT"
] | systemgregorypc/Agatha-inteligencia-artificial- | agathaIA-voice/agathaiaportal/Repository/DailyRepository.cs | 9,107 | C# |
using System;
namespace HeyUrl.Domain.Entities
{
public abstract class EntityBase
{
public Guid Id { get; private set; }
public EntityBase()
{
Id = Guid.NewGuid();
}
}
}
| 15.266667 | 44 | 0.537118 | [
"MIT"
] | EltonAlvess/short-url | src/HeyUrl.Domain/Entities/EntityBase.cs | 231 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BlazorServer
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
} | 27.44 | 95 | 0.706997 | [
"Apache-2.0"
] | ApolonTorq/Detection | sample/BlazorServer/Program.cs | 686 | C# |
/*!
* Paradigm Framework - Service Libraries
* Copyright(c) 2017 Miracle Devs, Inc
* Licensed under MIT(https://github.com/MiracleDevs/Paradigm.Services/blob/master/LICENSE)
*/
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Paradigm.Services.Providers
{
public partial interface IReadProvider<TView, in TId>
{
Task<List<TView>> FindViewAsync();
Task<TView> GetViewAsync(TId id);
}
} | 24.444444 | 90 | 0.727273 | [
"MIT"
] | MiracleDevs/Paradigm.Services | src/Paradigm.Services.Providers/IReadProvider.Async.cs | 440 | C# |
using System;
using System.Collections.Generic;
///二叉树后序遍历 :左子树 右子树 根节点 的方式遍历
//给定一个二叉树的根节点 root ,返回它的 中序 遍历。
//输入:root = [1,null,2,3]
//输出:[3,2,1]
public partial class Solution{
private IList<int> PostOrderTravel(TreeNode root){
List<int> list = new List<int>();
PostOrderTravelImpl(root,list);
return list;
}
private void PostOrderTravelImpl(TreeNode root, IList<int> list){
if(root == null)
return;
PostOrderTravelImpl(root.left,list);
PostOrderTravelImpl(root.right,list);
list.Add(root.val);
}
/// <summary>
/// 迭代法后序遍历二叉树 left->right->root
/// </summary>
private IList<int> PostOrderTravel2(TreeNode root){
List<int> res = new List<int>();
Stack<TreeNode> s = new Stack<TreeNode>();
var temp = root;
TreeNode pre = null;
while(s.Count > 0 || temp != null){
if(temp != null){
s.Push(temp);
temp = temp.left;
}
else{
temp = s.Pop();
if(temp.right != null && temp.right != pre ) //防止重复push之前已经push过的节点
{
s.Push(temp);
temp = temp.right;
}
else{
res.Add(temp.val);
pre = temp;
temp = null; //清空 取栈中的下个节点
}
}
}
return res;
}
public void PostOrderTravelTest()
{
//先构建树
TreeNode root = new TreeNode(1,null,null);
TreeNode node1 = new TreeNode(2,null,null);
TreeNode node2 = new TreeNode(3,null,null);
root.right = node1;
node1.left = node2;
var list = PostOrderTravel2(root);
for(int i = 0; i < list.Count; i++){
Console.WriteLine(list[i]);
}
}
}
| 25.092105 | 84 | 0.492921 | [
"Apache-2.0"
] | minjoy77/DoLeetCode | CodeProj/02_Tree/145_PostOrderTravel.cs | 2,075 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EZNEW.Cache.String
{
/// <summary>
/// String decrement options
/// </summary>
public class StringDecrementOptions : CacheOptions<StringDecrementResponse>
{
/// <summary>
/// Gets or sets the cache key
/// </summary>
public CacheKey Key { get; set; }
/// <summary>
/// Gets or sets the value
/// </summary>
public long Value { get; set; }
/// <summary>
/// Gets or sets the cache entry expiration
/// When the specified cache item is not found, the cache item is created with the change expiration information
/// </summary>
public CacheExpiration Expiration { get; set; }
/// <summary>
/// Execute cache operation
/// </summary>
/// <param name="cacheProvider">Cache provider</param>
/// <param name="server">Cache server</param>
/// <returns>Return string decrement response</returns>
protected override async Task<IEnumerable<StringDecrementResponse>> ExecuteCacheOperationAsync(ICacheProvider cacheProvider, CacheServer server)
{
return await cacheProvider.StringDecrementAsync(server, this).ConfigureAwait(false);
}
}
}
| 34.74359 | 153 | 0.605166 | [
"MIT"
] | eznew-net/EZNEW.Develop | EZNEW/Cache/String/Option/StringDecrementOptions.cs | 1,357 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ThreeColorLineSeries.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Represents a three-color line series.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.Series
{
using System.Collections.Generic;
/// <summary>
/// Represents a two-color line series.
/// </summary>
public class ThreeColorLineSeries : LineSeries
{
/// <summary>
/// The default low color.
/// </summary>
private OxyColor defaultColorLo;
/// <summary>
/// The default hi color.
/// </summary>
private OxyColor defaultColorHi;
/// <summary>
/// Initializes a new instance of the <see cref = "ThreeColorLineSeries" /> class.
/// </summary>
public ThreeColorLineSeries()
{
this.LimitLo = -5.0;
this.ColorLo = OxyColors.Blue;
this.LineStyleLo = LineStyle.Solid;
this.LimitHi = 5.0;
this.ColorHi = OxyColors.Red;
this.LineStyleHi = LineStyle.Solid;
}
/// <summary>
/// Gets or sets the color for the part of the line that is below the limit.
/// </summary>
public OxyColor ColorLo { get; set; }
/// <summary>
/// Gets or sets the color for the part of the line that is above the limit.
/// </summary>
public OxyColor ColorHi { get; set; }
/// <summary>
/// Gets the actual hi color.
/// </summary>
/// <value>The actual color.</value>
public OxyColor ActualColorLo
{
get { return this.ColorLo.GetActualColor(this.defaultColorLo); }
}
/// <summary>
/// Gets the actual low color.
/// </summary>
/// <value>The actual color.</value>
public OxyColor ActualColorHi
{
get { return this.ColorHi.GetActualColor(this.defaultColorHi); }
}
/// <summary>
/// Gets or sets the high limit.
/// </summary>
/// <remarks>The parts of the line that is below this limit will be rendered with ColorHi.
/// The parts of the line that is above the limit will be rendered with Color.</remarks>
public double LimitHi { get; set; }
/// <summary>
/// Gets or sets the low limit.
/// </summary>
/// <remarks>The parts of the line that is below this limit will be rendered with ColorLo.
/// The parts of the line that is above the limit will be rendered with Color.</remarks>
public double LimitLo { get; set; }
/// <summary>
/// Gets or sets the dash array for the rendered line that is above the limit (overrides <see cref="LineStyle" />).
/// </summary>
/// <value>The dash array.</value>
/// <remarks>If this is not <c>null</c> it overrides the <see cref="LineStyle" /> property.</remarks>
public double[] DashesHi { get; set; }
/// <summary>
/// Gets or sets the dash array for the rendered line that is below the limit (overrides <see cref="LineStyle" />).
/// </summary>
/// <value>The dash array.</value>
/// <remarks>If this is not <c>null</c> it overrides the <see cref="LineStyle" /> property.</remarks>
public double[] DashesLo { get; set; }
/// <summary>
/// Gets or sets the line style for the part of the line that is above the limit.
/// </summary>
/// <value>The line style.</value>
public LineStyle LineStyleHi { get; set; }
/// <summary>
/// Gets or sets the line style for the part of the line that is below the limit.
/// </summary>
/// <value>The line style.</value>
public LineStyle LineStyleLo { get; set; }
/// <summary>
/// Gets the actual line style for the part of the line that is above the limit.
/// </summary>
/// <value>The line style.</value>
public LineStyle ActualLineStyleHi
{
get
{
return this.LineStyleHi != LineStyle.Automatic ? this.LineStyleHi : LineStyle.Solid;
}
}
/// <summary>
/// Gets the actual line style for the part of the line that is below the limit.
/// </summary>
/// <value>The line style.</value>
public LineStyle ActualLineStyleLo
{
get
{
return this.LineStyleLo != LineStyle.Automatic ? this.LineStyleLo : LineStyle.Solid;
}
}
/// <summary>
/// Gets the actual dash array for the line that is above the limit.
/// </summary>
protected double[] ActualDashArrayHi
{
get
{
return this.DashesHi ?? this.ActualLineStyleHi.GetDashArray();
}
}
/// <summary>
/// Gets the actual dash array for the line that is below the limit.
/// </summary>
protected double[] ActualDashArrayLo
{
get
{
return this.DashesLo ?? this.ActualLineStyleLo.GetDashArray();
}
}
/// <summary>
/// Sets the default values.
/// </summary>
protected internal override void SetDefaultValues()
{
base.SetDefaultValues();
if (this.ColorLo.IsAutomatic())
{
this.defaultColorLo = this.PlotModel.GetDefaultColor();
}
if (this.LineStyleLo == LineStyle.Automatic)
{
this.LineStyleLo = this.PlotModel.GetDefaultLineStyle();
}
if (this.ColorHi.IsAutomatic())
{
this.defaultColorHi = this.PlotModel.GetDefaultColor();
}
if (this.LineStyleHi == LineStyle.Automatic)
{
this.LineStyleHi = this.PlotModel.GetDefaultLineStyle();
}
}
/// <summary>
/// Renders the smoothed line.
/// </summary>
/// <param name="rc">The render context.</param>
/// <param name="clippingRect">The clipping rectangle.</param>
/// <param name="pointsToRender">The points.</param>
protected override void RenderLine(IRenderContext rc, OxyRect clippingRect, IList<ScreenPoint> pointsToRender)
{
var bottom = clippingRect.Bottom;
var top = clippingRect.Top;
// todo: this does not work when y axis is reversed
var yLo = this.YAxis.Transform(this.LimitLo);
var yHi = this.YAxis.Transform(this.LimitHi);
if (yLo < clippingRect.Top)
{
yLo = clippingRect.Top;
}
if (yLo > clippingRect.Bottom)
{
yLo = clippingRect.Bottom;
}
if (yHi < clippingRect.Top)
{
yHi = clippingRect.Top;
}
if (yHi > clippingRect.Bottom)
{
yHi = clippingRect.Bottom;
}
clippingRect = new OxyRect(clippingRect.Left, yHi, clippingRect.Width, yLo - yHi);
rc.DrawClippedLine(
clippingRect,
pointsToRender,
this.MinimumSegmentLength * this.MinimumSegmentLength,
this.GetSelectableColor(this.ActualColor),
this.StrokeThickness,
this.ActualDashArray,
this.LineJoin,
false);
clippingRect = new OxyRect(clippingRect.Left, yLo, clippingRect.Width, bottom - yLo);
rc.DrawClippedLine(
clippingRect,
pointsToRender,
this.MinimumSegmentLength * this.MinimumSegmentLength,
this.GetSelectableColor(this.ActualColorLo),
this.StrokeThickness,
this.ActualDashArrayLo,
this.LineJoin,
false);
clippingRect = new OxyRect(clippingRect.Left, top, clippingRect.Width, yHi - top);
rc.DrawClippedLine(
clippingRect,
pointsToRender,
this.MinimumSegmentLength * this.MinimumSegmentLength,
this.GetSelectableColor(this.ActualColorHi),
this.StrokeThickness,
this.ActualDashArrayHi,
this.LineJoin,
false);
}
}
} | 34.234375 | 123 | 0.523848 | [
"MIT"
] | AlexeiScherbakov/oxyplot | Source/OxyPlot/Series/ThreeColorLineSeries.cs | 8,766 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace SolrNet.Cloud {
public static partial class SolrClusterStateParser {
private static ISolrClusterCollection BuildCollection(JProperty json) {
var collection = new SolrClusterCollection {
Name = json.Name,
Router = BuildRouter(json.Value["router"] as JObject)
};
collection.Shards = BuildShards(collection, json.Value["shards"] as JObject);
return collection;
}
private static ISolrClusterCollections BuildCollections(JObject json) {
return new SolrClusterCollections(
json.Properties().Select(BuildCollection));
}
private static ISolrClusterReplica BuildReplica(ISolrClusterCollection collection, JProperty json) {
var baseUrl = (string) json.Value["base_url"];
var leader = json.Value["leader"];
var state = GetState(json);
return new SolrClusterReplica {
BaseUrl = baseUrl,
IsLeader = leader != null && (bool) leader,
Name = json.Name,
NodeName = (string) json.Value["node_name"],
State = state,
IsActive = IsActive(state),
Url = baseUrl + "/" + collection.Name
};
}
private static ISolrClusterReplicas BuildReplicas(ISolrClusterCollection collection, JObject json) {
return new SolrClusterReplicas(
json.Properties().Select(property => BuildReplica(collection, property)));
}
private static ISolrClusterRouter BuildRouter(JObject json) {
return new SolrClusterRouter {
Name = (string) json["name"]
};
}
private static ISolrClusterShard BuildShard(ISolrClusterCollection collection, JProperty json) {
var state = GetState(json);
return new SolrClusterShard {
Name = json.Name,
Range = SolrClusterShardRange.Parse((string) json.Value["range"]),
State = state,
IsActive = IsActive(state),
Replicas = BuildReplicas(collection, json.Value["replicas"] as JObject)
};
}
private static ISolrClusterShards BuildShards(ISolrClusterCollection collection, JObject json) {
return new SolrClusterShards(
json.Properties().Select(property => BuildShard(collection, property)));
}
private static string GetState(JProperty json) {
return (string) json.Value["state"];
}
private static bool IsActive(string state) {
return "active".Equals(state, StringComparison.OrdinalIgnoreCase);
}
public static ISolrClusterCollections ParseJsonToCollections(string json) {
return BuildCollections(JObject.Parse(json));
}
}
} | 39.428571 | 108 | 0.607708 | [
"Apache-2.0"
] | nicholaspei/SoleCloudNet | SolrNet.Cloud/Extended/SolrClusterStateParser.cs | 3,038 | C# |
namespace AspNetSample
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSaaslane<AppTenant>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
} | 25.382353 | 80 | 0.573581 | [
"MIT"
] | dj-doMains/saaslane | samples/AspNetSample/Startup.cs | 865 | C# |
using System.Threading.Tasks;
namespace Knapcode.ExplorePackages.Entities
{
public class HasV2DiscrepancyPackageQuery : IPackageConsistencyQuery
{
private readonly V2ConsistencyService _service;
public HasV2DiscrepancyPackageQuery(V2ConsistencyService service)
{
_service = service;
}
public string Name => PackageQueryNames.HasV2DiscrepancyPackageQuery;
public string CursorName => CursorNames.HasV2DiscrepancyPackageQuery;
public async Task<bool> IsMatchAsync(PackageConsistencyContext context, PackageConsistencyState state)
{
var isConsistent = await _service.IsConsistentAsync(context, state, NullProgressReporter.Instance);
return !isConsistent;
}
}
}
| 32.625 | 111 | 0.719029 | [
"MIT"
] | loic-sharma/ExplorePackages | src/ExplorePackages.Entities.Logic/PackageQueries/PackageConsistencyQueries/HasV2DiscrepancyPackageQuery.cs | 785 | C# |
//-------------------------------------------------------------------
/*! @file ModbusClient.cs
* @brief This file defines Modbus helper definitiions and classes that are specific to Modbus Clients
*
* Copyright (c) Mosaic Systems Inc.
* Copyright (c) 2011 Mosaic Systems Inc.
* Copyright (c) 2010 Mosaic Systems Inc. (prior C++ library version)
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using MosaicLib.Utils;
using MosaicLib.Time;
using MosaicLib.Modular.Action;
using MosaicLib.Modular.Part;
namespace MosaicLib.SerialIO.Modbus.Client
{
//--------------------------------------------------------------------------
///<summary>Function Storage and Execution object for FC02_ReadDiscretes function code. <see cref="DiscreteFunctionBase{DerivedType}"/> for more details on use.</summary>
public class ReadDiscretes : DiscreteFunctionBase<ReadDiscretes>
{
/// <summary>Constructor</summary>
public ReadDiscretes() { FC = FunctionCode.FC02_ReadDiscretes; }
};
///<summary>Function Storage and Execution object for FC01_ReadCoils function code. <see cref="DiscreteFunctionBase{DerivedType}"/> for more details on use.</summary>
public class ReadCoils : DiscreteFunctionBase<ReadCoils>
{
/// <summary>Constructor</summary>
public ReadCoils() { FC = FunctionCode.FC01_ReadCoils; }
/// <summary>Defines the zero based coil address for the first coil that is read by this command. This is a proxy for the FirstDiscreteAddr property in the DiscreteFunctionBase base class.</summary>
public UInt16 FirstCoilAddr { get { return FirstDiscreteAddr; } set { FirstDiscreteAddr = value; } }
/// <summary>Defines the number of coils that will be read by this command. This is a proxy for the NumDiscretes property in the DiscreteFunctionBase base class</summary>
public UInt16 NumCoils { get { return NumDiscretes; } set { NumDiscretes = value; } }
};
///<summary>Function Storage and Execution object for FC05_WriteSingleCoil function code. <see cref="DiscreteFunctionBase{DerivedType}"/> and <see cref="ClientFunctionBase{DerivedType}"/> for more details on use.</summary>
public class WriteCoil : ClientFunctionBase<WriteCoil>
{
/// <summary>Constructor</summary>
public WriteCoil() { FC = FunctionCode.FC05_WriteSingleCoil; }
/// <summary>Defines the zero based coil address for the coil that is written by this command. This is a proxy for the FirstDiscreteAddr property in the DiscreteFunctionBase base class.</summary>
public UInt16 CoilAddr { get { return HeaderWord1; } set { HeaderWord1 = value; } }
/// <summary>
/// Gets or sets the boolean value that will be written to the coil.
/// This is a proxy for the HeaderWord2 in the DiscreteFunctionBase base class which contains 0xff00 when the coil is to be turned on and 0x0000 when the coil is to be turned off.
/// </summary>
public bool Value
{
get { return (HeaderWord2 != 0); }
set { HeaderWord2 = unchecked((UInt16)(value ? 0xff00 : 0x0000)); }
}
};
///<summary>Function Storage and Execution object for FC0f_WriteMultipleCoils function code. <see cref="DiscreteFunctionBase{DerivedType}"/> for more details on use.</summary>
public class WriteCoils : DiscreteFunctionBase<WriteCoils>
{
/// <summary>Constructor</summary>
public WriteCoils() { FC = FunctionCode.FC0f_WriteMultipleCoils; }
/// <summary>Defines the zero based coil address for the first coil that is written by this command. This is a proxy for the FirstDiscreteAddr property in the DiscreteFunctionBase base class.</summary>
public UInt16 FirstCoilAddr { get { return FirstDiscreteAddr; } set { FirstDiscreteAddr = value; } }
/// <summary>Defines the number of coils that will be written by this command. This is a proxy for the NumDiscretes property in the DiscreteFunctionBase base class</summary>
public UInt16 NumCoils { get { return NumDiscretes; } set { NumDiscretes = value; } }
};
///<summary>Function Storage and Execution object for FC04_ReadInputRegisters function code. <see cref="RegistersFunctionBase{DerivedType}"/> for more details on use.</summary>
public class ReadInputRegisters : RegistersFunctionBase<ReadInputRegisters>
{
/// <summary>Constructor</summary>
public ReadInputRegisters() { FC = FunctionCode.FC04_ReadInputRegisters; }
/// <summary>Defines the zero based input register address for the first input register that is read by this command. This is a proxy for the FirstRegAddr1 property in the RegistersFunctionBase base class.</summary>
public UInt16 FirstInputRegAddr { get { return FirstRegAddr1; } set { FirstRegAddr1 = value; } }
/// <summary>Defines the number of input registers that will be read by this command. This is a proxy for the NumRegs1 property in the RegistersFunctionBase base class</summary>
public UInt16 NumInputRegs { get { return NumRegs1; } set { NumRegs1 = value; } }
};
///<summary>Function Storage and Execution object for FC03_ReadHoldingRegisters function code. <see cref="RegistersFunctionBase{DerivedType}"/> for more details on use.</summary>
public class ReadHoldingRegisters : RegistersFunctionBase<ReadHoldingRegisters>
{
/// <summary>Constructor</summary>
public ReadHoldingRegisters() { FC = FunctionCode.FC03_ReadHoldingRegisters; }
/// <summary>Defines the zero based holding register address for the first holding register that is read by this command. This is a proxy for the FirstRegAddr1 property in the RegistersFunctionBase base class.</summary>
public UInt16 FirstHoldingRegAddr { get { return FirstRegAddr1; } set { FirstRegAddr1 = value; } }
/// <summary>Defines the number of holding registers that will be read by this command. This is a proxy for the NumRegs1 property in the RegistersFunctionBase base class</summary>
public UInt16 NumHoldingRegs { get { return NumRegs1; } set { NumRegs1 = value; } }
};
///<summary>Function Storage and Execution object for FC06_WriteSingleHoldingRegister function code. <see cref="RegistersFunctionBase{DerivedType}"/> and <see cref="ClientFunctionBase{DerivedType}"/> for more details on use.</summary>
public class WriteHoldingRegister : ClientFunctionBase<WriteHoldingRegister>
{
/// <summary>Constructor</summary>
public WriteHoldingRegister() { FC = FunctionCode.FC06_WriteSingleHoldingRegister; }
/// <summary>Defines the zero based holding register address that is written by this command. This is a proxy for the HeaderWord1 property in the ClientFunctionBase base class.</summary>
public UInt16 HoldingRegAddr { get { return HeaderWord1; } set { HeaderWord1 = value; } }
/// <summary>Defines the holding register value that is written by this command. This is a proxy for the HeaderWord2 property in the ClientFunctionBase base class.</summary>
public Int16 Value { get { return unchecked((Int16) HeaderWord2); } set { HeaderWord2 = unchecked((UInt16) value); } }
};
///<summary>Function Storage and Execution object for FC10_WriteMutlipleHoldingRegisters function code. <see cref="RegistersFunctionBase{DerivedType}"/> for more details on use.</summary>
public class WriteHoldingRegisters : RegistersFunctionBase<WriteHoldingRegisters>
{
/// <summary>Constructor</summary>
public WriteHoldingRegisters() { FC = FunctionCode.FC10_WriteMutlipleHoldingRegisters; }
/// <summary>Defines the zero based holding register address for the first holding register that will be written by this command. This is a proxy for the FirstRegAddr1 property in the RegistersFunctionBase base class.</summary>
public UInt16 FirstHoldingRegAddr { get { return FirstRegAddr1; } set { FirstRegAddr1 = value; } }
/// <summary>Defines the number of holding registers that will be written by this command. This is a proxy for the NumRegs1 property in the RegistersFunctionBase base class</summary>
public UInt16 NumHoldingRegs { get { return NumRegs1; } set { NumRegs1 = value; } }
};
///<summary>Function Storage and Execution object for FC17_ReadWriteMultipleRegisters function code. <see cref="RegistersFunctionBase{DerivedType}"/> for more details on use.</summary>
public class ReadWriteMultipleRegisters : RegistersFunctionBase<ReadWriteMultipleRegisters>
{
/// <summary>Constructor</summary>
public ReadWriteMultipleRegisters() { FC = FunctionCode.FC17_ReadWriteMultipleRegisters; }
/// <summary>Defines the zero based input register address for the first input register that is read by this command. This is a proxy for the FirstRegAddr1 property in the DiscreteFunctionBase base class.</summary>
public UInt16 FirstInputRegAddr { get { return FirstRegAddr1; } set { FirstRegAddr1 = value; } }
/// <summary>Defines the number of input registers that will be read by this command. This is a proxy for the NumRegs1 property in the DiscreteFunctionBase base class</summary>
public UInt16 NumInputRegs { get { return NumRegs1; } set { NumRegs1 = value; } }
/// <summary>Defines the zero based holding register address for the first holding register that will be written by this command. This is a proxy for the FirstRegAddr2 property in the RegistersFunctionBase base class.</summary>
public UInt16 FirstHoldingRegAddr { get { return FirstRegAddr2; } set { FirstRegAddr2 = value; } }
/// <summary>Defines the number of holding registers that will be written by this command. This is a proxy for the NumRegs2 property in the RegistersFunctionBase base class</summary>
public UInt16 NumHoldingRegs { get { return NumRegs2; } set { NumRegs2 = value; } }
};
///<summary>Function Storage and Execution object for FC16_MaskWriteRegister function code. <see cref="RegistersFunctionBase{DerivedType}"/> and <see cref="ClientFunctionBase{DerivedType}"/> for more details on use.</summary>
public class MaskWriteHoldingRegister : ClientFunctionBase<MaskWriteHoldingRegister>
{
/// <summary>Constructor</summary>
public MaskWriteHoldingRegister() { FC = FunctionCode.FC16_MaskWriteRegister; }
/// <summary>Defines the zero based holding register address that is modified by this command. This is a proxy for the HeaderWord1 property in the ClientFunctionBase base class.</summary>
public UInt16 HoldingRegAddr { get { return HeaderWord1; } set { HeaderWord1 = value; } }
/// <summary>Defines the value that will be And'ed into the holding register value by this command. This is a proxy for the HeaderWord2 property in the ClientFunctionBase base class.</summary>
public Int16 AndMask
{
get { return unchecked((Int16) HeaderWord2); }
set { HeaderWord2 = unchecked((UInt16) value); }
}
/// <summary>Defines the value that will be Or'ed into the holding register value by this command. This is a proxy for the HeaderWord3 property in the ClientFunctionBase base class.</summary>
public Int16 OrMask
{
get { return unchecked((Int16) HeaderWord3); }
set { HeaderWord3 = unchecked((UInt16) value); }
}
}
//--------------------------------------------------------------------------
#region Client function base classes: DiscreteFunctionBase, RegistersFunctionBase, ClientFunctionBase, ClientFunctionState
///<summary>Base class for Client side of Discrete related function codes. Derived from ClientFunctionBase</summary>
public class DiscreteFunctionBase<DerivedType> : ClientFunctionBase<DerivedType> where DerivedType : class
{
/// <summary>Defines the zero based discrete/coil address for the first discrete/coil that is handled by this command</summary>
public UInt16 FirstDiscreteAddr { get { return HeaderWord1; } set { HeaderWord1 = value; } }
/// <summary>Defines the number of dicrete/coil values that will be transfered using this command</summary>
public UInt16 NumDiscretes { get { return HeaderWord2; } set { HeaderWord2 = value; } }
};
///<summary>Base class for Client side of Register related function codes. Derived from ClientFunctionBase</summary>
public class RegistersFunctionBase<DerivedType> : ClientFunctionBase<DerivedType> where DerivedType : class
{
/// <summary>Defines the zero based register address for the first register in the first block of regsiters that will be handled by this command</summary>
public UInt16 FirstRegAddr1 { get { return HeaderWord1; } set { HeaderWord1 = value; } }
/// <summary>Defines the number of registers in the first block of registers that will be transfered using this command</summary>
public UInt16 NumRegs1 { get { return HeaderWord2; } set { HeaderWord2 = value; } }
/// <summary>Defines the zero based register address for the first register in the second block of regsiters that will be handled by this command</summary>
public UInt16 FirstRegAddr2 { get { return HeaderWord3; } set { HeaderWord3 = value; } }
/// <summary>Defines the number of registers in the second block of registers that will be transfered using this command</summary>
public UInt16 NumRegs2 { get { return HeaderWord4; } set { HeaderWord4 = value; } }
};
///<summary>Enum defines the progress state for a function storage and execution object (derived from FunctionBase)</summary>
public enum ClientFunctionState
{
///<summary>Function is ready to be run</summary>
Ready = 0,
///<summary>Function is in Progress</summary>
InProgress,
///<summary>Function completed successfully</summary>
Succeeded,
///<summary>Function completed unsuccessfully</summary>
Failed,
}
///<summary>
/// This class is the templatized version of the ClientFunctionBase. It allows the base class to implement a passthrough version of the Setup method.
/// This class is the base class for all Modbus Client Function Exection wrapper objects.
/// This class defines the storage and common execution pattern for all Modbus supported client operation/command objects that are generally used by a client
/// to run one or more modbus commands. Generally individual function execution objects will be derived from this object to implement each of the support
/// Modbus fucntion codes where the derived object will provide properties and methods that are specific to that function code while the logic in the base class
/// here will be provide the majority of the implementation of common execution flow patterns such as encoding command packets for transmission and checking and
/// decoding responses.
///</summary>
///<remarks>
/// Basic information in this object includes:
/// <list type="bullet">
/// <item>ADUType: RTU (RS232/485) or MBAP (TCP/UDP)</item>
/// <item>unit addr/RTU device addr</item>
/// <item>function code</item>
/// <item>default timeout</item>
/// <item>other characteristics about the specific command</item>
/// </list>
/// This object is expected to be a base class for a set of derived classes that define the construction and use for a specific modbus function codes, or sets thereof.
/// Common code supports construction of the header, definition and placement of the data, generation of the crc prior to sending the request paacket as well as
/// each of the reverse steps required after receiving the response packet (if any).
///
/// In addition, allowing the client to retain the prior storage for the data, setup and headers minimizes the repeated work that is required
/// when running the same modbus function repeatedly.
///</remarks>
public class ClientFunctionBase<DerivedType> : ClientFunctionBase where DerivedType : class
{
/// <summary>Constructor</summary>
public ClientFunctionBase() : base() { }
/// <summary>
/// This method is used to setup the Function after defining the setup property values and before attempting to Get or Set the data content of the fucntion
/// and before sending the function and/or calling PrepareToSend. This method Initializes the request ADU in which all of the header contents are stored and in
/// which the pre-response register/coil data can be accessed.
/// </summary>
/// <returns>This object as the DerivedType to support pass through chainging</returns>
public new DerivedType Setup()
{
base.Setup();
return (this as DerivedType);
}
}
///<summary>
/// This class is the base class for all Modbus Client Function Exection wrapper objects.
/// This class defines the storage and common execution pattern for all Modbus supported client operation/command objects that are generally used by a client
/// to run one or more modbus commands. Generally individual function execution objects will be derived from this object to implement each of the support
/// Modbus fucntion codes where the derived object will provide properties and methods that are specific to that function code while the logic in the base class
/// here will be provide the majority of the implementation of common execution flow patterns such as encoding command packets for transmission and checking and
/// decoding responses.
///</summary>
///<remarks>
/// Basic information in this object includes:
/// <list type="bullet">
/// <item>ADUType: RTU (RS232/485) or MBAP (TCP/UDP)</item>
/// <item>unit addr/RTU device addr</item>
/// <item>function code</item>
/// <item>default timeout</item>
/// <item>other characteristics about the specific command</item>
/// </list>
/// This object is expected to be a base class for a set of derived classes that define the construction and use for a specific modbus function codes, or sets thereof.
/// Common code supports construction of the header, definition and placement of the data, generation of the crc prior to sending the request paacket as well as
/// each of the reverse steps required after receiving the response packet (if any).
///
/// In addition, allowing the client to retain the prior storage for the data, setup and headers minimizes the repeated work that is required
/// when running the same modbus function repeatedly.
///</remarks>
public class ClientFunctionBase : FunctionBase
{
#region construction
/// <summary>Default constructor. Sets TimeLimit to default of 0.5 seconds and sets ClientFunctionState to Ready</summary>
public ClientFunctionBase()
{
TimeLimit = TimeSpan.FromSeconds(0.5); // set the default time limit
ClientFunctionState = ClientFunctionState.Ready;
ClientFunctionStateTime = QpcTimeStamp.Now;
LastSuccessTime = QpcTimeStamp.Zero;
}
#endregion
#region Object usage methods
/// <summary>
/// This method is used to setup the Function after defining the setup property values and before attempting to Get or Set the data content of the fucntion
/// and before sending the function and/or calling PrepareToSend. This method Initializes the request ADU in which all of the header contents are stored and in
/// which the pre-response register/coil data can be accessed.
/// </summary>
public void Setup()
{
requestAdu.InitializeRequestPDU(true);
}
/// <summary>
/// Updates requestADU immediately prior to sending the bytes from its Packet. Marks ClientFunctionState as InProgress unless a failure was detected.
/// This method signature variant sets defaultMaximiumNumberOfTries to 1.
/// </summary>
/// <returns>true on success, false if the command prepare to send failed and marked the command as Failed</returns>
public bool PrepareToSendRequest()
{
return PrepareToSendRequest(1);
}
/// <summary>
/// Updates requestADU immediately prior to sending the bytes from its Packet. Marks ClientFunctionState as InProgress unless a failure was detected.
/// returns true on success, false if the command prepare to send failed and marked the command as Failed.
/// </summary>
/// <param name="defaultMaximumNumberOfTries">
/// Provides the default maximum number of tries that the client is configured for.
/// This will be used to update the MaximumNumberOfTries property if it is less than 1.
/// </param>
public bool PrepareToSendRequest(int defaultMaximumNumberOfTries)
{
if (MaximumNumberOfTries < 1)
MaximumNumberOfTries = Math.Max(defaultMaximumNumberOfTries, 1);
ClientFunctionState = ClientFunctionState.InProgress;
ClientFunctionStateTime = QpcTimeStamp.Now;
ExceptionCode = ExceptionCode.None;
ErrorCodeStr = String.Empty;
ExceptionCodeIsFromResponse = false;
string s = requestAdu.PrepareToSendRequest();
if (!String.IsNullOrEmpty(s))
{
NoteFailed("Function Request ADU is not valid: " + s);
return false;
}
responseAdu.PrepareToReceiveResponse(requestAdu);
responseAdu.PktBuf.numBytes = 0;
return true;
}
///<summary>
/// Attempts to Decode the response packet in the responseADU. If the command has completed then the command state updated accordingly.
/// returns true if a complete response was found or if a fatal error was found.
///</summary>
public bool AttemptToDecodeResponsePkt()
{
string s;
bool complete = responseAdu.AttemptToDecodeResponsePkt(requestAdu, out s);
if (!String.IsNullOrEmpty(s))
NoteFailed(ExceptionCode.PacketDecodeFailed, false, s);
else if (complete && responseAdu.IsExceptionResponse)
{
ExceptionCode rxEC = responseAdu.ReceivedExceptionCode;
if (rxEC != ExceptionCode.None)
NoteFailed(rxEC, true, "");
else
NoteFailed(ExceptionCode.Undefined, true, "ADU contains explicit Exception Response with ExceptionCode.None");
}
else if (complete)
NoteSucceeded();
return complete;
}
#endregion
#region ClientFunctionState and related properties
/// <summary>Returns true if the ClientFunctionState is Succeeded</summary>
public bool Succeeded { get { return (ClientFunctionState == ClientFunctionState.Succeeded); } }
/// <summary>Returns true if the ClientFunctionState is Failed</summary>
public bool Failed { get { return (ClientFunctionState == ClientFunctionState.Failed); } }
/// <summary>Returns true if the function Succeeded or Failed</summary>
public bool IsComplete { get { return (Succeeded || Failed); } }
/// <summary>Gives he current State of this Client Function instance.</summary>
public ClientFunctionState ClientFunctionState { get; set; }
/// <summary>Gives the QpcTimeStamp of the last time the ClientFunctionState was internally assigned.</summary>
public QpcTimeStamp ClientFunctionStateTime { get; set; }
/// <summary>Gives an ExceptionCode that was returned in the command response or ExceptionCode.Custom if the failure came from some other source.</summary>
public ExceptionCode ExceptionCode { get; set; }
/// <summary>Set to true if this exception code was obtained from the resonseADU body.</summary>
public bool ExceptionCodeIsFromResponse { get; set; }
/// <summary>Gives a string description of the last detected failure/command fault reason or the reported ExceptionCode</summary>
public string ErrorCodeStr { get; set; }
/// <summary>Gives the QpcTimeStamp at the last time this command succeeded</summary>
public QpcTimeStamp LastSuccessTime { get; set; }
/// <summary>
/// Sets the ClientFunctionState to Failed.
/// Updates the contained ExceptionCode to be the given value and sets the ErrorCodeStr based on the function code, the ExceptionCode, and the given ecStr
/// </summary>
public string NoteFailed(ExceptionCode ec, bool ecIsFromResponseADU, string comment)
{
ExceptionCode = ec;
ExceptionCodeIsFromResponse = ecIsFromResponseADU;
if (String.IsNullOrEmpty(comment))
ErrorCodeStr = Fcns.CheckedFormat("{0} Response was Ex:${1:x2},{2}", requestAdu.FCInfo.FC.ToString(), unchecked((int) ExceptionCode), ExceptionCode.ToString());
else
ErrorCodeStr = Fcns.CheckedFormat("{0} Response was Ex:${1:x2},{2} comment:'{3}'", requestAdu.FCInfo.FC.ToString(), unchecked((int) ExceptionCode), ExceptionCode.ToString(), comment);
ClientFunctionState = ClientFunctionState.Failed;
ClientFunctionStateTime = QpcTimeStamp.Now;
return ErrorCodeStr;
}
/// <summary>
/// Sets the ClientFunctionState to Failed.
/// Updates the contained ExceptionCode to be ExceptionCode.Custom and sets the ErrorCodeStr based on the function code and the given ecStr
/// </summary>
public string NoteFailed(string ecStr)
{
ExceptionCode = ExceptionCode.Custom;
ExceptionCodeIsFromResponse = false;
ErrorCodeStr = Fcns.CheckedFormat("{0} failed: {1}", requestAdu.FCInfo.FC.ToString(), ecStr);
ClientFunctionState = ClientFunctionState.Failed;
ClientFunctionStateTime = QpcTimeStamp.Now;
return ErrorCodeStr;
}
/// <summary>Sets the ClientFunctionState to Succeeded.</summary>
public void NoteSucceeded()
{
ClientFunctionState = ClientFunctionState.Succeeded;
ClientFunctionStateTime = LastSuccessTime = QpcTimeStamp.Now;
}
#endregion
#region Additional local state information
/// <summary>
/// This property defines the maximum number of total attempts that the client will make to perform this request.
/// If this number is less than or equal to zero then the client will replace this property value with the current default maximum number of trys
/// which will be no less than 1.
/// </summary>
public int MaximumNumberOfTries { get; set; }
/// <summary>
/// This property is updated by the client during execution of the command to indicate the current try number (1..n). This property will also
/// reflect the number of tries that were required after the command has been successfully completed.
/// </summary>
public int CurrentTryNumber { get; set; }
#endregion
#region Common methods used by clients to Get and Set coils, discreets, holding registers and input registers
/// <summary>
/// This method is used to read discrete data from the correct ADU and saves this data into the given array's elements.
/// The ADU is choosen as the response ADU for FuntionCodes that do reading or the request ADU for all other FunctionCodes.
/// Transfer always starts with the first discrete value contained in the selected ADU. The given array must be non-null and
/// its length cannot exceed the number of discrete values contained in the selected ADU.
/// </summary>
/// <returns>True on success, false in all other cases.</returns>
public bool GetDiscretes(bool[] discreteValueArray)
{
bool readFromResponse = requestAdu.FCInfo.DoesRead;
return GetDiscretes(readFromResponse, discreteValueArray, 0, ((discreteValueArray != null) ? discreteValueArray.Length : 0));
}
/// <summary>
/// This method is used to read discrete data from the correct ADU and saves this data into the given array's elements.
/// The ADU is choosen as the response ADU for FuntionCodes that do reading or the request ADU for all other FunctionCodes.
/// result always starts with the first discrete value contained in the selected ADU.
/// </summary>
/// <returns>boolean array containing data from appropriate ADU</returns>
public bool[] GetDiscretes()
{
bool readFromResponse = requestAdu.FCInfo.DoesRead;
bool[] discretesArray = new bool[readFromResponse ? responseAdu.NumItemsInResponse : requestAdu.NumWriteItemsInRequest];
GetDiscretes(readFromResponse, discretesArray, 0, discretesArray.Length);
return discretesArray;
}
/// <summary>
/// This method is used to transfer coil data into the request ADU from the given array's elements.
/// Transfer always starts with the first discrete value contained in the request ADU. The given array must be non-null and
/// its length cannot exceed the number of discrete values contained in the request ADU.
/// </summary>
/// <returns>True on success, false in all other cases.</returns>
public bool SetDiscretes(bool[] discreteValueArray)
{
return SetDiscretes(discreteValueArray, 0, ((discreteValueArray != null) ? discreteValueArray.Length : 0));
}
/// <summary>
/// This method is used to read register data from the correct ADU and saves this data into the given array's elements.
/// The ADU is choosen as the response ADU for FuntionCodes that do reading or the request ADU for all other FunctionCodes.
/// Transfer always starts with the first register value contained in the selected ADU. The given array must be non-null and
/// its length cannot exceed the number of register values contained in the selected ADU.
/// </summary>
/// <returns>True on success, false in all other cases.</returns>
public bool GetRegisters(short[] regValueArray)
{
bool readFromResponse = requestAdu.FCInfo.DoesRead;
return GetRegisters(readFromResponse, regValueArray, 0, ((regValueArray != null) ? regValueArray.Length : 0));
}
/// <summary>
/// This method is used to read register data from the correct ADU and saves this data into the given array's elements.
/// The ADU is choosen as the response ADU for FuntionCodes that do reading or the request ADU for all other FunctionCodes.
/// result always starts with the first discrete value contained in the selected ADU.
/// </summary>
/// <returns>register array containing data from appropriate ADU</returns>
public short[] GetRegisters()
{
bool readFromResponse = requestAdu.FCInfo.DoesRead;
short[] registerArray = new short[readFromResponse ? responseAdu.NumItemsInResponse : requestAdu.NumWriteItemsInRequest];
GetRegisters(readFromResponse, registerArray, 0, registerArray.Length);
return registerArray;
}
/// <summary>
/// This method is used to transfer holding register data into the request ADU from the given array's elements.
/// Transfer always starts with the first holding register value contained in the request ADU. The given array must be non-null and
/// its length cannot exceed the number of holding register values contained in the request ADU.
/// </summary>
/// <returns>True on success, false in all other cases.</returns>
public bool SetRegisters(short[] regValueArray)
{
return SetRegisters(regValueArray, 0, ((regValueArray != null) ? regValueArray.Length : 0));
}
#endregion
};
#endregion
//--------------------------------------------------------------------------
#region Client port adapter(s)
/// <summary>
/// Each Modbus Client Function Adapter type of object supports a set of Run methods that may be used to run one or more Modbus Client Function
/// using some underlying communication medium. The <seealso cref="ModbusClientFunctionPortAdapter"/> class is an example of this which supports
/// running Modbus Client Functions using any type of SerialIO.IPort objet.
/// </summary>
public interface IModbusClientFunctionAdapter : IPartBase
{
/// <summary>
/// Attempts to run the given function. Returns true on success on false otherwise.
/// function's final state reflects the details of the success and failure (including the failure reason, as appropriate)
/// </summary>
bool Run(ClientFunctionBase function);
/// <summary>
/// Attempts to run a sequence of functions from the passed functionArray. Returns true on success on false otherwise.
/// function's final state reflects the details of the success and failure (including the failure reason, as appropriate)
/// </summary>
/// <param name="functionArray">Gives a list/array of ClientFunctionBase instances that are to be Run.</param>
/// <param name="stopOnFirstError">Set this to true to block executing functions after any first error is encountered. Set this to false to attempt to run each function regardless of the success of any prior function in the array.</param>
/// <returns>Returns true on success on false otherwise. </returns>
bool Run(IEnumerable<ClientFunctionBase> functionArray, bool stopOnFirstError);
}
/// <summary>
/// Thie class defines a Simple IPart that may be used to create and control an IPort instance (from a given <see cref="MosaicLib.SerialIO.PortConfig"/> object)
/// and to use that port to perform the underlying data transfers required to run Modbus Client Functions, assuming that the port can be used to connect
/// to an appropriately configured Modbus Server.
/// </summary>
public class ModbusClientFunctionPortAdapter : Modular.Part.SimplePartBase, IModbusClientFunctionAdapter
{
#region static values
static int DefaultMaximumNumberOfTriesForStreamPorts = 1;
static int DefaultMaximumNumberOfTriesForDatagramPorts = 3;
#endregion
#region Construction and Destruction
/// <summary>Contructor - requires <paramref name="partID"/> and <paramref name="portConfig"/></summary>
public ModbusClientFunctionPortAdapter(string partID, SerialIO.PortConfig portConfig)
: base(partID)
{
Timeout = portConfig.ReadTimeout;
portConfig.ReadTimeout = TimeSpan.FromSeconds(Math.Min(0.1, Timeout.TotalSeconds));
port = SerialIO.Factory.CreatePort(portConfig);
portBaseStateObserver = new SequencedRefObjectSourceObserver<IBaseState, Int32>(port.BaseStateNotifier);
IPortBehavior portBehavior = port.PortBehavior;
DefaultMaximumNumberOfTries = (portBehavior.IsDatagramPort ? DefaultMaximumNumberOfTriesForDatagramPorts : DefaultMaximumNumberOfTriesForStreamPorts);
FlushPeriod = (portBehavior.IsNetworkPort ? TimeSpan.FromSeconds(0.1) : TimeSpan.FromSeconds(0.3)); // use 0.1 as default for network connections, 0.2 for other types.
NominalSpinWaitPeriod = TimeSpan.FromSeconds(0.2);
portReadAction = port.CreateReadAction(portReadActionParam = new ReadActionParam() { WaitForAllBytes = false });
portWriteAction = port.CreateWriteAction(portWriteActionParam = new WriteActionParam());
portFlushAction = port.CreateFlushAction(FlushPeriod);
portReinitializeAction = port.CreateGoOnlineAction(true);
portReadAction.NotifyOnComplete.AddItem(actionWaitEvent);
portWriteAction.NotifyOnComplete.AddItem(actionWaitEvent);
portFlushAction.NotifyOnComplete.AddItem(actionWaitEvent);
portReinitializeAction.NotifyOnComplete.AddItem(actionWaitEvent);
}
/// <summary>
/// Requird implementation method which is used to handle explicit dispose operations from Part Base.
/// Signature is derived from abstract method in DisposeableBase base class.
/// </summary>
protected override void Dispose(DisposableBase.DisposeType disposeType)
{
if (disposeType == DisposeType.CalledExplicitly)
{
if (port != null)
port.StopPart();
Fcns.DisposeOfObject(ref port);
Fcns.DisposeOfObject(ref actionWaitEvent);
}
}
#endregion
#region internals
IPort port = null;
ISequencedObjectSourceObserver<IBaseState> portBaseStateObserver = null;
IReadAction portReadAction = null;
ReadActionParam portReadActionParam = null;
IWriteAction portWriteAction = null;
WriteActionParam portWriteActionParam = null;
IFlushAction portFlushAction = null;
IBasicAction portReinitializeAction = null;
WaitEventNotifier actionWaitEvent = new WaitEventNotifier(WaitEventNotifier.Behavior.WakeOne);
#endregion
#region Public properties and methods
/// <summary>Defines the transaction time limit value that is used by this client when running modbus transactions.</summary>
public TimeSpan Timeout { get; set; }
/// <summary>
/// Defines the default maximum number of attempts that the client will use when attempting to perform each transaction.
/// Defaults to value that depends on the serial port byte delivery behavior (1 try for stream ports, more for datagram ports).
/// Client will always make at least one attempt to perform each transaction even if this number is less than 1.
/// </summary>
public int DefaultMaximumNumberOfTries { get; set; }
/// <summary>Defines the period of time that is used for post-transaction failure flush operations.</summary>
public TimeSpan FlushPeriod { get; set; }
/// <summary>Defines the nominal spin speed for this client.</summary>
public TimeSpan NominalSpinWaitPeriod { get; set; }
/// <summary>Pass through method allows the caller to have the port create a GoOnline Action which is generally used to start the port.</summary>
public IBasicAction CreateGoOnlineActionOnPort(bool andInitialize)
{
return port.CreateGoOnlineAction(andInitialize);
}
/// <summary>Pass through method allows the caller to have the port create a GoOffline Action which is generally used to close the port.</summary>
public IBasicAction CreateGoOfflineActionOnPort()
{
return port.CreateGoOfflineAction();
}
/// <summary>Pass through method allows the caller to Stop the Port part that is managed by this client.</summary>
public void StopPort()
{
port.StopPart();
}
/// <summary>Service method used to propagate published port state information into and through this client object.</summary>
public void Service()
{
InnerServicePortStateRelay();
}
private void InnerServicePortStateRelay()
{
if (portBaseStateObserver.IsUpdateNeeded)
{
portBaseStateObserver.Update();
SetBaseState(portBaseStateObserver.Object, "Republishing from port", true);
}
}
/// <summary>
/// Attempts to run the given function. Returns true on success on false otherwise.
/// function's final state reflects the details of the success and failure (including the failure reason, as appropriate)
/// </summary>
public bool Run(ClientFunctionBase function)
{
return InnerRun(function);
}
/// <summary>
/// Attempts to run a sequence of functions from the passed functionArray. Returns true on success on false otherwise.
/// function's final state reflects the details of the success and failure (including the failure reason, as appropriate)
/// </summary>
/// <param name="functionArray">Gives a list/array of ClientFunctionBase instances that are to be Run.</param>
/// <param name="stopOnFirstError">Set this to true to block executing functions after any first error is encountered. Set this to false to attempt to run each function regardless of the success of any prior function in the array.</param>
/// <returns>Returns true on success on false otherwise. </returns>
public bool Run(IEnumerable<ClientFunctionBase> functionArray, bool stopOnFirstError)
{
bool success = true;
foreach (ClientFunctionBase function in functionArray)
{
if (Run(function))
continue;
success = false;
if (stopOnFirstError)
break;
}
return success;
}
private bool nextCommandInitialFlushIsNeeded = false;
/// <summary>
/// Performs the steps required to attempt to run the given function using the port for communications.
/// </summary>
/// <param name="function">Gives the function that the client will attempt to run.</param>
/// <returns>True if the function was completed successfully and false otherwise.</returns>
protected bool InnerRun(ClientFunctionBase function)
{
InnerServicePortStateRelay();
bool performInitialFlush = nextCommandInitialFlushIsNeeded;
nextCommandInitialFlushIsNeeded = false;
// assign a new transaction number and build the transmit buffer contents
if (!function.PrepareToSendRequest(DefaultMaximumNumberOfTries))
return false;
function.CurrentTryNumber = 1;
if (!portBaseStateObserver.Object.IsConnected)
{
function.NoteFailed("Port is not connected: " + portBaseStateObserver.Object.ToString());
nextCommandInitialFlushIsNeeded = true;
return false;
}
// Flush the port if the last command did not succeed.
if (performInitialFlush && FlushPeriod != TimeSpan.Zero)
{
portFlushAction.ParamValue = FlushPeriod;
portFlushAction.Run(); // failures will not directly effect the success/failure of the function execution
}
for (;;)
{
InnerServicePortStateRelay();
// logic to perform on later tries
if (function.CurrentTryNumber != 1)
{
Log.Debug.Emit("Function FC:{0} Starting Try {1} of {2}", function.requestAdu.FCInfo.FC, function.CurrentTryNumber, function.MaximumNumberOfTries);
if (FlushPeriod != TimeSpan.Zero)
{
portFlushAction.ParamValue = FlushPeriod;
portFlushAction.Run(); // failures will not directly effect the success/failure of the function execution
InnerServicePortStateRelay();
}
}
// Setup the write and read actions
portWriteActionParam.Reset();
portWriteActionParam.Buffer = function.requestAdu.PktBuf.bytes;
portWriteActionParam.BytesToWrite = function.requestAdu.PktBuf.numBytes;
portReadActionParam.Reset();
portReadActionParam.Buffer = function.responseAdu.PktBuf.bytes;
portReadActionParam.BytesToRead = function.responseAdu.PktBuf.bytes.Length;
portReadActionParam.BytesRead = 0; // start reading into the beginning of the buffer.
// reset the function's ClientFunctionState to InProgress if it was not already there.
if (function.ClientFunctionState != ClientFunctionState.InProgress)
{
ClientFunctionState priorState = function.ClientFunctionState;
function.ClientFunctionState = ClientFunctionState.InProgress;
Log.Debug.Emit("Function FC:{0} resetting state to {1} from {2} at try:{3}", function.requestAdu.FCInfo.FC, function.ClientFunctionState, priorState, function.CurrentTryNumber);
}
// Write the request to the target
portWriteAction.Run();
string resultCode = (function.IsComplete ? function.ErrorCodeStr : null);
ExceptionCode exceptionCode = ExceptionCode.Undefined;
if (resultCode == null && !portWriteAction.ActionState.Succeeded)
{
resultCode = Fcns.CheckedFormat("Port write failed: {0}", portWriteAction.ActionState);
exceptionCode = ExceptionCode.CommunicationError;
}
// wait to receive a usable response
QpcTimer timeLimitTimer = new QpcTimer() { TriggerInterval = Timeout, Started = true };
bool allowRetry = false;
if (resultCode == null)
resultCode = Fcns.MapNullOrEmptyTo(portReadAction.Start(), null);
while (resultCode == null && !function.IsComplete)
{
actionWaitEvent.Wait(NominalSpinWaitPeriod);
InnerServicePortStateRelay();
if (portReadAction.ActionState.IsComplete)
{
function.responseAdu.PktBuf.numBytes = portReadActionParam.BytesRead;
if (portReadAction.ActionState.Failed && portReadActionParam.ActionResultEnum != ActionResultEnum.ReadTimeout)
{
resultCode = "PortReadAction failed: " + portReadAction.ActionState.ResultCode;
exceptionCode = ExceptionCode.CommunicationError;
allowRetry = true;
break;
}
if (function.responseAdu.PktBuf.numBytes > 0)
{
if (function.AttemptToDecodeResponsePkt())
{
resultCode = function.ErrorCodeStr;
exceptionCode = function.ExceptionCode;
break;
}
if (portReadAction.ActionState.Succeeded && port.PortBehavior.IsDatagramPort)
{
resultCode = "Incomplete response received on Datagram Port";
exceptionCode = ExceptionCode.PacketDecodeFailed;
allowRetry = true;
break;
}
}
if (timeLimitTimer.IsTriggered)
{
resultCode = Fcns.CheckedFormat("Time limit reached after {0:f3} seconds, {1} bytes received", timeLimitTimer.ElapsedTimeInSeconds, portReadActionParam.BytesRead);
exceptionCode = ((portReadActionParam.BytesRead == 0) ? ExceptionCode.CommunciationTimeoutWithNoResponse : ExceptionCode.CommunicationTimeoutWithPartialResponse);
allowRetry = true;
break;
}
else
{
// setup to append bytes in the next read operation to the current buffer
portReadActionParam.BytesToRead = function.responseAdu.PktBuf.bytes.Length - portReadActionParam.BytesRead;
resultCode = Fcns.MapNullOrEmptyTo(portReadAction.Start(), null);
}
}
}
bool attemptRetry = (allowRetry && !function.Succeeded && !function.ExceptionCodeIsFromResponse && (function.CurrentTryNumber < function.MaximumNumberOfTries));
if (!attemptRetry)
{
if (!function.IsComplete)
{
if (resultCode != null)
function.NoteFailed(exceptionCode, false, resultCode);
else
function.NoteFailed(ExceptionCode.Undefined, false, "Internal: Run failed with no reported cause");
}
if (function.Failed && !function.ExceptionCodeIsFromResponse)
nextCommandInitialFlushIsNeeded = true;
if (function.CurrentTryNumber != 1)
{
if (function.Succeeded)
Log.Debug.Emit("Function FC:{0} succeeded at try:{1} of {2}", function.requestAdu.FCInfo.FC, function.CurrentTryNumber, function.MaximumNumberOfTries);
else
Log.Debug.Emit("Function FC:{0} failed at try:{1} of {2} [{3} {4}]", function.requestAdu.FCInfo.FC, function.CurrentTryNumber, function.MaximumNumberOfTries, function.ExceptionCode, function.ErrorCodeStr);
}
return function.Succeeded;
}
Log.Debug.Emit("Function FC:{0} attempting (re)try:{1} of {2} [prior ec:{3}]", function.requestAdu.FCInfo.FC, function.CurrentTryNumber, function.MaximumNumberOfTries, Fcns.MapNullToEmpty(resultCode));
function.CurrentTryNumber++;
if (function.ClientFunctionState != ClientFunctionState.InProgress)
{
function.ClientFunctionState = ClientFunctionState.InProgress;
function.ClientFunctionStateTime = QpcTimeStamp.Now;
}
}
}
#endregion
}
#endregion
//--------------------------------------------------------------------------
}
| 55.973233 | 248 | 0.65181 | [
"ECL-2.0",
"Apache-2.0"
] | mosaicsys/MosaicLibCS | Base/Serial/Modbus/ModbusClient.cs | 52,279 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the states-2016-11-23.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net;
using Amazon.StepFunctions.Model;
using Amazon.StepFunctions.Model.Internal.MarshallTransformations;
using Amazon.StepFunctions.Internal;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.StepFunctions
{
/// <summary>
/// Implementation for accessing StepFunctions
///
/// AWS Step Functions
/// <para>
/// AWS Step Functions is a service that lets you coordinate the components of distributed
/// applications and microservices using visual workflows.
/// </para>
///
/// <para>
/// You can use Step Functions to build applications from individual components, each
/// of which performs a discrete function, or <i>task</i>, allowing you to scale and change
/// applications quickly. Step Functions provides a console that helps visualize the components
/// of your application as a series of steps. Step Functions automatically triggers and
/// tracks each step, and retries steps when there are errors, so your application executes
/// predictably and in the right order every time. Step Functions logs the state of each
/// step, so you can quickly diagnose and debug any issues.
/// </para>
///
/// <para>
/// Step Functions manages operations and underlying infrastructure to ensure your application
/// is available at any scale. You can run tasks on AWS, your own servers, or any system
/// that has access to AWS. You can access and use Step Functions using the console, the
/// AWS SDKs, or an HTTP API. For more information about Step Functions, see the <i> <a
/// href="https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html">AWS Step
/// Functions Developer Guide</a> </i>.
/// </para>
/// </summary>
#if NETSTANDARD13
[Obsolete("Support for .NET Standard 1.3 is in maintenance mode and will only receive critical bug fixes and security patches. Visit https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/migration-from-net-standard-1-3.html for further details.")]
#endif
public partial class AmazonStepFunctionsClient : AmazonServiceClient, IAmazonStepFunctions
{
private static IServiceMetadata serviceMetadata = new AmazonStepFunctionsMetadata();
#region Constructors
/// <summary>
/// Constructs AmazonStepFunctionsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonStepFunctionsClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonStepFunctionsConfig()) { }
/// <summary>
/// Constructs AmazonStepFunctionsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonStepFunctionsClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonStepFunctionsConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonStepFunctionsClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonStepFunctionsClient Configuration Object</param>
public AmazonStepFunctionsClient(AmazonStepFunctionsConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonStepFunctionsClient(AWSCredentials credentials)
: this(credentials, new AmazonStepFunctionsConfig())
{
}
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonStepFunctionsClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonStepFunctionsConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Credentials and an
/// AmazonStepFunctionsClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonStepFunctionsClient Configuration Object</param>
public AmazonStepFunctionsClient(AWSCredentials credentials, AmazonStepFunctionsConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonStepFunctionsClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonStepFunctionsConfig())
{
}
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonStepFunctionsClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonStepFunctionsConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonStepFunctionsClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonStepFunctionsClient Configuration Object</param>
public AmazonStepFunctionsClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonStepFunctionsConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonStepFunctionsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonStepFunctionsConfig())
{
}
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonStepFunctionsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonStepFunctionsConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonStepFunctionsClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonStepFunctionsClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonStepFunctionsClient Configuration Object</param>
public AmazonStepFunctionsClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonStepFunctionsConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#if AWS_ASYNC_ENUMERABLES_API
private IStepFunctionsPaginatorFactory _paginators;
/// <summary>
/// Paginators for the service
/// </summary>
public IStepFunctionsPaginatorFactory Paginators
{
get
{
if (this._paginators == null)
{
this._paginators = new StepFunctionsPaginatorFactory(this);
}
return this._paginators;
}
}
#endif
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
/// <summary>
/// Capture metadata for the service.
/// </summary>
protected override IServiceMetadata ServiceMetadata
{
get
{
return serviceMetadata;
}
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateActivity
internal virtual CreateActivityResponse CreateActivity(CreateActivityRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateActivityRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateActivityResponseUnmarshaller.Instance;
return Invoke<CreateActivityResponse>(request, options);
}
/// <summary>
/// Creates an activity. An activity is a task that you write in any programming language
/// and host on any machine that has access to AWS Step Functions. Activities must poll
/// Step Functions using the <code>GetActivityTask</code> API action and respond using
/// <code>SendTask*</code> API actions. This function lets Step Functions know the existence
/// of your activity and returns an identifier for use in a state machine and when polling
/// from the activity.
///
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note> <note>
/// <para>
/// <code>CreateActivity</code> is an idempotent API. Subsequent requests won’t create
/// a duplicate resource if it was already created. <code>CreateActivity</code>'s idempotency
/// check is based on the activity <code>name</code>. If a following request has different
/// <code>tags</code> values, Step Functions will ignore these differences and treat it
/// as an idempotent request of the previous. In this case, <code>tags</code> will not
/// be updated, even if they are different.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateActivity service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateActivity service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.ActivityLimitExceededException">
/// The maximum number of activities has been reached. Existing activities must be deleted
/// before a new activity can be created.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidNameException">
/// The provided name is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TooManyTagsException">
/// You've exceeded the number of tags allowed for a resource. See the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/limits.html">
/// Limits Topic</a> in the AWS Step Functions Developer Guide.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/CreateActivity">REST API Reference for CreateActivity Operation</seealso>
public virtual Task<CreateActivityResponse> CreateActivityAsync(CreateActivityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateActivityRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateActivityResponseUnmarshaller.Instance;
return InvokeAsync<CreateActivityResponse>(request, options, cancellationToken);
}
#endregion
#region CreateStateMachine
internal virtual CreateStateMachineResponse CreateStateMachine(CreateStateMachineRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateStateMachineRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateStateMachineResponseUnmarshaller.Instance;
return Invoke<CreateStateMachineResponse>(request, options);
}
/// <summary>
/// Creates a state machine. A state machine consists of a collection of states that can
/// do work (<code>Task</code> states), determine to which states to transition next (<code>Choice</code>
/// states), stop an execution with an error (<code>Fail</code> states), and so on. State
/// machines are specified using a JSON-based, structured language. For more information,
/// see <a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html">Amazon
/// States Language</a> in the AWS Step Functions User Guide.
///
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note> <note>
/// <para>
/// <code>CreateStateMachine</code> is an idempotent API. Subsequent requests won’t create
/// a duplicate resource if it was already created. <code>CreateStateMachine</code>'s
/// idempotency check is based on the state machine <code>name</code>, <code>definition</code>,
/// <code>type</code>, <code>LoggingConfiguration</code> and <code>TracingConfiguration</code>.
/// If a following request has a different <code>roleArn</code> or <code>tags</code>,
/// Step Functions will ignore these differences and treat it as an idempotent request
/// of the previous. In this case, <code>roleArn</code> and <code>tags</code> will not
/// be updated, even if they are different.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateStateMachine service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateStateMachine service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidDefinitionException">
/// The provided Amazon States Language definition is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidLoggingConfigurationException">
///
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidNameException">
/// The provided name is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTracingConfigurationException">
/// Your <code>tracingConfiguration</code> key does not match, or <code>enabled</code>
/// has not been set to <code>true</code> or <code>false</code>.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineAlreadyExistsException">
/// A state machine with the same name but a different definition or role ARN already
/// exists.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineDeletingException">
/// The specified state machine is being deleted.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineLimitExceededException">
/// The maximum number of state machines has been reached. Existing state machines must
/// be deleted before a new state machine can be created.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineTypeNotSupportedException">
///
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TooManyTagsException">
/// You've exceeded the number of tags allowed for a resource. See the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/limits.html">
/// Limits Topic</a> in the AWS Step Functions Developer Guide.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/CreateStateMachine">REST API Reference for CreateStateMachine Operation</seealso>
public virtual Task<CreateStateMachineResponse> CreateStateMachineAsync(CreateStateMachineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = CreateStateMachineRequestMarshaller.Instance;
options.ResponseUnmarshaller = CreateStateMachineResponseUnmarshaller.Instance;
return InvokeAsync<CreateStateMachineResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteActivity
internal virtual DeleteActivityResponse DeleteActivity(DeleteActivityRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteActivityRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteActivityResponseUnmarshaller.Instance;
return Invoke<DeleteActivityResponse>(request, options);
}
/// <summary>
/// Deletes an activity.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteActivity service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteActivity service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DeleteActivity">REST API Reference for DeleteActivity Operation</seealso>
public virtual Task<DeleteActivityResponse> DeleteActivityAsync(DeleteActivityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteActivityRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteActivityResponseUnmarshaller.Instance;
return InvokeAsync<DeleteActivityResponse>(request, options, cancellationToken);
}
#endregion
#region DeleteStateMachine
internal virtual DeleteStateMachineResponse DeleteStateMachine(DeleteStateMachineRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteStateMachineRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteStateMachineResponseUnmarshaller.Instance;
return Invoke<DeleteStateMachineResponse>(request, options);
}
/// <summary>
/// Deletes a state machine. This is an asynchronous operation: It sets the state machine's
/// status to <code>DELETING</code> and begins the deletion process.
///
/// <note>
/// <para>
/// For <code>EXPRESS</code>state machines, the deletion will happen eventually (usually
/// less than a minute). Running executions may emit logs after <code>DeleteStateMachine</code>
/// API is called.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteStateMachine service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteStateMachine service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DeleteStateMachine">REST API Reference for DeleteStateMachine Operation</seealso>
public virtual Task<DeleteStateMachineResponse> DeleteStateMachineAsync(DeleteStateMachineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DeleteStateMachineRequestMarshaller.Instance;
options.ResponseUnmarshaller = DeleteStateMachineResponseUnmarshaller.Instance;
return InvokeAsync<DeleteStateMachineResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeActivity
internal virtual DescribeActivityResponse DescribeActivity(DescribeActivityRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeActivityRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeActivityResponseUnmarshaller.Instance;
return Invoke<DescribeActivityResponse>(request, options);
}
/// <summary>
/// Describes an activity.
///
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeActivity service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeActivity service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.ActivityDoesNotExistException">
/// The specified activity does not exist.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DescribeActivity">REST API Reference for DescribeActivity Operation</seealso>
public virtual Task<DescribeActivityResponse> DescribeActivityAsync(DescribeActivityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeActivityRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeActivityResponseUnmarshaller.Instance;
return InvokeAsync<DescribeActivityResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeExecution
internal virtual DescribeExecutionResponse DescribeExecution(DescribeExecutionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeExecutionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeExecutionResponseUnmarshaller.Instance;
return Invoke<DescribeExecutionResponse>(request, options);
}
/// <summary>
/// Describes an execution.
///
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note>
/// <para>
/// This API action is not supported by <code>EXPRESS</code> state machines.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeExecution service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeExecution service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.ExecutionDoesNotExistException">
/// The specified execution does not exist.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DescribeExecution">REST API Reference for DescribeExecution Operation</seealso>
public virtual Task<DescribeExecutionResponse> DescribeExecutionAsync(DescribeExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeExecutionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeExecutionResponseUnmarshaller.Instance;
return InvokeAsync<DescribeExecutionResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeStateMachine
internal virtual DescribeStateMachineResponse DescribeStateMachine(DescribeStateMachineRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeStateMachineRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeStateMachineResponseUnmarshaller.Instance;
return Invoke<DescribeStateMachineResponse>(request, options);
}
/// <summary>
/// Describes a state machine.
///
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeStateMachine service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeStateMachine service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineDoesNotExistException">
/// The specified state machine does not exist.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DescribeStateMachine">REST API Reference for DescribeStateMachine Operation</seealso>
public virtual Task<DescribeStateMachineResponse> DescribeStateMachineAsync(DescribeStateMachineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeStateMachineRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeStateMachineResponseUnmarshaller.Instance;
return InvokeAsync<DescribeStateMachineResponse>(request, options, cancellationToken);
}
#endregion
#region DescribeStateMachineForExecution
internal virtual DescribeStateMachineForExecutionResponse DescribeStateMachineForExecution(DescribeStateMachineForExecutionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeStateMachineForExecutionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeStateMachineForExecutionResponseUnmarshaller.Instance;
return Invoke<DescribeStateMachineForExecutionResponse>(request, options);
}
/// <summary>
/// Describes the state machine associated with a specific execution.
///
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note>
/// <para>
/// This API action is not supported by <code>EXPRESS</code> state machines.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeStateMachineForExecution service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeStateMachineForExecution service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.ExecutionDoesNotExistException">
/// The specified execution does not exist.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/DescribeStateMachineForExecution">REST API Reference for DescribeStateMachineForExecution Operation</seealso>
public virtual Task<DescribeStateMachineForExecutionResponse> DescribeStateMachineForExecutionAsync(DescribeStateMachineForExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeStateMachineForExecutionRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeStateMachineForExecutionResponseUnmarshaller.Instance;
return InvokeAsync<DescribeStateMachineForExecutionResponse>(request, options, cancellationToken);
}
#endregion
#region GetActivityTask
internal virtual GetActivityTaskResponse GetActivityTask(GetActivityTaskRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetActivityTaskRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetActivityTaskResponseUnmarshaller.Instance;
return Invoke<GetActivityTaskResponse>(request, options);
}
/// <summary>
/// Used by workers to retrieve a task (with the specified activity ARN) which has been
/// scheduled for execution by a running state machine. This initiates a long poll, where
/// the service holds the HTTP connection open and responds as soon as a task becomes
/// available (i.e. an execution of a task of this type is needed.) The maximum time the
/// service holds on to the request before responding is 60 seconds. If no task is available
/// within 60 seconds, the poll returns a <code>taskToken</code> with a null string.
///
/// <important>
/// <para>
/// Workers should set their client side socket timeout to at least 65 seconds (5 seconds
/// higher than the maximum time the service may hold the poll request).
/// </para>
///
/// <para>
/// Polling with <code>GetActivityTask</code> can cause latency in some implementations.
/// See <a href="https://docs.aws.amazon.com/step-functions/latest/dg/bp-activity-pollers.html">Avoid
/// Latency When Polling for Activity Tasks</a> in the Step Functions Developer Guide.
/// </para>
/// </important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetActivityTask service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetActivityTask service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.ActivityDoesNotExistException">
/// The specified activity does not exist.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.ActivityWorkerLimitExceededException">
/// The maximum number of workers concurrently polling for activity tasks has been reached.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/GetActivityTask">REST API Reference for GetActivityTask Operation</seealso>
public virtual Task<GetActivityTaskResponse> GetActivityTaskAsync(GetActivityTaskRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetActivityTaskRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetActivityTaskResponseUnmarshaller.Instance;
return InvokeAsync<GetActivityTaskResponse>(request, options, cancellationToken);
}
#endregion
#region GetExecutionHistory
internal virtual GetExecutionHistoryResponse GetExecutionHistory(GetExecutionHistoryRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = GetExecutionHistoryRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetExecutionHistoryResponseUnmarshaller.Instance;
return Invoke<GetExecutionHistoryResponse>(request, options);
}
/// <summary>
/// Returns the history of the specified execution as a list of events. By default, the
/// results are returned in ascending order of the <code>timeStamp</code> of the events.
/// Use the <code>reverseOrder</code> parameter to get the latest events first.
///
///
/// <para>
/// If <code>nextToken</code> is returned, there are more results available. The value
/// of <code>nextToken</code> is a unique pagination token for each page. Make the call
/// again using the returned token to retrieve the next page. Keep all other arguments
/// unchanged. Each pagination token expires after 24 hours. Using an expired pagination
/// token will return an <i>HTTP 400 InvalidToken</i> error.
/// </para>
///
/// <para>
/// This API action is not supported by <code>EXPRESS</code> state machines.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetExecutionHistory service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetExecutionHistory service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.ExecutionDoesNotExistException">
/// The specified execution does not exist.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTokenException">
/// The provided token is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/GetExecutionHistory">REST API Reference for GetExecutionHistory Operation</seealso>
public virtual Task<GetExecutionHistoryResponse> GetExecutionHistoryAsync(GetExecutionHistoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = GetExecutionHistoryRequestMarshaller.Instance;
options.ResponseUnmarshaller = GetExecutionHistoryResponseUnmarshaller.Instance;
return InvokeAsync<GetExecutionHistoryResponse>(request, options, cancellationToken);
}
#endregion
#region ListActivities
internal virtual ListActivitiesResponse ListActivities(ListActivitiesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListActivitiesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListActivitiesResponseUnmarshaller.Instance;
return Invoke<ListActivitiesResponse>(request, options);
}
/// <summary>
/// Lists the existing activities.
///
///
/// <para>
/// If <code>nextToken</code> is returned, there are more results available. The value
/// of <code>nextToken</code> is a unique pagination token for each page. Make the call
/// again using the returned token to retrieve the next page. Keep all other arguments
/// unchanged. Each pagination token expires after 24 hours. Using an expired pagination
/// token will return an <i>HTTP 400 InvalidToken</i> error.
/// </para>
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListActivities service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListActivities service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTokenException">
/// The provided token is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/ListActivities">REST API Reference for ListActivities Operation</seealso>
public virtual Task<ListActivitiesResponse> ListActivitiesAsync(ListActivitiesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListActivitiesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListActivitiesResponseUnmarshaller.Instance;
return InvokeAsync<ListActivitiesResponse>(request, options, cancellationToken);
}
#endregion
#region ListExecutions
internal virtual ListExecutionsResponse ListExecutions(ListExecutionsRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListExecutionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListExecutionsResponseUnmarshaller.Instance;
return Invoke<ListExecutionsResponse>(request, options);
}
/// <summary>
/// Lists the executions of a state machine that meet the filtering criteria. Results
/// are sorted by time, with the most recent execution first.
///
///
/// <para>
/// If <code>nextToken</code> is returned, there are more results available. The value
/// of <code>nextToken</code> is a unique pagination token for each page. Make the call
/// again using the returned token to retrieve the next page. Keep all other arguments
/// unchanged. Each pagination token expires after 24 hours. Using an expired pagination
/// token will return an <i>HTTP 400 InvalidToken</i> error.
/// </para>
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note>
/// <para>
/// This API action is not supported by <code>EXPRESS</code> state machines.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListExecutions service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListExecutions service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTokenException">
/// The provided token is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineDoesNotExistException">
/// The specified state machine does not exist.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineTypeNotSupportedException">
///
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/ListExecutions">REST API Reference for ListExecutions Operation</seealso>
public virtual Task<ListExecutionsResponse> ListExecutionsAsync(ListExecutionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListExecutionsRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListExecutionsResponseUnmarshaller.Instance;
return InvokeAsync<ListExecutionsResponse>(request, options, cancellationToken);
}
#endregion
#region ListStateMachines
internal virtual ListStateMachinesResponse ListStateMachines(ListStateMachinesRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListStateMachinesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListStateMachinesResponseUnmarshaller.Instance;
return Invoke<ListStateMachinesResponse>(request, options);
}
/// <summary>
/// Lists the existing state machines.
///
///
/// <para>
/// If <code>nextToken</code> is returned, there are more results available. The value
/// of <code>nextToken</code> is a unique pagination token for each page. Make the call
/// again using the returned token to retrieve the next page. Keep all other arguments
/// unchanged. Each pagination token expires after 24 hours. Using an expired pagination
/// token will return an <i>HTTP 400 InvalidToken</i> error.
/// </para>
/// <note>
/// <para>
/// This operation is eventually consistent. The results are best effort and may not reflect
/// very recent updates and changes.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListStateMachines service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListStateMachines service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTokenException">
/// The provided token is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/ListStateMachines">REST API Reference for ListStateMachines Operation</seealso>
public virtual Task<ListStateMachinesResponse> ListStateMachinesAsync(ListStateMachinesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListStateMachinesRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListStateMachinesResponseUnmarshaller.Instance;
return InvokeAsync<ListStateMachinesResponse>(request, options, cancellationToken);
}
#endregion
#region ListTagsForResource
internal virtual ListTagsForResourceResponse ListTagsForResource(ListTagsForResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return Invoke<ListTagsForResourceResponse>(request, options);
}
/// <summary>
/// List tags for a given resource.
///
///
/// <para>
/// Tags may only contain Unicode letters, digits, white space, or these symbols: <code>_
/// . : / = + - @</code>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListTagsForResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListTagsForResource service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.ResourceNotFoundException">
/// Could not find the referenced resource. Only state machine and activity ARNs are supported.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/ListTagsForResource">REST API Reference for ListTagsForResource Operation</seealso>
public virtual Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = ListTagsForResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = ListTagsForResourceResponseUnmarshaller.Instance;
return InvokeAsync<ListTagsForResourceResponse>(request, options, cancellationToken);
}
#endregion
#region SendTaskFailure
internal virtual SendTaskFailureResponse SendTaskFailure(SendTaskFailureRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = SendTaskFailureRequestMarshaller.Instance;
options.ResponseUnmarshaller = SendTaskFailureResponseUnmarshaller.Instance;
return Invoke<SendTaskFailureResponse>(request, options);
}
/// <summary>
/// Used by activity workers and task states using the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token">callback</a>
/// pattern to report that the task identified by the <code>taskToken</code> failed.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SendTaskFailure service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the SendTaskFailure service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTokenException">
/// The provided token is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TaskDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TaskTimedOutException">
///
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/SendTaskFailure">REST API Reference for SendTaskFailure Operation</seealso>
public virtual Task<SendTaskFailureResponse> SendTaskFailureAsync(SendTaskFailureRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = SendTaskFailureRequestMarshaller.Instance;
options.ResponseUnmarshaller = SendTaskFailureResponseUnmarshaller.Instance;
return InvokeAsync<SendTaskFailureResponse>(request, options, cancellationToken);
}
#endregion
#region SendTaskHeartbeat
internal virtual SendTaskHeartbeatResponse SendTaskHeartbeat(SendTaskHeartbeatRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = SendTaskHeartbeatRequestMarshaller.Instance;
options.ResponseUnmarshaller = SendTaskHeartbeatResponseUnmarshaller.Instance;
return Invoke<SendTaskHeartbeatResponse>(request, options);
}
/// <summary>
/// Used by activity workers and task states using the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token">callback</a>
/// pattern to report to Step Functions that the task represented by the specified <code>taskToken</code>
/// is still making progress. This action resets the <code>Heartbeat</code> clock. The
/// <code>Heartbeat</code> threshold is specified in the state machine's Amazon States
/// Language definition (<code>HeartbeatSeconds</code>). This action does not in itself
/// create an event in the execution history. However, if the task times out, the execution
/// history contains an <code>ActivityTimedOut</code> entry for activities, or a <code>TaskTimedOut</code>
/// entry for for tasks using the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-sync">job
/// run</a> or <a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token">callback</a>
/// pattern.
///
/// <note>
/// <para>
/// The <code>Timeout</code> of a task, defined in the state machine's Amazon States Language
/// definition, is its maximum allowed duration, regardless of the number of <a>SendTaskHeartbeat</a>
/// requests received. Use <code>HeartbeatSeconds</code> to configure the timeout interval
/// for heartbeats.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SendTaskHeartbeat service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the SendTaskHeartbeat service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTokenException">
/// The provided token is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TaskDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TaskTimedOutException">
///
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/SendTaskHeartbeat">REST API Reference for SendTaskHeartbeat Operation</seealso>
public virtual Task<SendTaskHeartbeatResponse> SendTaskHeartbeatAsync(SendTaskHeartbeatRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = SendTaskHeartbeatRequestMarshaller.Instance;
options.ResponseUnmarshaller = SendTaskHeartbeatResponseUnmarshaller.Instance;
return InvokeAsync<SendTaskHeartbeatResponse>(request, options, cancellationToken);
}
#endregion
#region SendTaskSuccess
internal virtual SendTaskSuccessResponse SendTaskSuccess(SendTaskSuccessRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = SendTaskSuccessRequestMarshaller.Instance;
options.ResponseUnmarshaller = SendTaskSuccessResponseUnmarshaller.Instance;
return Invoke<SendTaskSuccessResponse>(request, options);
}
/// <summary>
/// Used by activity workers and task states using the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token">callback</a>
/// pattern to report that the task identified by the <code>taskToken</code> completed
/// successfully.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SendTaskSuccess service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the SendTaskSuccess service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidOutputException">
/// The provided JSON output data is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTokenException">
/// The provided token is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TaskDoesNotExistException">
///
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TaskTimedOutException">
///
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/SendTaskSuccess">REST API Reference for SendTaskSuccess Operation</seealso>
public virtual Task<SendTaskSuccessResponse> SendTaskSuccessAsync(SendTaskSuccessRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = SendTaskSuccessRequestMarshaller.Instance;
options.ResponseUnmarshaller = SendTaskSuccessResponseUnmarshaller.Instance;
return InvokeAsync<SendTaskSuccessResponse>(request, options, cancellationToken);
}
#endregion
#region StartExecution
internal virtual StartExecutionResponse StartExecution(StartExecutionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StartExecutionRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartExecutionResponseUnmarshaller.Instance;
return Invoke<StartExecutionResponse>(request, options);
}
/// <summary>
/// Starts a state machine execution.
///
/// <note>
/// <para>
/// <code>StartExecution</code> is idempotent. If <code>StartExecution</code> is called
/// with the same name and input as a running execution, the call will succeed and return
/// the same response as the original request. If the execution is closed or if the input
/// is different, it will return a 400 <code>ExecutionAlreadyExists</code> error. Names
/// can be reused after 90 days.
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartExecution service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the StartExecution service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.ExecutionAlreadyExistsException">
/// The execution has the same <code>name</code> as another execution (but a different
/// <code>input</code>).
///
/// <note>
/// <para>
/// Executions with the same <code>name</code> and <code>input</code> are considered idempotent.
/// </para>
/// </note>
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.ExecutionLimitExceededException">
/// The maximum number of running executions has been reached. Running executions must
/// end or be stopped before a new execution can be started.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidExecutionInputException">
/// The provided JSON input data is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidNameException">
/// The provided name is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineDeletingException">
/// The specified state machine is being deleted.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineDoesNotExistException">
/// The specified state machine does not exist.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/StartExecution">REST API Reference for StartExecution Operation</seealso>
public virtual Task<StartExecutionResponse> StartExecutionAsync(StartExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = StartExecutionRequestMarshaller.Instance;
options.ResponseUnmarshaller = StartExecutionResponseUnmarshaller.Instance;
return InvokeAsync<StartExecutionResponse>(request, options, cancellationToken);
}
#endregion
#region StopExecution
internal virtual StopExecutionResponse StopExecution(StopExecutionRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = StopExecutionRequestMarshaller.Instance;
options.ResponseUnmarshaller = StopExecutionResponseUnmarshaller.Instance;
return Invoke<StopExecutionResponse>(request, options);
}
/// <summary>
/// Stops an execution.
///
///
/// <para>
/// This API action is not supported by <code>EXPRESS</code> state machines.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopExecution service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the StopExecution service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.ExecutionDoesNotExistException">
/// The specified execution does not exist.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/StopExecution">REST API Reference for StopExecution Operation</seealso>
public virtual Task<StopExecutionResponse> StopExecutionAsync(StopExecutionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = StopExecutionRequestMarshaller.Instance;
options.ResponseUnmarshaller = StopExecutionResponseUnmarshaller.Instance;
return InvokeAsync<StopExecutionResponse>(request, options, cancellationToken);
}
#endregion
#region TagResource
internal virtual TagResourceResponse TagResource(TagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return Invoke<TagResourceResponse>(request, options);
}
/// <summary>
/// Add a tag to a Step Functions resource.
///
///
/// <para>
/// An array of key-value pairs. For more information, see <a href="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html">Using
/// Cost Allocation Tags</a> in the <i>AWS Billing and Cost Management User Guide</i>,
/// and <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_iam-tags.html">Controlling
/// Access Using IAM Tags</a>.
/// </para>
///
/// <para>
/// Tags may only contain Unicode letters, digits, white space, or these symbols: <code>_
/// . : / = + - @</code>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the TagResource service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.ResourceNotFoundException">
/// Could not find the referenced resource. Only state machine and activity ARNs are supported.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.TooManyTagsException">
/// You've exceeded the number of tags allowed for a resource. See the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/limits.html">
/// Limits Topic</a> in the AWS Step Functions Developer Guide.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/TagResource">REST API Reference for TagResource Operation</seealso>
public virtual Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = TagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance;
return InvokeAsync<TagResourceResponse>(request, options, cancellationToken);
}
#endregion
#region UntagResource
internal virtual UntagResourceResponse UntagResource(UntagResourceRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return Invoke<UntagResourceResponse>(request, options);
}
/// <summary>
/// Remove a tag from a Step Functions resource
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UntagResource service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.ResourceNotFoundException">
/// Could not find the referenced resource. Only state machine and activity ARNs are supported.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/UntagResource">REST API Reference for UntagResource Operation</seealso>
public virtual Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UntagResourceRequestMarshaller.Instance;
options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance;
return InvokeAsync<UntagResourceResponse>(request, options, cancellationToken);
}
#endregion
#region UpdateStateMachine
internal virtual UpdateStateMachineResponse UpdateStateMachine(UpdateStateMachineRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateStateMachineRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateStateMachineResponseUnmarshaller.Instance;
return Invoke<UpdateStateMachineResponse>(request, options);
}
/// <summary>
/// Updates an existing state machine by modifying its <code>definition</code>, <code>roleArn</code>,
/// or <code>loggingConfiguration</code>. Running executions will continue to use the
/// previous <code>definition</code> and <code>roleArn</code>. You must include at least
/// one of <code>definition</code> or <code>roleArn</code> or you will receive a <code>MissingRequiredParameter</code>
/// error.
///
/// <note>
/// <para>
/// All <code>StartExecution</code> calls within a few seconds will use the updated <code>definition</code>
/// and <code>roleArn</code>. Executions started immediately after calling <code>UpdateStateMachine</code>
/// may use the previous state machine <code>definition</code> and <code>roleArn</code>.
///
/// </para>
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateStateMachine service method.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the UpdateStateMachine service method, as returned by StepFunctions.</returns>
/// <exception cref="Amazon.StepFunctions.Model.InvalidArnException">
/// The provided Amazon Resource Name (ARN) is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidDefinitionException">
/// The provided Amazon States Language definition is invalid.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidLoggingConfigurationException">
///
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.InvalidTracingConfigurationException">
/// Your <code>tracingConfiguration</code> key does not match, or <code>enabled</code>
/// has not been set to <code>true</code> or <code>false</code>.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.MissingRequiredParameterException">
/// Request is missing a required parameter. This error occurs if both <code>definition</code>
/// and <code>roleArn</code> are not specified.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineDeletingException">
/// The specified state machine is being deleted.
/// </exception>
/// <exception cref="Amazon.StepFunctions.Model.StateMachineDoesNotExistException">
/// The specified state machine does not exist.
/// </exception>
/// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/UpdateStateMachine">REST API Reference for UpdateStateMachine Operation</seealso>
public virtual Task<UpdateStateMachineResponse> UpdateStateMachineAsync(UpdateStateMachineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var options = new InvokeOptions();
options.RequestMarshaller = UpdateStateMachineRequestMarshaller.Instance;
options.ResponseUnmarshaller = UpdateStateMachineResponseUnmarshaller.Instance;
return InvokeAsync<UpdateStateMachineResponse>(request, options, cancellationToken);
}
#endregion
}
} | 50.714859 | 256 | 0.664779 | [
"Apache-2.0"
] | Singh400/aws-sdk-net | sdk/src/Services/StepFunctions/Generated/_netstandard/AmazonStepFunctionsClient.cs | 75,772 | 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.Immutable;
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationMethodInfo
{
private static readonly ConditionalWeakTable<
IMethodSymbol,
CodeGenerationMethodInfo
> s_methodToInfoMap = new();
private readonly bool _isNew;
private readonly bool _isUnsafe;
private readonly bool _isPartial;
private readonly bool _isAsync;
private readonly ImmutableArray<SyntaxNode> _statements;
private readonly ImmutableArray<SyntaxNode> _handlesExpressions;
private CodeGenerationMethodInfo(
bool isNew,
bool isUnsafe,
bool isPartial,
bool isAsync,
ImmutableArray<SyntaxNode> statements,
ImmutableArray<SyntaxNode> handlesExpressions
)
{
_isNew = isNew;
_isUnsafe = isUnsafe;
_isPartial = isPartial;
_isAsync = isAsync;
_statements = statements.NullToEmpty();
_handlesExpressions = handlesExpressions.NullToEmpty();
}
public static void Attach(
IMethodSymbol method,
bool isNew,
bool isUnsafe,
bool isPartial,
bool isAsync,
ImmutableArray<SyntaxNode> statements,
ImmutableArray<SyntaxNode> handlesExpressions
)
{
var info = new CodeGenerationMethodInfo(
isNew,
isUnsafe,
isPartial,
isAsync,
statements,
handlesExpressions
);
s_methodToInfoMap.Add(method, info);
}
private static CodeGenerationMethodInfo GetInfo(IMethodSymbol method)
{
s_methodToInfoMap.TryGetValue(method, out var info);
return info;
}
public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol method) =>
GetStatements(GetInfo(method));
public static ImmutableArray<SyntaxNode> GetHandlesExpressions(IMethodSymbol method) =>
GetHandlesExpressions(GetInfo(method));
public static bool GetIsNew(IMethodSymbol method) => GetIsNew(GetInfo(method));
public static bool GetIsUnsafe(IMethodSymbol method) => GetIsUnsafe(GetInfo(method));
public static bool GetIsPartial(IMethodSymbol method) => GetIsPartial(GetInfo(method));
public static bool GetIsAsyncMethod(IMethodSymbol method) =>
GetIsAsyncMethod(GetInfo(method));
private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationMethodInfo info) =>
info?._statements ?? ImmutableArray<SyntaxNode>.Empty;
private static ImmutableArray<SyntaxNode> GetHandlesExpressions(
CodeGenerationMethodInfo info
) => info?._handlesExpressions ?? ImmutableArray<SyntaxNode>.Empty;
private static bool GetIsNew(CodeGenerationMethodInfo info) => info != null && info._isNew;
private static bool GetIsUnsafe(CodeGenerationMethodInfo info) =>
info != null && info._isUnsafe;
private static bool GetIsPartial(CodeGenerationMethodInfo info) =>
info != null && info._isPartial;
private static bool GetIsAsyncMethod(CodeGenerationMethodInfo info) =>
info != null && info._isAsync;
}
}
| 35.442308 | 99 | 0.646772 | [
"MIT"
] | belav/roslyn | src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationMethodInfo.cs | 3,688 | C# |
using com.threerings.config;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ThreeRingsSharp.Utility;
using ThreeRingsSharp.XansData.Extensions;
using ThreeRingsSharp.XansData.XML.ConfigReferences;
//using java.io;
namespace ThreeRingsSharp.DataHandlers.Properties {
/// <summary>
/// Represents a <see cref="Parameter.Direct"/> in a different manner that allows directly
/// accessing the object or data it points to.<para/>
/// <para/>
/// WARNING: Object not functional entirely.
/// </summary>
public class WrappedDirect {
/// <summary>
/// The reference to the Clyde object associated with this direct.
/// </summary>
public ParameterizedConfig Config { get; }
/// <summary>
/// A reference to <see cref="BaseDirect"/>'s <c>name</c> property (see <see cref="Parameter.name"/>).
/// </summary>
public string Name => BaseDirect.name;
/// <summary>
/// The raw text-based paths for this direct.
/// </summary>
public string[] Paths { get; set; }
/// <summary>
/// If this direct references a ConfigReference, and if that ConfigReference points to one of the packed configs, this is the name of the packed config (e.g. <c>"material"</c>)
/// </summary>
public string ConfigReferenceContainerName { get; private set; }
/// <summary>
/// If this is non-null, this is a reference to the parent <see cref="Parameter.Choice"/> that contains this <see cref="WrappedDirect"/>.
/// </summary>
public WrappedChoice ParentChoice { get; }
/// <summary>
/// A reference to the <see cref="Parameter.Direct"/> that this <see cref="WrappedDirect"/> was created from.
/// </summary>
public Parameter.Direct BaseDirect { get; }
public ArgumentMap Arguments { get; } = null;
/// <summary>
/// The object at the end of each path in this <see cref="WrappedDirect"/>.<para/>
/// Some of these objects may be other <see cref="WrappedDirect"/>s or <see cref="WrappedChoice"/>s. See <see cref="DirectEndReference"/> for more information on how to handle this.
/// </summary>
public IReadOnlyList<DirectEndReference> EndReferences => _EndReferences;
private readonly List<DirectEndReference> _EndReferences = new List<DirectEndReference>();
public WrappedDirect(ParameterizedConfig cfg, Parameter.Direct direct, WrappedChoice parentChoice = null, ArgumentMap args = null) {
Config = cfg;
BaseDirect = direct;
ParentChoice = parentChoice;
Arguments = args;
foreach (string path in direct.paths) {
TraverseDirectPath(path);
}
}
/// <summary>
/// Since Directs always point to a specific value, it is possible to get this value.<para/>
/// Some directs may branch into more than one sub-direct, but since it is not possible to select which branch is traversed, all values are the same.
/// </summary>
public object GetValue() {
if (EndReferences.Count == 0) return null;
DirectEndReference endRef = EndReferences[0];
while (endRef.Object is WrappedDirect subDir) {
if (subDir.EndReferences.Count == 0) return null;
endRef = subDir.EndReferences[0];
}
return endRef.Object;
}
/// <summary>
/// Sets the value of all items this Direct affects (in <see cref="Config"/>) to the given value.
/// </summary>
public void SetValue(object value) {
SetDataOn(Config, BaseDirect.paths, value, true);
}
/// <summary>
/// Assuming this <see cref="WrappedDirect"/> has arguments, this will apply the arguments to <see cref="Config"/>.
/// </summary>
public void ApplyArgs() {
SetDataOn(Config, BaseDirect.paths, Arguments?.getOrDefault(BaseDirect.name, null));
}
/// <summary>
/// Given a full path from a <see cref="Parameter.Direct"/>, this will traverse it and acquire the data at the end.<para/>
/// This will stop if it runs into another direct and instantiate a new <see cref="WrappedDirect"/>. This will occur if there is a reference chain, for instance, in many textures it references material["Texture"] (a direct) followed by a second direct ["File"]. Since each may have multiple paths, it's best to reference a new <see cref="WrappedDirect"/>.
/// </summary>
/// <param name="path"></param>
private void TraverseDirectPath(string path) {
// implementation.material_mappings[0].material["Texture"]["File"]
// A bit of a hack to make splitting this path easier:
path = path.Replace("[", ".[");
// The latest object stored when traversing this direct's path.
object latestObject = Config;
// Split it by the segments of this path, and get rid of the implementation word at the start if needed.
string[] pathSegments = path.Split('.');
if (pathSegments[0] == "implementation") {
latestObject = ReflectionHelper.Get(latestObject, "implementation");
pathSegments = pathSegments.Skip(1).ToArray();
}
for (int idx = 0; idx < pathSegments.Length; idx++) {
string currentIndex = pathSegments[idx].SnakeToCamel();
string betweenBrackets = currentIndex.BetweenBrackets();
if (betweenBrackets != null) {
// This is either an array index, or a reference to a config.
// The simple way to test this is that if it's a numeric index, it's an array index.
if (int.TryParse(betweenBrackets, out int arrayIndex)) {
// Access this array index. It is a number in brackets like [0]
latestObject = ReflectionHelper.GetArray(latestObject, arrayIndex);
} else {
// Access the config reference. This is branching from a config reference and accesses a parameter ["Parameter Name"]
ConfigReference latestAsCfg = (ConfigReference)latestObject;
string parameterName = betweenBrackets.Substring(1, betweenBrackets.Length - 2);
// First things first: Resolve the config reference (AND CLONE IT. Don't edit the template object!)
string configRefPath = latestAsCfg.getName();
if (!latestAsCfg.IsRealReference()) {
// Catch case: This isn't actually pointing to a *configuration*, rather a direct object reference.
_EndReferences.Add(new DirectEndReference(configRefPath));
return;
}
ParameterizedConfig referencedConfig = ConfigReferenceBootstrapper.ConfigReferences.TryGetReferenceFromName(configRefPath)?.CloneAs<ParameterizedConfig>();
if (referencedConfig == null) {
XanLogger.WriteLine("Something failed to reference a ConfigReference (It tried to search for \"" + configRefPath + "\", which doesn't exist). Some information on this model may not load properly!", XanLogger.DEBUG, System.Drawing.Color.DarkGoldenrod);
return;
}
ArgumentMap args = latestAsCfg.getArguments();
// So there's our reference. Now we need to get a parameter from it.
ConfigReferenceContainerName = ConfigReferenceBootstrapper.ConfigReferences.GetCategoryFromEntryName(configRefPath);
Parameter referencedParam = referencedConfig.getParameter(parameterName);
if (referencedParam is Parameter.Direct referencedDirect) {
_EndReferences.Add(new DirectEndReference(new WrappedDirect(referencedConfig, referencedDirect, null, args)));
} else if (referencedParam is Parameter.Choice referencedChoice) {
_EndReferences.Add(new DirectEndReference(new WrappedChoice(referencedConfig, referencedChoice, args)));
}
return;
}
} else {
// This is referencing a property.
latestObject = ReflectionHelper.Get(latestObject, currentIndex);
}
}
// Now here's something important: Does an argument override this?
if (Arguments != null && Arguments.containsKey(Name) && latestObject != null) {
// This direct is included as an argument...
// And if we're down here, then we're not referencing another direct, we're referencing a property.
// But as a final sanity check:
if (latestObject.GetType() == Arguments.get(Name)?.GetType()) {
// Yep! Our argument is the same type as the latestObject.
// Let's set latestObject to that argument.
latestObject = Arguments.get(Name);
}
}
_EndReferences.Add(new DirectEndReference(latestObject));
}
/// <summary>
/// Given a <see cref="ParameterizedConfig"/> and a set of paths from a direct as well as a target value, this will modify the <see cref="ParameterizedConfig"/> so that its fields reflect the given value.<para/>
/// Returns an array where the indices of given <see cref="ConfigReference"/>s correspond to the indices of the <paramref name="paths"/>, or <see langword="null"/> if there were no returned <see cref="ConfigReference"/>s due to a direct chain.
/// </summary>
/// <param name="config"></param>
/// <param name="paths"></param>
/// <param name="argValue"></param>
/// <param name="setToNull">If true, and if argValue is null, the property will actually be set to null (if this is false, it will skip applying it)</param>
public static ConfigReference[] SetDataOn(ParameterizedConfig config, string[] paths, object argValue, bool setToNull = false) {
if (argValue == null && !setToNull) return null;
List<ConfigReference> refs = new List<ConfigReference>();
for (int index = 0; index < paths.Length; index++) {
string path = paths[index];
refs.Add(SetDataOn(config, path, argValue, setToNull));
}
return refs.Count > 0 ? refs.ToArray() : null;
}
/// <summary>
/// Given a <see cref="ParameterizedConfig"/> and a path from a direct as well as a target value, this will modify the <see cref="ParameterizedConfig"/> so that its fields reflect the given value.<para/>
/// If this data cannot be set due to it being on a direct chain (the end value is a <see cref="ConfigReference"/>), that <see cref="ConfigReference"/> will be returned
/// </summary>
/// <param name="config"></param>
/// <param name="path"></param>
/// <param name="argValue"></param>
/// <param name="setToNull">If true, and if argValue is null, the property will actually be set to null (if this is false, it will skip applying it)</param>
public static ConfigReference SetDataOn(ParameterizedConfig config, string path, object argValue, bool setToNull = false) {
if (argValue == null && !setToNull) return null;
// implementation.material_mappings[0].material["Texture"]["File"]
// A bit of a hack to make splitting this path easier:
path = path.Replace("[", ".[");
// The latest object stored when traversing this direct's path.
object latestObject = config;
string previousIndex = null;
object previousObject = null;
// Split it by the segments of this path, and get rid of the implementation word at the start if needed.
string[] pathSegments = path.Split('.');
if (pathSegments[0] == "implementation") {
latestObject = ReflectionHelper.Get(latestObject, "implementation");
pathSegments = pathSegments.Skip(1).ToArray();
}
for (int idx = 0; idx < pathSegments.Length; idx++) {
string currentIndex = pathSegments[idx].SnakeToCamel();
string betweenBrackets = currentIndex.BetweenBrackets();
if (betweenBrackets != null) {
// This is either an array index, or a reference to a config.
// The simple way to test this is that if it's a numeric index, it's an array index.
if (int.TryParse(betweenBrackets, out int arrayIndex)) {
// Access this array index. It is a number in brackets like [0]
previousObject = latestObject;
latestObject = ReflectionHelper.GetArray(latestObject, arrayIndex);
} else {
// Access the config reference. This is branching from a config reference and accesses a parameter ["Parameter Name"]
ConfigReference latestAsCfg = (ConfigReference)latestObject;
string parameterName = betweenBrackets.Substring(1, betweenBrackets.Length - 2);
// First things first: Resolve the config reference.
string configRefPath = latestAsCfg.getName();
// cloning this is super important as the tryget method will return a template object.
// Do not edit the template!
if (!latestAsCfg.IsRealReference()) {
// Catch case: This isn't actually pointing to a *configuration*, rather a direct object reference.
latestAsCfg.getArguments().put(parameterName, argValue);
return null;
}
ParameterizedConfig referencedConfig = ConfigReferenceBootstrapper.ConfigReferences.TryGetReferenceFromName(configRefPath)?.CloneAs<ParameterizedConfig>();
if (referencedConfig == null) {
XanLogger.WriteLine("Something failed to reference a ConfigReference (It tried to search for \"" + configRefPath + "\", which doesn't exist). Some information on this model may not load properly!", XanLogger.DEBUG, System.Drawing.Color.DarkGoldenrod);
return null;
}
// So there's our reference. Now we need to get a parameter from it.
Parameter referencedParam = referencedConfig.getParameter(parameterName);
if (referencedParam is Parameter.Direct referencedDirect) {
ConfigReference[] chainRefs = SetDataOn(referencedConfig, referencedDirect.paths, argValue);
if (chainRefs != null) {
// We're pointing to other ConfigReferences which means that this is a direct chain. Oh brother.
foreach (ConfigReference reference in chainRefs) {
if (reference != null) {
if (File.Exists(ResourceDirectoryGrabber.ResourceDirectoryPath + configRefPath)) {
// Catch case: This isn't actually pointing to a *configuration*, rather a direct object reference.
latestAsCfg.getArguments().put(parameterName, argValue);
} else {
ParameterizedConfig forwardRefConfig = reference.Resolve<ParameterizedConfig>();
// Using as because it might be null.
if (forwardRefConfig != null) {
foreach (Parameter subRefParam in forwardRefConfig.parameters) {
if (subRefParam is Parameter.Direct subRefDirect) {
WrappedDirect wrappedSubRefDir = new WrappedDirect(forwardRefConfig, subRefDirect);
wrappedSubRefDir.SetValue(argValue);
}
}
latestAsCfg.getArguments().put(parameterName, ConfigReferenceConstructor.MakeConfigReferenceTo(forwardRefConfig));
} else {
XanLogger.WriteLine("ALERT: Model attempted to set value of Direct [" + currentIndex + "] but it failed because the target object was not a ParameterizedConfig! Some information may be incorrect on this model.", XanLogger.DEBUG, System.Drawing.Color.DarkGoldenrod);
return null;
}
}
}
}
} else {
// This is by far one of the most hacky methods I've ever done in OOO stuff.
// So basically, a model has a property for something like say, materials.
// This property is a ConfigReference to a material object, and that ConfigReference has arguments in it
// that tell the referenced material what it should be.
// Rather than trying to traverse that ConfigReference and set the data on the remote object (PAINFUL), I
// instead decided to write a system that can wrap any ParameterizedConfig into a ConfigReference and just
// call it a day.
ReflectionHelper.Set(previousObject, previousIndex, ConfigReferenceConstructor.MakeConfigReferenceTo(referencedConfig));
}
} else {
//throw new NotImplementedException("Cannot set data on referenced parameters that are not Directs (yet).");
XanLogger.WriteLine("Feature Not Implemented: Cannot set data on referenced parameters that aren't directs (e.g. parameters that are choices)", XanLogger.STANDARD, System.Drawing.Color.Orange);
return null;
}
return null;
}
} else {
// This is referencing a property.
// But wait: If this is the second to last object, then we gotta modify it.
if (idx == pathSegments.Length - 1) {
// Second to last object. latestObject will contain the property that we want to set.
// Let's manually find that field and set it
if (currentIndex.BetweenBrackets() == null) {
// We're good here.
if (argValue is ConfigReference argValueCfg) {
// There's some cases when a variant wants to set a config reference.
// In these cases, we need to make sure the property is also a config reference so we know it's safe to set.
// ... But before that, catch case: Not actually a config.
if (argValueCfg.IsRealReference()) {
object ptr = ReflectionHelper.Get(previousObject, previousIndex);
if (ptr is ConfigReference) {
ReflectionHelper.Set(previousObject, previousIndex, argValueCfg);
} else {
if (ReflectionHelper.GetTypeOfField(latestObject, currentIndex) == argValueCfg.GetType()) {
ReflectionHelper.Set(latestObject, currentIndex, argValueCfg);
return null;
} else {
XanLogger.WriteLine("ALERT: Model attempted to set value of Direct [" + currentIndex + "] but it failed due to a type mismatch! Certain data on this model might be incorrect.", XanLogger.DEBUG, System.Drawing.Color.DarkGoldenrod);
return null;
}
}
} else {
if (ReflectionHelper.GetTypeOfField(latestObject, currentIndex) == argValueCfg.GetType()) {
ReflectionHelper.Set(latestObject, currentIndex, argValueCfg);
return null;
} else {
XanLogger.WriteLine("ALERT: Model attempted to set value of Direct [" + currentIndex + "] but it failed due to a type mismatch! Certain data on this model might be incorrect.", XanLogger.DEBUG, System.Drawing.Color.DarkGoldenrod);
return null;
}
}
} else {
// Contrary to the oddball case above, if the result value at the end of this direct is a ConfigReference
// then we need to return it so that whatever called this knows that it has more to traverse.
// Ideally, this is only returned in the nested call above.
string targetIndex = previousIndex;
/*if (int.TryParse(previousIndex.BetweenBrackets(), out int _)) {
// The previous index was an array accessor. This means we want to actually reference the CURRENT index
// on the PREVIOUS object. A bit odd but it's intentional.
// This is done because the previous object will be the result of that indexer, which is identical
// to the current object. As such, we need to use the current index to reference it.
targetIndex = currentIndex;
}*/
if (previousObject == null || targetIndex == null) return null;
object ptr = ReflectionHelper.Get(previousObject, targetIndex);
if (ptr is ConfigReference cfgRef) {
// Special handling. argValue goes to a property on the config reference
return cfgRef;
}
if (ptr.GetType() == argValue.GetType()) {
ReflectionHelper.Set(previousObject, targetIndex, argValue);
} else {
// In some cases, the object it's pointing to isn't the same time.
// In cases where the previous index is used, this *might* mean we need to step forward like so:
if (ReflectionHelper.GetTypeOfField(ptr, currentIndex) == argValue.GetType()) {
ReflectionHelper.Set(ptr, currentIndex, argValue);
} else {
// But in other cases, it's not pointing to a prop up ahead.
if (ReflectionHelper.Get(ptr, currentIndex) is ConfigReference cfgRefLow) {
return cfgRefLow;
} else {
XanLogger.WriteLine("ALERT: Model attempted to set value of Direct [" + currentIndex + "] but it failed due to a type mismatch! Certain data on this model might be incorrect.", XanLogger.DEBUG, System.Drawing.Color.DarkGoldenrod);
return null;
}
}
}
return null;
}
}
}
if (previousIndex != null) {
if (int.TryParse(previousIndex.BetweenBrackets(), out int _) && idx == pathSegments.Length - 1) {
if (currentIndex.BetweenBrackets() == null) {
// We're good here.
ReflectionHelper.Set(previousObject, previousIndex, argValue);
return null;
}
}
}
previousObject = latestObject;
latestObject = ReflectionHelper.Get(latestObject, currentIndex);
if (previousObject == null || latestObject == null) return null; // Failed to traverse.
}
previousIndex = currentIndex;
}
return null;
}
/// <summary>
/// An object at the end of a direct path. This is used because in some cases, the end of a direct chain might be early because it points to another direct (which needs to be resolved separately)<para/>
/// Rather than storing <see cref="object"/>s in <see cref="WrappedDirect.EndReferences"/>, this is used so that developers can easily discern between cases like mentioned above and know whether to continue traversing or that they truly have their end object.
/// </summary>
public class DirectEndReference {
/// <summary>
/// Discerns what type of object <see cref="Object"/> is, which will either be a generic object (your end goal), a <see cref="WrappedDirect"/>, or a <see cref="WrappedChoice"/>.
/// </summary>
public ReferenceType Reference { get; } = ReferenceType.Object;
/// <summary>
/// The object that the <see cref="WrappedDirect"/> containing this <see cref="DirectEndReference"/> is pointing to. This may need to be cast to a <see cref="WrappedDirect"/> or <see cref="WrappedChoice"/> depending on <see cref="Reference"/>'s value.
/// </summary>
public object Object { get; }
public DirectEndReference(object endObject) {
Object = endObject;
if (endObject is WrappedDirect) {
Reference = ReferenceType.Direct;
} else if (endObject is WrappedChoice) {
Reference = ReferenceType.Choice;
}
}
/// <summary>
/// Used to discern what a <see cref="DirectEndReference"/> is referencing.
/// </summary>
public enum ReferenceType {
/// <summary>
/// The <see cref="DirectEndReference"/> associated with this <see cref="ReferenceType"/> is a generic object.
/// </summary>
Object,
/// <summary>
/// The <see cref="DirectEndReference"/> associated with this <see cref="ReferenceType"/> is a <see cref="WrappedDirect"/>.
/// </summary>
Direct,
/// <summary>
/// The <see cref="DirectEndReference"/> associated with this <see cref="ReferenceType"/> is a <see cref="WrappedChoice"/>.
/// </summary>
Choice
}
}
}
}
| 51.404922 | 358 | 0.672295 | [
"MIT"
] | aytimothy/ThreeRingsSharp | ThreeRingsSharp/DataHandlers/Properties/WrappedDirect.cs | 22,980 | C# |
using System.IO;
using System.Collections.Generic;
using WinDirStat.Net.Settings.Geometry;
using WinDirStat.Net.Model.Data.Nodes;
namespace WinDirStat.Net.Drawing {
public class TreemapItem : ITreemapItem {
private List<TreemapItem> children;
private long size;
private Rectangle2S rectangle;
private string extension;
private string name;
private TreemapItem parent;
private Rgb24Color color;
private FileNodeType type;
public TreemapItem(FileNodeBase file) : this(file, null) {
}
private TreemapItem(FileNodeBase file, TreemapItem parent) {
this.parent = parent;
int count = file.ChildCount;
children = new List<TreemapItem>(count);
for (int i = 0; i < count; i++)
children.Add(new TreemapItem(file[i], this));
children.Sort(CompareReverse);
children.Sort(Compare);
size = file.Size;
extension = file.Extension + "";
name = file.Name + "";
type = file.Type;
//color = file.Color;
}
public TreemapItem(TreemapItem file) : this(file, null) {
}
private TreemapItem(TreemapItem file, TreemapItem parent) {
this.parent = parent;
int count = file.ChildCount;
children = new List<TreemapItem>(count);
for (int i = 0; i < count; i++)
children.Add(new TreemapItem(file[i], this));
children.Sort(CompareReverse);
children.Sort(Compare);
size = file.Size;
extension = file.Extension + "";
name = file.name + "";
type = file.type;
color = file.Color;
}
public void AddChild(FileNodeBase file) {
children.Add(new TreemapItem(file, this));
}
public void AddChild(TreemapItem item) {
children.Add(item);
item.parent = this;
}
/*public void Validate(WinDirDocument document) {
size = 0;
color = document.Extensions[extension].Color;
for (int i = 0; i < children.Count; i++) {
TreemapItem child = children[i];
if (child.children.Count > 0)
child.Validate(document);
//else
// child.color = document.Extensions[extension].Color;
size += child.size;
}
children.Sort(Compare);
}*/
private int Compare(TreemapItem a, TreemapItem b) {
int diff = b.Size.CompareTo(a.Size);
if (diff == 0)
diff = string.Compare(b.name, a.name, true);
return diff;
}
private int CompareReverse(TreemapItem b, TreemapItem a) {
int diff = b.Size.CompareTo(a.Size);
if (diff == 0)
diff = string.Compare(b.name, a.name, true);
return diff;
}
public string Extension => extension;
public bool IsLeaf => children.Count == 0;
public Rectangle2S Rectangle {
get => rectangle;
set => rectangle = value;
}
public long Size => size;
public int ChildCount => children.Count;
public TreemapItem this[int index] => children[index];
ITreemapItem ITreemapItem.this[int index] => children[index];
//private static readonly TreemapItem[] Empty = new TreemapItem[0];
/*public TreemapItem(FileNode file) {
int count = file.ChildCount;
if (count > 0) {
children = new TreemapItem[count];
for (int i = 0; i < count; i++)
children[i] = new TreemapItem(file[i]);
}
else {
children = Empty;
}
size = file.Size;
color = file.Color;
extension = file.Extension;
}*/
//public Rgb24Color Color => Rgb24Color.White;
public Rgb24Color Color => color;
/*public string Extension {
get => extension;
}
public bool IsLeaf {
get => children.Length == 0;
}
public Rectangle2S Rectangle {
get => rectangle;
set => rectangle = value;
}
public Rgb24Color Color {
get => color;
}
public long Size {
get => size;
}
public int ChildCount {
get => children.Length;
}
public TreemapItem this[int index] {
get => children[index];
}
/*public FileNode File {
get => file;
}*/
Rectangle2I ITreemapItem.Rectangle {
get => rectangle;
set => rectangle = value;
}
/*ITreemapItem ITreemapItem.this[int index] {
get => children[index];
}*/
}
}
| 23.380952 | 69 | 0.657332 | [
"MIT"
] | ImportTaste/WinDirStat.Net | WinDirStat.Net/Drawing/TreemapItem.cs | 3,930 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
namespace Azure.ResourceManager.ConnectedVMwarevSphere.Models
{
/// <summary> Defines the network interface ip settings. </summary>
public partial class NicIPSettings
{
/// <summary> Initializes a new instance of NicIPSettings. </summary>
public NicIPSettings()
{
DnsServers = new ChangeTrackingList<string>();
Gateway = new ChangeTrackingList<string>();
IpAddressInfo = new ChangeTrackingList<NicIPAddressSettings>();
}
/// <summary> Initializes a new instance of NicIPSettings. </summary>
/// <param name="allocationMethod"> Gets or sets the nic allocation method. </param>
/// <param name="dnsServers"> Gets or sets the dns servers. </param>
/// <param name="gateway"> Gets or sets the gateway. </param>
/// <param name="ipAddress"> Gets or sets the ip address for the nic. </param>
/// <param name="subnetMask"> Gets or sets the mask. </param>
/// <param name="primaryWinsServer"> Gets or sets the primary server. </param>
/// <param name="secondaryWinsServer"> Gets or sets the secondary server. </param>
/// <param name="ipAddressInfo"> Gets or sets the IP address information being reported for this NIC. This contains the same IPv4 information above plus IPV6 information. </param>
internal NicIPSettings(IPAddressAllocationMethod? allocationMethod, IList<string> dnsServers, IList<string> gateway, string ipAddress, string subnetMask, string primaryWinsServer, string secondaryWinsServer, IReadOnlyList<NicIPAddressSettings> ipAddressInfo)
{
AllocationMethod = allocationMethod;
DnsServers = dnsServers;
Gateway = gateway;
IpAddress = ipAddress;
SubnetMask = subnetMask;
PrimaryWinsServer = primaryWinsServer;
SecondaryWinsServer = secondaryWinsServer;
IpAddressInfo = ipAddressInfo;
}
/// <summary> Gets or sets the nic allocation method. </summary>
public IPAddressAllocationMethod? AllocationMethod { get; set; }
/// <summary> Gets or sets the dns servers. </summary>
public IList<string> DnsServers { get; }
/// <summary> Gets or sets the gateway. </summary>
public IList<string> Gateway { get; }
/// <summary> Gets or sets the ip address for the nic. </summary>
public string IpAddress { get; set; }
/// <summary> Gets or sets the mask. </summary>
public string SubnetMask { get; set; }
/// <summary> Gets or sets the primary server. </summary>
public string PrimaryWinsServer { get; }
/// <summary> Gets or sets the secondary server. </summary>
public string SecondaryWinsServer { get; }
/// <summary> Gets or sets the IP address information being reported for this NIC. This contains the same IPv4 information above plus IPV6 information. </summary>
public IReadOnlyList<NicIPAddressSettings> IpAddressInfo { get; }
}
}
| 51.31746 | 266 | 0.665326 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/connectedvmwarevsphere/Azure.ResourceManager.ConnectedVMwarevSphere/src/Generated/Models/NicIPSettings.cs | 3,233 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
namespace TestOkur.Configuration
{
[Serializable]
[ExcludeFromCodeCoverage]
public class ConfigurationValidationException : Exception
{
public ConfigurationValidationException()
{
}
public ConfigurationValidationException(string message)
: base(message)
{
}
public ConfigurationValidationException(string message, Exception inner)
: base(message, inner)
{
}
protected ConfigurationValidationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
} | 24.2 | 100 | 0.652893 | [
"MIT"
] | testokur/sabit | src/TestOkur.Configuration/ConfigurationValidationException.cs | 728 | C# |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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 System.IO;
using Behaviac.Design.Attributes;
namespace PluginBehaviac.DataExporters
{
public class ParInfoCsExporter
{
public static string GenerateCode(Behaviac.Design.ParInfo par, StreamWriter stream, string indent, string typename, string var, string caller)
{
bool shouldDefineType = true;
if (string.IsNullOrEmpty(typename))
{
shouldDefineType = false;
typename = par.NativeType;
}
typename = DataCsExporter.GetGeneratedNativeType(typename);
uint id = Behaviac.Design.CRC32.CalcCRC(par.Name);
stream.WriteLine("{0}Debug.Check(behaviac.Utils.MakeVariableId(\"{1}\") == {2}u);", indent, par.Name, id);
string retStr = string.Format("pAgent.GetVariable<{0}>({1}u)", typename, id);
if (!string.IsNullOrEmpty(var))
{
if (shouldDefineType)
stream.WriteLine("{0}{1} {2} = {3};", indent, typename, var, retStr);
else
stream.WriteLine("{0}{1} = {2};", indent, var, retStr);
}
return retStr;
}
public static void PostGenerateCode(Behaviac.Design.ParInfo par, StreamWriter stream, string indent, string typename, string var, string caller)
{
if (string.IsNullOrEmpty(typename))
{
typename = par.NativeType;
}
typename = DataCsExporter.GetGeneratedNativeType(typename);
uint id = Behaviac.Design.CRC32.CalcCRC(par.Name);
stream.WriteLine("{0}Debug.Check(behaviac.Utils.MakeVariableId(\"{1}\") == {2}u);", indent, par.Name, id);
stream.WriteLine("{0}pAgent.SetVariable<{1}>(\"{2}\", {3}, {4}u);", indent, typename, par.Name, var, id);
}
}
}
| 43.923077 | 152 | 0.583187 | [
"BSD-3-Clause"
] | Manistein/behaviac | tools/designer/Plugins/PluginBehaviac/DataExporters/Cs/ParInfoCsExporter.cs | 2,855 | C# |
using Aurora.Settings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using YeeLightAPI.YeeLightDeviceLocator;
using YeeLightAPI.YeeLightConstants;
using YeeLightAPI.YeeLightExceptions;
using YeeLightAPI;
using static YeeLightAPI.YeeLightExceptions.Exceptions;
namespace Aurora.Devices.YeeLight
{
public class YeeLightDevice : DefaultDevice
{
public override string DeviceName => "YeeLight";
private const int LightListenPort = 55443;
private readonly Stopwatch _updateDelayStopWatch = new();
private readonly List<YeeLightAPI.YeeLightDevice> _lights = new();
protected override string DeviceInfo => String.Join(
", ",
_lights.Select(light => light.GetLightIPAddressAndPort().ipAddress + ":" + light.GetLightIPAddressAndPort().port + "w:" + _whiteCounter + (light.IsMusicMode() ? "(m)" : ""))
);
public override bool Initialize()
{
if (IsInitialized) return IsInitialized;
try
{
_lights.Clear();
var ipListString = Global.Configuration.VarRegistry.GetVariable<string>($"{DeviceName}_IP");
var lightIpList = new List<IPAddress>();
//Auto discover a device if the IP is empty and auto-discovery is enabled
if (string.IsNullOrWhiteSpace(ipListString) && Global.Configuration.VarRegistry.GetVariable<bool>($"{DeviceName}_auto_discovery"))
{
var devices = DeviceLocator.DiscoverDevices(10000, 2);
if (!devices.Any())
{
throw new Exception("Auto-discovery is enabled but no devices have been located.");
}
lightIpList.AddRange(devices.Select(v => v.GetLightIPAddressAndPort().ipAddress));
}
else
{
lightIpList = ipListString.Split(',').Select(x => IPAddress.Parse(x.Replace(" ", ""))).ToList();
if (lightIpList.Count == 0)
{
throw new Exception("Device IP list is empty.");
}
}
for (var i = 0; i < lightIpList.Count; i++)
{
var ipaddr = lightIpList[i];
try
{
ConnectNewDevice(ipaddr);
}
catch (Exception exc)
{
LogError($"Encountered an error while connecting to the {i}. light. Exception: {exc}");
}
}
_updateDelayStopWatch.Start();
IsInitialized = _lights.All(x => x.IsConnected());
}
catch (Exception exc)
{
LogError($"Encountered an error while initializing. Exception: {exc}");
IsInitialized = false;
return false;
}
return IsInitialized;
}
public override void Shutdown()
{
foreach (var light in _lights.Where(x => x.IsConnected()))
{
light.CloseConnection();
}
_lights.Clear();
IsInitialized = false;
if (_updateDelayStopWatch.IsRunning)
{
_updateDelayStopWatch.Stop();
}
}
private Color _previousColor = Color.Empty;
private int _whiteCounter = 10;
protected override bool UpdateDevice(Dictionary<DeviceKeys, Color> keyColors, DoWorkEventArgs e, bool forced = false)
{
try
{
return TryUpdate(keyColors);
}catch(Exception excp)
{
Reset();
return TryUpdate(keyColors);
}
}
private bool TryUpdate(IReadOnlyDictionary<DeviceKeys, Color> keyColors)
{
var sendDelay = Math.Max(5, Global.Configuration.VarRegistry.GetVariable<int>($"{DeviceName}_send_delay"));
if (_updateDelayStopWatch.ElapsedMilliseconds <= sendDelay)
return false;
var targetKey = Global.Configuration.VarRegistry.GetVariable<DeviceKeys>($"{DeviceName}_devicekey");
if (!keyColors.TryGetValue(targetKey, out var targetColor))
return false;
if (_previousColor.Equals(targetColor))
return ProceedSameColor(targetColor);
_previousColor = targetColor;
if (IsWhiteTone(targetColor))
{
return ProceedDifferentWhiteColor(targetColor);
}
_whiteCounter = Global.Configuration.VarRegistry.GetVariable<int>($"{DeviceName}_white_delay");
return ProceedColor(targetColor);
}
protected override void RegisterVariables(VariableRegistry variableRegistry)
{
var devKeysEnumAsEnumerable = Enum.GetValues(typeof(DeviceKeys)).Cast<DeviceKeys>();
variableRegistry.Register($"{DeviceName}_devicekey", DeviceKeys.Peripheral_Logo, "Key to Use", devKeysEnumAsEnumerable.Max(), devKeysEnumAsEnumerable.Min());
variableRegistry.Register($"{DeviceName}_send_delay", 35, "Send delay (ms)");
variableRegistry.Register($"{DeviceName}_IP", "", "YeeLight IP(s)", null, null, "Comma separated IPv4 or IPv6 addresses.");
variableRegistry.Register($"{DeviceName}_auto_discovery", false, "Auto-discovery", null, null, "Enable this and empty out the IP field to auto-discover lights.");
variableRegistry.Register($"{DeviceName}_white_delay", 10, "White mode delay(ticks)", null, null, "How many ticks should happen before white mode is activated.");
}
private bool ProceedSameColor(Color targetColor)
{
if (IsWhiteTone(targetColor))
{
return ProceedWhiteColor(targetColor);
}
if (ShouldSendKeepAlive())
{
return ProceedColor(targetColor);
}
_updateDelayStopWatch.Restart();
return true;
}
private bool ProceedWhiteColor(Color targetColor)
{
if (_whiteCounter == 0)
{
if (ShouldSendKeepAlive())
{
_lights.ForEach(x =>
{
x.SetTemperature(6500);
x.SetBrightness(targetColor.R * 100 / 255);
});
}
_updateDelayStopWatch.Restart();
return true;
}
if (_whiteCounter == 1)
{
_lights.ForEach(x =>
{
x.SetTemperature(6500);
x.SetBrightness(targetColor.R * 100 / 255);
});
}
_whiteCounter--;
_updateDelayStopWatch.Restart();
return true;
}
private bool ProceedDifferentWhiteColor(Color targetColor)
{
if (_whiteCounter > 0)
{
_whiteCounter--;
return ProceedColor(targetColor);
}
_lights.ForEach(x =>
{
x.SetTemperature(6500);
x.SetBrightness(targetColor.R * 100 / 255);
});
_updateDelayStopWatch.Restart();
return true;
}
private bool ProceedColor(Color targetColor)
{
_lights.ForEach(x =>
{
x.SetColor(targetColor.R, targetColor.G, targetColor.B);
x.SetBrightness(Math.Max(targetColor.R, Math.Max(targetColor.G, Math.Max(targetColor.B, (short)1))) * 100 / 255);
});
_updateDelayStopWatch.Restart();
return true;
}
private const int KeepAliveCounter = 500;
private int _keepAlive = KeepAliveCounter;
private bool ShouldSendKeepAlive()
{
if (_keepAlive-- != 0) return false;
_keepAlive = KeepAliveCounter;
return true;
}
private bool IsWhiteTone(Color color)
{
return color.R == color.G && color.G == color.B;
}
private void ConnectNewDevice(IPAddress lightIp)
{
if (_lights.Any(x => x.IsConnected() && Equals(x.GetLightIPAddressAndPort().ipAddress, lightIp)))
{
return;
}
var light = new YeeLightAPI.YeeLightDevice();
light.SetLightIPAddressAndPort(lightIp, Constants.DefaultCommandPort);
LightConnectAndEnableMusicMode(light);
_lights.Add(light);
}
private int _connectionTries;
private void LightConnectAndEnableMusicMode(YeeLightAPI.YeeLightDevice light)
{
var localMusicModeListenPort = GetFreeTCPPort(); // This can be any free port
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0);
var lightIp = light.GetLightIPAddressAndPort().ipAddress;
socket.Connect(lightIp, LightListenPort);
var localIp = ((IPEndPoint)socket.LocalEndPoint).Address;
light.Connect();
_connectionTries = 100;
Thread.Sleep(500);
while (!light.IsConnected() && --_connectionTries > 0)
{
Thread.Sleep(500);
}
try
{
light.SetMusicMode(localIp, (ushort)localMusicModeListenPort, true);
}
catch (Exception e)
{
// ignored
}
}
private int GetFreeTCPPort()
{
// When a TCPListener is created with 0 as port, the TCP/IP stack will assign it a free port
var listener = new TcpListener(IPAddress.Loopback, 0); // Create a TcpListener on loopback with 0 as the port
listener.Start();
var freePort = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return freePort;
}
}
}
| 36.770548 | 186 | 0.533203 | [
"MIT"
] | ematt/Aurora | Project-Aurora/Project-Aurora/Devices/YeeLight/YeeLightDevice.cs | 10,448 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Net;
using System.Threading.Tasks;
using BuildXL.Distribution.Grpc;
using BuildXL.Utilities.Configuration;
using BuildXL.Utilities.Instrumentation.Common;
using BuildXL.Utilities.Tasks;
using Grpc.Core;
using Grpc.Core.Interceptors;
namespace BuildXL.Engine.Distribution.Grpc
{
/// <summary>
/// Orchestrator service impl
/// </summary>
public sealed class GrpcOrchestratorServer : Orchestrator.OrchestratorBase, IServer
{
private readonly OrchestratorService m_orchestratorService;
private readonly LoggingContext m_loggingContext;
private readonly string m_buildId;
private Server m_server;
/// <summary>
/// Class constructor
/// </summary>
public GrpcOrchestratorServer(LoggingContext loggingContext, OrchestratorService orchestratorService, string buildId)
{
m_loggingContext = loggingContext;
m_orchestratorService = orchestratorService;
m_buildId = buildId;
}
/// <nodoc/>
public void Start(int port)
{
var interceptor = new ServerInterceptor(m_loggingContext, m_buildId);
m_server = new Server(ClientConnectionManager.ServerChannelOptions)
{
Services = { Orchestrator.BindService(this).Intercept(interceptor) },
Ports = { new ServerPort(IPAddress.Any.ToString(), port, ServerCredentials.Insecure) },
};
m_server.Start();
}
/// <nodoc/>
public async Task ShutdownAsync()
{
if (m_server != null)
{
try
{
await m_server.ShutdownAsync();
}
catch (InvalidOperationException)
{
// Shutdown was already requested
}
}
}
/// <inheritdoc />
public void Dispose() => DisposeAsync().GetAwaiter().GetResult();
/// <inheritdoc />
public Task DisposeAsync() => ShutdownAsync();
#region Service Methods
/// <inheritdoc/>
public override Task<RpcResponse> AttachCompleted(AttachCompletionInfo message, ServerCallContext context)
{
var bondMessage = message.ToOpenBond();
m_orchestratorService.AttachCompleted(bondMessage);
return Task.FromResult(new RpcResponse());
}
/// <inheritdoc/>
public override async Task<RpcResponse> Notify(WorkerNotificationArgs message, ServerCallContext context)
{
var bondMessage = message.ToOpenBond();
var notifyTask = m_orchestratorService.ReceivedWorkerNotificationAsync(bondMessage);
if (EngineEnvironmentSettings.InlineWorkerXLGHandling)
{
await notifyTask;
}
else
{
notifyTask.Forget();
}
return new RpcResponse();
}
#endregion Service Methods
}
} | 31.563107 | 126 | 0.581052 | [
"MIT"
] | dfederm/BuildXL | Public/Src/Engine/Dll/Distribution/Grpc/GrpcOrchestratorServer.cs | 3,251 | C# |
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using Verse;
namespace NotMyBestWork
{
public class NotMyBestWorkSettings : ModSettings
{
public int normalLevelLimit = 8;
public int minorPassionLimit = 12;
public int majorPassionLimit = 16;
public override void ExposeData()
{
base.ExposeData();
Scribe_Values.Look(ref normalLevelLimit, "normalLevelLimit", 8);
Scribe_Values.Look(ref minorPassionLimit, "minorPassionLimit", 12);
Scribe_Values.Look(ref majorPassionLimit, "majorPassionLimit", 16);
}
}
}
| 25.642857 | 79 | 0.679666 | [
"MIT"
] | neronix17/-O21-Not-My-Best-Work | 1.3/Source/NotMyBestWork/NotMyBestWorkSettings.cs | 720 | C# |
using Dicom;
using RT.Core.Geometry;
using RT.Core.ROIs;
using RT.Core.DICOM;
using System;
using System.Collections.Generic;
namespace RT.Core.IO.Loaders
{
public class ROILoader:BaseDicomLoader
{
public void Load(DicomFile[] files, StructureSet structureSet, IProgress<double> progress)
{
base.Load(files, structureSet, progress);
DicomFile file = files[0];
Load(file, structureSet, progress);
}
public void Load(DicomFile file, StructureSet structureSet, IProgress<double> progress)
{
structureSet.FileName = file.File.Name;
structureSet.Name = file.Dataset.GetSingleValueOrDefault<string>(DicomTag.StructureSetLabel, "");
Dictionary<int, string> roi_names = new Dictionary<int, string>();
DicomSequence structs = file.Dataset.GetSequence(DicomTag.StructureSetROISequence);
foreach (DicomDataset item in structs)
{
roi_names.Add(item.GetSingleValue<int>(DicomTag.ROINumber), item.GetSingleValue<string>(DicomTag.ROIName));
}
DicomSequence s = file.Dataset.GetSequence(DicomTag.ROIContourSequence);
//Track the item number to report progress
double total = s.Items.Count;
double num = 0;
foreach (DicomDataset item in s.Items)
{
num++;
if(progress!=null)
{
progress.Report(100 * num / total);
}
RegionOfInterest roi = new RegionOfInterest();
int[] color = new int[] { 0, 0, 0 };
if(item.TryGetValues<int>(DicomTag.ROIDisplayColor, out int[] tmp))
{
color = tmp;
}
roi.Color = DicomColor.FromRgb(color[0],color[1],color[2]);
roi.ROINumber = item.GetSingleValue<int>(DicomTag.ReferencedROINumber);
if (roi_names.ContainsKey(roi.ROINumber))
roi.Name = roi_names[roi.ROINumber];
DicomSequence roi_definitions;
try
{
roi_definitions = item.GetSequence(DicomTag.ContourSequence);
}
#pragma warning disable CS0168 // The variable 'e' is declared but never used
catch (Exception e)
#pragma warning restore CS0168 // The variable 'e' is declared but never used
{
continue;
}
double xmin = double.MaxValue, ymin = double.MaxValue, zmin = double.MaxValue, xmax = double.MinValue, ymax = double.MinValue, zmax = double.MinValue;
foreach (DicomDataset contourSlice in roi_definitions.Items)
{
if (!contourSlice.Contains(DicomTag.ContourData))
{
continue;
}
int vertex_count = contourSlice.GetSingleValue<int>(DicomTag.NumberOfContourPoints);
double[] vertices = contourSlice.GetValues<double>(DicomTag.ContourData);
//Attempt to get the contour type from the dicom tag
string type = contourSlice.GetSingleValueOrDefault<string>(DicomTag.ContourGeometricType, "");
Enum.TryParse<ContourType>(type, out ContourType contourType);
//Assume that each contour of the roi is of the same type...
roi.Type = contourType;
PlanarPolygon poly = new PlanarPolygon();
// we divide the number of vertices here by 1.5 because we are going from a 3d poly to a 2d poly on the z plane
poly.Vertices = new double[(int)(vertices.Length / 1.5)];
double zcoord = vertices[2];
int polyIndex = 0;
RegionOfInterestSlice slice = roi.GetSlice(zcoord);
if (slice == null)
slice = new RegionOfInterestSlice() { ZCoord = zcoord, };
for (int i = 0; i < vertices.Length; i += 3)
{
poly.Vertices[polyIndex] = vertices[i];
poly.Vertices[polyIndex + 1] = vertices[i + 1];
if (vertices[i] < xmin) xmin = vertices[i];
if (vertices[i] > xmax) xmax = vertices[i];
if (vertices[i + 1] < ymin) ymin = vertices[i + 1];
if (vertices[i + 1] > ymax) ymax = vertices[i + 1];
if (zcoord < zmin) zmin = zcoord;
if (zcoord > zmax) zmax = zcoord;
polyIndex += 2;
}
if (zmin < roi.ZRange.Minimum)
roi.ZRange.Minimum = zmin;
if (zmax > roi.ZRange.Maximum)
roi.ZRange.Maximum = zmax;
slice.AddPolygon(poly);
roi.AddSlice(slice, zcoord);
}
roi.XRange = new Geometry.Range(xmin, xmax);
roi.YRange = new Geometry.Range(ymin, ymax);
roi.ZRange = new Geometry.Range(zmin, zmax);
for (int i = 0; i < roi.RegionOfInterestSlices.Count; i++)
{
for (int j = 0; j < roi.RegionOfInterestSlices[i].Polygons.Count; j++)
{
roi.RegionOfInterestSlices[i].Polygons[j].XRange = new Geometry.Range(xmin, xmax);
roi.RegionOfInterestSlices[i].Polygons[j].YRange = new Geometry.Range(ymin, ymax);
}
roi.RegionOfInterestSlices[i].ComputeBinaryMask();
}
structureSet.ROIs.Add(roi.Name, roi);
}
GC.Collect();
}
}
}
| 42.726619 | 166 | 0.522479 | [
"Apache-2.0"
] | aomiit/rt-dtools | RT.Core/IO/Loaders/ROILoader.cs | 5,941 | C# |
using System;
namespace CoherentSolutions.Extensions.Hosting.ServiceFabric.Fabric
{
public interface IStatefulServiceHostDelegateReplicaTemplateConfigurator
: IServiceHostDelegateReplicaTemplateConfigurator
{
void UseEvent(
StatefulServiceLifecycleEvent @event);
void UseDelegateInvoker(
Func<Delegate, IServiceProvider, IStatefulServiceHostDelegateInvoker> factoryFunc);
}
} | 31.285714 | 95 | 0.757991 | [
"MIT"
] | coherentsolutionsinc/aspnetcore-service-fabric-hosting | src/CoherentSolutions.Extensions.Hosting.ServiceFabric/src/Fabric/IStatefulServiceHostDelegateReplicaTemplateConfigurator.cs | 440 | C# |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Routing.Configuration
{
using System;
using System.Xml;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using SR2 = System.ServiceModel.Routing.SR;
public class RoutingSection : ConfigurationSection
{
[ConfigurationProperty(ConfigurationStrings.Filters, Options = ConfigurationPropertyOptions.None)]
public FilterElementCollection Filters
{
get { return (FilterElementCollection)base[ConfigurationStrings.Filters]; }
}
[ConfigurationProperty(ConfigurationStrings.FilterTables, Options = ConfigurationPropertyOptions.None)]
public FilterTableCollection FilterTables
{
get { return (FilterTableCollection)base[ConfigurationStrings.FilterTables]; }
}
[ConfigurationProperty(ConfigurationStrings.BackupLists, Options = ConfigurationPropertyOptions.None)]
public BackupListCollection BackupLists
{
get { return (BackupListCollection)base[ConfigurationStrings.BackupLists]; }
}
[ConfigurationProperty(ConfigurationStrings.NamespaceTable, Options = ConfigurationPropertyOptions.None)]
public NamespaceElementCollection NamespaceTable
{
get { return (NamespaceElementCollection)base[ConfigurationStrings.NamespaceTable]; }
}
public static MessageFilterTable<IEnumerable<ServiceEndpoint>> CreateFilterTable(string name)
{
if (string.IsNullOrEmpty(name))
{
throw FxTrace.Exception.ArgumentNullOrEmpty("name");
}
RoutingSection routingSection = (RoutingSection)ConfigurationManager.GetSection("system.serviceModel/routing");
if (routingSection == null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.RoutingSectionNotFound));
}
FilterTableEntryCollection routingTableElement = routingSection.FilterTables[name];
if (routingTableElement == null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.RoutingTableNotFound(name)));
}
XmlNamespaceManager xmlNamespaces = new XPathMessageContext();
foreach (NamespaceElement nsElement in routingSection.NamespaceTable)
{
xmlNamespaces.AddNamespace(nsElement.Prefix, nsElement.Namespace);
}
FilterElementCollection filterElements = routingSection.Filters;
MessageFilterTable<IEnumerable<ServiceEndpoint>> routingTable = new MessageFilterTable<IEnumerable<ServiceEndpoint>>();
foreach (FilterTableEntryElement entry in routingTableElement)
{
FilterElement filterElement = filterElements[entry.FilterName];
if (filterElement == null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.FilterElementNotFound(entry.FilterName)));
}
MessageFilter filter = filterElement.CreateFilter(xmlNamespaces, filterElements);
//retreive alternate service endpoints
IList<ServiceEndpoint> endpoints = new List<ServiceEndpoint>();
if (!string.IsNullOrEmpty(entry.BackupList))
{
BackupEndpointCollection alternateEndpointListElement = routingSection.BackupLists[entry.BackupList];
if (alternateEndpointListElement == null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.BackupListNotFound(entry.BackupList)));
}
endpoints = alternateEndpointListElement.CreateAlternateEndpoints();
}
//add first endpoint to beginning of list
endpoints.Insert(0, ClientEndpointLoader.LoadEndpoint(entry.EndpointName));
routingTable.Add(filter, endpoints, entry.Priority);
}
return routingTable;
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")]
[ConfigurationCollection(typeof(FilterTableEntryCollection), AddItemName = ConfigurationStrings.FilterTable)]
public class FilterTableCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new FilterTableEntryCollection();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((FilterTableEntryCollection)element).Name;
}
public void Add(FilterTableEntryCollection element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseAdd(element);
}
public void Clear()
{
BaseClear();
}
public void Remove(FilterTableEntryCollection element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseRemove(this.GetElementKey(element));
}
new public FilterTableEntryCollection this[string name]
{
get
{
return (FilterTableEntryCollection)BaseGet(name);
}
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")]
[ConfigurationCollection(typeof(FilterTableEntryElement))]
public class FilterTableEntryCollection : ConfigurationElementCollection
{
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.Name, DefaultValue = null, Options = ConfigurationPropertyOptions.IsKey | ConfigurationPropertyOptions.IsRequired)]
public string Name
{
get
{
return (string)this[ConfigurationStrings.Name];
}
set
{
this[ConfigurationStrings.Name] = value;
}
}
protected override ConfigurationElement CreateNewElement()
{
return new FilterTableEntryElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
FilterTableEntryElement entry = (FilterTableEntryElement)element;
return entry.FilterName + ":" + entry.EndpointName;
}
public void Add(FilterTableEntryElement element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseAdd(element);
}
public void Clear()
{
BaseClear();
}
public void Remove(FilterTableEntryElement element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseRemove(this.GetElementKey(element));
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")]
[ConfigurationCollection(typeof(BackupEndpointCollection), AddItemName = ConfigurationStrings.BackupList)]
public class BackupListCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new BackupEndpointCollection();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((BackupEndpointCollection)element).Name;
}
public void Add(BackupEndpointCollection element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseAdd(element);
}
public void Clear()
{
BaseClear();
}
public void Remove(BackupEndpointCollection element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseRemove(this.GetElementKey(element));
}
new public BackupEndpointCollection this[string name]
{
get
{
return (BackupEndpointCollection)BaseGet(name);
}
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")]
[ConfigurationCollection(typeof(BackupEndpointElement))]
public class BackupEndpointCollection : ConfigurationElementCollection
{
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.Name, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)]
public string Name
{
get
{
return (string)this[ConfigurationStrings.Name];
}
set
{
this[ConfigurationStrings.Name] = value;
}
}
protected override ConfigurationElement CreateNewElement()
{
return new BackupEndpointElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
BackupEndpointElement entry = (BackupEndpointElement)element;
return entry.Key;
}
public void Add(BackupEndpointElement element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseAdd(element);
}
public void Clear()
{
BaseClear();
}
public void Remove(BackupEndpointElement element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseRemove(this.GetElementKey(element));
}
internal IList<ServiceEndpoint> CreateAlternateEndpoints()
{
IList<ServiceEndpoint> toReturn = new List<ServiceEndpoint>();
foreach (BackupEndpointElement entryElement in this)
{
ServiceEndpoint serviceEnpoint = ClientEndpointLoader.LoadEndpoint(entryElement.EndpointName);
toReturn.Add(serviceEnpoint);
}
return toReturn;
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")]
[ConfigurationCollection(typeof(FilterElement), AddItemName = ConfigurationStrings.Filter)]
public class FilterElementCollection : ConfigurationElementCollection
{
public override bool IsReadOnly()
{
return false;
}
protected override bool IsElementRemovable(ConfigurationElement element)
{
return true;
}
protected override ConfigurationElement CreateNewElement()
{
return new FilterElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((FilterElement)element).Name;
}
public void Add(FilterElement element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseAdd(element);
}
public void Clear()
{
BaseClear();
}
public void Remove(FilterElement element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseRemove(this.GetElementKey(element));
}
public FilterElement this[int index]
{
get
{
return (FilterElement)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
new public FilterElement this[string name]
{
get
{
return (FilterElement)BaseGet(name);
}
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")]
[ConfigurationCollection(typeof(NamespaceElement))]
public class NamespaceElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new NamespaceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((NamespaceElement)element).Prefix;
}
public void Add(NamespaceElement element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseAdd(element);
}
public void Clear()
{
BaseClear();
}
public void Remove(NamespaceElement element)
{
if (!this.IsReadOnly())
{
if (element == null)
{
throw FxTrace.Exception.ArgumentNull("element");
}
}
BaseRemove(this.GetElementKey(element));
}
public NamespaceElement this[int index]
{
get
{
return (NamespaceElement)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
new public NamespaceElement this[string name]
{
get
{
return (NamespaceElement)BaseGet(name);
}
}
}
public class FilterElement : ConfigurationElement
{
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.Name, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)]
public string Name
{
get
{
return (string)this[ConfigurationStrings.Name];
}
set
{
this[ConfigurationStrings.Name] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like validator")]
[ConfigurationProperty(ConfigurationStrings.FilterType, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired)]
public FilterType FilterType
{
get
{
return (FilterType)this[ConfigurationStrings.FilterType];
}
set
{
if (value < FilterType.Action || value > FilterType.XPath)
{
throw FxTrace.Exception.AsError(new ArgumentOutOfRangeException("value"));
}
this[ConfigurationStrings.FilterType] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.FilterData, DefaultValue = null, Options = ConfigurationPropertyOptions.None)]
public string FilterData
{
get
{
return (string)this[ConfigurationStrings.FilterData];
}
set
{
this[ConfigurationStrings.FilterData] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.Filter1, DefaultValue = null, Options = ConfigurationPropertyOptions.None)]
public string Filter1
{
get
{
return (string)this[ConfigurationStrings.Filter1];
}
set
{
this[ConfigurationStrings.Filter1] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.Filter2, DefaultValue = null, Options = ConfigurationPropertyOptions.None)]
public string Filter2
{
get
{
return (string)this[ConfigurationStrings.Filter2];
}
set
{
this[ConfigurationStrings.Filter2] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.CustomType, DefaultValue = null, Options = ConfigurationPropertyOptions.None)]
public string CustomType
{
get
{
return (string)this[ConfigurationStrings.CustomType];
}
set
{
this[ConfigurationStrings.CustomType] = value;
}
}
internal MessageFilter CreateFilter(XmlNamespaceManager xmlNamespaces, FilterElementCollection filters)
{
MessageFilter filter;
switch (this.FilterType)
{
case FilterType.Action:
filter = new ActionMessageFilter(this.FilterData);
break;
case FilterType.EndpointAddress:
filter = new EndpointAddressMessageFilter(new EndpointAddress(this.FilterData), false);
break;
case FilterType.PrefixEndpointAddress:
filter = new PrefixEndpointAddressMessageFilter(new EndpointAddress(this.FilterData), false);
break;
case FilterType.And:
MessageFilter filter1 = filters[this.Filter1].CreateFilter(xmlNamespaces, filters);
MessageFilter filter2 = filters[this.Filter2].CreateFilter(xmlNamespaces, filters);
filter = new StrictAndMessageFilter(filter1, filter2);
break;
case FilterType.EndpointName:
filter = new EndpointNameMessageFilter(this.FilterData);
break;
case FilterType.MatchAll:
filter = new MatchAllMessageFilter();
break;
case FilterType.Custom:
filter = CreateCustomFilter(this.CustomType, this.FilterData);
break;
case FilterType.XPath:
filter = new XPathMessageFilter(this.FilterData, xmlNamespaces);
break;
default:
// We can't really ever get here because set_FilterType performs validation.
throw FxTrace.Exception.AsError(new InvalidOperationException());
}
return filter;
}
static MessageFilter CreateCustomFilter(string customType, string filterData)
{
if (string.IsNullOrEmpty(customType))
{
throw FxTrace.Exception.ArgumentNullOrEmpty("customType");
}
Type customFilterType = Type.GetType(customType, true);
return (MessageFilter)Activator.CreateInstance(customFilterType, filterData);
}
}
public class NamespaceElement : ConfigurationElement
{
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.Prefix, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)]
public string Prefix
{
get
{
return (string)this[ConfigurationStrings.Prefix];
}
set
{
this[ConfigurationStrings.Prefix] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.Namespace, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired)]
public string Namespace
{
get
{
return (string)this[ConfigurationStrings.Namespace];
}
set
{
this[ConfigurationStrings.Namespace] = value;
}
}
}
public class FilterTableEntryElement : ConfigurationElement
{
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.FilterName, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)]
public string FilterName
{
get
{
return (string)this[ConfigurationStrings.FilterName];
}
set
{
this[ConfigurationStrings.FilterName] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationPropertyNameRule, Justification = "fxcop rule throws null ref if fixed")]
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.EndpointName, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)]
public string EndpointName
{
get
{
return (string)this[ConfigurationStrings.EndpointName];
}
set
{
this[ConfigurationStrings.EndpointName] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like IntegerValidator")]
[ConfigurationProperty(ConfigurationStrings.Priority, DefaultValue = 0, Options = ConfigurationPropertyOptions.None)]
public int Priority
{
get
{
return (int)this[ConfigurationStrings.Priority];
}
set
{
this[ConfigurationStrings.Priority] = value;
}
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.BackupList, DefaultValue = null, Options = ConfigurationPropertyOptions.None)]
public string BackupList
{
get
{
return (string)this[ConfigurationStrings.BackupList];
}
set
{
this[ConfigurationStrings.BackupList] = value;
}
}
}
public class BackupEndpointElement : ConfigurationElement
{
public BackupEndpointElement()
{
this.Key = new object();
}
//needed to allow duplicate alternate endpoints
internal object Key
{
get;
private set;
}
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")]
[ConfigurationProperty(ConfigurationStrings.EndpointName, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired)]
public string EndpointName
{
get
{
return (string)this[ConfigurationStrings.EndpointName];
}
set
{
this[ConfigurationStrings.EndpointName] = value;
}
}
}
}
| 36.2786 | 175 | 0.585717 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/cdf/src/NetFx40/System.ServiceModel.Routing/System/ServiceModel/Routing/Configuration/RoutingSection.cs | 26,957 | C# |
#if REVIT_2018
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DB = Autodesk.Revit.DB;
using DBES = Autodesk.Revit.DB.ExternalService;
using DB3D = Autodesk.Revit.DB.DirectContext3D;
using RhinoInside.Revit.Convert.Geometry;
using Grasshopper;
using Grasshopper.Kernel;
using Grasshopper.GUI.Canvas;
namespace RhinoInside.Revit.GH
{
public class PreviewServer : DirectContext3DServer
{
static GH_Document ActiveDefinition => Instances.ActiveCanvas?.Document;
List<ParamPrimitive> primitives = new List<ParamPrimitive>();
Rhino.Geometry.BoundingBox primitivesBoundingBox = Rhino.Geometry.BoundingBox.Empty;
int RebuildPrimitives = 1;
public static GH_PreviewMode PreviewMode = GH_PreviewMode.Shaded;
public PreviewServer()
{
Instances.CanvasCreatedEventHandler CanvasCreated = default;
Instances.CanvasCreated += CanvasCreated = (canvas) =>
{
Instances.CanvasCreated -= CanvasCreated;
canvas.DocumentChanged += ActiveCanvas_DocumentChanged;
};
Instances.CanvasDestroyedEventHandler Canvas_Destroyed = default;
Instances.CanvasDestroyed += Canvas_Destroyed = (canvas) =>
{
Instances.CanvasDestroyed -= Canvas_Destroyed;
canvas.DocumentChanged -= ActiveCanvas_DocumentChanged;
};
}
#region IExternalServer
public override string GetName() => "Grasshopper";
public override string GetDescription() => "Grasshopper previews server";
public override Guid GetServerId() => Instances.GrasshopperPluginId;
#endregion
#region IDirectContext3DServer
public override bool UseInTransparentPass(DB.View dBView) =>
((ActiveDefinition is null ? GH_PreviewMode.Disabled : PreviewMode) == GH_PreviewMode.Shaded);
public override bool CanExecute(DB.View dBView) =>
GH_Document.EnableSolutions &&
PreviewMode != GH_PreviewMode.Disabled &&
ActiveDefinition is object &&
IsModelView(dBView);
List<IGH_DocumentObject> lastSelection;
private void SelectionChanged(object sender, EventArgs e)
{
var newSelection = ActiveDefinition.SelectedObjects();
if (PreviewMode != GH_PreviewMode.Disabled && GH_Document.EnableSolutions)
{
if (lastSelection.Count != newSelection.Count || lastSelection.Except(newSelection).Any())
Revit.RefreshActiveView();
}
lastSelection = newSelection;
}
static void Document_DefaultPreviewColourChanged(System.Drawing.Color colour) => Revit.RefreshActiveView();
private void ActiveCanvas_DocumentChanged(GH_Canvas sender, GH_CanvasDocumentChangedEventArgs e)
{
if (e.OldDocument is object)
{
Rhino.RhinoApp.Idle -= SelectionChanged;
e.OldDocument.SolutionEnd -= ActiveDefinition_SolutionEnd;
e.OldDocument.SettingsChanged -= ActiveDefinition_SettingsChanged;
GH_Document.DefaultSelectedPreviewColourChanged -= Document_DefaultPreviewColourChanged;
GH_Document.DefaultPreviewColourChanged -= Document_DefaultPreviewColourChanged;
}
RebuildPrimitives = 1;
lastSelection = new List<IGH_DocumentObject>();
if (e.NewDocument is object)
{
GH_Document.DefaultPreviewColourChanged += Document_DefaultPreviewColourChanged;
GH_Document.DefaultSelectedPreviewColourChanged += Document_DefaultPreviewColourChanged;
e.NewDocument.SettingsChanged += ActiveDefinition_SettingsChanged;
e.NewDocument.SolutionEnd += ActiveDefinition_SolutionEnd;
Rhino.RhinoApp.Idle += SelectionChanged;
}
}
void ActiveDefinition_SettingsChanged(object sender, GH_DocSettingsEventArgs e)
{
if (e.Kind == GH_DocumentSettings.Properties)
RebuildPrimitives = 1;
if (PreviewMode != GH_PreviewMode.Disabled)
Revit.RefreshActiveView();
}
void ActiveDefinition_SolutionEnd(object sender, GH_SolutionEventArgs e)
{
RebuildPrimitives = 1;
if (PreviewMode != GH_PreviewMode.Disabled)
Revit.RefreshActiveView();
}
protected class ParamPrimitive : Primitive
{
readonly IGH_DocumentObject docObject;
public ParamPrimitive(IGH_DocumentObject o, Rhino.Geometry.Point p) : base(p) { docObject = o; o.ObjectChanged += ObjectChanged; }
public ParamPrimitive(IGH_DocumentObject o, Rhino.Geometry.Curve c) : base(c) { docObject = o; o.ObjectChanged += ObjectChanged; }
public ParamPrimitive(IGH_DocumentObject o, Rhino.Geometry.Mesh m) : base(m) { docObject = o; o.ObjectChanged += ObjectChanged; }
void ObjectChanged(IGH_DocumentObject sender, GH_ObjectChangedEventArgs e)
{
if (e.Type == GH_ObjectEventType.Preview)
Revit.RefreshActiveView();
}
public override DB3D.EffectInstance EffectInstance(DB.DisplayStyle displayStyle, bool IsShadingPass)
{
var ei = base.EffectInstance(displayStyle, IsShadingPass);
var topAttributes = docObject.Attributes?.GetTopLevel ?? docObject.Attributes;
var color = topAttributes.Selected ? ActiveDefinition.PreviewColourSelected : ActiveDefinition.PreviewColour;
if (IsShadingPass)
{
var vc = HasVertexColors(vertexFormatBits) && ShowsVertexColors(displayStyle);
if (!vc)
{
ei.SetTransparency(Math.Max(1.0 / 255.0, (255 - color.A) / 255.0));
ei.SetEmissiveColor(new DB.Color(color.R, color.G, color.B));
}
}
else ei.SetColor(new DB.Color(color.R, color.G, color.B));
return ei;
}
public override void Draw(DB.DisplayStyle displayStyle)
{
if (docObject is IGH_PreviewObject preview)
{
if (preview.Hidden || !preview.IsPreviewCapable)
return;
}
var topObject = docObject.Attributes?.GetTopLevel?.DocObject ?? docObject;
if (topObject is IGH_PreviewObject topPreview)
{
if (topPreview.Hidden || !topPreview.IsPreviewCapable)
return;
}
if (ActiveDefinition.PreviewFilter == GH_PreviewFilter.Selected && !topObject.Attributes.Selected)
return;
base.Draw(displayStyle);
}
}
void DrawData(Grasshopper.Kernel.Data.IGH_Structure volatileData, IGH_DocumentObject docObject)
{
if (!volatileData.IsEmpty)
{
foreach (var value in volatileData.AllData(true))
{
// First check for IGH_PreviewData to discard no graphic elements like strings, doubles, vectors...
if (value is IGH_PreviewData)
{
switch (value.ScriptVariable())
{
case Rhino.Geometry.Point3d point: primitives.Add(new ParamPrimitive(docObject, new Rhino.Geometry.Point(point))); break;
case Rhino.Geometry.Line line: primitives.Add(new ParamPrimitive(docObject, new Rhino.Geometry.LineCurve(line))); break;
case Rhino.Geometry.Rectangle3d rect: primitives.Add(new ParamPrimitive(docObject, rect.ToNurbsCurve())); break;
case Rhino.Geometry.Arc arc: primitives.Add(new ParamPrimitive(docObject, new Rhino.Geometry.ArcCurve(arc))); break;
case Rhino.Geometry.Circle circle: primitives.Add(new ParamPrimitive(docObject, new Rhino.Geometry.ArcCurve(circle))); break;
case Rhino.Geometry.Ellipse ellipse: primitives.Add(new ParamPrimitive(docObject, ellipse.ToNurbsCurve())); break;
case Rhino.Geometry.Curve curve: primitives.Add(new ParamPrimitive(docObject, curve)); break;
case Rhino.Geometry.Mesh mesh: primitives.Add(new ParamPrimitive(docObject, mesh)); break;
case Rhino.Geometry.Box box:
{
if(Rhino.Geometry.Mesh.CreateFromBox(box, 1, 1, 1) is Rhino.Geometry.Mesh previewMesh)
primitives.Add(new ParamPrimitive(docObject, previewMesh));
}
break;
case Rhino.Geometry.SubD subd:
{
if (Rhino.Geometry.Mesh.CreateFromSubD(subd, 3) is Rhino.Geometry.Mesh previewMesh)
primitives.Add(new ParamPrimitive(docObject, previewMesh));
}
break;
case Rhino.Geometry.Brep brep:
{
if (Rhino.Geometry.Mesh.CreateFromBrep(brep, ActiveDefinition.PreviewCurrentMeshParameters()) is Rhino.Geometry.Mesh[] brepMeshes)
{
var previewMesh = new Rhino.Geometry.Mesh();
previewMesh.Append(brepMeshes);
primitives.Add(new ParamPrimitive(docObject, previewMesh));
}
}
break;
}
}
}
}
}
Rhino.Geometry.BoundingBox BuildScene(DB.View dBView)
{
if (Interlocked.Exchange(ref RebuildPrimitives, 0) != 0)
{
primitivesBoundingBox = Rhino.Geometry.BoundingBox.Empty;
// Dispose previous primitives
{
foreach (var primitive in primitives)
((IDisposable) primitive).Dispose();
primitives.Clear();
}
var previewColour = ActiveDefinition.PreviewColour;
var previewColourSelected = ActiveDefinition.PreviewColourSelected;
foreach (var obj in ActiveDefinition.Objects.OfType<IGH_ActiveObject>())
{
if (obj.Locked)
continue;
if (obj is IGH_PreviewObject previewObject)
{
if (previewObject.IsPreviewCapable)
{
primitivesBoundingBox = Rhino.Geometry.BoundingBox.Union(primitivesBoundingBox, previewObject.ClippingBox);
if (obj is IGH_Component component)
{
foreach (var param in component.Params.Output)
{
if(param is IGH_PreviewObject preview)
DrawData(param.VolatileData, param);
}
}
else if (obj is IGH_Param param)
{
DrawData(param.VolatileData, param);
}
}
}
}
}
return primitivesBoundingBox;
}
public override DB.Outline GetBoundingBox(DB.View dBView) => primitivesBoundingBox.ToOutline();
public override void RenderScene(DB.View dBView, DB.DisplayStyle displayStyle)
{
try
{
BuildScene(dBView);
DB3D.DrawContext.SetWorldTransform(DB.Transform.Identity.ScaleBasis(UnitConverter.ToHostUnits));
var CropBox = dBView.CropBox.ToBoundingBox();
foreach (var primitive in primitives)
{
if (DB3D.DrawContext.IsInterrupted())
break;
if (dBView.CropBoxActive && !Rhino.Geometry.BoundingBox.Intersection(CropBox, primitive.ClippingBox).IsValid)
continue;
primitive.Draw(displayStyle);
}
}
catch (Exception e)
{
Debug.Fail(e.Source, e.Message);
}
}
#endregion
}
}
#else
namespace RhinoInside.Revit.GH
{
public class PreviewServer
{
public void Register() { }
public void Unregister() { }
}
}
#endif
| 35.945687 | 146 | 0.656653 | [
"MIT"
] | IMVVVVVIP/rhino.inside-revit | src/RhinoInside.Revit/GH/PreviewServer.cs | 11,251 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FilePicker.Utils
{
public class SettingsHelper
{
public static string UserTokenCacheKey
{
get { return "USER_TOKEN"; }
}
public static string ClientId
{
get { return ConfigurationManager.AppSettings["ida:ClientID"]; }
}
public static string ClientSecret
{
get { return ConfigurationManager.AppSettings["ida:ClientSecret"]; }
}
public static string AzureAdTenant
{
get { return ConfigurationManager.AppSettings["ida:Domain"]; }
}
public static string AzureAdTenantId
{
get { return ConfigurationManager.AppSettings["ida:TenantId"]; }
}
public static string UnifiedApiResource
{
get { return "https://graph.microsoft.com/"; }
}
public static string AzureADAuthority
{
get { return string.Format("https://login.microsoftonline.com/{0}/", AzureAdTenantId); }
}
public static string ClaimTypeObjectIdentifier
{
get { return "http://schemas.microsoft.com/identity/claims/objectidentifier"; }
}
public static string DiscoveryResource
{
get { return "https://api.office.com/discovery/"; }
}
public static string DiscoveryEndpoint
{
get { return "https://api.office.com/discovery/v1.0/me/"; }
}
}
}
| 25.825397 | 100 | 0.592502 | [
"MIT"
] | OfficeDev/O365-TenantWide-File-Picker | FilePicker/Utils/SettingsHelper.cs | 1,629 | C# |
using System;
using System.IO;
using System.Web.Configuration;
using System.Web.Mvc;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.WxOpen.Entities.Request;
using Senparc.Weixin.MP.MvcExtension;
using Senparc.Weixin.MP.Sample.CommonService.TemplateMessage.WxOpen;
using Senparc.Weixin.MP.Sample.CommonService.WxOpenMessageHandler;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using Senparc.Weixin.WxOpen.Containers;
using Senparc.Weixin.WxOpen.Entities;
using Senparc.Weixin.WxOpen.Helpers;
using Senparc.Weixin.MP.TenPayLibV3;
using Senparc.CO2NET.Cache;
using Senparc.CO2NET.Extensions;
namespace Senparc.Weixin.MP.Sample.Controllers.WxOpen
{
/// <summary>
/// 微信小程序Controller
/// </summary>
public partial class WxOpenController : Controller
{
public static readonly string Token = Config.SenparcWeixinSetting.WxOpenToken;//与微信公众账号后台的Token设置保持一致,区分大小写。
public static readonly string EncodingAESKey = Config.SenparcWeixinSetting.EncodingAESKey;//与微信公众账号后台的EncodingAESKey设置保持一致,区分大小写。
public static readonly string WxOpenAppId = Config.SenparcWeixinSetting.WxOpenAppId;//与微信小程序账号后台的AppId设置保持一致,区分大小写。
public static readonly string WxOpenAppSecret = Config.SenparcWeixinSetting.WxOpenAppSecret;//与微信小程序账号后台的AppId设置保持一致,区分大小写。
readonly Func<string> _getRandomFileName = () => DateTime.Now.ToString("yyyyMMdd-HHmmss") + Guid.NewGuid().ToString("n").Substring(0, 6);
/// <summary>
/// GET请求用于处理微信小程序后台的URL验证
/// </summary>
/// <returns></returns>
[HttpGet]
[ActionName("Index")]
public ActionResult Get(PostModel postModel, string echostr)
{
if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
{
return Content(echostr); //返回随机字符串则表示验证通过
}
else
{
return Content("failed:" + postModel.Signature + "," + MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" +
"如果你在浏览器中看到这句话,说明此地址可以被作为微信小程序后台的Url,请注意保持Token一致。");
}
}
/// <summary>
/// 用户发送消息后,微信平台自动Post一个请求到这里,并等待响应XML。
/// </summary>
[HttpPost]
[ActionName("Index")]
public ActionResult Post(PostModel postModel)
{
if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
{
return Content("参数错误!");
}
postModel.Token = Token;//根据自己后台的设置保持一致
postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致
postModel.AppId = WxOpenAppId;//根据自己后台的设置保持一致
//v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制
var maxRecordCount = 10;
var logPath = Server.MapPath(string.Format("~/App_Data/WxOpen/{0}/", DateTime.Now.ToString("yyyy-MM-dd")));
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
}
//自定义MessageHandler,对微信请求的详细判断操作都在这里面。
var messageHandler = new CustomWxOpenMessageHandler(Request.InputStream, postModel, maxRecordCount);
try
{
//测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName)));
if (messageHandler.UsingEcryptMessage)
{
messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName)));
}
/* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
* 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/
messageHandler.OmitRepeatedMessage = true;
//执行微信处理过程
messageHandler.Execute();
//测试时可开启,帮助跟踪数据
//if (messageHandler.ResponseDocument == null)
//{
// throw new Exception(messageHandler.RequestDocument.ToString());
//}
if (messageHandler.ResponseDocument != null)
{
messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName)));
}
if (messageHandler.UsingEcryptMessage)
{
//记录加密后的响应信息
messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName)));
}
//return Content(messageHandler.ResponseDocument.ToString());//v0.7-
return new FixWeixinBugWeixinResult(messageHandler);//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
//return new WeixinResult(messageHandler);//v0.8+
}
catch (Exception ex)
{
using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_WxOpen_" + _getRandomFileName() + ".txt")))
{
tw.WriteLine("ExecptionMessage:" + ex.Message);
tw.WriteLine(ex.Source);
tw.WriteLine(ex.StackTrace);
//tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);
if (messageHandler.ResponseDocument != null)
{
tw.WriteLine(messageHandler.ResponseDocument.ToString());
}
if (ex.InnerException != null)
{
tw.WriteLine("========= InnerException =========");
tw.WriteLine(ex.InnerException.Message);
tw.WriteLine(ex.InnerException.Source);
tw.WriteLine(ex.InnerException.StackTrace);
}
tw.Flush();
tw.Close();
}
return Content("");
}
}
[HttpPost]
public ActionResult RequestData(string nickName)
{
var data = new
{
msg = string.Format("服务器时间:{0},昵称:{1}", DateTime.Now, nickName)
};
return Json(data);
}
/// <summary>
/// wx.login登陆成功之后发送的请求
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
[HttpPost]
public ActionResult OnLogin(string code)
{
var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code);
if (jsonResult.errcode == ReturnCode.请求成功)
{
//Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息(不推荐)
//使用SessionContainer管理登录信息(推荐)
var unionId = "";
var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId);
//注意:生产环境下SessionKey属于敏感信息,不能进行传输!
return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey });
}
else
{
return Json(new { success = false, msg = jsonResult.errmsg });
}
}
[HttpPost]
public ActionResult CheckWxOpenSignature(string sessionId, string rawData, string signature)
{
try
{
var checkSuccess = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.CheckSignature(sessionId, rawData, signature);
return Json(new { success = checkSuccess, msg = checkSuccess ? "签名校验成功" : "签名校验失败" });
}
catch (Exception ex)
{
return Json(new { success = false, msg = ex.Message });
}
}
[HttpPost]
public ActionResult DecodeEncryptedData(string type, string sessionId, string encryptedData, string iv)
{
DecodeEntityBase decodedEntity = null;
switch (type.ToUpper())
{
case "USERINFO"://wx.getUserInfo()
decodedEntity = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecodeUserInfoBySessionId(
sessionId,
encryptedData, iv);
break;
default:
break;
}
//检验水印
var checkWartmark = false;
if (decodedEntity != null)
{
checkWartmark = decodedEntity.CheckWatermark(WxOpenAppId);
}
//注意:此处仅为演示,敏感信息请勿传递到客户端!
return Json(new
{
success = checkWartmark,
//decodedEntity = decodedEntity,
msg = string.Format("水印验证:{0}",
checkWartmark ? "通过" : "不通过")
});
}
[HttpPost]
public ActionResult TemplateTest(string sessionId, string formId)
{
var sessionBag = SessionContainer.GetSession(sessionId);
var openId = sessionBag != null ? sessionBag.OpenId : "用户未正确登陆";
string title = null;
decimal price = 100;
string productName = null;
string orderNumber = null;
if (formId.StartsWith("prepay_id="))
{
formId = formId.Replace("prepay_id=", "");
title = "这是来自小程序支付的模板消息";
var cacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance();
var unifiedorderRequestData = cacheStrategy.Get<TenPayV3UnifiedorderRequestData>($"WxOpenUnifiedorderRequestData-{openId}");//获取订单请求信息缓存
var unifedorderResult = cacheStrategy.Get<UnifiedorderResult>($"WxOpenUnifiedorderResultData-{openId}");//获取订单信息缓存
if (unifedorderResult != null && formId == unifedorderResult.prepay_id)
{
price = unifiedorderRequestData.TotalFee;
productName = unifiedorderRequestData.Body + "/缓存获取 prepay_id 成功";
orderNumber = unifiedorderRequestData.OutTradeNo;
}
else
{
productName = "缓存获取 prepay_id 失败";
orderNumber = "1234567890";
}
productName += " | 注意:这条消息是从小程序发起的!仅作为UI上支付成功的演示!不能确定支付真实成功! | prepay_id:" + unifedorderResult.prepay_id;
}
else
{
title = "在线购买(小程序Demo测试)";
productName = "商品名称-模板消息测试";
orderNumber = "9876543210";
}
var data = new WxOpenTemplateMessage_PaySuccessNotice(title, DateTime.Now, productName, orderNumber, price,
"400-031-8816", "https://sdk.senparc.weixin.com");
try
{
Senparc.Weixin.WxOpen.AdvancedAPIs
.Template.TemplateApi
.SendTemplateMessage(
WxOpenAppId, openId, data.TemplateId, data, formId, "pages/index/index", "图书", "#fff00");
return Json(new { success = true, msg = "发送成功,请返回消息列表中的【服务通知】查看模板消息。\r\n点击模板消息还可重新回到小程序内。" });
}
catch (Exception ex)
{
return Json(new { success = false, openId = openId, formId = formId, msg = ex.Message });
}
}
public ActionResult DecryptPhoneNumber(string sessionId, string encryptedData, string iv)
{
var sessionBag = SessionContainer.GetSession(sessionId);
try
{
var phoneNumber = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecryptPhoneNumber(sessionId, encryptedData,
iv);
//throw new WeixinException("解密PhoneNumber异常测试");//启用这一句,查看客户端返回的异常信息
return Json(new { success = true, phoneNumber = phoneNumber });
}
catch (Exception ex)
{
return Json(new { success = false, msg = ex.Message });
}
}
public ActionResult GetPrepayid(string sessionId)
{
try
{
var sessionBag = SessionContainer.GetSession(sessionId);
var openId = sessionBag.OpenId;
//生成订单10位序列号,此处用时间和随机数生成,商户根据自己调整,保证唯一
var sp_billno = string.Format("{0}{1}{2}", Config.SenparcWeixinSetting.TenPayV3_MchId /*10位*/, DateTime.Now.ToString("yyyyMMddHHmmss"),
TenPayV3Util.BuildRandomStr(6));
var timeStamp = TenPayV3Util.GetTimestamp();
var nonceStr = TenPayV3Util.GetNoncestr();
var body = "小程序微信支付Demo";
var price = 1;//单位:分
var xmlDataInfo = new TenPayV3UnifiedorderRequestData(WxOpenAppId, Config.SenparcWeixinSetting.TenPayV3_MchId, body, sp_billno,
price, Request.UserHostAddress, Config.SenparcWeixinSetting.TenPayV3_WxOpenTenpayNotify, TenPayV3Type.JSAPI, openId, Config.SenparcWeixinSetting.TenPayV3_Key, nonceStr);
var result = TenPayV3.Unifiedorder(xmlDataInfo);//调用统一订单接口
WeixinTrace.SendCustomLog("统一订单接口调用结束", "请求:" + xmlDataInfo.ToJson() + "\r\n\r\n返回结果:" + result.ToJson());
var packageStr = "prepay_id=" + result.prepay_id;
//记录到缓存
var cacheStrategy = CacheStrategyFactory.GetObjectCacheStrategyInstance();
cacheStrategy.Set($"WxOpenUnifiedorderRequestData-{openId}", xmlDataInfo, TimeSpan.FromDays(4));//3天内可以发送模板消息
cacheStrategy.Set($"WxOpenUnifiedorderResultData-{openId}", result, TimeSpan.FromDays(4));//3天内可以发送模板消息
return Json(new
{
success = true,
prepay_id = result.prepay_id,
appId = Config.SenparcWeixinSetting.WxOpenAppId,
timeStamp,
nonceStr,
package = packageStr,
//signType = "MD5",
paySign = TenPayV3.GetJsPaySign(WxOpenAppId, timeStamp, nonceStr, packageStr, Config.SenparcWeixinSetting.TenPayV3_Key)
});
}
catch (Exception ex)
{
return Json(new
{
success = false,
msg = ex.Message
});
}
}
}
} | 41.033058 | 196 | 0.564149 | [
"Apache-2.0"
] | Flysem/WeiXinMPSDK | Samples/Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Controllers/WxOpen/WxOpenController.cs | 16,651 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
namespace Imaginet.Samples.WebJobs
{
// To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976
class Program
{
// Please set the following connection strings in app.config for this WebJob to run:
// AzureWebJobsDashboard and AzureWebJobsStorage
static void Main()
{
var host = new JobHost();
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
}
}
| 29.782609 | 112 | 0.680292 | [
"Apache-2.0"
] | Imaginet-Resources/AzureQueuesAndWebJobs | Imaginet.Samples.AzureQueuesAndWebJobs/Imaginet.Samples.WebJobs/Program.cs | 687 | C# |
using System;
using System.Runtime.InteropServices;
namespace NAudio.Wave
{
//http://svn.xiph.org/tags/vorbisacm_20020708/src/vorbisacm/vorbisacm.h
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack=2)]
class OggWaveFormat : WaveFormat
{
//public short cbSize;
public uint dwVorbisACMVersion;
public uint dwLibVorbisVersion;
}
}
| 25.8 | 75 | 0.715762 | [
"MIT"
] | ArisAgnew/NAudio | NAudio.Core/Wave/WaveFormats/OggWaveFormat.cs | 387 | C# |
using SolutionEdit;
using Xunit;
namespace SolutionEditTest
{
public class ProjectTypeTest
{
[Fact]
public void ConvertProjectToGuidAndBack()
{
// Arrange.
var projType = ProjectType.Project;
// Act.
var typeGuid = projType.ToGuid();
var andBack = typeGuid.ToProjectType();
// Assert.
Assert.Equal(projType, andBack);
Assert.Equal(typeGuid.ToProjectGuidString(), andBack.ToProjectGuidString());
}
}
} | 23.608696 | 88 | 0.570902 | [
"MIT"
] | Timboski/solution-edit | SolutionParserTest/ProjectTypeTest.cs | 543 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Persistence;
namespace Persistence.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20200116164529_AddedFollowingEntity")]
partial class AddedFollowingEntity
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.0-rtm-35687");
modelBuilder.Entity("Domain.Activity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Category");
b.Property<string>("City");
b.Property<DateTime>("Date");
b.Property<string>("Description");
b.Property<string>("Title");
b.Property<string>("Venue");
b.HasKey("Id");
b.ToTable("Activities");
});
modelBuilder.Entity("Domain.AppUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("Bio");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("DisplayName");
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Domain.Comment", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<Guid?>("ActivityId");
b.Property<string>("AuthorId");
b.Property<string>("Body");
b.Property<DateTime>("CreatedAt");
b.HasKey("Id");
b.HasIndex("ActivityId");
b.HasIndex("AuthorId");
b.ToTable("Comments");
});
modelBuilder.Entity("Domain.Photo", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AppUserId");
b.Property<bool>("IsMain");
b.Property<string>("Url");
b.HasKey("Id");
b.HasIndex("AppUserId");
b.ToTable("Photos");
});
modelBuilder.Entity("Domain.UserActivity", b =>
{
b.Property<string>("AppUserId");
b.Property<Guid>("ActivityId");
b.Property<DateTime>("DateJoined");
b.Property<bool>("IsHost");
b.HasKey("AppUserId", "ActivityId");
b.HasIndex("ActivityId");
b.ToTable("UserActivities");
});
modelBuilder.Entity("Domain.UserFollowing", b =>
{
b.Property<string>("ObserverId");
b.Property<string>("TargetId");
b.HasKey("ObserverId", "TargetId");
b.HasIndex("TargetId");
b.ToTable("Followings");
});
modelBuilder.Entity("Domain.Value", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Values");
b.HasData(
new
{
Id = 1,
Name = "Value 101"
},
new
{
Id = 2,
Name = "Value 102"
},
new
{
Id = 3,
Name = "Value 103"
});
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Domain.Comment", b =>
{
b.HasOne("Domain.Activity", "Activity")
.WithMany("Comments")
.HasForeignKey("ActivityId");
b.HasOne("Domain.AppUser", "Author")
.WithMany()
.HasForeignKey("AuthorId");
});
modelBuilder.Entity("Domain.Photo", b =>
{
b.HasOne("Domain.AppUser")
.WithMany("Photos")
.HasForeignKey("AppUserId");
});
modelBuilder.Entity("Domain.UserActivity", b =>
{
b.HasOne("Domain.Activity", "Activity")
.WithMany("UserActivities")
.HasForeignKey("ActivityId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Domain.AppUser", "AppUser")
.WithMany("UserActivities")
.HasForeignKey("AppUserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Domain.UserFollowing", b =>
{
b.HasOne("Domain.AppUser", "Observer")
.WithMany("Followings")
.HasForeignKey("ObserverId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("Domain.AppUser", "Target")
.WithMany("Followers")
.HasForeignKey("TargetId")
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Domain.AppUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Domain.AppUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Domain.AppUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Domain.AppUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 31.508861 | 95 | 0.426 | [
"MIT"
] | helderboone/reactivity | persistence/Migrations/20200116164529_AddedFollowingEntity.Designer.cs | 12,448 | C# |
namespace QuranX.Persistence.Services
{
public interface ISettings
{
string DataPath { get; }
}
public class Settings : ISettings
{
public string DataPath { get; private set; }
public Settings(string dataPath)
{
DataPath = dataPath;
}
}
}
| 14.5 | 46 | 0.689655 | [
"MIT"
] | QuranX/QuranX | src/QuranX.Persistence/Services/Settings.cs | 263 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace IdentityServer4.Admin.Web
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 24.84 | 76 | 0.697262 | [
"MIT"
] | DORAdreamless/IdentityServer4.AdminUI | src/IdentityServer4.Admin/IdentityServer4.Admin.Web/Program.cs | 623 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Управление общими сведениями о сборке осуществляется с помощью
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("ArgusWatcher")]
[assembly: AssemblyDescription("Программа управления для Аргус")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("tzi73.ru")]
[assembly: AssemblyProduct("ArgusWatcher")]
[assembly: AssemblyCopyright("Copyright © РАЦ 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
// для COM-компонентов. Если требуется обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("7c2e2e20-45fb-4040-9fdd-177cba92caa9")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.189189 | 99 | 0.763448 | [
"MIT"
] | Shkarlatov/ArgusWatcher | ArgusWatcher/Properties/AssemblyInfo.cs | 2,040 | C# |
using System;
using System.ComponentModel;
using Android.Content;
using Android.Graphics;
using Android.Util;
using Android.Views;
using Android.Widget;
using AndroidX.AppCompat.Widget;
using AndroidX.Core.View;
using Microsoft.Maui.Controls.Internals;
using Microsoft.Maui.Controls.Compatibility.Platform.Android.FastRenderers;
using AColor = Android.Graphics.Color;
using AView = Android.Views.View;
namespace Microsoft.Maui.Controls.Compatibility.Platform.Android
{
public class RadioButtonRenderer : AppCompatRadioButton,
IBorderVisualElementRenderer, IVisualElementRenderer, IViewRenderer, ITabStop,
AView.IOnFocusChangeListener,
CompoundButton.IOnCheckedChangeListener
{
float _defaultFontSize;
int? _defaultLabelFor;
Typeface _defaultTypeface;
bool _isDisposed;
bool _inputTransparent;
Lazy<TextColorSwitcher> _textColorSwitcher;
AutomationPropertiesProvider _automationPropertiesProvider;
VisualElementTracker _tracker;
VisualElementRenderer _visualElementRenderer;
BorderBackgroundManager _backgroundTracker;
IPlatformElementConfiguration<PlatformConfiguration.Android, RadioButton> _platformElementConfiguration;
public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
public event EventHandler<PropertyChangedEventArgs> ElementPropertyChanged;
public RadioButtonRenderer(Context context) : base(context)
{
Initialize();
}
protected RadioButton Element { get; set; }
protected AppCompatRadioButton Control => this;
VisualElement IBorderVisualElementRenderer.Element => Element;
VisualElement IVisualElementRenderer.Element => Element;
AView IVisualElementRenderer.View => this;
ViewGroup IVisualElementRenderer.ViewGroup => null;
VisualElementTracker IVisualElementRenderer.Tracker => _tracker;
AView ITabStop.TabStop => this;
void IOnFocusChangeListener.OnFocusChange(AView v, bool hasFocus)
{
((IElementController)Element).SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, hasFocus);
}
SizeRequest IVisualElementRenderer.GetDesiredSize(int widthConstraint, int heightConstraint)
{
Measure(widthConstraint, heightConstraint);
return new SizeRequest(new Size(MeasuredWidth, MeasuredHeight));
}
void IVisualElementRenderer.SetElement(VisualElement element)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
if (!(element is RadioButton))
{
throw new ArgumentException($"{nameof(element)} must be of type {nameof(RadioButton)}");
}
RadioButton oldElement = Element;
Element = (RadioButton)element;
Performance.Start(out string reference);
if (oldElement != null)
{
oldElement.PropertyChanged -= OnElementPropertyChanged;
}
element.PropertyChanged += OnElementPropertyChanged;
if (_tracker == null)
{
// Can't set up the tracker in the constructor because it access the Element (for now)
SetTracker(new VisualElementTracker(this));
}
if (_visualElementRenderer == null)
{
_visualElementRenderer = new VisualElementRenderer(this);
}
OnElementChanged(new ElementChangedEventArgs<RadioButton>(oldElement, Element));
SendVisualElementInitialized(element, this);
Performance.Stop(reference);
}
void IVisualElementRenderer.SetLabelFor(int? id)
{
if (_defaultLabelFor == null)
{
_defaultLabelFor = ViewCompat.GetLabelFor(this);
}
ViewCompat.SetLabelFor(this, (int)(id ?? _defaultLabelFor));
}
void IVisualElementRenderer.UpdateLayout() => _tracker?.UpdateLayout();
void IViewRenderer.MeasureExactly()
{
ViewRenderer.MeasureExactly(this, Element, Context);
}
protected override void Dispose(bool disposing)
{
if (_isDisposed)
{
return;
}
_isDisposed = true;
if (disposing)
{
SetOnClickListener(null);
SetOnTouchListener(null);
OnFocusChangeListener = null;
SetOnCheckedChangeListener(null);
if (Element != null)
{
Element.PropertyChanged -= OnElementPropertyChanged;
}
_automationPropertiesProvider?.Dispose();
_tracker?.Dispose();
_visualElementRenderer?.Dispose();
_backgroundTracker?.Dispose();
_backgroundTracker = null;
if (Element != null)
{
if (AppCompat.Platform.GetRenderer(Element) == this)
Element.ClearValue(AppCompat.Platform.RendererProperty);
}
}
base.Dispose(disposing);
}
public override bool OnTouchEvent(MotionEvent e)
{
if (!Enabled || (_inputTransparent && Enabled))
return false;
return base.OnTouchEvent(e);
}
protected virtual void OnElementChanged(ElementChangedEventArgs<RadioButton> e)
{
if (e.NewElement != null && !_isDisposed)
{
this.EnsureId();
_textColorSwitcher = new Lazy<TextColorSwitcher>(
() => new TextColorSwitcher(TextColors, e.NewElement.UseLegacyColorManagement()));
UpdateFont();
UpdateTextColor();
UpdateInputTransparent();
UpdateBackgroundColor();
UpdateIsChecked();
UpdateContent();
ElevationHelper.SetElevation(this, e.NewElement);
}
ElementChanged?.Invoke(this, new VisualElementChangedEventArgs(e.OldElement, e.NewElement));
}
protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == RadioButton.TextColorProperty.PropertyName)
{
UpdateTextColor();
}
else if (e.IsOneOf(RadioButton.FontAttributesProperty, RadioButton.FontFamilyProperty, RadioButton.FontSizeProperty))
{
UpdateFont();
}
else if (e.PropertyName == VisualElement.InputTransparentProperty.PropertyName)
{
UpdateInputTransparent();
}
else if (e.PropertyName == RadioButton.IsCheckedProperty.PropertyName)
{
UpdateIsChecked();
}
else if (e.PropertyName == RadioButton.ContentProperty.PropertyName)
{
UpdateContent();
}
ElementPropertyChanged?.Invoke(this, e);
}
void SetTracker(VisualElementTracker tracker)
{
_tracker = tracker;
}
void UpdateBackgroundColor()
{
_backgroundTracker?.UpdateDrawable();
}
internal void OnNativeFocusChanged(bool hasFocus)
{
}
internal void SendVisualElementInitialized(VisualElement element, AView nativeView)
{
element.SendViewInitialized(nativeView);
}
void Initialize()
{
_automationPropertiesProvider = new AutomationPropertiesProvider(this);
_backgroundTracker = new BorderBackgroundManager(this);
SoundEffectsEnabled = false;
OnFocusChangeListener = this;
SetOnCheckedChangeListener(this);
Tag = this;
}
void UpdateFont()
{
if (Element == null || _isDisposed)
{
return;
}
Font font = Font.OfSize(Element.FontFamily, Element.FontSize).WithAttributes(Element.FontAttributes);
if (font == Font.Default && _defaultFontSize == 0f)
{
return;
}
if (_defaultFontSize == 0f)
{
_defaultTypeface = Typeface;
_defaultFontSize = TextSize;
}
if (font == Font.Default)
{
Typeface = _defaultTypeface;
SetTextSize(ComplexUnitType.Px, _defaultFontSize);
}
else
{
Typeface = font.ToTypeface();
SetTextSize(ComplexUnitType.Sp, font.ToScaledPixel());
}
}
void UpdateInputTransparent()
{
if (Element == null || _isDisposed)
{
return;
}
_inputTransparent = Element.InputTransparent;
}
void UpdateTextColor()
{
if (Element == null || _isDisposed || _textColorSwitcher == null)
{
return;
}
_textColorSwitcher.Value.UpdateTextColor(this, Element.TextColor);
}
void UpdateIsChecked()
{
if (Element == null || Control == null)
return;
Checked = ((RadioButton)Element).IsChecked;
}
void UpdateContent()
{
if (Element == null || Control == null)
{
return;
}
Control.Text = Element.ContentAsString();
}
void IOnCheckedChangeListener.OnCheckedChanged(CompoundButton buttonView, bool isChecked)
{
((IElementController)Element).SetValueFromRenderer(RadioButton.IsCheckedProperty, isChecked);
}
float IBorderVisualElementRenderer.ShadowRadius => ShadowRadius;
float IBorderVisualElementRenderer.ShadowDx => ShadowDx;
float IBorderVisualElementRenderer.ShadowDy => ShadowDy;
AColor IBorderVisualElementRenderer.ShadowColor => ShadowColor;
bool IBorderVisualElementRenderer.IsShadowEnabled() => true;
AView IBorderVisualElementRenderer.View => this;
IPlatformElementConfiguration<PlatformConfiguration.Android, RadioButton> OnThisPlatform()
{
if (_platformElementConfiguration == null)
_platformElementConfiguration = Element.OnThisPlatform();
return _platformElementConfiguration;
}
bool IBorderVisualElementRenderer.UseDefaultPadding() => true;
bool IBorderVisualElementRenderer.UseDefaultShadow() => true;
}
} | 25.749263 | 120 | 0.738687 | [
"MIT"
] | pictos/maui | src/Compatibility/Core/src/Android/AppCompat/RadioButtonRenderer.cs | 8,729 | C# |
namespace HBM.Web.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddUserStats : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.UserStats",
c => new
{
Id = c.Int(nullable: false),
Rating = c.Int(nullable: false),
TimesBanned = c.Int(nullable: false),
ArticlesPosted = c.Int(nullable: false),
CommentsWritten = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.ApplicationUsers", t => t.Id)
.Index(t => t.Id, unique: true, name: "IX_UserStats");
CreateTable(
"dbo.UserArticleActivities",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.Int(nullable: false),
ArticleId = c.Int(nullable: false),
Viewed = c.Boolean(nullable: false),
Vote = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Articles", t => t.ArticleId, cascadeDelete: false)
.ForeignKey("dbo.ApplicationUsers", t => t.UserId, cascadeDelete: false)
.Index(t => new { t.UserId, t.ArticleId }, unique: true, name: "IX_UserArticle");
AddColumn("dbo.ApplicationUsers", "FullName", c => c.String(maxLength: 64, unicode: false));
AddColumn("dbo.ApplicationUsers", "UserStatsId", c => c.Int(nullable: false));
}
public override void Down()
{
DropForeignKey("dbo.UserArticleActivities", "UserId", "dbo.ApplicationUsers");
DropForeignKey("dbo.UserArticleActivities", "ArticleId", "dbo.Articles");
DropForeignKey("dbo.UserStats", "Id", "dbo.ApplicationUsers");
DropIndex("dbo.UserArticleActivities", "IX_UserArticle");
DropIndex("dbo.UserStats", "IX_UserStats");
DropColumn("dbo.ApplicationUsers", "UserStatsId");
DropColumn("dbo.ApplicationUsers", "FullName");
DropTable("dbo.UserArticleActivities");
DropTable("dbo.UserStats");
}
}
}
| 43 | 104 | 0.503876 | [
"MIT"
] | ViktoriiaDubova/HumanBehaviorModel | HBM.Web/HBM.Web/Migrations/201812081701118_AddUserStats.cs | 2,451 | C# |
using Prism.Navigation;
namespace Nuits.Prism.Navigation
{
public interface INavigatable
{
INavigationService NavigationService { get; }
}
} | 18 | 53 | 0.703704 | [
"MIT"
] | nuitsjp/Nuits.Prism | Source/Nuits.Prism.Forms/Navigation/INavigatable.cs | 164 | C# |
using Khooversoft.Toolbox;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Khooversoft.Security
{
/// <summary>
/// Calculates HMAC signature based on HMAC configuration of client is present in properties
/// </summary>
public class HmacHandler : DelegatingHandler
{
private static readonly Tag _tag = new Tag(nameof(HmacHandler));
public HmacHandler()
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IWorkContext context = (request.Properties.Get<IWorkContext>() ?? WorkContext.Empty)
.WithTag(_tag);
// Check to see if we have a HMAC configuration
HmacClient hmacClient = request.Properties.Get<HmacClient>();
if (hmacClient == null)
{
return await base.SendAsync(request, cancellationToken);
}
SecurityEventSource.Log.Verbose(context, "Processing HMAC");
// Collection header values
List<KeyValuePair<string, IEnumerable<string>>> headers = request.Headers.ToList();
if (request.Content != null)
{
await AddContentMd5Hash(request);
IEnumerable<KeyValuePair<string, IEnumerable<string>>> contentHeaders = request.Content.Headers;
headers.AddRange(contentHeaders);
}
string siguature = await hmacClient.CreateSignature(context, request.Method.Method, request.RequestUri, headers);
request.Headers.Authorization = new AuthenticationHeaderValue("hmac", siguature);
HttpResponseMessage result = await base.SendAsync(request, cancellationToken);
return result;
}
private async Task AddContentMd5Hash(HttpRequestMessage request)
{
// Calculate MD5 hash for content
using (var ms = new MemoryStream())
{
byte[] content = await request.Content.ReadAsByteArrayAsync();
if (content.Length > 0)
{
request.Content.Headers.ContentMD5 = content.ToMd5Hash();
}
}
}
}
}
| 34.267606 | 133 | 0.625154 | [
"MIT"
] | khoover768/Khooversoft | Src/Common/Khooversoft.Toolbox/Khooversoft.Security/DelegatingHandlers/HmacHandler.cs | 2,435 | C# |
using System;
using System.Drawing;
using Gwen.Control;
namespace Gwen.ControlInternal
{
/// <summary>
/// Property button.
/// </summary>
public class ColorButton : Button
{
private Color m_Color;
/// <summary>
/// Current color value.
/// </summary>
public Color Color { get { return m_Color; } set { m_Color = value; } }
/// <summary>
/// Initializes a new instance of the <see cref="ColorButton"/> class.
/// </summary>
/// <param name="parent">Parent control.</param>
public ColorButton(Base parent) : base(parent)
{
m_Color = Color.Black;
Text = String.Empty;
}
/// <summary>
/// Renders the control using specified skin.
/// </summary>
/// <param name="skin">Skin to use.</param>
protected override void Render(Skin.Base skin)
{
skin.Renderer.DrawColor = m_Color;
skin.Renderer.DrawFilledRect(RenderBounds);
}
}
}
| 26.25 | 79 | 0.546667 | [
"MIT"
] | BreyerW/Sharp.Engine | Gwen/ControlInternal/ColorButton.cs | 1,052 | C# |
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
private const string _clientId = "";
private const string _tenantId = "";
public static async Task Main(string[] args)
{
IPublicClientApplication app;
app = PublicClientApplicationBuilder
.Create(_clientId)
.WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
.WithRedirectUri("http://localhost")
.Build();
List<string> scopes = new List<string>
{
"user.read"
};
AuthenticationResult result;
result = await app
.AcquireTokenInteractive(scopes)
.ExecuteAsync();
Console.WriteLine($"Token:\t{result.AccessToken}");
/*DeviceCodeProvider provider = new DeviceCodeProvider(app, scopes);
GraphServiceClient client = new GraphServiceClient(provider);
User myProfile = await client.Me
.Request()
.GetAsync();
Console.WriteLine($"Name:\t{myProfile.DisplayName}");
Console.WriteLine($"AAD Id:\t{myProfile.Id}");*/
}
} | 26.468085 | 76 | 0.628617 | [
"Unlicense"
] | andko3/AZ-204 | Labs/06/Starter/Program.cs | 1,246 | C# |
namespace ExampleDLLProjectForUnitTestDependingOnAnotherClass
{
interface ISalaryCalculator
{
int calculateSalary();
}
} | 20.142857 | 62 | 0.737589 | [
"MIT"
] | maxcuevas/UnitTestingTutorialCSharp | SourceCode/ExampleDLLProjectForUnitTestDependingOnAnotherClass/ISalaryCalculator.cs | 143 | C# |
using System;
using Foundation;
using Steepshot.Core.Presenters;
using Steepshot.iOS.Cells;
using UIKit;
namespace Steepshot.iOS.ViewSources
{
public class UserSearchTableViewSource : UITableViewSource
{
private const string CellIdentifier = nameof(UsersSearchViewCell);
private readonly UserFriendPresenter _presenter;
public event RowSelectedHandler RowSelectedEvent;
public UserSearchTableViewSource(UserFriendPresenter presenter)
{
_presenter = presenter;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return _presenter.Count;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = (UsersSearchViewCell)tableView.DequeueReusableCell(CellIdentifier, indexPath);
var user = _presenter[indexPath.Row]; //TODO:KOA: if null?
if (user != null)
cell.UpdateCell(user);
return cell;
}
public override void RowHighlighted(UITableView tableView, NSIndexPath rowIndexPath)
{
if (RowSelectedEvent != null) RowSelectedEvent(rowIndexPath.Row);
}
}
}
| 31.325 | 101 | 0.669593 | [
"MIT"
] | Chainers/steepshot-mobile | Sources/Steepshot/Steepshot.iOS/ViewSources/UserSearchTableViewSource.cs | 1,255 | C# |
using System;
namespace Elders.Cronus
{
public class AggregateRootId : AggregateUrn, IAggregateRootId
{
/// <summary>
/// Prevents a default instance of the <see cref="AggregateRootId"/> class from being created.
/// </summary>
/// <remarks>Used only for serizalization.</remarks>
protected AggregateRootId() { }
public AggregateRootId(string idBase, string aggregateRootName, string tenant)
: base(tenant, aggregateRootName, idBase)
{
}
public AggregateRootId(string aggregateRootName, AggregateUrn urn)
: base(urn.Tenant, urn)
{
if (aggregateRootName.Equals(urn.AggregateRootName, StringComparison.OrdinalIgnoreCase) == false)
throw new ArgumentException("AggregateRootName missmatch");
}
}
public abstract class AggregateRootId<T> : AggregateUrn, IAggregateRootId
where T : AggregateRootId<T>
{
static UberUrnFormatProvider urnFormatProvider = new UberUrnFormatProvider();
protected AggregateRootId() { }
protected AggregateRootId(string id, string rootName, string tenant) : base(tenant, rootName, id) { }
public static T New(string tenant)
{
var instance = (T)System.Activator.CreateInstance(typeof(T), true);
return instance.Construct(System.Guid.NewGuid().ToString(), tenant);
}
public static T New(string tenant, string id)
{
var instance = (T)System.Activator.CreateInstance(typeof(T), true);
return instance.Construct(id, tenant);
}
protected abstract T Construct(string id, string tenant);
new public static T Parse(string id)
{
var instance = (T)System.Activator.CreateInstance(typeof(T), true);
var stringTenantUrn = AggregateUrn.Parse(id, urnFormatProvider);
var newId = instance.Construct(stringTenantUrn.Id, stringTenantUrn.Tenant);
if (stringTenantUrn.AggregateRootName == newId.AggregateRootName)
return newId;
else
throw new System.Exception("bum");
//todo check if ar name mateches..
}
public static bool TryParse(string id, out T result)
{
try
{
var instance = (T)System.Activator.CreateInstance(typeof(T), true);
var stringTenantUrn = AggregateUrn.Parse(id, urnFormatProvider);
var newId = instance.Construct(stringTenantUrn.Id, stringTenantUrn.Tenant);
if (stringTenantUrn.AggregateRootName == newId.AggregateRootName)
result = newId;
else
throw new System.Exception("bum");
//todo check if ar name mateches..
return true;
}
catch (Exception)
{
result = null;
return false;
}
}
}
}
| 35.197674 | 109 | 0.594979 | [
"Apache-2.0"
] | Elders/Cronus.DomainModeling | src/Elders.Cronus.DomainModeling/AggregateRootId.cs | 3,027 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20150501Preview.Outputs
{
[OutputType]
public sealed class ExpressRouteCircuitPeeringConfigResponse
{
/// <summary>
/// Gets or sets the reference of AdvertisedPublicPrefixes
/// </summary>
public readonly ImmutableArray<string> AdvertisedPublicPrefixes;
/// <summary>
/// Gets or sets AdvertisedPublicPrefixState of the Peering resource
/// </summary>
public readonly string? AdvertisedPublicPrefixesState;
/// <summary>
/// Gets or Sets CustomerAsn of the peering.
/// </summary>
public readonly int? CustomerASN;
/// <summary>
/// Gets or Sets RoutingRegistryName of the config.
/// </summary>
public readonly string? RoutingRegistryName;
[OutputConstructor]
private ExpressRouteCircuitPeeringConfigResponse(
ImmutableArray<string> advertisedPublicPrefixes,
string? advertisedPublicPrefixesState,
int? customerASN,
string? routingRegistryName)
{
AdvertisedPublicPrefixes = advertisedPublicPrefixes;
AdvertisedPublicPrefixesState = advertisedPublicPrefixesState;
CustomerASN = customerASN;
RoutingRegistryName = routingRegistryName;
}
}
}
| 33.12 | 81 | 0.666667 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Network/V20150501Preview/Outputs/ExpressRouteCircuitPeeringConfigResponse.cs | 1,656 | C# |
// ===========
// DO NOT EDIT - this file is automatically regenerated.
// ===========
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Profiling;
using Unity.Mathematics;
using Unity.Entities;
using Unity.Collections;
using Improbable.Gdk.Core;
using Improbable.Gdk.Core.CodegenAdapters;
namespace Improbable.DependentSchema
{
public partial class DependentComponent
{
internal class ComponentReplicator : IComponentReplicationHandler
{
public uint ComponentId => 198800;
public EntityQueryDesc ComponentUpdateQuery => new EntityQueryDesc
{
All = new[]
{
ComponentType.ReadWrite<global::Improbable.DependentSchema.DependentComponent.Component>(),
ComponentType.ReadWrite<global::Improbable.DependentSchema.DependentComponent.ComponentAuthority>(),
ComponentType.ReadOnly<SpatialEntityId>()
},
};
public void SendUpdates(
NativeArray<ArchetypeChunk> chunkArray,
ComponentSystemBase system,
EntityManager entityManager,
ComponentUpdateSystem componentUpdateSystem)
{
Profiler.BeginSample("DependentComponent");
var spatialOSEntityType = system.GetArchetypeChunkComponentType<SpatialEntityId>(true);
var componentType = system.GetArchetypeChunkComponentType<global::Improbable.DependentSchema.DependentComponent.Component>();
var authorityType = system.GetArchetypeChunkSharedComponentType<ComponentAuthority>();
foreach (var chunk in chunkArray)
{
var entityIdArray = chunk.GetNativeArray(spatialOSEntityType);
var componentArray = chunk.GetNativeArray(componentType);
var authorityIndex = chunk.GetSharedComponentIndex(authorityType);
if (!entityManager.GetSharedComponentData<ComponentAuthority>(authorityIndex).HasAuthority)
{
continue;
}
for (var i = 0; i < componentArray.Length; i++)
{
var data = componentArray[i];
if (data.IsDataDirty())
{
Update update = new Update();
if (data.IsDataDirty(0))
{
update.A = data.A;
}
if (data.IsDataDirty(1))
{
update.B = data.B;
}
if (data.IsDataDirty(2))
{
update.C = data.C;
}
if (data.IsDataDirty(3))
{
update.D = data.D;
}
if (data.IsDataDirty(4))
{
update.E = data.E;
}
componentUpdateSystem.SendUpdate(in update, entityIdArray[i].EntityId);
data.MarkDataClean();
componentArray[i] = data;
}
}
}
Profiler.EndSample();
}
}
}
}
| 35.666667 | 141 | 0.481034 | [
"MIT"
] | DenDrummer/TI-conf_19-20_groep-1 | POC/SpatialOS Maze/gdk-for-unity/test-project/Assets/Generated/Source/improbable/dependentschema/DependentComponentUpdateSender.cs | 3,638 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyCall.modelo
{
public class Devedor
{
public int iddevedor;
public string nome;
public string cpf;
public string email;
public string telefone;
}
}
| 18.388889 | 33 | 0.670695 | [
"MIT"
] | luisc13/EasyCall | modelo/Devedor.cs | 333 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace ILPad
{
public class MarginManager
{
public static Thickness GetMargin(DependencyObject obj)
{
return (Thickness)obj.GetValue(MarginProperty);
}
public static void SetMargin(DependencyObject obj, Thickness value)
{
obj.SetValue(MarginProperty, value);
}
// Using a DependencyProperty as the backing store for Margin. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MarginProperty =
DependencyProperty.RegisterAttached("Margin", typeof(Thickness), typeof(MarginManager), new UIPropertyMetadata(new Thickness(), MarginChangedCallback));
public static void MarginChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
{
// Make sure this is put on a panel
var panel = sender as Panel;
if (panel == null) return;
panel.Loaded += new RoutedEventHandler(panel_Loaded);
}
static void panel_Loaded(object sender, RoutedEventArgs e)
{
var panel = sender as Panel;
// Go over the children and set margin for them:
foreach (var child in panel.Children)
{
var fe = child as FrameworkElement;
if (fe == null) continue;
fe.Margin = MarginManager.GetMargin(panel);
}
}
}
}
| 31.764706 | 164 | 0.634568 | [
"MIT"
] | mzboray/ILPad | ILPad/MarginManager.cs | 1,622 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.AppService
{
/// <summary> A Class representing a LogsSiteConfig along with the instance operations that can be performed on it. </summary>
public partial class LogsSiteConfig : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="LogsSiteConfig"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string name)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/logs";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _logsSiteConfigWebAppsClientDiagnostics;
private readonly WebAppsRestOperations _logsSiteConfigWebAppsRestClient;
private readonly SiteLogsConfigData _data;
/// <summary> Initializes a new instance of the <see cref="LogsSiteConfig"/> class for mocking. </summary>
protected LogsSiteConfig()
{
}
/// <summary> Initializes a new instance of the <see cref = "LogsSiteConfig"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal LogsSiteConfig(ArmClient client, SiteLogsConfigData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="LogsSiteConfig"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal LogsSiteConfig(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_logsSiteConfigWebAppsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.AppService", ResourceType.Namespace, DiagnosticOptions);
TryGetApiVersion(ResourceType, out string logsSiteConfigWebAppsApiVersion);
_logsSiteConfigWebAppsRestClient = new WebAppsRestOperations(Pipeline, DiagnosticOptions.ApplicationId, BaseUri, logsSiteConfigWebAppsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Web/sites/config";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual SiteLogsConfigData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary>
/// Description for Gets the logging configuration of an app.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/logs
/// Operation Id: WebApps_GetDiagnosticLogsConfiguration
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<LogsSiteConfig>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _logsSiteConfigWebAppsClientDiagnostics.CreateScope("LogsSiteConfig.Get");
scope.Start();
try
{
var response = await _logsSiteConfigWebAppsRestClient.GetDiagnosticLogsConfigurationAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new LogsSiteConfig(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Gets the logging configuration of an app.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/logs
/// Operation Id: WebApps_GetDiagnosticLogsConfiguration
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<LogsSiteConfig> Get(CancellationToken cancellationToken = default)
{
using var scope = _logsSiteConfigWebAppsClientDiagnostics.CreateScope("LogsSiteConfig.Get");
scope.Start();
try
{
var response = _logsSiteConfigWebAppsRestClient.GetDiagnosticLogsConfiguration(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new LogsSiteConfig(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Updates the logging configuration of an app.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/logs
/// Operation Id: WebApps_UpdateDiagnosticLogsConfig
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="siteLogsConfig"> A SiteLogsConfig JSON object that contains the logging configuration to change in the "properties" property. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="siteLogsConfig"/> is null. </exception>
public virtual async Task<ArmOperation<LogsSiteConfig>> CreateOrUpdateAsync(WaitUntil waitUntil, SiteLogsConfigData siteLogsConfig, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(siteLogsConfig, nameof(siteLogsConfig));
using var scope = _logsSiteConfigWebAppsClientDiagnostics.CreateScope("LogsSiteConfig.CreateOrUpdate");
scope.Start();
try
{
var response = await _logsSiteConfigWebAppsRestClient.UpdateDiagnosticLogsConfigAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, siteLogsConfig, cancellationToken).ConfigureAwait(false);
var operation = new AppServiceArmOperation<LogsSiteConfig>(Response.FromValue(new LogsSiteConfig(Client, response), response.GetRawResponse()));
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Description for Updates the logging configuration of an app.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/logs
/// Operation Id: WebApps_UpdateDiagnosticLogsConfig
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="siteLogsConfig"> A SiteLogsConfig JSON object that contains the logging configuration to change in the "properties" property. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="siteLogsConfig"/> is null. </exception>
public virtual ArmOperation<LogsSiteConfig> CreateOrUpdate(WaitUntil waitUntil, SiteLogsConfigData siteLogsConfig, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(siteLogsConfig, nameof(siteLogsConfig));
using var scope = _logsSiteConfigWebAppsClientDiagnostics.CreateScope("LogsSiteConfig.CreateOrUpdate");
scope.Start();
try
{
var response = _logsSiteConfigWebAppsRestClient.UpdateDiagnosticLogsConfig(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, siteLogsConfig, cancellationToken);
var operation = new AppServiceArmOperation<LogsSiteConfig>(Response.FromValue(new LogsSiteConfig(Client, response), response.GetRawResponse()));
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 56.443299 | 480 | 0.676073 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/websites/Azure.ResourceManager.AppService/src/Generated/LogsSiteConfig.cs | 10,950 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2020 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:[email protected]
//------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
namespace GameFramework.FileSystem
{
/// <summary>
/// 文件系统。
/// </summary>
internal sealed partial class FileSystem : IFileSystem
{
private const int ClusterSize = 1024 * 4;
private const int CachedBytesLength = 0x1000;
private static readonly string[] EmptyStringArray = new string[] { };
private static readonly byte[] s_CachedBytes = new byte[CachedBytesLength];
private static readonly int HeaderDataSize = Marshal.SizeOf(typeof(HeaderData));
private static readonly int BlockDataSize = Marshal.SizeOf(typeof(BlockData));
private static readonly int StringDataSize = Marshal.SizeOf(typeof(StringData));
private readonly string m_FullPath;
private readonly FileSystemAccess m_Access;
private readonly FileSystemStream m_Stream;
private readonly Dictionary<string, int> m_FileDatas;
private readonly List<BlockData> m_BlockDatas;
private readonly GameFrameworkMultiDictionary<int, int> m_FreeBlockIndexes;
private readonly SortedDictionary<int, StringData> m_StringDatas;
private readonly Queue<KeyValuePair<int, StringData>> m_FreeStringDatas;
private HeaderData m_HeaderData;
private int m_BlockDataOffset;
private int m_StringDataOffset;
private int m_FileDataOffset;
/// <summary>
/// 初始化文件系统的新实例。
/// </summary>
/// <param name="fullPath">文件系统完整路径。</param>
/// <param name="access">文件系统访问方式。</param>
/// <param name="stream">文件系统流。</param>
private FileSystem(string fullPath, FileSystemAccess access, FileSystemStream stream)
{
if (string.IsNullOrEmpty(fullPath))
{
throw new GameFrameworkException("Full path is invalid.");
}
if (access == FileSystemAccess.Unspecified)
{
throw new GameFrameworkException("Access is invalid.");
}
if (stream == null)
{
throw new GameFrameworkException("Stream is invalid.");
}
m_FullPath = fullPath;
m_Access = access;
m_Stream = stream;
m_FileDatas = new Dictionary<string, int>(StringComparer.Ordinal);
m_BlockDatas = new List<BlockData>();
m_FreeBlockIndexes = new GameFrameworkMultiDictionary<int, int>();
m_StringDatas = new SortedDictionary<int, StringData>();
m_FreeStringDatas = new Queue<KeyValuePair<int, StringData>>();
m_HeaderData = default(HeaderData);
m_BlockDataOffset = 0;
m_StringDataOffset = 0;
m_FileDataOffset = 0;
Utility.Marshal.EnsureCachedHGlobalSize(CachedBytesLength);
}
/// <summary>
/// 获取文件系统完整路径。
/// </summary>
public string FullPath
{
get
{
return m_FullPath;
}
}
/// <summary>
/// 获取文件系统访问方式。
/// </summary>
public FileSystemAccess Access
{
get
{
return m_Access;
}
}
/// <summary>
/// 获取文件数量。
/// </summary>
public int FileCount
{
get
{
return m_FileDatas.Count;
}
}
/// <summary>
/// 获取最大文件数量。
/// </summary>
public int MaxFileCount
{
get
{
return m_HeaderData.MaxFileCount;
}
}
/// <summary>
/// 创建文件系统。
/// </summary>
/// <param name="fullPath">要创建的文件系统的完整路径。</param>
/// <param name="access">要创建的文件系统的访问方式。</param>
/// <param name="stream">要创建的文件系统的文件系统流。</param>
/// <param name="maxFileCount">要创建的文件系统的最大文件数量。</param>
/// <param name="maxBlockCount">要创建的文件系统的最大块数据数量。</param>
/// <returns>创建的文件系统。</returns>
public static FileSystem Create(string fullPath, FileSystemAccess access, FileSystemStream stream, int maxFileCount, int maxBlockCount)
{
if (maxFileCount <= 0)
{
throw new GameFrameworkException("Max file count is invalid.");
}
if (maxBlockCount <= 0)
{
throw new GameFrameworkException("Max block count is invalid.");
}
if (maxFileCount > maxBlockCount)
{
throw new GameFrameworkException("Max file count can not larger than max block count.");
}
FileSystem fileSystem = new FileSystem(fullPath, access, stream);
fileSystem.m_HeaderData = new HeaderData(maxFileCount, maxBlockCount);
CalcOffsets(fileSystem);
Utility.Marshal.StructureToBytes(fileSystem.m_HeaderData, HeaderDataSize, s_CachedBytes);
try
{
stream.Write(s_CachedBytes, 0, HeaderDataSize);
stream.SetLength(fileSystem.m_FileDataOffset);
return fileSystem;
}
catch
{
fileSystem.Shutdown();
return null;
}
}
/// <summary>
/// 加载文件系统。
/// </summary>
/// <param name="fullPath">要加载的文件系统的完整路径。</param>
/// <param name="access">要加载的文件系统的访问方式。</param>
/// <param name="stream">要加载的文件系统的文件系统流。</param>
/// <returns>加载的文件系统。</returns>
public static FileSystem Load(string fullPath, FileSystemAccess access, FileSystemStream stream)
{
FileSystem fileSystem = new FileSystem(fullPath, access, stream);
stream.Read(s_CachedBytes, 0, HeaderDataSize);
fileSystem.m_HeaderData = Utility.Marshal.BytesToStructure<HeaderData>(HeaderDataSize, s_CachedBytes);
CalcOffsets(fileSystem);
if (fileSystem.m_BlockDatas.Capacity < fileSystem.m_HeaderData.BlockCount)
{
fileSystem.m_BlockDatas.Capacity = fileSystem.m_HeaderData.BlockCount;
}
for (int i = 0; i < fileSystem.m_HeaderData.BlockCount; i++)
{
stream.Read(s_CachedBytes, 0, BlockDataSize);
BlockData blockData = Utility.Marshal.BytesToStructure<BlockData>(BlockDataSize, s_CachedBytes);
fileSystem.m_BlockDatas.Add(blockData);
}
for (int i = 0; i < fileSystem.m_BlockDatas.Count; i++)
{
BlockData blockData = fileSystem.m_BlockDatas[i];
if (blockData.Using)
{
StringData stringData = fileSystem.ReadStringData(blockData.StringIndex);
fileSystem.m_StringDatas.Add(blockData.StringIndex, stringData);
fileSystem.m_FileDatas.Add(stringData.GetString(fileSystem.m_HeaderData.GetEncryptBytes()), i);
}
else
{
fileSystem.m_FreeBlockIndexes.Add(blockData.Length, i);
}
}
return fileSystem;
}
/// <summary>
/// 关闭并清理文件系统。
/// </summary>
public void Shutdown()
{
m_Stream.Close();
m_FileDatas.Clear();
m_BlockDatas.Clear();
m_FreeBlockIndexes.Clear();
m_StringDatas.Clear();
m_FreeStringDatas.Clear();
m_BlockDataOffset = 0;
m_StringDataOffset = 0;
m_FileDataOffset = 0;
}
/// <summary>
/// 获取文件信息。
/// </summary>
/// <param name="name">要获取文件信息的文件名称。</param>
/// <returns>获取的文件信息。</returns>
public FileInfo GetFileInfo(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
int blockIndex = 0;
if (!m_FileDatas.TryGetValue(name, out blockIndex))
{
return default(FileInfo);
}
BlockData blockData = m_BlockDatas[blockIndex];
return new FileInfo(name, GetClusterOffset(blockData.ClusterIndex), blockData.Length);
}
/// <summary>
/// 获取所有文件信息。
/// </summary>
/// <returns>获取的所有文件信息。</returns>
public FileInfo[] GetAllFileInfos()
{
int index = 0;
FileInfo[] results = new FileInfo[m_FileDatas.Count];
foreach (KeyValuePair<string, int> fileData in m_FileDatas)
{
BlockData blockData = m_BlockDatas[fileData.Value];
results[index++] = new FileInfo(fileData.Key, GetClusterOffset(blockData.ClusterIndex), blockData.Length);
}
return results;
}
/// <summary>
/// 获取所有文件信息。
/// </summary>
/// <param name="results">获取的所有文件信息。</param>
public void GetAllFileInfos(List<FileInfo> results)
{
if (results == null)
{
throw new GameFrameworkException("Results is invalid.");
}
results.Clear();
foreach (KeyValuePair<string, int> fileData in m_FileDatas)
{
BlockData blockData = m_BlockDatas[fileData.Value];
results.Add(new FileInfo(fileData.Key, GetClusterOffset(blockData.ClusterIndex), blockData.Length));
}
}
/// <summary>
/// 检查是否存在指定文件。
/// </summary>
/// <param name="name">要检查的文件名称。</param>
/// <returns>是否存在指定文件。</returns>
public bool HasFile(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
return m_FileDatas.ContainsKey(name);
}
/// <summary>
/// 读取指定文件。
/// </summary>
/// <param name="name">要读取的文件名称。</param>
/// <returns>存储读取文件内容的二进制流。</returns>
public byte[] ReadFile(string name)
{
if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not readable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
FileInfo fileInfo = GetFileInfo(name);
if (!fileInfo.IsValid)
{
return null;
}
int length = fileInfo.Length;
byte[] buffer = new byte[length];
if (length > 0)
{
m_Stream.Position = fileInfo.Offset;
m_Stream.Read(buffer, 0, length);
}
return buffer;
}
/// <summary>
/// 读取指定文件。
/// </summary>
/// <param name="name">要读取的文件名称。</param>
/// <param name="buffer">存储读取文件内容的二进制流。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFile(string name, byte[] buffer)
{
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
return ReadFile(name, buffer, 0, buffer.Length);
}
/// <summary>
/// 读取指定文件。
/// </summary>
/// <param name="name">要读取的文件名称。</param>
/// <param name="buffer">存储读取文件内容的二进制流。</param>
/// <param name="startIndex">存储读取文件内容的二进制流的起始位置。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFile(string name, byte[] buffer, int startIndex)
{
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
return ReadFile(name, buffer, startIndex, buffer.Length - startIndex);
}
/// <summary>
/// 读取指定文件。
/// </summary>
/// <param name="name">要读取的文件名称。</param>
/// <param name="buffer">存储读取文件内容的二进制流。</param>
/// <param name="startIndex">存储读取文件内容的二进制流的起始位置。</param>
/// <param name="length">存储读取文件内容的二进制流的长度。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFile(string name, byte[] buffer, int startIndex, int length)
{
if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not readable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
if (startIndex < 0 || length < 0 || startIndex + length > buffer.Length)
{
throw new GameFrameworkException("Start index or length is invalid.");
}
FileInfo fileInfo = GetFileInfo(name);
if (!fileInfo.IsValid)
{
return 0;
}
m_Stream.Position = fileInfo.Offset;
if (length > fileInfo.Length)
{
length = fileInfo.Length;
}
if (length > 0)
{
return m_Stream.Read(buffer, startIndex, length);
}
return 0;
}
/// <summary>
/// 读取指定文件。
/// </summary>
/// <param name="name">要读取的文件名称。</param>
/// <param name="stream">存储读取文件内容的二进制流。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFile(string name, Stream stream)
{
if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not readable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
if (stream == null)
{
throw new GameFrameworkException("Stream is invalid.");
}
if (!stream.CanWrite)
{
throw new GameFrameworkException("Stream is not writable.");
}
FileInfo fileInfo = GetFileInfo(name);
if (!fileInfo.IsValid)
{
return 0;
}
int length = fileInfo.Length;
if (length > 0)
{
m_Stream.Position = fileInfo.Offset;
return m_Stream.Read(stream, length);
}
return 0;
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="length">要读取片段的长度。</param>
/// <returns>存储读取文件片段内容的二进制流。</returns>
public byte[] ReadFileSegment(string name, int length)
{
return ReadFileSegment(name, 0, length);
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="offset">要读取片段的偏移。</param>
/// <param name="length">要读取片段的长度。</param>
/// <returns>存储读取文件片段内容的二进制流。</returns>
public byte[] ReadFileSegment(string name, int offset, int length)
{
if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not readable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
if (offset < 0)
{
throw new GameFrameworkException("Index is invalid.");
}
if (length < 0)
{
throw new GameFrameworkException("Length is invalid.");
}
FileInfo fileInfo = GetFileInfo(name);
if (!fileInfo.IsValid)
{
return null;
}
if (offset > fileInfo.Length)
{
offset = fileInfo.Length;
}
int leftLength = fileInfo.Length - offset;
if (length > leftLength)
{
length = leftLength;
}
byte[] buffer = new byte[length];
if (length > 0)
{
m_Stream.Position = fileInfo.Offset + offset;
m_Stream.Read(buffer, 0, length);
}
return buffer;
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="buffer">存储读取文件片段内容的二进制流。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFileSegment(string name, byte[] buffer)
{
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
return ReadFileSegment(name, 0, buffer, 0, buffer.Length);
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="buffer">存储读取文件片段内容的二进制流。</param>
/// <param name="length">要读取片段的长度。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFileSegment(string name, byte[] buffer, int length)
{
return ReadFileSegment(name, 0, buffer, 0, length);
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="buffer">存储读取文件片段内容的二进制流。</param>
/// <param name="startIndex">存储读取文件片段内容的二进制流的起始位置。</param>
/// <param name="length">要读取片段的长度。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFileSegment(string name, byte[] buffer, int startIndex, int length)
{
return ReadFileSegment(name, 0, buffer, startIndex, length);
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="offset">要读取片段的偏移。</param>
/// <param name="buffer">存储读取文件片段内容的二进制流。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFileSegment(string name, int offset, byte[] buffer)
{
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
return ReadFileSegment(name, offset, buffer, 0, buffer.Length);
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="offset">要读取片段的偏移。</param>
/// <param name="buffer">存储读取文件片段内容的二进制流。</param>
/// <param name="length">要读取片段的长度。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFileSegment(string name, int offset, byte[] buffer, int length)
{
return ReadFileSegment(name, offset, buffer, 0, length);
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="offset">要读取片段的偏移。</param>
/// <param name="buffer">存储读取文件片段内容的二进制流。</param>
/// <param name="startIndex">存储读取文件片段内容的二进制流的起始位置。</param>
/// <param name="length">要读取片段的长度。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFileSegment(string name, int offset, byte[] buffer, int startIndex, int length)
{
if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not readable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
if (offset < 0)
{
throw new GameFrameworkException("Index is invalid.");
}
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
if (startIndex < 0 || length < 0 || startIndex + length > buffer.Length)
{
throw new GameFrameworkException("Start index or length is invalid.");
}
FileInfo fileInfo = GetFileInfo(name);
if (!fileInfo.IsValid)
{
return 0;
}
if (offset > fileInfo.Length)
{
offset = fileInfo.Length;
}
int leftLength = fileInfo.Length - offset;
if (length > leftLength)
{
length = leftLength;
}
if (length > 0)
{
m_Stream.Position = fileInfo.Offset + offset;
return m_Stream.Read(buffer, startIndex, length);
}
return 0;
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="stream">存储读取文件片段内容的二进制流。</param>
/// <param name="length">要读取片段的长度。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFileSegment(string name, Stream stream, int length)
{
return ReadFileSegment(name, 0, stream, length);
}
/// <summary>
/// 读取指定文件的指定片段。
/// </summary>
/// <param name="name">要读取片段的文件名称。</param>
/// <param name="offset">要读取片段的偏移。</param>
/// <param name="stream">存储读取文件片段内容的二进制流。</param>
/// <param name="length">要读取片段的长度。</param>
/// <returns>实际读取了多少字节。</returns>
public int ReadFileSegment(string name, int offset, Stream stream, int length)
{
if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not readable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
if (offset < 0)
{
throw new GameFrameworkException("Index is invalid.");
}
if (stream == null)
{
throw new GameFrameworkException("Stream is invalid.");
}
if (!stream.CanWrite)
{
throw new GameFrameworkException("Stream is not writable.");
}
if (length < 0)
{
throw new GameFrameworkException("Length is invalid.");
}
FileInfo fileInfo = GetFileInfo(name);
if (!fileInfo.IsValid)
{
return 0;
}
if (offset > fileInfo.Length)
{
offset = fileInfo.Length;
}
int leftLength = fileInfo.Length - offset;
if (length > leftLength)
{
length = leftLength;
}
if (length > 0)
{
m_Stream.Position = fileInfo.Offset + offset;
return m_Stream.Read(stream, length);
}
return 0;
}
/// <summary>
/// 写入指定文件。
/// </summary>
/// <param name="name">要写入的文件名称。</param>
/// <param name="buffer">存储写入文件内容的二进制流。</param>
/// <returns>是否写入指定文件成功。</returns>
public bool WriteFile(string name, byte[] buffer)
{
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
return WriteFile(name, buffer, 0, buffer.Length);
}
/// <summary>
/// 写入指定文件。
/// </summary>
/// <param name="name">要写入的文件名称。</param>
/// <param name="buffer">存储写入文件内容的二进制流。</param>
/// <param name="startIndex">存储写入文件内容的二进制流的起始位置。</param>
/// <returns>是否写入指定文件成功。</returns>
public bool WriteFile(string name, byte[] buffer, int startIndex)
{
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
return WriteFile(name, buffer, startIndex, buffer.Length - startIndex);
}
/// <summary>
/// 写入指定文件。
/// </summary>
/// <param name="name">要写入的文件名称。</param>
/// <param name="buffer">存储写入文件内容的二进制流。</param>
/// <param name="startIndex">存储写入文件内容的二进制流的起始位置。</param>
/// <param name="length">存储写入文件内容的二进制流的长度。</param>
/// <returns>是否写入指定文件成功。</returns>
public bool WriteFile(string name, byte[] buffer, int startIndex, int length)
{
if (m_Access != FileSystemAccess.Write && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not writable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
if (name.Length > byte.MaxValue)
{
throw new GameFrameworkException(Utility.Text.Format("Name '{0}' is too long.", name));
}
if (buffer == null)
{
throw new GameFrameworkException("Buffer is invalid.");
}
if (startIndex < 0 || length < 0 || startIndex + length > buffer.Length)
{
throw new GameFrameworkException("Start index or length is invalid.");
}
bool hasFile = false;
int oldBlockIndex = -1;
if (m_FileDatas.TryGetValue(name, out oldBlockIndex))
{
hasFile = true;
}
if (!hasFile && m_FileDatas.Count >= m_HeaderData.MaxFileCount)
{
return false;
}
int blockIndex = AllocBlock(length);
if (blockIndex < 0)
{
return false;
}
if (length > 0)
{
m_Stream.Position = GetClusterOffset(m_BlockDatas[blockIndex].ClusterIndex);
m_Stream.Write(buffer, startIndex, length);
}
ProcessWriteFile(name, hasFile, oldBlockIndex, blockIndex, length);
m_Stream.Flush();
return true;
}
/// <summary>
/// 写入指定文件。
/// </summary>
/// <param name="name">要写入的文件名称。</param>
/// <param name="stream">存储写入文件内容的二进制流。</param>
/// <returns>是否写入指定文件成功。</returns>
public bool WriteFile(string name, Stream stream)
{
if (m_Access != FileSystemAccess.Write && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not writable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
if (name.Length > byte.MaxValue)
{
throw new GameFrameworkException(Utility.Text.Format("Name '{0}' is too long.", name));
}
if (stream == null)
{
throw new GameFrameworkException("Stream is invalid.");
}
if (!stream.CanRead)
{
throw new GameFrameworkException("Stream is not readable.");
}
bool hasFile = false;
int oldBlockIndex = -1;
if (m_FileDatas.TryGetValue(name, out oldBlockIndex))
{
hasFile = true;
}
if (!hasFile && m_FileDatas.Count >= m_HeaderData.MaxFileCount)
{
return false;
}
int length = (int)(stream.Length - stream.Position);
int blockIndex = AllocBlock(length);
if (blockIndex < 0)
{
return false;
}
if (length > 0)
{
m_Stream.Position = GetClusterOffset(m_BlockDatas[blockIndex].ClusterIndex);
m_Stream.Write(stream, length);
}
ProcessWriteFile(name, hasFile, oldBlockIndex, blockIndex, length);
m_Stream.Flush();
return true;
}
/// <summary>
/// 写入指定文件。
/// </summary>
/// <param name="name">要写入的文件名称。</param>
/// <param name="filePath">存储写入文件内容的文件路径。</param>
/// <returns>是否写入指定文件成功。</returns>
public bool WriteFile(string name, string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new GameFrameworkException("File path is invalid");
}
if (!File.Exists(filePath))
{
return false;
}
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return WriteFile(name, fileStream);
}
}
/// <summary>
/// 将指定文件另存为物理文件。
/// </summary>
/// <param name="name">要另存为的文件名称。</param>
/// <param name="filePath">存储写入文件内容的文件路径。</param>
/// <returns>是否将指定文件另存为物理文件成功。</returns>
public bool SaveAsFile(string name, string filePath)
{
if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not readable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
if (string.IsNullOrEmpty(filePath))
{
throw new GameFrameworkException("File path is invalid");
}
FileInfo fileInfo = GetFileInfo(name);
if (!fileInfo.IsValid)
{
return false;
}
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
string directory = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
int length = fileInfo.Length;
if (length > 0)
{
m_Stream.Position = fileInfo.Offset;
return m_Stream.Read(fileStream, length) == length;
}
return true;
}
}
catch
{
return false;
}
}
/// <summary>
/// 重命名指定文件。
/// </summary>
/// <param name="oldName">要重命名的文件名称。</param>
/// <param name="newName">重命名后的文件名称。</param>
/// <returns>是否重命名指定文件成功。</returns>
public bool RenameFile(string oldName, string newName)
{
if (m_Access != FileSystemAccess.Write && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not writable.");
}
if (string.IsNullOrEmpty(oldName))
{
throw new GameFrameworkException("Old name is invalid.");
}
if (string.IsNullOrEmpty(newName))
{
throw new GameFrameworkException("New name is invalid.");
}
if (newName.Length > byte.MaxValue)
{
throw new GameFrameworkException(Utility.Text.Format("New name '{0}' is too long.", newName));
}
if (oldName == newName)
{
return true;
}
if (m_FileDatas.ContainsKey(newName))
{
return false;
}
int blockIndex = 0;
if (!m_FileDatas.TryGetValue(oldName, out blockIndex))
{
return false;
}
int stringIndex = m_BlockDatas[blockIndex].StringIndex;
StringData stringData = m_StringDatas[stringIndex].SetString(newName, m_HeaderData.GetEncryptBytes());
m_StringDatas[stringIndex] = stringData;
WriteStringData(stringIndex, stringData);
m_FileDatas.Add(newName, blockIndex);
m_FileDatas.Remove(oldName);
m_Stream.Flush();
return true;
}
/// <summary>
/// 删除指定文件。
/// </summary>
/// <param name="name">要删除的文件名称。</param>
/// <returns>是否删除指定文件成功。</returns>
public bool DeleteFile(string name)
{
if (m_Access != FileSystemAccess.Write && m_Access != FileSystemAccess.ReadWrite)
{
throw new GameFrameworkException("File system is not writable.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Name is invalid.");
}
int blockIndex = 0;
if (!m_FileDatas.TryGetValue(name, out blockIndex))
{
return false;
}
m_FileDatas.Remove(name);
BlockData blockData = m_BlockDatas[blockIndex];
int stringIndex = blockData.StringIndex;
StringData stringData = m_StringDatas[stringIndex].Clear();
m_FreeStringDatas.Enqueue(new KeyValuePair<int, StringData>(stringIndex, stringData));
m_StringDatas.Remove(stringIndex);
WriteStringData(stringIndex, stringData);
blockData = blockData.Free();
m_BlockDatas[blockIndex] = blockData;
if (!TryCombineFreeBlocks(blockIndex))
{
m_FreeBlockIndexes.Add(blockData.Length, blockIndex);
WriteBlockData(blockIndex);
}
m_Stream.Flush();
return true;
}
private void ProcessWriteFile(string name, bool hasFile, int oldBlockIndex, int blockIndex, int length)
{
BlockData blockData = m_BlockDatas[blockIndex];
if (hasFile)
{
BlockData oldBlockData = m_BlockDatas[oldBlockIndex];
blockData = new BlockData(oldBlockData.StringIndex, blockData.ClusterIndex, length);
m_BlockDatas[blockIndex] = blockData;
WriteBlockData(blockIndex);
oldBlockData = oldBlockData.Free();
m_BlockDatas[oldBlockIndex] = oldBlockData;
if (!TryCombineFreeBlocks(oldBlockIndex))
{
m_FreeBlockIndexes.Add(oldBlockData.Length, oldBlockIndex);
WriteBlockData(oldBlockIndex);
}
}
else
{
int stringIndex = AllocString(name);
blockData = new BlockData(stringIndex, blockData.ClusterIndex, length);
m_BlockDatas[blockIndex] = blockData;
WriteBlockData(blockIndex);
}
if (hasFile)
{
m_FileDatas[name] = blockIndex;
}
else
{
m_FileDatas.Add(name, blockIndex);
}
}
private bool TryCombineFreeBlocks(int freeBlockIndex)
{
BlockData freeBlockData = m_BlockDatas[freeBlockIndex];
if (freeBlockData.Length <= 0)
{
return false;
}
int previousFreeBlockIndex = -1;
int nextFreeBlockIndex = -1;
int nextBlockDataClusterIndex = freeBlockData.ClusterIndex + GetUpBoundClusterCount(freeBlockData.Length);
foreach (KeyValuePair<int, GameFrameworkLinkedListRange<int>> blockIndexes in m_FreeBlockIndexes)
{
if (blockIndexes.Key <= 0)
{
continue;
}
int blockDataClusterCount = GetUpBoundClusterCount(blockIndexes.Key);
foreach (int blockIndex in blockIndexes.Value)
{
BlockData blockData = m_BlockDatas[blockIndex];
if (blockData.ClusterIndex + blockDataClusterCount == freeBlockData.ClusterIndex)
{
previousFreeBlockIndex = blockIndex;
}
else if (blockData.ClusterIndex == nextBlockDataClusterIndex)
{
nextFreeBlockIndex = blockIndex;
}
}
}
if (previousFreeBlockIndex < 0 && nextFreeBlockIndex < 0)
{
return false;
}
m_FreeBlockIndexes.Remove(freeBlockData.Length, freeBlockIndex);
if (previousFreeBlockIndex >= 0)
{
BlockData previousFreeBlockData = m_BlockDatas[previousFreeBlockIndex];
m_FreeBlockIndexes.Remove(previousFreeBlockData.Length, previousFreeBlockIndex);
freeBlockData = new BlockData(previousFreeBlockData.ClusterIndex, previousFreeBlockData.Length + freeBlockData.Length);
m_BlockDatas[previousFreeBlockIndex] = BlockData.Empty;
m_FreeBlockIndexes.Add(0, previousFreeBlockIndex);
WriteBlockData(previousFreeBlockIndex);
}
if (nextFreeBlockIndex >= 0)
{
BlockData nextFreeBlockData = m_BlockDatas[nextFreeBlockIndex];
m_FreeBlockIndexes.Remove(nextFreeBlockData.Length, nextFreeBlockIndex);
freeBlockData = new BlockData(freeBlockData.ClusterIndex, freeBlockData.Length + nextFreeBlockData.Length);
m_BlockDatas[nextFreeBlockIndex] = BlockData.Empty;
m_FreeBlockIndexes.Add(0, nextFreeBlockIndex);
WriteBlockData(nextFreeBlockIndex);
}
m_BlockDatas[freeBlockIndex] = freeBlockData;
m_FreeBlockIndexes.Add(freeBlockData.Length, freeBlockIndex);
WriteBlockData(freeBlockIndex);
return true;
}
private int GetEmptyBlockIndex()
{
GameFrameworkLinkedListRange<int> lengthRange = default(GameFrameworkLinkedListRange<int>);
if (m_FreeBlockIndexes.TryGetValue(0, out lengthRange))
{
int blockIndex = lengthRange.First.Value;
m_FreeBlockIndexes.Remove(0, blockIndex);
return blockIndex;
}
if (m_BlockDatas.Count < m_HeaderData.MaxBlockCount)
{
int blockIndex = m_BlockDatas.Count;
m_BlockDatas.Add(BlockData.Empty);
WriteHeaderData();
return blockIndex;
}
return -1;
}
private int AllocBlock(int length)
{
if (length <= 0)
{
return GetEmptyBlockIndex();
}
length = (int)GetUpBoundClusterOffset(length);
int lengthFound = -1;
GameFrameworkLinkedListRange<int> lengthRange = default(GameFrameworkLinkedListRange<int>);
foreach (KeyValuePair<int, GameFrameworkLinkedListRange<int>> i in m_FreeBlockIndexes)
{
if (i.Key < length)
{
continue;
}
if (lengthFound >= 0 && lengthFound < i.Key)
{
continue;
}
lengthFound = i.Key;
lengthRange = i.Value;
}
if (lengthFound >= 0)
{
if (lengthFound > length && m_BlockDatas.Count >= m_HeaderData.MaxBlockCount)
{
return -1;
}
int blockIndex = lengthRange.First.Value;
m_FreeBlockIndexes.Remove(lengthFound, blockIndex);
if (lengthFound > length)
{
BlockData blockData = m_BlockDatas[blockIndex];
m_BlockDatas[blockIndex] = new BlockData(blockData.ClusterIndex, length);
WriteBlockData(blockIndex);
int deltaLength = lengthFound - length;
int anotherBlockIndex = GetEmptyBlockIndex();
m_BlockDatas[anotherBlockIndex] = new BlockData(blockData.ClusterIndex + GetUpBoundClusterCount(length), deltaLength);
m_FreeBlockIndexes.Add(deltaLength, anotherBlockIndex);
WriteBlockData(anotherBlockIndex);
}
return blockIndex;
}
else
{
int blockIndex = GetEmptyBlockIndex();
if (blockIndex < 0)
{
return -1;
}
long fileLength = m_Stream.Length;
try
{
m_Stream.SetLength(fileLength + length);
}
catch
{
return -1;
}
m_BlockDatas[blockIndex] = new BlockData(GetUpBoundClusterCount(fileLength), length);
WriteBlockData(blockIndex);
return blockIndex;
}
}
private int AllocString(string value)
{
int stringIndex = -1;
StringData stringData = default(StringData);
if (m_FreeStringDatas.Count > 0)
{
KeyValuePair<int, StringData> freeStringData = m_FreeStringDatas.Dequeue();
stringIndex = freeStringData.Key;
stringData = freeStringData.Value;
}
else
{
int index = 0;
foreach (KeyValuePair<int, StringData> i in m_StringDatas)
{
if (i.Key == index)
{
index++;
continue;
}
break;
}
if (index < m_HeaderData.MaxFileCount)
{
stringIndex = index;
byte[] bytes = new byte[byte.MaxValue];
Utility.Random.GetRandomBytes(bytes);
stringData = new StringData(0, bytes);
}
}
if (stringIndex < 0)
{
throw new GameFrameworkException("Alloc string internal error.");
}
stringData = stringData.SetString(value, m_HeaderData.GetEncryptBytes());
m_StringDatas.Add(stringIndex, stringData);
WriteStringData(stringIndex, stringData);
return stringIndex;
}
private void WriteHeaderData()
{
m_HeaderData = m_HeaderData.SetBlockCount(m_BlockDatas.Count);
Utility.Marshal.StructureToBytes(m_HeaderData, HeaderDataSize, s_CachedBytes);
m_Stream.Position = 0L;
m_Stream.Write(s_CachedBytes, 0, HeaderDataSize);
}
private void WriteBlockData(int blockIndex)
{
Utility.Marshal.StructureToBytes(m_BlockDatas[blockIndex], BlockDataSize, s_CachedBytes);
m_Stream.Position = m_BlockDataOffset + BlockDataSize * blockIndex;
m_Stream.Write(s_CachedBytes, 0, BlockDataSize);
}
private StringData ReadStringData(int stringIndex)
{
m_Stream.Position = m_StringDataOffset + StringDataSize * stringIndex;
m_Stream.Read(s_CachedBytes, 0, StringDataSize);
return Utility.Marshal.BytesToStructure<StringData>(StringDataSize, s_CachedBytes);
}
private void WriteStringData(int stringIndex, StringData stringData)
{
Utility.Marshal.StructureToBytes(stringData, StringDataSize, s_CachedBytes);
m_Stream.Position = m_StringDataOffset + StringDataSize * stringIndex;
m_Stream.Write(s_CachedBytes, 0, StringDataSize);
}
private static void CalcOffsets(FileSystem fileSystem)
{
fileSystem.m_BlockDataOffset = HeaderDataSize;
fileSystem.m_StringDataOffset = fileSystem.m_BlockDataOffset + BlockDataSize * fileSystem.m_HeaderData.MaxBlockCount;
fileSystem.m_FileDataOffset = (int)GetUpBoundClusterOffset(fileSystem.m_StringDataOffset + StringDataSize * fileSystem.m_HeaderData.MaxFileCount);
}
private static long GetUpBoundClusterOffset(long offset)
{
return (offset - 1L + ClusterSize) / ClusterSize * ClusterSize;
}
private static int GetUpBoundClusterCount(long length)
{
return (int)((length - 1L + ClusterSize) / ClusterSize);
}
private static long GetClusterOffset(int clusterIndex)
{
return (long)ClusterSize * clusterIndex;
}
}
}
| 33.453362 | 158 | 0.519561 | [
"MIT"
] | 297496732/GameFramework | GameFramework/FileSystem/FileSystem.cs | 49,445 | C# |
using System;
using AutoBogus;
using Bogus;
using FluentAssertions;
using Moq;
using SlothEnterprise.External;
using SlothEnterprise.External.V1;
using SlothEnterprise.ProductApplication.Applications;
using SlothEnterprise.ProductApplication.Handlers;
using SlothEnterprise.ProductApplication.Products;
using Xunit;
namespace SlothEnterprise.ProductApplication.Tests.Handlers
{
public class ConfidentialInvoiceApplicationHandlerTests
{
private readonly Mock<IConfidentialInvoiceService> _confidentialInvoiceServiceMock;
// Fake data generators
private readonly Faker<SellerApplication> _sellerApplicationFaker;
public ConfidentialInvoiceApplicationHandlerTests()
{
_confidentialInvoiceServiceMock = new Mock<IConfidentialInvoiceService>();
var cidFaker = new AutoFaker<ConfidentialInvoiceDiscount>();
var companyDataFaker = new AutoFaker<SellerCompanyData>();
_sellerApplicationFaker = new AutoFaker<SellerApplication>()
.RuleFor(l => l.Product, () => cidFaker.Generate())
.RuleFor(l => l.CompanyData, () => companyDataFaker.Generate());
}
[Fact]
public void SubmitApplicationFor_ProductIsNotSupported_ThrowsInvalidOperationException()
{
var handler = new ConfidentialInvoiceApplicationHandler(_confidentialInvoiceServiceMock.Object);
var sellerApplicationMock = new Mock<ISellerApplication>();
var nonExistentProductMock = new Mock<IProduct>();
sellerApplicationMock.SetupProperty(p => p.Product, nonExistentProductMock.Object);
Func<int> act = () => handler.SubmitApplicationFor(sellerApplicationMock.Object);
act.Should().Throw<InvalidOperationException>();
}
[Fact]
public void SubmitApplicationFor_SubmitSuccessful_ReturnsApplicationId()
{
var handler = new ConfidentialInvoiceApplicationHandler(_confidentialInvoiceServiceMock.Object);
var sellerApplication = _sellerApplicationFaker.Generate();
var cid = (ConfidentialInvoiceDiscount) sellerApplication.Product;
var applicationId = AutoFaker.Generate<int>();
var applicationResultMock = new Mock<IApplicationResult>();
applicationResultMock.SetupProperty(r => r.Success, true);
applicationResultMock.SetupProperty(r => r.ApplicationId, applicationId);
_confidentialInvoiceServiceMock
.Setup(m => m.SubmitApplicationFor(
It.Is<CompanyDataRequest>(
req => req.CompanyNumber == sellerApplication.CompanyData.Number),
cid.TotalLedgerNetworth, cid.AdvancePercentage, cid.VatRate))
.Returns(applicationResultMock.Object);
var result = handler.SubmitApplicationFor(sellerApplication);
result.Should().Be(applicationId);
}
[Fact]
public void SubmitApplicationFor_SubmitFailed_ReturnsNegativeValue()
{
var handler = new ConfidentialInvoiceApplicationHandler(_confidentialInvoiceServiceMock.Object);
var sellerApplication = _sellerApplicationFaker.Generate();
var cid = (ConfidentialInvoiceDiscount) sellerApplication.Product;
var applicationResultMock = new Mock<IApplicationResult>();
applicationResultMock.SetupProperty(r => r.Success, false);
_confidentialInvoiceServiceMock
.Setup(m => m.SubmitApplicationFor(
It.Is<CompanyDataRequest>(
req => req.CompanyNumber == sellerApplication.CompanyData.Number),
cid.TotalLedgerNetworth, cid.AdvancePercentage, cid.VatRate))
.Returns(applicationResultMock.Object);
var result = handler.SubmitApplicationFor(sellerApplication);
result.Should().Be(-1);
}
}
} | 46.91954 | 108 | 0.666585 | [
"MIT"
] | jarto666/code-test-backend | SlothEnterprise.ProductApplication.Tests/Handlers/ConfidentialInvoiceApplicationHandlerTests.cs | 4,082 | C# |
using System;
using System.Reflection;
using AutoFixture.Kernel;
using NSubstitute;
using Xunit;
namespace AutoFixture.AutoNSubstitute.UnitTest
{
public class SubstituteRequestHandlerTest
{
[Fact]
public void ClassImplementsISpecimenBuilderToServeAsFixtureCustomization()
{
// Arrange
// Act
// Assert
Assert.True(typeof(ISpecimenBuilder).IsAssignableFrom(typeof(SubstituteRequestHandler)));
}
[Fact]
public void ConstructorThrowsArgumentNullExceptionWhenSubstituteConstructorIsNull()
{
// Arrange
// Act
var e = Assert.Throws<ArgumentNullException>(() => new SubstituteRequestHandler((ISpecimenBuilder)null));
// Assert
Assert.Equal("substituteFactory", e.ParamName);
}
[Fact]
public void SubstituteConstructorReturnsValueSpecifiedInConstructorToEnableTestingOfCustomizations()
{
// Arrange
var substituteConstructor = Substitute.For<ISpecimenBuilder>();
// Act
var sut = new SubstituteRequestHandler(substituteConstructor);
// Assert
Assert.Same(substituteConstructor, sut.SubstituteFactory);
}
[Fact]
public void CreateReturnsNoSpecimenWhenRequestIsNotAnExplicitSubstituteRequest()
{
// Arrange
var constructor = Substitute.For<ISpecimenBuilder>();
var sut = new SubstituteRequestHandler(constructor);
var request = typeof(IComparable);
var context = Substitute.For<ISpecimenContext>();
// Act
object result = sut.Create(request, context);
// Assert
var expected = new NoSpecimen();
Assert.Equal(expected, result);
}
[Fact]
public void CreatePassesRequestedSubstituteTypeAndSpecimenContextToSubstituteConstructorAndReturnsInstanceItCreates()
{
// Arrange
var context = Substitute.For<ISpecimenContext>();
Type targetType = typeof(IComparable);
var constructedSubstute = Substitute.For(new[] { targetType}, new object[0]);
var constructor = Substitute.For<ISpecimenBuilder>();
constructor.Create(targetType, context).Returns(constructedSubstute);
var sut = new SubstituteRequestHandler(constructor);
var request = new SubstituteRequest(targetType);
// Act
object result = sut.Create(request, context);
// Assert
Assert.Same(constructedSubstute, result);
}
}
}
| 36.27027 | 125 | 0.624441 | [
"MIT"
] | damian-krychowski/AutoFixture | Src/AutoNSubstituteUnitTest/SubstituteRequestHandlerTest.cs | 2,686 | C# |
using System.Linq;
using System.Threading.Tasks;
using Autofac.Extras.NLog;
using Wiz.Gringotts.UIWeb.Tests.Helpers;
using Wiz.Gringotts.UIWeb.Infrastructure.Multitenancy;
using Wiz.Gringotts.UIWeb.Models;
using Wiz.Gringotts.UIWeb.Models.Clients;
using Wiz.Gringotts.UIWeb.Models.Organizations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
namespace Wiz.Gringotts.UIWeb.Tests.Models.Clients
{
[TestClass]
public class ClientEditorFormQueryHandlerTests
{
private ILookup<ClientIdentifierType> identifierTypes;
private ClientEditorFormQueryHandler handler;
private ITenantOrganizationProvider tenantOrganizationProvider;
private ISearch<Client> clients;
[TestInitialize]
public void Init()
{
identifierTypes = Substitute.For<ILookup<ClientIdentifierType>>();
clients = Substitute.For<ISearch<Client>>();
tenantOrganizationProvider = Substitute.For<ITenantOrganizationProvider>();
handler = new ClientEditorFormQueryHandler(clients, identifierTypes, tenantOrganizationProvider)
{
Logger = Substitute.For<ILogger>()
};
}
[TestMethod]
public async Task Can_get_form()
{
var identifierTypes = new[] { new ClientIdentifierType{Id =1, Name = "foo"} };
var query = new ClientEditorFormQuery();
this.identifierTypes.All.Returns(identifierTypes.AsEnumerable());
var result = await handler.Handle(query);
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(ClientEditorForm));
Assert.IsNull(result.ClientId);
}
[TestMethod]
public async Task Can_get_form_for_client()
{
var organization = new Organization {Id = 1};
var clientId = 42;
var identifierTypes = new[] {new ClientIdentifierType {Id = 1, Name = "foo"}};
var client = new Client
{
Id = clientId,
Identifiers = new[]
{
new ClientIdentifier {ClientIdentifierType = identifierTypes.First()}
}
};
client.AddResidency(organization);
var query = new ClientEditorFormQuery(clientId: clientId);
tenantOrganizationProvider.GetTenantOrganization().Returns(organization);
clients.GetById(Arg.Is(clientId)).Returns(new[] {client}.AsAsyncQueryable());
this.identifierTypes.All.Returns(identifierTypes.AsEnumerable());
var result = await handler.Handle(query);
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(ClientEditorForm));
Assert.AreEqual(result.ClientId, client.Id);
}
[TestMethod]
public async Task Can_get_form_for_missing_client()
{
var clientId = 42;
var identifierTypes = new[] { new ClientIdentifierType { Id = 1, Name = "foo" } };
var query = new ClientEditorFormQuery(clientId: clientId);
clients.GetById(Arg.Is(clientId)).Returns(Enumerable.Empty<Client>().AsAsyncQueryable());
this.identifierTypes.All.Returns(identifierTypes.AsEnumerable());
var result = await handler.Handle(query);
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(ClientEditorForm));
handler.Logger.Received().Warn(Arg.Any<string>(), clientId);
}
[TestMethod]
public async Task Missing_identifiertypes_generate_warning()
{
var clientId = 42;
var query = new ClientEditorFormQuery(clientId: clientId);
clients.GetById(Arg.Is(clientId)).Returns(Enumerable.Empty<Client>().AsAsyncQueryable());
identifierTypes.All.Returns(Enumerable.Empty<ClientIdentifierType>().AsEnumerable());
await handler.Handle(query);
handler.Logger.Received().Warn(Arg.Any<string>(), clientId);
}
}
}
| 35.169492 | 108 | 0.630602 | [
"MIT"
] | NotMyself/Gringotts | src/UIWeb.Tests/Models/Clients/ClientEditorFormQueryHandlerTests.cs | 4,152 | C# |
using System;
namespace StackHeap
{
public class Person
{
public int Id { get; set; }
}
class Program
{
static void Main(string[] args)
{
int number = 19;
string text = "some text";
bool isTrue = true;
Person person = new Person() { Id = 1 };
Person person1 = new Person() { Id = 1 };
Console.WriteLine(person == person1);
person.Id = 2;
person.Id = 5;
CreatePerson();
//STACK
//------
// number = 19
// text = some text
// isTrue = true
// person = 1212121546465465 --> place in memory
// person1 = 4654312685432516541 --> place in memory
//HEAP
//------
// Person -- Id = 1
// person1 -- Id = 1
Console.ReadLine();
}
public static void CreatePerson()
{
var person = new Person();
person.Id = 1;
}
}
}
| 21.4 | 64 | 0.42243 | [
"MIT"
] | chris-t-yan/SEDC-Homework | CSharpHomeworks/AdvancedCSharpHomework/Class10.HeapStackDesposingNullables/StackHeap/Program.cs | 1,072 | C# |
namespace PucSp.DesignPatterns.HtmlBuilder.Core
{
public interface IHtmlElement
{
string Tag { get; }
IHtmlElement AddNode(IHtmlElement node);
IHtmlElement AddAttribute(string name, string value);
IHtmlElement AddAttribute(HtmlAttribute attribute);
IHtmlElement RemoveAttribute(string name);
string ToHtml();
}
}
| 25 | 61 | 0.685333 | [
"Apache-2.0"
] | xavierThiago/pucsp | dotnet/src/HtmlBuilder/Core/IHtmlElement.cs | 375 | C# |
namespace Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation.StandardPerfCollector;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation.WebAppPerfCollector;
#if NETSTANDARD2_0
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.Implementation.XPlatform;
#endif
/// <summary>
/// Utility functionality for performance counter collection.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification =
"This class has different code for Net45/NetCore")]
internal static class PerformanceCounterUtility
{
#if NETSTANDARD2_0
public static bool IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#endif
// Internal for testing
internal static bool? isAzureWebApp = null;
private const string Win32ProcessInstancePlaceholder = @"APP_WIN32_PROC";
private const string ClrProcessInstancePlaceholder = @"APP_CLR_PROC";
private const string W3SvcProcessInstancePlaceholder = @"APP_W3SVC_PROC";
private const string Win32ProcessCategoryName = "Process";
private const string ClrProcessCategoryName = ".NET CLR Memory";
private const string Win32ProcessCounterName = "ID Process";
private const string ClrProcessCounterName = "Process ID";
#if NETSTANDARD2_0
private const string StandardSdkVersionPrefix = "pccore:";
#else
private const string StandardSdkVersionPrefix = "pc:";
#endif
private const string AzureWebAppSdkVersionPrefix = "azwapc:";
private const string AzureWebAppCoreSdkVersionPrefix = "azwapccore:";
private const string WebSiteEnvironmentVariable = "WEBSITE_SITE_NAME";
private const string WebSiteIsolationEnvironmentVariable = "WEBSITE_ISOLATION";
private const string WebSiteIsolationHyperV = "hyperv";
private static readonly ConcurrentDictionary<string, Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>> cache = new ConcurrentDictionary<string, Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>>();
private static readonly ConcurrentDictionary<string, string> PlaceholderCache =
new ConcurrentDictionary<string, string>();
private static readonly Regex InstancePlaceholderRegex = new Regex(
@"^\?\?(?<placeholder>[a-zA-Z0-9_]+)\?\?$",
RegexOptions.Compiled);
private static readonly Regex PerformanceCounterRegex =
new Regex(
@"^\\(?<categoryName>[^(]+)(\((?<instanceName>[^)]+)\)){0,1}\\(?<counterName>[\s\S]+)$",
RegexOptions.Compiled);
/// <summary>
/// Formats a counter into a readable string.
/// </summary>
public static string FormatPerformanceCounter(PerformanceCounter pc)
{
return FormatPerformanceCounter(pc.CategoryName, pc.CounterName, pc.InstanceName);
}
public static bool IsPerfCounterSupported()
{
return true;
}
#if NET45
public static IPerformanceCollector GetPerformanceCollector()
{
IPerformanceCollector collector;
if (PerformanceCounterUtility.IsWebAppRunningInAzure())
{
collector = (IPerformanceCollector)new WebAppPerfCollector.WebAppPerformanceCollector();
PerformanceCollectorEventSource.Log.InitializedWithCollector(collector.GetType().Name);
}
else
{
collector = (IPerformanceCollector)new StandardPerformanceCollector();
PerformanceCollectorEventSource.Log.InitializedWithCollector(collector.GetType().Name);
}
return collector;
}
#elif NETSTANDARD2_0
public static IPerformanceCollector GetPerformanceCollector()
{
IPerformanceCollector collector;
if (PerformanceCounterUtility.IsWebAppRunningInAzure())
{
if (PerformanceCounterUtility.IsWindows)
{
// WebApp For windows
collector = (IPerformanceCollector)new WebAppPerformanceCollector();
PerformanceCollectorEventSource.Log.InitializedWithCollector(collector.GetType().Name);
}
else
{
// We are in WebApp, but not Windows. Use XPlatformPerfCollector.
collector = (IPerformanceCollector)new PerformanceCollectorXPlatform();
PerformanceCollectorEventSource.Log.InitializedWithCollector(collector.GetType().Name);
}
}
else if (PerformanceCounterUtility.IsWindows)
{
// The original Windows PerformanceCounter collector which is also
// supported in NetStandard2.0 in Windows.
collector = (IPerformanceCollector)new StandardPerformanceCollector();
PerformanceCollectorEventSource.Log.InitializedWithCollector(collector.GetType().Name);
}
else
{
// This is NetStandard2.0 and non-windows. Use XPlatformPerfCollector
collector = (IPerformanceCollector)new PerformanceCollectorXPlatform();
PerformanceCollectorEventSource.Log.InitializedWithCollector(collector.GetType().Name);
}
return collector;
}
#endif
/// <summary>
/// Formats a counter into a readable string.
/// </summary>
/// <param name="pc">Performance counter structure.</param>
public static string FormatPerformanceCounter(PerformanceCounterStructure pc)
{
return FormatPerformanceCounter(pc.CategoryName, pc.CounterName, pc.InstanceName);
}
/// <summary>
/// Searches for the environment variable specific to Azure Web App.
/// </summary>
/// <returns>Boolean, which is true if the current application is an Azure Web App.</returns>
public static bool IsWebAppRunningInAzure()
{
if (!isAzureWebApp.HasValue)
{
try
{
// Presence of "WEBSITE_SITE_NAME" indicate web apps.
// "WEBSITE_ISOLATION"!="hyperv" indicate premium containers. In this case, perf counters
// can be read using regular mechanism and hence this method retuns false for
// premium containers.
isAzureWebApp = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(WebSiteEnvironmentVariable)) &&
Environment.GetEnvironmentVariable(WebSiteIsolationEnvironmentVariable) != WebSiteIsolationHyperV;
}
catch (Exception ex)
{
PerformanceCollectorEventSource.Log.AccessingEnvironmentVariableFailedWarning(WebSiteEnvironmentVariable, ex.ToString());
return false;
}
}
return (bool)isAzureWebApp;
}
/// <summary>
/// Gets the processor count from the appropriate environment variable depending on whether the app is a WebApp or not.
/// </summary>
/// <returns>The number of processors in the system or null if failed to determine.</returns>
public static int? GetProcessorCount()
{
int count;
try
{
count = Environment.ProcessorCount;
}
catch (Exception ex)
{
PerformanceCollectorEventSource.Log.ProcessorsCountIncorrectValueError(ex.ToString());
return null;
}
if (count < 1 || count > 1000)
{
PerformanceCollectorEventSource.Log.ProcessorsCountIncorrectValueError(count.ToString(CultureInfo.InvariantCulture));
return null;
}
return count;
}
/// <summary>
/// Differentiates the SDK version prefix for azure web applications with standard applications.
/// </summary>
/// <returns>Returns the SDK version prefix based on the platform.</returns>
public static string SDKVersionPrefix()
{
if (IsWebAppRunningInAzure())
{
#if NETSTANDARD2_0
return AzureWebAppCoreSdkVersionPrefix;
#else
return AzureWebAppSdkVersionPrefix;
#endif
}
else
{
return StandardSdkVersionPrefix;
}
}
/// <summary>
/// Formats a counter into a readable string.
/// </summary>
public static string FormatPerformanceCounter(string categoryName, string counterName, string instanceName)
{
if (string.IsNullOrWhiteSpace(instanceName))
{
return string.Format(CultureInfo.InvariantCulture, @"\{0}\{1}", categoryName, counterName);
}
return string.Format(
CultureInfo.InvariantCulture,
@"\{0}({2})\{1}",
categoryName,
counterName,
instanceName);
}
/// <summary>
/// Validates the counter by parsing.
/// </summary>
/// <param name="perfCounterName">Performance counter name to validate.</param>
/// <param name="win32Instances">Windows 32 instances.</param>
/// <param name="clrInstances">CLR instances.</param>
/// <param name="supportInstanceNames">Boolean indicating if InstanceNames are supported. For WebApp and XPlatform counters, counters are always read from own process instance.</param>
/// <param name="usesInstanceNamePlaceholder">Boolean to check if it is using an instance name place holder.</param>
/// <param name="error">Error message.</param>
/// <returns>Performance counter.</returns>
public static PerformanceCounterStructure CreateAndValidateCounter(
string perfCounterName,
IEnumerable<string> win32Instances,
IEnumerable<string> clrInstances,
bool supportInstanceNames,
out bool usesInstanceNamePlaceholder,
out string error)
{
error = null;
try
{
return PerformanceCounterUtility.ParsePerformanceCounter(
perfCounterName,
win32Instances,
clrInstances,
supportInstanceNames,
out usesInstanceNamePlaceholder);
}
catch (Exception e)
{
usesInstanceNamePlaceholder = false;
PerformanceCollectorEventSource.Log.CounterParsingFailedEvent(e.Message, perfCounterName);
error = e.Message;
return null;
}
}
/// <summary>
/// Parses a performance counter canonical string into a PerformanceCounter object.
/// </summary>
/// <remarks>This method also performs placeholder expansion.</remarks>
public static PerformanceCounterStructure ParsePerformanceCounter(
string performanceCounter,
IEnumerable<string> win32Instances,
IEnumerable<string> clrInstances,
bool supportInstanceNames,
out bool usesInstanceNamePlaceholder)
{
var match = PerformanceCounterRegex.Match(performanceCounter);
if (!match.Success)
{
throw new ArgumentException(
string.Format(
CultureInfo.InvariantCulture,
@"Invalid performance counter name format: {0}. Expected formats are \category(instance)\counter or \category\counter",
performanceCounter),
nameof(performanceCounter));
}
return new PerformanceCounterStructure()
{
CategoryName = match.Groups["categoryName"].Value,
InstanceName =
ExpandInstanceName(
match.Groups["instanceName"].Value,
win32Instances,
clrInstances,
supportInstanceNames,
out usesInstanceNamePlaceholder),
CounterName = match.Groups["counterName"].Value,
};
}
/// <summary>
/// Invalidates placeholder cache.
/// </summary>
public static void InvalidatePlaceholderCache()
{
PlaceholderCache.Clear();
}
/// <summary>
/// Matches an instance name against the placeholder regex.
/// </summary>
/// <param name="instanceName">Instance name to match.</param>
/// <returns>Regex match.</returns>
public static Match MatchInstancePlaceholder(string instanceName)
{
var match = InstancePlaceholderRegex.Match(instanceName);
if (!match.Success || !match.Groups["placeholder"].Success)
{
return null;
}
return match;
}
internal static string GetInstanceForCurrentW3SvcWorker()
{
#if NETSTANDARD2_0
string name = new AssemblyName(Assembly.GetEntryAssembly().FullName).Name;
#else
string name = AppDomain.CurrentDomain.FriendlyName;
#endif
return GetInstanceFromApplicationDomain(name);
}
internal static string GetInstanceFromApplicationDomain(string domainFriendlyName)
{
const string Separator = "-";
string[] segments = domainFriendlyName.Split(Separator.ToCharArray());
var nameWithoutTrailingData = string.Join(
Separator,
segments.Take(segments.Length > 2 ? segments.Length - 2 : segments.Length));
return nameWithoutTrailingData.Replace('/', '_');
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "This method has different code for Net45/NetCore")]
internal static string GetInstanceForWin32Process(IEnumerable<string> win32Instances)
{
return FindProcessInstance(
Process.GetCurrentProcess().Id,
win32Instances,
Win32ProcessCategoryName,
Win32ProcessCounterName);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "This method has different code for Net45/NetCore")]
internal static string GetInstanceForClrProcess(IEnumerable<string> clrInstances)
{
return FindProcessInstance(
Process.GetCurrentProcess().Id,
clrInstances,
ClrProcessCategoryName,
ClrProcessCounterName);
}
internal static IList<string> GetWin32ProcessInstances()
{
return GetInstances(Win32ProcessCategoryName);
}
internal static IList<string> GetClrProcessInstances()
{
return GetInstances(ClrProcessCategoryName);
}
private static string ExpandInstanceName(
string instanceName,
IEnumerable<string> win32Instances,
IEnumerable<string> clrInstances,
bool supportInstanceNames,
out bool usesPlaceholder)
{
if (!supportInstanceNames)
{
usesPlaceholder = false;
return instanceName;
}
var match = MatchInstancePlaceholder(instanceName);
if (match == null)
{
// not a placeholder, do not expand
usesPlaceholder = false;
return instanceName;
}
usesPlaceholder = true;
var placeholder = match.Groups["placeholder"].Value;
// use a cached value if available
string cachedResult;
if (PlaceholderCache.TryGetValue(placeholder, out cachedResult))
{
return cachedResult;
}
// expand
if (string.Equals(placeholder, Win32ProcessInstancePlaceholder, StringComparison.OrdinalIgnoreCase))
{
cachedResult = GetInstanceForWin32Process(win32Instances);
}
else if (string.Equals(placeholder, ClrProcessInstancePlaceholder, StringComparison.OrdinalIgnoreCase))
{
cachedResult = GetInstanceForClrProcess(clrInstances);
}
else if (string.Equals(placeholder, W3SvcProcessInstancePlaceholder, StringComparison.OrdinalIgnoreCase))
{
cachedResult = GetInstanceForCurrentW3SvcWorker();
}
else
{
// a non-supported placeholder, return as is
return instanceName;
}
// add to cache
PlaceholderCache[placeholder] = cachedResult;
return cachedResult;
}
private static string FindProcessInstance(int pid, IEnumerable<string> instances, string categoryName, string counterName)
{
Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection> cached;
DateTime utcNow = DateTime.UtcNow;
InstanceDataCollectionCollection result = null;
PerformanceCounterCategory category = null;
if (cache.TryGetValue(categoryName, out cached))
{
category = cached.Item2;
if (cached.Item1 < utcNow)
{
result = cached.Item3;
}
}
if (result == null)
{
if (category == null)
{
category = new PerformanceCounterCategory(categoryName);
}
result = category.ReadCategory();
cache.TryAdd(categoryName, new Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>(utcNow.AddMinutes(1), category, result));
}
InstanceDataCollection counters = result[counterName];
if (counters != null)
{
foreach (string i in instances)
{
InstanceData instance = counters[i];
if ((instance != null) && (pid == instance.RawValue))
{
return i;
}
}
}
return null;
}
private static IList<string> GetInstances(string categoryName)
{
var cat = new PerformanceCounterCategory() { CategoryName = categoryName };
try
{
return cat.GetInstanceNames();
}
catch (Exception)
{
// something went wrong and the category hasn't been found
// we can't perform this operation
#if NETSTANDARD2_0
return Array.Empty<string>();
#else
return new string[] { };
#endif
}
}
}
} | 38.785992 | 262 | 0.59681 | [
"MIT"
] | Bhaskers-Blu-Org2/ApplicationInsights-dotnet | WEB/Src/PerformanceCollector/PerformanceCollector/Implementation/PerformanceCounterUtility.cs | 19,938 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Input;
using System.Linq;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using QuickGraph;
using SIL.Cog.Application.Services;
using SIL.Cog.Domain;
using SIL.Machine.FeatureModel;
namespace SIL.Cog.Application.ViewModels
{
public class GlobalCorrespondencesViewModel : WorkspaceViewModelBase
{
private readonly IProjectService _projectService;
private readonly IImageExportService _imageExportService;
private readonly WordPairsViewModel _observedWordPairs;
private GlobalCorrespondencesGraphEdge _selectedCorrespondence;
private SyllablePosition _syllablePosition;
private readonly TaskAreaIntegerViewModel _correspondenceFilter;
private readonly IDialogService _dialogService;
private readonly IBusyService _busyService;
private readonly IGraphService _graphService;
private readonly ICommand _findCommand;
private IBidirectionalGraph<GlobalCorrespondencesGraphVertex, GlobalCorrespondencesGraphEdge> _graph;
private readonly HashSet<Variety> _selectedVarieties;
private readonly WordPairViewModel.Factory _wordPairFactory;
private FindViewModel _findViewModel;
public GlobalCorrespondencesViewModel(IProjectService projectService, IBusyService busyService, IDialogService dialogService, IImageExportService imageExportService, IGraphService graphService,
WordPairsViewModel.Factory wordPairsFactory, WordPairViewModel.Factory wordPairFactory)
: base("Global Correspondences")
{
_projectService = projectService;
_busyService = busyService;
_dialogService = dialogService;
_imageExportService = imageExportService;
_graphService = graphService;
_wordPairFactory = wordPairFactory;
_selectedVarieties = new HashSet<Variety>();
_projectService.ProjectOpened += _projectService_ProjectOpened;
Messenger.Default.Register<ComparisonPerformedMessage>(this, msg => GenerateGraph());
Messenger.Default.Register<DomainModelChangedMessage>(this, msg =>
{
if (msg.AffectsComparison)
ClearGraph();
});
Messenger.Default.Register<PerformingComparisonMessage>(this, msg => ClearGraph());
_findCommand = new RelayCommand(Find);
TaskAreas.Add(new TaskAreaCommandGroupViewModel("Syllable position",
new TaskAreaCommandViewModel("Onset", new RelayCommand(() => SyllablePosition = SyllablePosition.Onset)),
new TaskAreaCommandViewModel("Nucleus", new RelayCommand(() => SyllablePosition = SyllablePosition.Nucleus)),
new TaskAreaCommandViewModel("Coda", new RelayCommand(() => SyllablePosition = SyllablePosition.Coda))));
_correspondenceFilter = new TaskAreaIntegerViewModel("Frequency threshold");
_correspondenceFilter.PropertyChanging += _correspondenceFilter_PropertyChanging;
_correspondenceFilter.PropertyChanged += _correspondenceFilter_PropertyChanged;
TaskAreas.Add(_correspondenceFilter);
TaskAreas.Add(new TaskAreaItemsViewModel("Common tasks",
new TaskAreaCommandViewModel("Find words", _findCommand),
new TaskAreaItemsViewModel("Sort word pairs by", new TaskAreaCommandGroupViewModel(
new TaskAreaCommandViewModel("Gloss", new RelayCommand(() => _observedWordPairs.UpdateSort("Meaning.Gloss", ListSortDirection.Ascending))),
new TaskAreaCommandViewModel("Similarity", new RelayCommand(() => _observedWordPairs.UpdateSort("PhoneticSimilarityScore", ListSortDirection.Descending))))),
new TaskAreaCommandViewModel("Select varieties", new RelayCommand(SelectVarieties))
));
TaskAreas.Add(new TaskAreaItemsViewModel("Other tasks",
new TaskAreaCommandViewModel("Export chart", new RelayCommand(ExportChart, CanExportChart))));
_observedWordPairs = wordPairsFactory();
_observedWordPairs.IncludeVarietyNamesInSelectedText = true;
_observedWordPairs.UpdateSort("Meaning.Gloss", ListSortDirection.Ascending);
}
private void _projectService_ProjectOpened(object sender, EventArgs e)
{
_selectedVarieties.Clear();
_selectedVarieties.UnionWith(_projectService.Project.Varieties);
_projectService.Project.Varieties.CollectionChanged += VarietiesChanged;
if (_projectService.AreAllVarietiesCompared)
GenerateGraph();
else
ClearGraph();
}
private void VarietiesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
_selectedVarieties.ExceptWith(e.OldItems.Cast<Variety>());
if (e.NewItems != null)
_selectedVarieties.UnionWith(e.NewItems.Cast<Variety>());
}
private void SelectVarieties()
{
var vm = new SelectVarietiesViewModel(_projectService.Project.Varieties, _selectedVarieties);
if (_dialogService.ShowModalDialog(this, vm) == true)
{
_selectedVarieties.Clear();
_selectedVarieties.UnionWith(vm.Varieties.Where(v => v.IsSelected).Select(v => v.DomainVariety));
GenerateGraph();
}
}
private bool CanExportChart()
{
return _projectService.AreAllVarietiesCompared;
}
private void ExportChart()
{
_imageExportService.ExportCurrentGlobalCorrespondencesChart(this);
}
private void Find()
{
if ( _findViewModel != null)
return;
_findViewModel = new FindViewModel(_dialogService, FindNext);
_findViewModel.PropertyChanged += (sender, args) => _observedWordPairs.ResetSearch();
_dialogService.ShowModelessDialog(this, _findViewModel, () => _findViewModel = null);
}
private void FindNext()
{
if (!_observedWordPairs.FindNext(_findViewModel.Field, _findViewModel.String, true, false))
_findViewModel.ShowSearchEndedMessage();
}
protected override void OnIsSelectedChanged()
{
if (IsSelected)
{
Messenger.Default.Send(new HookFindMessage(_findCommand));
}
else if (_findViewModel != null)
{
_dialogService.CloseDialog(_findViewModel);
Messenger.Default.Send(new HookFindMessage(null));
}
}
private void GenerateGraph()
{
if (!_projectService.AreAllVarietiesCompared)
return;
_busyService.ShowBusyIndicatorUntilFinishDrawing();
SelectedCorrespondence = null;
Graph = _graphService.GenerateGlobalCorrespondencesGraph(_syllablePosition, _selectedVarieties);
}
private void ClearGraph()
{
SelectedCorrespondence = null;
Graph = null;
}
public ICommand FindCommand
{
get { return _findCommand; }
}
public GlobalCorrespondencesGraphEdge SelectedCorrespondence
{
get { return _selectedCorrespondence; }
set
{
GlobalCorrespondencesGraphEdge oldCorr = _selectedCorrespondence;
if (Set(() => SelectedCorrespondence, ref _selectedCorrespondence, value))
{
_busyService.ShowBusyIndicatorUntilFinishDrawing();
if (oldCorr != null)
oldCorr.IsSelected = false;
_observedWordPairs.WordPairs.Clear();
if (_selectedCorrespondence != null)
{
_selectedCorrespondence.IsSelected = true;
var seg1 = (GlobalSegmentVertex) _selectedCorrespondence.Source;
var seg2 = (GlobalSegmentVertex) _selectedCorrespondence.Target;
foreach (WordPair wp in _selectedCorrespondence.DomainWordPairs)
{
WordPairViewModel vm = _wordPairFactory(wp, true);
foreach (AlignedNodeViewModel an in vm.AlignedNodes)
{
if ((seg1.StrReps.Contains(an.StrRep1) && seg2.StrReps.Contains(an.StrRep2))
|| (seg1.StrReps.Contains(an.StrRep2) && seg2.StrReps.Contains(an.StrRep1)))
{
FeatureSymbol pos = null;
switch (_syllablePosition)
{
case SyllablePosition.Onset:
pos = CogFeatureSystem.Onset;
break;
case SyllablePosition.Nucleus:
pos = CogFeatureSystem.Nucleus;
break;
case SyllablePosition.Coda:
pos = CogFeatureSystem.Coda;
break;
}
SymbolicFeatureValue curPos1, curPos2;
if (!an.DomainCell1.IsNull && !an.DomainCell2.IsNull
&& an.DomainCell1.First.Annotation.FeatureStruct.TryGetValue(CogFeatureSystem.SyllablePosition, out curPos1) && (FeatureSymbol) curPos1 == pos
&& an.DomainCell2.First.Annotation.FeatureStruct.TryGetValue(CogFeatureSystem.SyllablePosition, out curPos2) && (FeatureSymbol) curPos2 == pos)
{
an.IsSelected = true;
}
}
}
_observedWordPairs.WordPairs.Add(vm);
}
}
}
}
}
public WordPairsViewModel ObservedWordPairs
{
get { return _observedWordPairs; }
}
public SyllablePosition SyllablePosition
{
get { return _syllablePosition; }
set
{
if (Set(() => SyllablePosition, ref _syllablePosition, value) && _graph != null)
GenerateGraph();
}
}
public IBidirectionalGraph<GlobalCorrespondencesGraphVertex, GlobalCorrespondencesGraphEdge> Graph
{
get { return _graph; }
set { Set(() => Graph, ref _graph, value); }
}
public int CorrespondenceFilter
{
get { return _correspondenceFilter.Value; }
set { _correspondenceFilter.Value = value; }
}
private void _correspondenceFilter_PropertyChanging(object sender, PropertyChangingEventArgs e)
{
switch (e.PropertyName)
{
case "Value":
RaisePropertyChanging(() => CorrespondenceFilter);
break;
}
}
private void _correspondenceFilter_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Value":
RaisePropertyChanged(() => CorrespondenceFilter);
if (_selectedCorrespondence != null && _selectedCorrespondence.Frequency < CorrespondenceFilter)
SelectedCorrespondence = null;
break;
}
}
}
}
| 34.711191 | 195 | 0.745918 | [
"MIT"
] | sillsdev/cog | Cog.Application/ViewModels/GlobalCorrespondencesViewModel.cs | 9,615 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AntfortuneEquityInstpointSendModel Data Structure.
/// </summary>
public class AntfortuneEquityInstpointSendModel : AlipayObject
{
/// <summary>
/// 积分发放备注
/// </summary>
[JsonPropertyName("memo")]
public string Memo { get; set; }
/// <summary>
/// 比如某种业务标准外部订单号,比如交易外部订单号,代表商户端自己订单号
/// </summary>
[JsonPropertyName("out_biz_no")]
public string OutBizNo { get; set; }
/// <summary>
/// 本次发放的积分值,商户必须设置值指定本次发放给用户的具体积分值,取值范围[1,10000]
/// </summary>
[JsonPropertyName("point")]
public long Point { get; set; }
/// <summary>
/// 积分预算模板号,商户在财富开放后台创建积分模板后获得
/// </summary>
[JsonPropertyName("template_no")]
public string TemplateNo { get; set; }
/// <summary>
/// 蚂蚁统一会员ID
/// </summary>
[JsonPropertyName("user_id")]
public string UserId { get; set; }
}
}
| 26.658537 | 66 | 0.563586 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AntfortuneEquityInstpointSendModel.cs | 1,309 | C# |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace IFPS.Factory.Domain.Helper
{
public class ParsedHoleComperator : IComparer<ParsedHole>
{
public int Compare( ParsedHole x, ParsedHole y)
{
if (x.Plane == y.Plane && x.Diameter == y.Diameter)
{
return 0;
}
else if (x.Plane < y.Plane || (x.Plane == y.Plane && x.Diameter < y.Diameter))
{
return -1;
}
return 1;
}
}
}
| 25.090909 | 90 | 0.514493 | [
"MIT"
] | encosoftware/ifps | ButorRevolutionWebAPI/src/backend/factory/IFPS.Factory.Domain/Helper/TriDCorpusParser/ParsedHoleComperator.cs | 554 | C# |
using Eve.Core.Events;
using System;
using System.Collections.Generic;
using System.Text;
namespace Eve.Core.Subscriptions
{
public interface ISubscription<TEvent, TEventContext> : ISubscription
where TEvent : IContextfulEvent
where TEventContext: IEventContext<TEvent>
{
void Handle(TEventContext context);
}
public interface ISubscription<TEvent> : ISubscription
where TEvent : IContextlessEvent
{
void Handle();
}
public interface ISubscription { }
}
| 22.869565 | 73 | 0.701521 | [
"MIT"
] | AlexSolari/eve | Eve.Core/Subscriptions/ISubscription.cs | 528 | C# |
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Phonebook.Services.Entry.Domain.Models;
using Phonebook.Services.Entry.Domain.Repositories;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Phonebook.Services.Entry.Repositories
{
public class EntryRepository : IEntryRepository
{
private readonly IMongoDatabase _database;
public EntryRepository(IMongoDatabase database)
{
_database = database;
}
public async Task AddAsync(xEntry entry)
=> await Collection.InsertOneAsync(entry);
public async Task<xEntry> GetAsync(Guid id)
=> await Collection
.AsQueryable()
.FirstOrDefaultAsync(x => x.Id == id);
private IMongoCollection<xEntry> Collection
=> _database.GetCollection<xEntry>("Entries");
}
}
| 28.258065 | 58 | 0.66895 | [
"MIT"
] | brentwhittaker/react-asp-net-core-phonebook | Phonebook.Services.Entry/Repositories/EntryRepository.cs | 876 | C# |
using Windows.UI.Xaml.Controls;
using FormsCommunityToolkit.Effects.UWP;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;
using Thickness = Windows.UI.Xaml.Thickness;
[assembly: ExportEffect(typeof(RemoveBorderEffect), nameof(RemoveBorderEffect))]
namespace FormsCommunityToolkit.Effects.UWP
{
public class RemoveBorderEffect : PlatformEffect
{
Thickness old;
protected override void OnAttached()
{
var textBox = Control as TextBox;
if (textBox == null)
return;
old = textBox.BorderThickness;
textBox.BorderThickness = new Thickness(0);
}
protected override void OnDetached()
{
var textBox = Control as TextBox;
if (textBox == null)
return;
textBox.BorderThickness = old;
}
}
}
| 25 | 80 | 0.620571 | [
"MIT"
] | JanDeDobbeleer/Effects | src/Effects.UWP/Effects/RemoveBorderEffect.cs | 877 | C# |
using System;
using Orleans;
namespace UnitTests.DtosRefOrleans
{
[Serializable]
[GenerateSerializer]
public class ClassReferencingOrleansTypeDto
{
static ClassReferencingOrleansTypeDto()
{
typeof(IGrain).ToString();
}
[Id(0)]
public string MyProperty { get; set; }
}
} | 19.111111 | 47 | 0.619186 | [
"MIT"
] | AmedeoV/orleans | test/Misc/TestInternalDtosRefOrleans/ClassReferencingOrleansTypeDto.cs | 346 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if NET452 || NETCOREAPP1_0
using System;
using System.Collections.Generic;
using System.Linq;
namespace Internal.Microsoft.Extensions.DependencyModel
{
internal class DependencyContextPaths
{
private static readonly string DepsFilesProperty = "APP_CONTEXT_DEPS_FILES";
private static readonly string FxDepsFileProperty = "FX_DEPS_FILE";
public static DependencyContextPaths Current { get; } = GetCurrent();
public string Application { get; }
public string SharedRuntime { get; }
public IEnumerable<string> NonApplicationPaths { get; }
public DependencyContextPaths(
string application,
string sharedRuntime,
IEnumerable<string> nonApplicationPaths)
{
Application = application;
SharedRuntime = sharedRuntime;
NonApplicationPaths = nonApplicationPaths ?? Enumerable.Empty<string>();
}
private static DependencyContextPaths GetCurrent()
{
#if NETCOREAPP1_0
var deps = AppContext.GetData(DepsFilesProperty);
var fxDeps = AppContext.GetData(FxDepsFileProperty);
#elif NET452
var deps = AppDomain.CurrentDomain.GetData(DepsFilesProperty);
var fxDeps = AppDomain.CurrentDomain.GetData(FxDepsFileProperty);
#endif
return Create(deps as string, fxDeps as string);
}
internal static DependencyContextPaths Create(string depsFiles, string sharedRuntime)
{
var files = depsFiles?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var application = files != null && files.Length > 0 ? files[0] : null;
var nonApplicationPaths = files?
.Skip(1) // the application path
.ToArray();
return new DependencyContextPaths(
application,
sharedRuntime,
nonApplicationPaths);
}
}
}
#endif
| 33.6875 | 101 | 0.652134 | [
"Apache-2.0"
] | erikbra/xunit | src/common/Microsoft.Extensions.DependencyModel/DependencyContextPaths.cs | 2,156 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.ComponentModel;
using System.Threading;
using System.Collections;
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
using PubNubMessaging.Core;
namespace PubNubMessaging.Tests
{
[TestFixture]
public class WhenAMessageIsPublished
{
ManualResetEvent mreUnencryptedPublish = new ManualResetEvent(false);
ManualResetEvent mreOptionalSecretKeyPublish = new ManualResetEvent(false);
ManualResetEvent mreNoSslPublish = new ManualResetEvent(false);
ManualResetEvent mreUnencryptObjectPublish = new ManualResetEvent(false);
ManualResetEvent mreEncryptObjectPublish = new ManualResetEvent(false);
ManualResetEvent mreEncryptPublish = new ManualResetEvent(false);
ManualResetEvent mreSecretEncryptPublish = new ManualResetEvent(false);
ManualResetEvent mreComplexObjectPublish = new ManualResetEvent(false);
ManualResetEvent mreLaregMessagePublish = new ManualResetEvent(false);
ManualResetEvent mreEncryptDetailedHistory = new ManualResetEvent(false);
ManualResetEvent mreSecretEncryptDetailedHistory = new ManualResetEvent(false);
ManualResetEvent mreUnencryptDetailedHistory = new ManualResetEvent(false);
ManualResetEvent mreUnencryptObjectDetailedHistory = new ManualResetEvent(false);
ManualResetEvent mreEncryptObjectDetailedHistory = new ManualResetEvent(false);
ManualResetEvent mreComplexObjectDetailedHistory = new ManualResetEvent(false);
ManualResetEvent mreSerializedObjectMessageForPublish = new ManualResetEvent(false);
ManualResetEvent mreSerializedMessagePublishDetailedHistory = new ManualResetEvent(false);
ManualResetEvent grantManualEvent = new ManualResetEvent(false);
bool isPublished2 = false;
bool isPublished3 = false;
bool isUnencryptPublished = false;
bool isUnencryptObjectPublished = false;
bool isEncryptObjectPublished = false;
bool isUnencryptDetailedHistory = false;
bool isUnencryptObjectDetailedHistory = false;
bool isEncryptObjectDetailedHistory = false;
bool isEncryptPublished = false;
bool isSecretEncryptPublished = false;
bool isEncryptDetailedHistory = false;
bool isSecretEncryptDetailedHistory = false;
bool isComplexObjectPublished = false;
bool isComplexObjectDetailedHistory = false;
bool isSerializedObjectMessagePublished = false;
bool isSerializedObjectMessageDetailedHistory = false;
bool isLargeMessagePublished = false;
bool receivedGrantMessage = false;
long unEncryptPublishTimetoken = 0;
long unEncryptObjectPublishTimetoken = 0;
long encryptObjectPublishTimetoken = 0;
long encryptPublishTimetoken = 0;
long secretEncryptPublishTimetoken = 0;
long complexObjectPublishTimetoken = 0;
long serializedMessagePublishTimetoken = 0;
const string messageForUnencryptPublish = "Pubnub Messaging API 1";
const string messageForEncryptPublish = "漢語";
const string messageForSecretEncryptPublish = "Pubnub Messaging API 2";
const string messageLarge32K = "Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. Numerous questions remain about the origins of the chemical and what impact its apparent use could have on the ongoing Syrian civil war and international involvement in it.When asked if the intelligence community's conclusion pushed the situation across President Barack Obama's \"red line\" that could potentially trigger more U.S. involvement in the Syrian civil war, Hagel said it's too soon to say.\"We need all the facts. We need all the information,\" he said. \"What I've just given you is what our intelligence community has said they know. As I also said, they are still assessing and they are still looking at what happened, who was responsible and the other specifics that we'll need.\" In a letter sent to lawmakers before Hagel's announcement, the White House said that intelligence analysts have concluded \"with varying degrees of confidence that the Syrian regime has used chemical weapons on a small scale in Syria, specifically the chemical agent sarin.\" In the letter, signed by White House legislative affairs office Director Miguel Rodriguez, the White House said the \"chain of custody\" of the chemicals was not clear and that intelligence analysts could not confirm the circumstances under which the sarin was used, including the role of Syrian President Bashar al-Assad's regime. Read Rodriguez's letter to Levin (PDF) But, the letter said, \"we do believe that any use of chemical weapons in Syria would very likely have originated with the Assad regime.\" The Syrian government has been battling a rebellion for more than two years, bringing international condemnation of the regime and pleas for greater international assistance. The United Nations estimated in February that more than 70,000 people had died since the conflict began. The administration is \"pressing for a comprehensive United Nations investigation that can credibly evaluate the evidence and establish what took place,\" the White House letter said. Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. ONE..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. TWO..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. THREE..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. FOUR..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. FIVE..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. SIX..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. SEVEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. EIGHT..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. NINE..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. TEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. ELEVEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. THIRTEEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. FOURTEEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. FIFTEEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. SIXTEEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. SEVENTEEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. EIGHTEEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. NINETEEN..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. TWENTY..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. TWENTY ONE..Sen. John McCain, one of the lawmakers who received the letter, said the use of chemical weapons was only a matter of time. alpha beta 12";
string messageObjectForUnencryptPublish = "";
string messageObjectForEncryptPublish = "";
string messageComplexObjectForPublish = "";
string serializedObjectMessageForPublish;
int manualResetEventsWaitTimeout = 310 * 1000;
Pubnub pubnub = null;
[SetUp]
public void Init()
{
if (!PubnubCommon.PAMEnabled) return;
receivedGrantMessage = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "GrantRequestUnitTest";
unitTest.TestCaseName = "Init";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
pubnub.GrantAccess<string>(channel, true, true, 20, ThenPublishInitializeShouldReturnGrantMessage, DummyErrorCallback);
Thread.Sleep(1000);
grantManualEvent.WaitOne();
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.True(receivedGrantMessage, "WhenAMessageIsPublished Grant access failed.");
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ThenNullMessageShouldReturnException()
{
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
string channel = "hello_my_channel";
object message = null;
pubnub.Publish<string>(channel, message, null, DummyErrorCallback);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenUnencryptPublishShouldReturnSuccessCodeAndInfo()
{
isUnencryptPublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenUnencryptPublishShouldReturnSuccessCodeAndInfo";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = messageForUnencryptPublish;
pubnub.Publish<string>(channel, message, ReturnSuccessUnencryptPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mreUnencryptedPublish.WaitOne(manualResetEventsWaitTimeout);
if (!isUnencryptPublished)
{
Assert.True(isUnencryptPublished, "Unencrypt Publish Failed");
}
else
{
Thread.Sleep(1000);
pubnub.DetailedHistory<string>(channel, -1, unEncryptPublishTimetoken, -1, false, CaptureUnencryptDetailedHistoryCallback, DummyErrorCallback);
mreUnencryptDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.True(isUnencryptDetailedHistory, "Unable to match the successful unencrypt Publish");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenUnencryptObjectPublishShouldReturnSuccessCodeAndInfo()
{
isUnencryptObjectPublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenUnencryptObjectPublishShouldReturnSuccessCodeAndInfo";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
object message = new CustomClass();
//messageObjectForUnencryptPublish = JsonConvert.SerializeObject(message);
messageObjectForUnencryptPublish = pubnub.JsonPluggableLibrary.SerializeToJsonString(message);
pubnub.Publish<string>(channel, message, ReturnSuccessUnencryptObjectPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mreUnencryptObjectPublish.WaitOne(manualResetEventsWaitTimeout);
if (!isUnencryptObjectPublished)
{
Assert.True(isUnencryptObjectPublished, "Unencrypt Publish Failed");
}
else
{
Thread.Sleep(1000);
pubnub.DetailedHistory<string>(channel, -1, unEncryptObjectPublishTimetoken, -1, false, CaptureUnencryptObjectDetailedHistoryCallback, DummyErrorCallback);
mreUnencryptObjectDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.True(isUnencryptObjectDetailedHistory, "Unable to match the successful unencrypt object Publish");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenEncryptObjectPublishShouldReturnSuccessCodeAndInfo()
{
isEncryptObjectPublished = false;
isEncryptObjectDetailedHistory = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "enigma", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenEncryptObjectPublishShouldReturnSuccessCodeAndInfo";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
object message = new SecretCustomClass();
//messageObjectForEncryptPublish = JsonConvert.SerializeObject(message);
messageObjectForEncryptPublish = pubnub.JsonPluggableLibrary.SerializeToJsonString(message);
mreEncryptObjectPublish = new ManualResetEvent(false);
pubnub.Publish<string>(channel, message, ReturnSuccessEncryptObjectPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mreEncryptObjectPublish.WaitOne(manualResetEventsWaitTimeout);
if (!isEncryptObjectPublished)
{
Assert.True(isEncryptObjectPublished, "Encrypt Object Publish Failed");
}
else
{
Thread.Sleep(1000);
mreEncryptObjectDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, -1, encryptObjectPublishTimetoken, -1, false, CaptureEncryptObjectDetailedHistoryCallback, DummyErrorCallback);
mreEncryptObjectDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.True(isEncryptObjectDetailedHistory, "Unable to match the successful encrypt object Publish");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenEncryptObjectPublishShouldReturnSuccessCodeAndInfoWithSSL()
{
isEncryptObjectPublished = false;
isEncryptObjectDetailedHistory = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "enigma", true);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenEncryptObjectPublishShouldReturnSuccessCodeAndInfo";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
object message = new SecretCustomClass();
//messageObjectForEncryptPublish = JsonConvert.SerializeObject(message);
messageObjectForEncryptPublish = pubnub.JsonPluggableLibrary.SerializeToJsonString(message);
mreEncryptObjectPublish = new ManualResetEvent(false);
pubnub.Publish<string>(channel, message, ReturnSuccessEncryptObjectPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mreEncryptObjectPublish.WaitOne(manualResetEventsWaitTimeout);
if (!isEncryptObjectPublished)
{
Assert.True(isEncryptObjectPublished, "Encrypt Object Publish with SSL Failed");
}
else
{
Thread.Sleep(1000);
mreEncryptObjectDetailedHistory = new ManualResetEvent(false);
pubnub.DetailedHistory<string>(channel, -1, encryptObjectPublishTimetoken, -1, false, CaptureEncryptObjectDetailedHistoryCallback, DummyErrorCallback);
mreEncryptObjectDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.True(isEncryptObjectDetailedHistory, "Unable to match the successful encrypt object Publish with SSL");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenEncryptPublishShouldReturnSuccessCodeAndInfo()
{
isEncryptPublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "enigma", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenEncryptPublishShouldReturnSuccessCodeAndInfo";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = messageForEncryptPublish;
pubnub.Publish<string>(channel, message, ReturnSuccessEncryptPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mreEncryptPublish.WaitOne(manualResetEventsWaitTimeout);
if (!isEncryptPublished)
{
Assert.True(isEncryptPublished, "Encrypt Publish Failed");
}
else
{
Thread.Sleep(1000);
pubnub.DetailedHistory<string>(channel, -1, encryptPublishTimetoken, -1, false, CaptureEncryptDetailedHistoryCallback, DummyErrorCallback);
mreEncryptDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.True(isEncryptDetailedHistory, "Unable to decrypt the successful Publish");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenSecretKeyWithEncryptPublishShouldReturnSuccessCodeAndInfo()
{
isSecretEncryptPublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "key", "enigma", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenSecretKeyWithEncryptPublishShouldReturnSuccessCodeAndInfo";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = messageForSecretEncryptPublish;
pubnub.Publish<string>(channel, message, ReturnSuccessSecretEncryptPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mreSecretEncryptPublish.WaitOne(manualResetEventsWaitTimeout);
if (!isSecretEncryptPublished)
{
Assert.True(isSecretEncryptPublished, "Secret Encrypt Publish Failed");
}
else
{
Thread.Sleep(1000);
pubnub.DetailedHistory<string>(channel, -1, secretEncryptPublishTimetoken, -1, false, CaptureSecretEncryptDetailedHistoryCallback, DummyErrorCallback);
mreSecretEncryptDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.True(isSecretEncryptDetailedHistory, "Unable to decrypt the successful Secret key Publish");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenComplexMessageObjectShouldReturnSuccessCodeAndInfo()
{
isComplexObjectPublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenComplexMessageObjectShouldReturnSuccessCodeAndInfo";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
object message = new PubnubDemoObject();
messageComplexObjectForPublish = pubnub.JsonPluggableLibrary.SerializeToJsonString(message);
pubnub.Publish<string>(channel, message, ReturnSuccessComplexObjectPublishCodeCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 310 * 1000 : 310 * 1000;
mreComplexObjectPublish.WaitOne(manualResetEventsWaitTimeout);
Thread.Sleep (1000);
if (!isComplexObjectPublished)
{
Assert.True(isComplexObjectPublished, "Complex Object Publish Failed");
}
else
{
Console.WriteLine("WhenAMessageIsPublished-ThenComplexMessageObjectShouldReturnSuccessCodeAndInfo - Publish OK. Now checking detailed history");
pubnub.DetailedHistory<string>(channel, -1, complexObjectPublishTimetoken, -1, false, CaptureComplexObjectDetailedHistoryCallback, DummyErrorCallback);
mreComplexObjectDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.True(isComplexObjectDetailedHistory, "Unable to match the successful unencrypt object Publish");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenDisableJsonEncodeShouldSendSerializedObjectMessage()
{
isSerializedObjectMessagePublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
pubnub.EnableJsonEncodingForPublish = false;
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenDisableJsonEncodeShouldSendSerializedObjectMessage";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
object message = "{\"operation\":\"ReturnData\",\"channel\":\"Mobile1\",\"sequenceNumber\":0,\"data\":[\"ping 1.0.0.1\"]}";
serializedObjectMessageForPublish = message.ToString();
pubnub.Publish<string>(channel, message, ReturnSuccessSerializedObjectMessageForPublishCallback, DummyErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
mreSerializedObjectMessageForPublish.WaitOne(manualResetEventsWaitTimeout);
Thread.Sleep (1000);
if (!isSerializedObjectMessagePublished)
{
Assert.True(isSerializedObjectMessagePublished, "Serialized Object Message Publish Failed");
}
else
{
pubnub.DetailedHistory<string>(channel, -1, serializedMessagePublishTimetoken, -1, false, CaptureSerializedMessagePublishDetailedHistoryCallback, DummyErrorCallback);
mreSerializedMessagePublishDetailedHistory.WaitOne(manualResetEventsWaitTimeout);
Assert.True(isSerializedObjectMessageDetailedHistory, "Unable to match the successful serialized object message Publish");
}
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
}
[Test]
public void ThenLargeMessageShoudFailWithMessageTooLargeInfo()
{
isLargeMessagePublished = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenLargeMessageShoudFailWithMessageTooLargeInfo";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = messageLarge32K;
pubnub.Publish<string>(channel, message, DummyPublishMessageTooLargeInfoCallback, ReturnPublishMessageTooLargeErrorCallback);
manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 310 * 1000 : 310 * 1000;
mreLaregMessagePublish.WaitOne(manualResetEventsWaitTimeout);
pubnub.EndPendingRequests();
pubnub.PubnubUnitTest = null;
pubnub = null;
Assert.True(isLargeMessagePublished, "Message Too Large is not failing as expected.");
}
void ThenPublishInitializeShouldReturnGrantMessage(string receivedMessage)
{
try
{
if (!string.IsNullOrEmpty(receivedMessage) && !string.IsNullOrEmpty(receivedMessage.Trim()))
{
List<object> serializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(receivedMessage);
if (serializedMessage != null && serializedMessage.Count > 0)
{
Dictionary<string, object> dictionary = pubnub.JsonPluggableLibrary.ConvertToDictionaryObject(serializedMessage[0]);
if (dictionary != null && dictionary.Count > 0)
{
var status = dictionary["status"].ToString();
if (status == "200")
{
receivedGrantMessage = true;
}
}
}
}
}
catch { }
finally
{
grantManualEvent.Set();
}
}
private void ReturnSuccessUnencryptPublishCodeCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isUnencryptPublished = true;
unEncryptPublishTimetoken = Convert.ToInt64(deserializedMessage[2].ToString());
}
}
}
mreUnencryptedPublish.Set();
}
private void ReturnSuccessUnencryptObjectPublishCodeCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isUnencryptObjectPublished = true;
unEncryptObjectPublishTimetoken = Convert.ToInt64(deserializedMessage[2].ToString());
}
}
}
mreUnencryptObjectPublish.Set();
}
private void ReturnSuccessEncryptObjectPublishCodeCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isEncryptObjectPublished = true;
encryptObjectPublishTimetoken = Convert.ToInt64(deserializedMessage[2].ToString());
}
}
}
mreEncryptObjectPublish.Set();
}
private void ReturnSuccessEncryptPublishCodeCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isEncryptPublished = true;
encryptPublishTimetoken = Convert.ToInt64(deserializedMessage[2].ToString());
}
}
}
mreEncryptPublish.Set();
}
private void ReturnSuccessSecretEncryptPublishCodeCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isSecretEncryptPublished = true;
secretEncryptPublishTimetoken = Convert.ToInt64(deserializedMessage[2].ToString());
}
}
}
mreSecretEncryptPublish.Set();
}
private void CaptureUnencryptDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length > 0 && message[0].ToString() == messageForUnencryptPublish)
{
isUnencryptDetailedHistory = true;
}
}
}
mreUnencryptDetailedHistory.Set();
}
private void CaptureUnencryptObjectDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length > 0)
{
string publishedMesaage = pubnub.JsonPluggableLibrary.SerializeToJsonString(message[0]);
if (publishedMesaage == messageObjectForUnencryptPublish)
{
isUnencryptObjectDetailedHistory = true;
}
}
}
}
mreUnencryptObjectDetailedHistory.Set();
}
private void CaptureEncryptObjectDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length > 0)
{
string publishedMesaage = pubnub.JsonPluggableLibrary.SerializeToJsonString(message[0]);
if (publishedMesaage == messageObjectForEncryptPublish)
{
isEncryptObjectDetailedHistory = true;
}
}
}
}
mreEncryptObjectDetailedHistory.Set();
}
private void CaptureEncryptDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length > 0)
{
string publishedMesaage = message[0].ToString();
if (publishedMesaage == messageForEncryptPublish)
{
isEncryptDetailedHistory = true;
}
}
}
}
mreEncryptDetailedHistory.Set();
}
private void CaptureSecretEncryptDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length > 0)
{
string publishedMesaage = message[0].ToString();
if (publishedMesaage == messageForSecretEncryptPublish)
{
isSecretEncryptDetailedHistory = true;
}
}
}
}
mreSecretEncryptDetailedHistory.Set();
}
private void ReturnSuccessComplexObjectPublishCodeCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isComplexObjectPublished = true;
complexObjectPublishTimetoken = Convert.ToInt64(deserializedMessage[2].ToString());
}
}
}
mreComplexObjectPublish.Set();
}
private void CaptureComplexObjectDetailedHistoryCallback(string result)
{
Console.WriteLine("CaptureComplexObjectDetailedHistoryCallback = \n" + result);
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length > 0)
{
string publishedMesaage = pubnub.JsonPluggableLibrary.SerializeToJsonString(message[0]);
if (publishedMesaage == messageComplexObjectForPublish)
{
isComplexObjectDetailedHistory = true;
}
}
}
}
mreComplexObjectDetailedHistory.Set();
}
private void ReturnPublishMessageTooLargeErrorCallback(PubnubClientError pubnubError)
{
Console.WriteLine(pubnubError);
if (pubnubError != null)
{
if (pubnubError.Message.ToLower().IndexOf("message too large") >= 0)
{
isLargeMessagePublished = true;
}
}
mreLaregMessagePublish.Set();
}
private void DummyPublishMessageTooLargeInfoCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 0 && statusMessage.ToLower().IndexOf("message too large") >= 0)
{
isLargeMessagePublished = true;
}
}
}
mreLaregMessagePublish.Set();
}
[Test]
public void ThenPubnubShouldGenerateUniqueIdentifier()
{
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
Assert.NotNull(pubnub.GenerateGuid());
pubnub = null;
}
[Test]
[ExpectedException(typeof(MissingMemberException))]
public void ThenPublishKeyShouldNotBeEmpty()
{
pubnub = new Pubnub("", PubnubCommon.SubscribeKey, "", "", false);
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenPublishKeyShouldNotBeEmpty";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = "Pubnub API Usage Example";
pubnub.Publish<string>(channel, message, null, DummyErrorCallback);
pubnub = null;
}
[Test]
public void ThenOptionalSecretKeyShouldBeProvidedInConstructor()
{
isPublished2 = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "key");
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "ThenOptionalSecretKeyShouldBeProvidedInConstructor";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = "Pubnub API Usage Example";
pubnub.Publish<string>(channel, message, ReturnSecretKeyPublishCallback, DummyErrorCallback);
mreOptionalSecretKeyPublish.WaitOne(310 * 1000);
pubnub.EndPendingRequests();
pubnub = null;
Assert.True(isPublished2, "Publish Failed with secret key");
}
private void ReturnSecretKeyPublishCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isPublished2 = true;
}
}
}
mreOptionalSecretKeyPublish.Set();
}
[Test]
public void IfSSLNotProvidedThenDefaultShouldBeFalse()
{
isPublished3 = false;
pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "");
PubnubUnitTest unitTest = new PubnubUnitTest();
unitTest.TestClassName = "WhenAMessageIsPublished";
unitTest.TestCaseName = "IfSSLNotProvidedThenDefaultShouldBeFalse";
pubnub.PubnubUnitTest = unitTest;
string channel = "hello_my_channel";
string message = "Pubnub API Usage Example";
pubnub.Publish<string>(channel, message, ReturnNoSSLDefaultFalseCallback, DummyErrorCallback);
mreNoSslPublish.WaitOne(310 * 1000);
pubnub.EndPendingRequests();
pubnub = null;
Assert.True(isPublished3, "Publish Failed with no SSL");
}
private void ReturnNoSSLDefaultFalseCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isPublished3 = true;
}
}
}
mreNoSslPublish.Set();
}
private void ReturnSuccessSerializedObjectMessageForPublishCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
long statusCode = Int64.Parse(deserializedMessage[0].ToString());
string statusMessage = (string)deserializedMessage[1];
if (statusCode == 1 && statusMessage.ToLower() == "sent")
{
isSerializedObjectMessagePublished = true;
serializedMessagePublishTimetoken = Convert.ToInt64(deserializedMessage[2].ToString());
}
}
}
mreSerializedObjectMessageForPublish.Set();
}
private void CaptureSerializedMessagePublishDetailedHistoryCallback(string result)
{
if (!string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(result.Trim()))
{
List<object> deserializedMessage = pubnub.JsonPluggableLibrary.DeserializeToListOfObject(result);
if (deserializedMessage != null && deserializedMessage.Count > 0)
{
object[] message = pubnub.JsonPluggableLibrary.ConvertToObjectArray(deserializedMessage[0]);
if (message != null && message.Length > 0)
{
string publishedMesaage = pubnub.JsonPluggableLibrary.SerializeToJsonString(message[0]);
if (publishedMesaage == serializedObjectMessageForPublish)
{
isSerializedObjectMessageDetailedHistory = true;
}
}
}
}
mreSerializedMessagePublishDetailedHistory.Set();
}
private void DummyErrorCallback(PubnubClientError result)
{
if (result != null)
{
Console.WriteLine(result.Message);
}
}
}
}
| 70.618063 | 23,411 | 0.68093 | [
"MIT"
] | redarrowlabs/pubnub-c-sharp | mono-for-android/Andr.Unit-master/Andr.Unit/WhenAMessageIsPublished.cs | 64,904 | C# |
using System.Data.Common;
using DBManager.Default.DataBaseConnection;
using DBManager.Default.MetadataFactory;
using DBManager.Default.Normalizers;
using DBManager.Default.Printers;
using DBManager.Default.Providers;
using DBManager.Default.Tree.Hierarchy;
namespace DBManager.Default
{
public interface IDialectComponent
{
DialectType Type { get; }
IPrinter Printer { get; }
IScriptProvider ScriptProvider { get; }
IMetadataHierarchy Hierarchy { get; }
IMetadataFactory ObjectFactory { get; }
NormalizerBase Normalizer { get; }
DbCommand CreateCommand();
DbParameter CreateParameter();
IConnectionData CreateConnectionData();
}
}
| 21.382353 | 47 | 0.712517 | [
"Apache-2.0"
] | meCtd/DBManager | src/DBManager.Default/IDialectComponent.cs | 729 | C# |
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
namespace StatisticalLearning.Math.MatrixDecompositions
{
public class SchurDecomposition
{
private SchurDecomposition(Vector eigenValues, Matrix eigenVectors)
{
EigenValues = eigenValues;
EigenVectors = eigenVectors;
}
public Vector EigenValues { get; set; }
public Matrix EigenVectors { get; set; }
/// <summary>
/// http://web.math.ucsb.edu/~padraic/ucsb_2013_14/math108b_w2014/math108b_w2014_lecture5.pdf
/// </summary>
/// <param name="matrix"></param>
/// <param name="min"></param>
/// <returns></returns>
public static SchurDecomposition Decompose(Matrix matrix, double min = 1E-6)
{
var a = (Matrix)matrix.Clone();
var eingenVectors = Matrix.BuildIdentityMatrix(matrix.NbColumns);
while(true)
{
var res = QRDecomposition.Decompose(a);
a = res.R.Multiply(res.Q).Evaluate();
eingenVectors = eingenVectors.Multiply(res.Q).Evaluate();
if (CheckConvergence(a, min))
{
break;
}
}
return new SchurDecomposition(a.GetDiagonal(), eingenVectors);
}
private static bool CheckConvergence(Matrix matrix, double min)
{
for (int column = 0; column < matrix.NbColumns; column++)
{
for(int row = column + 1; row < matrix.NbRows; row++)
{
if (matrix.GetValue(row, column).GetNumber() > min)
{
return false;
}
}
}
return true;
}
}
}
| 32.983051 | 107 | 0.534943 | [
"Apache-2.0"
] | simpleidserver/StatisticalLearning | src/StatisticalLearning/Math/MatrixDecompositions/SchurDecomposition.cs | 1,948 | C# |
using System;
using System.Collections.Generic;
using System.Security.Claims;
using ErrorCentral.Application.DTOs;
using ErrorCentral.Application.ServiceInterfaces;
using ErrorCentral.Domain.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace ErrorCentral.API.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class LogController : ControllerBase
{
//underline utilizado porque a classe e privada (padrão da comunidade)
private readonly ILogService _app;
private readonly IErrorService _err;
public LogController(ILogService app, IErrorService err)
{
_app = app;
_err = err;
}
[HttpGet]
public ActionResult<IEnumerable<LogDTO>> Get()
{
try
{
if (_app.SelectAll().Count > 0)
{
return Ok(_app.SelectAll());
}
else
{
return NoContent();
}
}
catch (Exception ex)
{
_err.Add(ex, HttpContext.User.Identity.Name);
return BadRequest(ex.Message);
}
}
[HttpGet("{id}")]
public ActionResult<LogDTO> Get(int id)
{
try
{
if (_app.SelectById(id) != null)
{
return Ok(_app.SelectById(id));
}
else
{
return NoContent();
}
}
catch (Exception ex)
{
_err.Add(ex, HttpContext.User.Identity.Name);
return BadRequest(ex.Message);
}
}
[HttpPost]
public ActionResult<IEnumerable<LogDTO>> Post([FromBody] LogAddDTO log)
{
try
{
if (!ModelState.IsValid)
throw new Exception("Fail on model validation");
_app.Add(log);
return _app.SelectAll();
}
catch (Exception ex)
{
_err.Add(ex, HttpContext.User.Identity.Name);
return BadRequest(ex.Message);
}
}
[HttpPut]
public ActionResult<IEnumerable<LogDTO>> Put([FromBody] LogUpdateDTO log)
{
try
{
if (!ModelState.IsValid)
throw new Exception("Fail on model validation");
_app.Update(log);
return Ok(_app.SelectAll());
}
catch (Exception ex)
{
_err.Add(ex, HttpContext.User.Identity.Name);
return BadRequest(ex.Message);
}
}
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
try
{
if (_app.SelectById(id) != null)
{
_app.Delete(id);
return NoContent();
}
else
{
return BadRequest($"Log with id {id} not found");
}
}
catch (Exception ex)
{
_err.Add(ex, HttpContext.User.Identity.Name);
return BadRequest(ex.Message);
}
}
[HttpPost]
[Route("/[action]")]
public ActionResult<IEnumerable<LogDTO>> DeleteMany([FromBody] List<int> ids)
{
try
{
_app.DeleteMany(ids);
return Ok(_app.SelectAll());
}
catch (Exception ex)
{
_err.Add(ex, HttpContext.User.Identity.Name);
return BadRequest(ex.Message);
}
}
}
} | 27.268966 | 85 | 0.458776 | [
"MIT"
] | conradoalexsander/Error-Central-API | ErrorCentral.API/Controllers/LogController.cs | 3,957 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/services/keyword_theme_constant_service.proto
// </auto-generated>
// Original file comments:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
//
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace Google.Ads.GoogleAds.V10.Services {
/// <summary>
/// Service to fetch Smart Campaign keyword themes.
/// </summary>
public static partial class KeywordThemeConstantService
{
static readonly string __ServiceName = "google.ads.googleads.v10.services.KeywordThemeConstantService";
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context)
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (message is global::Google.Protobuf.IBufferMessage)
{
context.SetPayloadLength(message.CalculateSize());
global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter());
context.Complete();
return;
}
#endif
context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message));
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static class __Helper_MessageCache<T>
{
public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T));
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T>
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (__Helper_MessageCache<T>.IsBufferMessage)
{
return parser.ParseFrom(context.PayloadAsReadOnlySequence());
}
#endif
return parser.ParseFrom(context.PayloadAsNewBuffer());
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest> __Marshaller_google_ads_googleads_v10_services_SuggestKeywordThemeConstantsRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse> __Marshaller_google_ads_googleads_v10_services_SuggestKeywordThemeConstantsResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest, global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse> __Method_SuggestKeywordThemeConstants = new grpc::Method<global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest, global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"SuggestKeywordThemeConstants",
__Marshaller_google_ads_googleads_v10_services_SuggestKeywordThemeConstantsRequest,
__Marshaller_google_ads_googleads_v10_services_SuggestKeywordThemeConstantsResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Ads.GoogleAds.V10.Services.KeywordThemeConstantServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of KeywordThemeConstantService</summary>
[grpc::BindServiceMethod(typeof(KeywordThemeConstantService), "BindService")]
public abstract partial class KeywordThemeConstantServiceBase
{
/// <summary>
/// Returns KeywordThemeConstant suggestions by keyword themes.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse> SuggestKeywordThemeConstants(global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for KeywordThemeConstantService</summary>
public partial class KeywordThemeConstantServiceClient : grpc::ClientBase<KeywordThemeConstantServiceClient>
{
/// <summary>Creates a new client for KeywordThemeConstantService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public KeywordThemeConstantServiceClient(grpc::ChannelBase channel) : base(channel)
{
}
/// <summary>Creates a new client for KeywordThemeConstantService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public KeywordThemeConstantServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected KeywordThemeConstantServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected KeywordThemeConstantServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Returns KeywordThemeConstant suggestions by keyword themes.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse SuggestKeywordThemeConstants(global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return SuggestKeywordThemeConstants(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns KeywordThemeConstant suggestions by keyword themes.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse SuggestKeywordThemeConstants(global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_SuggestKeywordThemeConstants, null, options, request);
}
/// <summary>
/// Returns KeywordThemeConstant suggestions by keyword themes.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse> SuggestKeywordThemeConstantsAsync(global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return SuggestKeywordThemeConstantsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns KeywordThemeConstant suggestions by keyword themes.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse> SuggestKeywordThemeConstantsAsync(global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_SuggestKeywordThemeConstants, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected override KeywordThemeConstantServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new KeywordThemeConstantServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public static grpc::ServerServiceDefinition BindService(KeywordThemeConstantServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_SuggestKeywordThemeConstants, serviceImpl.SuggestKeywordThemeConstants).Build();
}
/// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary>
/// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public static void BindService(grpc::ServiceBinderBase serviceBinder, KeywordThemeConstantServiceBase serviceImpl)
{
serviceBinder.AddMethod(__Method_SuggestKeywordThemeConstants, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsRequest, global::Google.Ads.GoogleAds.V10.Services.SuggestKeywordThemeConstantsResponse>(serviceImpl.SuggestKeywordThemeConstants));
}
}
}
#endregion
| 58.334677 | 431 | 0.732633 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V10/Services/KeywordThemeConstantServiceGrpc.g.cs | 14,467 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DocumentDB.Latest.Outputs
{
[OutputType]
public sealed class CorsPolicyResponse
{
/// <summary>
/// The request headers that the origin domain may specify on the CORS request.
/// </summary>
public readonly string? AllowedHeaders;
/// <summary>
/// The methods (HTTP request verbs) that the origin domain may use for a CORS request.
/// </summary>
public readonly string? AllowedMethods;
/// <summary>
/// The origin domains that are permitted to make a request against the service via CORS.
/// </summary>
public readonly string AllowedOrigins;
/// <summary>
/// The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer.
/// </summary>
public readonly string? ExposedHeaders;
/// <summary>
/// The maximum amount time that a browser should cache the preflight OPTIONS request.
/// </summary>
public readonly int? MaxAgeInSeconds;
[OutputConstructor]
private CorsPolicyResponse(
string? allowedHeaders,
string? allowedMethods,
string allowedOrigins,
string? exposedHeaders,
int? maxAgeInSeconds)
{
AllowedHeaders = allowedHeaders;
AllowedMethods = allowedMethods;
AllowedOrigins = allowedOrigins;
ExposedHeaders = exposedHeaders;
MaxAgeInSeconds = maxAgeInSeconds;
}
}
}
| 33.333333 | 135 | 0.635263 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/DocumentDB/Latest/Outputs/CorsPolicyResponse.cs | 1,900 | C# |
using Ryujinx.Common.Logging;
namespace Ryujinx.HLE.HOS.Tamper.Operations
{
class OpLog<T> : IOperation where T : unmanaged
{
int _logId;
IOperand _source;
public OpLog(int logId, IOperand source)
{
_logId = logId;
_source = source;
}
public void Execute()
{
Logger.Debug?.Print(LogClass.TamperMachine, $"Tamper debug log id={_logId} value={(dynamic)_source.Get<T>():X}");
}
}
}
| 22.454545 | 125 | 0.566802 | [
"MIT"
] | 0MrDarn0/Ryujinx | Ryujinx.HLE/HOS/Tamper/Operations/OpLog.cs | 494 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WireMock.Http;
using WireMock.Models;
using WireMock.Util;
#if !USE_ASPNETCORE
using IRequest = Microsoft.Owin.IOwinRequest;
#else
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using IRequest = Microsoft.AspNetCore.Http.HttpRequest;
#endif
namespace WireMock.Owin.Mappers
{
/// <summary>
/// OwinRequestMapper
/// </summary>
internal class OwinRequestMapper : IOwinRequestMapper
{
/// <inheritdoc cref="IOwinRequestMapper.MapAsync"/>
public async Task<RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options)
{
(UrlDetails urldetails, string clientIP) = ParseRequest(request);
string method = request.Method;
Dictionary<string, string[]> headers = null;
IEnumerable<string> contentEncodingHeader = null;
if (request.Headers.Any())
{
headers = new Dictionary<string, string[]>();
foreach (var header in request.Headers)
{
headers.Add(header.Key, header.Value);
if (string.Equals(header.Key, HttpKnownHeaderNames.ContentEncoding, StringComparison.OrdinalIgnoreCase))
{
contentEncodingHeader = header.Value;
}
}
}
IDictionary<string, string> cookies = null;
if (request.Cookies.Any())
{
cookies = new Dictionary<string, string>();
foreach (var cookie in request.Cookies)
{
cookies.Add(cookie.Key, cookie.Value);
}
}
BodyData body = null;
if (request.Body != null && BodyParser.ShouldParseBody(method, options.AllowBodyForAllHttpMethods == true))
{
var bodyParserSettings = new BodyParserSettings
{
Stream = request.Body,
ContentType = request.ContentType,
DeserializeJson = !options.DisableJsonBodyParsing.GetValueOrDefault(false),
ContentEncoding = contentEncodingHeader?.FirstOrDefault(),
DecompressGZipAndDeflate = !options.DisableRequestBodyDecompressing.GetValueOrDefault(false)
};
body = await BodyParser.Parse(bodyParserSettings);
}
return new RequestMessage(urldetails, method, clientIP, body, headers, cookies) { DateTime = DateTime.UtcNow };
}
private (UrlDetails UrlDetails, string ClientIP) ParseRequest(IRequest request)
{
#if !USE_ASPNETCORE
var urldetails = UrlUtils.Parse(request.Uri, request.PathBase);
string clientIP = request.RemoteIpAddress;
#else
var urldetails = UrlUtils.Parse(new Uri(request.GetEncodedUrl()), request.PathBase);
var connection = request.HttpContext.Connection;
string clientIP = connection.RemoteIpAddress.IsIPv4MappedToIPv6
? connection.RemoteIpAddress.MapToIPv4().ToString()
: connection.RemoteIpAddress.ToString();
#endif
return (urldetails, clientIP);
}
}
} | 37.730337 | 124 | 0.607207 | [
"Apache-2.0"
] | APIWT/WireMock.Net | src/WireMock.Net/Owin/Mappers/OwinRequestMapper.cs | 3,360 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace RoutingSample.Web.HelloExtension
{
public class HelloOptions
{
public string Greeter { get; set; }
}
}
| 27.454545 | 111 | 0.711921 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/HelloOptions.cs | 304 | C# |
namespace Clients.Models.Basket
{
public class BasketRequest
{
public string basketId { get; set; }
}
} | 17.714286 | 44 | 0.629032 | [
"MIT"
] | kubilayeldemir/ecommerce-microservices | ApiGateway/Clients/Models/Basket/BasketRequest.cs | 126 | C# |
Subsets and Splits