content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.Collections.Generic;
using Newtonsoft.Json;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.gpdb.Model.V20160503
{
public class TagResourcesResponse : AcsResponse
{
private string requestId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 26.790698 | 63 | 0.719618 | [
"Apache-2.0"
] | pengweiqhca/aliyun-openapi-net-sdk | aliyun-net-sdk-gpdb/Gpdb/Model/V20160503/TagResourcesResponse.cs | 1,152 | C# |
// -----------------------------------------------------------------------
// <copyright file="ModuleUserBase.cs" company="OSharp开源团队">
// Copyright (c) 2014-2018 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2018-05-11 1:28</last-date>
// -----------------------------------------------------------------------
using System;
using System.ComponentModel;
using OSharp.Entity;
namespace OSharp.Authorization.Entities
{
/// <summary>
/// 模块用户信息基类
/// </summary>
/// <typeparam name="TModuleKey">模块编号</typeparam>
/// <typeparam name="TUserKey">用户编号</typeparam>
[TableNamePrefix("Auth")]
public abstract class ModuleUserBase<TModuleKey, TUserKey> : EntityBase<Guid>
{
/// <summary>
/// 获取或设置 模块编号
/// </summary>
[DisplayName("模块编号")]
public TModuleKey ModuleId { get; set; }
/// <summary>
/// 获取或设置 用户编号
/// </summary>
[DisplayName("用户编号")]
public TUserKey UserId { get; set; }
/// <summary>
/// 获取或设置 是否禁用。用户与模块的关系,默认从角色继承得来,如禁用,则禁用从角色继承的权限(黑名单),如不禁用,则相当于用户额外添加角色继承以外的权限(白名单)
/// </summary>
public bool Disabled { get; set; }
}
} | 29.674419 | 92 | 0.528213 | [
"Apache-2.0"
] | 1051324354/osharp | src/OSharp.Authorization.Functions/Entities/ModuleUserBase.cs | 1,534 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//////////////////////////////////////////////////////////
// L-1-3-1.cs - Beta1 Layout Test - RDawson
//
// Tests layout of classes using 1-deep nesting in
// the same assembly and module
//
// See ReadMe.txt in the same project as this source for
// further details about these tests.
//
using System;
class Test
{
public static int Main()
{
int mi_RetCode;
A a = new A();
mi_RetCode = a.Test();
if (mi_RetCode == 100)
Console.WriteLine("Pass");
else
Console.WriteLine("FAIL");
return mi_RetCode;
}
}
struct A
{
//@csharp - C# will not allow family or famorassem accessibility on value class members
public int Test()
{
int mi_RetCode = 100;
/////////////////////////////////
// Test nested class access
if (Test_Nested(ClsPubInst) != 100)
mi_RetCode = 0;
if (Test_Nested(ClsPrivInst) != 100)
mi_RetCode = 0;
if (Test_Nested(ClsAsmInst) != 100)
mi_RetCode = 0;
// to get rid of compiler warning
// warning CS0414: The private field 'A.ClsPrivStat' is assigned but its value is never used
A.ClsPubStat.ToString();
A.ClsPrivStat.ToString();
return mi_RetCode;
}
public int Test_Nested(Cls Nested_Cls)
{
int mi_RetCode = 100;
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// ACCESS NESTED FIELDS/MEMBERS
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////
// Test instance field access
Nested_Cls.NestFldPubInst = 100;
if (Nested_Cls.NestFldPubInst != 100)
mi_RetCode = 0;
Nested_Cls.NestFldAsmInst = 100;
if (Nested_Cls.NestFldAsmInst != 100)
mi_RetCode = 0;
/////////////////////////////////
// Test static field access
Cls.NestFldPubStat = 100;
if (Cls.NestFldPubStat != 100)
mi_RetCode = 0;
Cls.NestFldAsmStat = 100;
if (Cls.NestFldAsmStat != 100)
mi_RetCode = 0;
/////////////////////////////////
// Test instance method access
if (Nested_Cls.NestMethPubInst() != 100)
mi_RetCode = 0;
if (Nested_Cls.NestMethAsmInst() != 100)
mi_RetCode = 0;
/////////////////////////////////
// Test static method access
if (Cls.NestMethPubStat() != 100)
mi_RetCode = 0;
if (Cls.NestMethAsmStat() != 100)
mi_RetCode = 0;
////////////////////////////////////////////
// Test access from within the nested class
if (Nested_Cls.Test() != 100)
mi_RetCode = 0;
return mi_RetCode;
}
//////////////////////////////
// Instance Fields
public int FldPubInst;
private int FldPrivInst;
internal int FldAsmInst; //Translates to "assembly"
//////////////////////////////
// Static Fields
public static int FldPubStat;
private static int FldPrivStat;
internal static int FldAsmStat; //assembly
//////////////////////////////////////
// Instance fields for nested classes
public Cls ClsPubInst;
private Cls ClsPrivInst;
internal Cls ClsAsmInst;
/////////////////////////////////////
// Static fields of nested classes
public static Cls ClsPubStat = new Cls();
private static Cls ClsPrivStat = new Cls();
//////////////////////////////
// Instance Methods
public int MethPubInst()
{
Console.WriteLine("A::MethPubInst()");
return 100;
}
private int MethPrivInst()
{
Console.WriteLine("A::MethPrivInst()");
return 100;
}
internal int MethAsmInst()
{
Console.WriteLine("A::MethAsmInst()");
return 100;
}
//////////////////////////////
// Static Methods
public static int MethPubStat()
{
Console.WriteLine("A::MethPubStat()");
return 100;
}
private static int MethPrivStat()
{
Console.WriteLine("A::MethPrivStat()");
return 100;
}
internal static int MethAsmStat()
{
Console.WriteLine("A::MethAsmStat()");
return 100;
}
public struct Cls
{
public int Test()
{
int mi_RetCode = 100;
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// ACCESS ENCLOSING FIELDS/MEMBERS
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
//@csharp - C# will not allow nested classes to access non-static members of their enclosing classes
/////////////////////////////////
// Test static field access
FldPubStat = 100;
if (FldPubStat != 100)
mi_RetCode = 0;
FldAsmStat = 100;
if (FldAsmStat != 100)
mi_RetCode = 0;
/////////////////////////////////
// Test static method access
if (MethPubStat() != 100)
mi_RetCode = 0;
if (MethAsmStat() != 100)
mi_RetCode = 0;
////////////////////////////////////////////
// Test access from within the nested class
//@todo - Look at testing accessing one nested class from another, @bugug - NEED TO ADD SUCH TESTING, access the public nested class fields from here, etc...
return mi_RetCode;
}
//////////////////////////////
// Instance Fields
public int NestFldPubInst;
private int NestFldPrivInst;
internal int NestFldAsmInst; //Translates to "assembly"
//////////////////////////////
// Static Fields
public static int NestFldPubStat;
private static int NestFldPrivStat;
internal static int NestFldAsmStat; //assembly
//////////////////////////////
// Instance NestMethods
public int NestMethPubInst()
{
Console.WriteLine("A::NestMethPubInst()");
return 100;
}
private int NestMethPrivInst()
{
Console.WriteLine("A::NestMethPrivInst()");
return 100;
}
internal int NestMethAsmInst()
{
Console.WriteLine("A::NestMethAsmInst()");
return 100;
}
//////////////////////////////
// Static NestMethods
public static int NestMethPubStat()
{
Console.WriteLine("A::NestMethPubStat()");
return 100;
}
private static int NestMethPrivStat()
{
Console.WriteLine("A::NestMethPrivStat()");
return 100;
}
internal static int NestMethAsmStat()
{
Console.WriteLine("A::NestMethAsmStat()");
return 100;
}
}
}
| 27.832714 | 169 | 0.451583 | [
"MIT"
] | belav/runtime | src/tests/Loader/classloader/v1/Beta1/Layout/Matrix/cs/L-2-3-1.cs | 7,487 | C# |
/*
MIT LICENSE
Copyright 2017 Digital Ruby, LLC - http://www.digitalruby.com
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.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using ExchangeSharp;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ExchangeSharpTests
{
using System.Diagnostics;
using System.Globalization;
using System.Security;
using System.Security.Cryptography;
[TestClass]
public class CryptoUtilityTests
{
private static Action Invoking(Action action) => action;
[TestMethod]
public void RoundDown()
{
CryptoUtility.RoundDown(1.2345m, 2).Should().Be(1.23m);
CryptoUtility.RoundDown(1.2345m, 4).Should().Be(1.2345m);
CryptoUtility.RoundDown(1.2345m, 5).Should().Be(1.2345m);
CryptoUtility.RoundDown(1.2345m, 0).Should().Be(1m);
CryptoUtility.RoundDown(1.2345m).Should().Be(1.234m);
}
[TestMethod]
public void RoundDownDefaultRules()
{
CryptoUtility.RoundDown(0.000123456789m).Should().Be(0.0001234m);
CryptoUtility.RoundDown(1.2345678m).Should().Be(1.234m);
CryptoUtility.RoundDown(10.2345678m).Should().Be(10m);
}
[TestMethod]
public void RoundDownOutOfRange()
{
void a() => CryptoUtility.RoundDown(1.2345m, -1);
Invoking(a).Should().Throw<ArgumentOutOfRangeException>();
}
[TestMethod]
public void ClampPrice()
{
CryptoUtility.ClampDecimal(0.00000100m, 100000.00000000m, 0.00000100m, 0.05507632m).Should().Be(0.055076m);
CryptoUtility.ClampDecimal(0.00000010m, 100000.00000000m, 0.00000010m, 0.00052286m).Should().Be(0.0005228m);
CryptoUtility.ClampDecimal(0.00001000m, 100000.00000000m, 0.00001000m, 0.02525215m).Should().Be(0.02525m);
CryptoUtility.ClampDecimal(0.00001000m, 100000.00000000m, null, 0.00401212m).Should().Be(0.00401212m);
}
[TestMethod]
public void ClampDecimalTrailingZeroesRemoved()
{
decimal result = CryptoUtility.ClampDecimal(0, Decimal.MaxValue, 0.01m, 1.23456789m);
result.Should().Be(1.23m);
result.ToString(CultureInfo.InvariantCulture).Should().NotEndWith("0");
}
[TestMethod]
public void ClampPriceOutOfRange()
{
void a() => CryptoUtility.ClampDecimal(-0.00000100m, 100000.00000000m, 0.00000100m, 0.05507632m);
Invoking(a).Should().Throw<ArgumentOutOfRangeException>();
void b() => CryptoUtility.ClampDecimal(0.00000100m, -100000.00000000m, 0.00000100m, 0.05507632m);
Invoking(b).Should().Throw<ArgumentOutOfRangeException>();
void c() => CryptoUtility.ClampDecimal(0.00000100m, 100000.00000000m, 0.00000100m, -0.05507632m);
Invoking(c).Should().Throw<ArgumentOutOfRangeException>();
void d() => CryptoUtility.ClampDecimal(0.00000100m, 100000.00000000m, -0.00000100m, 0.05507632m);
Invoking(d).Should().Throw<ArgumentOutOfRangeException>();
void e() => CryptoUtility.ClampDecimal(100000.00000000m, 0.00000100m, -0.00000100m, 0.05507632m);
Invoking(e).Should().Throw<ArgumentOutOfRangeException>();
}
[TestMethod]
public void ClampQuantity()
{
CryptoUtility.ClampDecimal(0.01000000m, 90000000.00000000m, 0.01000000m, 34.55215m).Should().Be(34.55m);
CryptoUtility.ClampDecimal(0.00100000m, 90000000.00000000m, 0.00100000m, 941.4192m).Should().Be(941.419m);
CryptoUtility.ClampDecimal(0.00000100m, 90000000.00000000m, 0.00000100m, 172.94102192m).Should().Be(172.941021m);
CryptoUtility.ClampDecimal(0.00010000m, 90000000.00000000m, null, 1837.31935m).Should().Be(1837.31935m);
}
[TestMethod]
public void ClampQuantityOutOfRange()
{
void a() => CryptoUtility.ClampDecimal(-0.00010000m, 900000.00000000m, 0.00010000m, 33.393832m);
Invoking(a).Should().Throw<ArgumentOutOfRangeException>();
void b() => CryptoUtility.ClampDecimal(0.00010000m, -900000.00000000m, 0.00010000m, 33.393832m);
Invoking(b).Should().Throw<ArgumentOutOfRangeException>();
void c() => CryptoUtility.ClampDecimal(0.00010000m, 900000.00000000m, 0.00010000m, -33.393832m);
Invoking(c).Should().Throw<ArgumentOutOfRangeException>();
void d() => CryptoUtility.ClampDecimal(0.00010000m, 900000.00000000m, -0.00010000m, 33.393832m);
Invoking(d).Should().Throw<ArgumentOutOfRangeException>();
void e() => CryptoUtility.ClampDecimal(900000.00000000m, 0.00010000m, -0.00010000m, 33.393832m);
Invoking(e).Should().Throw<ArgumentOutOfRangeException>();
}
[TestMethod]
public void CalculatePrecision_NoDecimals_Returns1()
{
CryptoUtility.CalculatePrecision("24").Should().Be(1);
CryptoUtility.CalculatePrecision("1000").Should().Be(1);
CryptoUtility.CalculatePrecision("123456789123456789465132").Should().Be(1);
}
[TestMethod]
public void CalculatePrecision_WithDecimals()
{
CryptoUtility.CalculatePrecision("1.12").Should().Be(0.01m);
CryptoUtility.CalculatePrecision("1.123456789").Should().Be(0.000000001m);
CryptoUtility.CalculatePrecision("1.0").Should().Be(0.1m);
CryptoUtility.CalculatePrecision("0.00000").Should().Be(0.00001m);
}
[TestMethod]
public void AESEncryption()
{
byte[] salt = new byte[] { 65, 61, 53, 222, 105, 5, 199, 241, 213, 56, 19, 120, 251, 37, 66, 185 };
byte[] data = new byte[255];
for (int i = 0; i < data.Length; i++)
{
data[i] = (byte)i;
}
byte[] password = new byte[16];
for (int i = password.Length - 1; i >= 0; i--)
{
password[i] = (byte)i;
}
byte[] encrypted = CryptoUtility.AesEncryption(data, password, salt);
byte[] decrypted = CryptoUtility.AesDecryption(encrypted, password, salt);
Assert.IsTrue(decrypted.SequenceEqual(data));
byte[] protectedData = DataProtector.Protect(salt);
byte[] unprotectedData = DataProtector.Unprotect(protectedData);
Assert.IsTrue(unprotectedData.SequenceEqual(salt));
}
[TestMethod]
public void RSAFromFile()
{
byte[] originalValue = new byte[256];
new System.Random().NextBytes(originalValue);
for (int i = 0; i < 4; i++)
{
DataProtector.DataProtectionScope scope = (i < 2 ? DataProtector.DataProtectionScope.CurrentUser : DataProtector.DataProtectionScope.LocalMachine);
RSA rsa = DataProtector.RSAFromFile(scope);
byte[] encrypted = rsa.Encrypt(originalValue, RSAEncryptionPadding.Pkcs1);
byte[] decrypted = rsa.Decrypt(encrypted, RSAEncryptionPadding.Pkcs1);
Assert.IsTrue(originalValue.SequenceEqual(decrypted));
}
}
[TestMethod]
public void KeyStore()
{
// store keys
string path = Path.Combine(Path.GetTempPath(), "keystore.test.bin");
string publicKey = "public key test aa45c0";
string privateKey = "private key test bb270a";
string[] keys = new string[] { publicKey, privateKey };
CryptoUtility.SaveUnprotectedStringsToFile(path, keys);
// read keys
SecureString[] keysRead = CryptoUtility.LoadProtectedStringsFromFile(path);
string publicKeyRead = CryptoUtility.ToUnsecureString(keysRead[0]);
string privateKeyRead = CryptoUtility.ToUnsecureString(keysRead[1]);
Assert.AreEqual(privateKeyRead, privateKey);
Assert.AreEqual(publicKeyRead, publicKey);
}
[TestMethod]
public void ConvertInvariantTest()
{
CultureInfo info = Thread.CurrentThread.CurrentCulture;
try
{
CultureInfo info2 = new CultureInfo("fr-FR");
string[] decimals = new string[] { "7800.07", "0.00172", "155975495", "7.93E+3", "0.00018984", "155975362" };
foreach (string doubleString in decimals)
{
Thread.CurrentThread.CurrentCulture = info;
decimal value = doubleString.ConvertInvariant<decimal>();
Thread.CurrentThread.CurrentCulture = info2;
decimal value2 = doubleString.ConvertInvariant<decimal>();
Assert.AreEqual(value, value2);
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
decimal value3 = doubleString.ConvertInvariant<decimal>();
Assert.AreEqual(value2, value3);
}
}
finally
{
Thread.CurrentThread.CurrentCulture = info;
}
}
[TestMethod]
public void RateGate()
{
const int timesPerPeriod = 1;
const int ms = 100;
const int loops = 5;
double msMax = (double)ms * 1.5;
double msMin = (double)ms * (1.0 / 1.5);
RateGate gate = new RateGate(timesPerPeriod, TimeSpan.FromMilliseconds(ms));
if (!gate.WaitToProceedAsync(0).Sync())
{
throw new APIException("Rate gate should have allowed immediate access to first attempt");
}
for (int i = 0; i < loops; i++)
{
Stopwatch timer = Stopwatch.StartNew();
gate.WaitToProceedAsync().Sync();
timer.Stop();
if (i > 0)
{
// check for too much elapsed time with a little fudge
Assert.IsTrue(timer.Elapsed.TotalMilliseconds <= msMax, "Rate gate took too long to wait in between calls: " + timer.Elapsed.TotalMilliseconds + "ms");
Assert.IsTrue(timer.Elapsed.TotalMilliseconds >= msMin, "Rate gate took too little to wait in between calls: " + timer.Elapsed.TotalMilliseconds + "ms");
}
}
}
}
} | 45.167969 | 460 | 0.620341 | [
"MIT"
] | abdullahkaracabey/ExchangeSharp | ExchangeSharpTests/CryptoUtilityTests.cs | 11,565 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using Nucleo.Presentation;
using Nucleo.Web.Services;
using Nucleo.Views;
using Nucleo.Web.Views;
using Nucleo.EventArguments;
namespace Nucleo.WebServices
{
public class MvpSampleWcfServicePresenter : BasePresenter<IMvpSampleWcfSWerviceView>
{
public MvpSampleWcfServicePresenter(IMvpSampleWcfSWerviceView view)
: base(view)
{
view.Starting += View_Starting;
}
void View_Starting(object sender, EventArgs e)
{
this.View.Model = new MvpSampleWcfServiceModel
{
Data = this.GetValues()
};
}
public string[] GetValues()
{
return new string[] { "A", "B", "C", "D", "E" };
}
}
public interface IMvpSampleWcfSWerviceView : IView<MvpSampleWcfServiceModel>
{
}
public class MvpSampleWcfServiceModel
{
public string[] Data { get; set; }
}
[ServiceContract(Namespace = "Nucleo.WebServices")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[PresenterBinding("Nucleo.WebServices.MvpSampleWcfServicePresenter, Nucleo.OnlineMVPTests")]
public class MvpSampleWcfService : ViewWcfService<MvpSampleWcfServiceModel>, IMvpSampleWcfSWerviceView
{
#region " Methods "
[
OperationContract,
WebGet(ResponseFormat = WebMessageFormat.Json)
]
public string[] GetValues()
{
return this.Model.Data;
}
#endregion
}
}
| 21.690141 | 103 | 0.755195 | [
"MIT"
] | brianmains/Nucleo.NET | src/Backup/Nucleo.OnlineMVPTests/WebServices/MvpSampleWcfService.svc.cs | 1,542 | C# |
// https://supportcenter.devexpress.com/ticket/details/t239143/auto-select-first-row-on-load
// a datagrid service which enable focusing the first row , even when rows get ordered
/*
<dxg:GridControl SelectionMode="Row" EnableSmartColumnsGeneration="True" ItemsSource="{Binding CompositionHistories}" ItemsSourceChanged="OnItemsSourceChanged" SelectedItem="{Binding SelectedHistory, Mode=TwoWay}" SourceUpdated="onSourceUpdated" >
<dxmvvm:Interaction.Behaviors>
<viewModels:DataGridService/>
</dxmvvm:Interaction.Behaviors>
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DevExpress.Mvvm.UI;
using DevExpress.Xpf.Grid;
namespace WeRockClient.ViewModels
{
public interface IDataGridService
{
void FocusFirstRow();
void FocusRow(object value);
}
public class DataGridService:ServiceBase,IDataGridService
{
void IDataGridService.FocusFirstRow()
{
GridControl grid = ((GridControl)AssociatedObject);
grid.View.FocusedRowHandle = 0;
grid.SelectedItem = grid.GetRow(0);
}
}
}
| 30.756757 | 249 | 0.746924 | [
"MIT"
] | yacper/DevexpressLearning | Devexpress/Controls/DataGrid/DataGrid_AutoFocusFirstRow/DataGridService.cs | 1,138 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Tasks.V2Beta3.Snippets
{
using Google.Cloud.Tasks.V2Beta3;
public sealed partial class GeneratedCloudTasksClientStandaloneSnippets
{
/// <summary>Snippet for CreateTask</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CreateTaskRequestObject()
{
// Create client
CloudTasksClient cloudTasksClient = CloudTasksClient.Create();
// Initialize request argument(s)
CreateTaskRequest request = new CreateTaskRequest
{
ParentAsQueueName = QueueName.FromProjectLocationQueue("[PROJECT]", "[LOCATION]", "[QUEUE]"),
Task = new Task(),
ResponseView = Task.Types.View.Unspecified,
};
// Make the request
Task response = cloudTasksClient.CreateTask(request);
}
}
}
| 37.909091 | 109 | 0.661871 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/tasks/v2beta3/google-cloud-tasks-v2beta3-csharp/Google.Cloud.Tasks.V2Beta3.StandaloneSnippets/CloudTasksClient.CreateTaskRequestObjectSnippet.g.cs | 1,668 | C# |
namespace nuPickers.PropertyEditors.DotNetLabels
{
using nuPickers.EmbeddedResource;
using Umbraco.Core.PropertyEditors;
internal class DotNetLabelsPreValueEditor : PreValueEditor
{
[PreValueField("dataSource", "", EmbeddedResource.ROOT_URL + "DotNetDataSource/DotNetDataSourceConfig.html", HideLabel = true)]
public string DataSource { get; set; }
[PreValueField("customLabel", "", EmbeddedResource.ROOT_URL + "CustomLabel/CustomLabelConfig.html", HideLabel = true)]
public string CustomLabel { get; set; }
/// <summary>
/// currently no ui, but forces controller to be loaded
/// </summary>
[PreValueField("labels", "", EmbeddedResource.ROOT_URL + "Labels/LabelsConfig.html", HideLabel = true)]
public string Labels { get; set; }
[PreValueField("layoutDirection", "Layout Direction", EmbeddedResource.ROOT_URL + "LayoutDirection/LayoutDirectionConfig.html")]
public string LayoutDirection { get; set; }
}
} | 44.391304 | 136 | 0.694417 | [
"MIT"
] | OxygenAS/nuPickers | source/nuPickers/PropertyEditors/DotNetLabels/DotNetLabelsPreValueEditor.cs | 1,023 | C# |
[assembly: SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "<Pending>", Scope = "member", Target = "~M:Test.InformationManager.Infrastructure.Modules.Applications.InfrastructureTest.OnCatalogInitialize(System.ComponentModel.Composition.Hosting.AggregateCatalog)")]
[assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "<Pending>", Scope = "member", Target = "~M:Test.InformationManager.Infrastructure.Modules.Applications.InfrastructureTest.OnCatalogInitialize(System.ComponentModel.Composition.Hosting.AggregateCatalog)")]
[assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "<Pending>", Scope = "member", Target = "~M:Test.InformationManager.Infrastructure.Modules.Applications.Services.MockDocumentService.GetStream(System.String,System.String,System.IO.FileMode)~System.IO.Stream")]
| 186.6 | 314 | 0.814577 | [
"MIT"
] | orangesocks/waf | src/System.Waf/Samples/InformationManager/Infrastructure.Modules.Applications.Test/GlobalSuppressions.cs | 935 | C# |
namespace IGExtensions.Common.Controls
{
/// <summary>
/// Represents common <see cref="System.Windows.Controls.Expander"/> control wrapper for SL and WPF
/// </summary>
public class Expander : System.Windows.Controls.Expander
{
}
} | 24.181818 | 103 | 0.654135 | [
"MIT"
] | Infragistics/wpf-samples | Applications/IGExtensions/IGExtensions.Common/Controls/Toolkit/Expander.cs | 266 | C# |
using DynamicData;
using MonikDesktop.Common.Enums;
using MonikDesktop.Common.Interfaces;
using MonikDesktop.Common.ModelsApi;
using MonikDesktop.Common.ModelsApp;
using MonikDesktop.ViewModels.ShowModels;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Ui.Wpf.Common;
using Ui.Wpf.Common.ViewModels;
namespace MonikDesktop.ViewModels
{
public class LogsViewModel : ViewModelBase, IShowViewModel
{
private readonly LogsModel _model;
private IDisposable _updateExecutor;
public LogsViewModel(IShell aShell, ISourcesCacheProvider cacheProvider)
{
ScrollTo = new Interaction<LogItem, Unit>();
LogsSource = new SourceList<LogItem>();
LogsSource
.Connect()
.ObserveOnDispatcher()
.Bind(out _logsList)
.Subscribe()
.DisposeWith(Disposables);
_model = new LogsModel
{
Caption = "Logs",
Cache = cacheProvider.CurrentCache
}.DisposeWith(Disposables);
_model.WhenAnyValue(x => x.Caption, x => x.Online)
.ObserveOnDispatcher()
.Subscribe(v => Title = v.Item1 + (v.Item2 ? " >" : " ||"))
.DisposeWith(Disposables);
_model.ObservableForProperty(x => x.Online)
.Subscribe(p =>
{
if (p.Value)
{
LastId = null;
LogsSource.Clear();
var interval = TimeSpan.FromSeconds(_model.RefreshSec);
_updateExecutor = Observable
.Timer(interval, interval)
.Select(_ => Unit.Default)
.InvokeCommand(UpdateCommand);
}
else
_updateExecutor?.Dispose();
})
.DisposeWith(Disposables);
var canStart = _model.WhenAny(x => x.Online, x => !x.Value);
StartCommand = ReactiveCommand.Create(() =>
{
_model.Online = true;
return Unit.Default;
}, canStart);
var canStop = _model.WhenAny(x => x.Online, x => x.Value);
StopCommand = ReactiveCommand.Create(() =>
{
_model.Online = false;
return Unit.Default;
}, canStop);
UpdateCommand = ReactiveCommand.Create(OnUpdate);
UpdateCommand.Subscribe(result =>
{
LogsSource.AddRange(result);
});
Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
h => ((INotifyCollectionChanged) _logsList).CollectionChanged += h,
h => ((INotifyCollectionChanged) _logsList).CollectionChanged -= h)
.Where(x => x.EventArgs.Action == NotifyCollectionChangedAction.Add)
.Throttle(TimeSpan.FromSeconds(.1), RxApp.MainThreadScheduler)
.Where(_ => _model.AutoScroll)
.Subscribe(_ =>
{
var last = LogsSource.Items.LastOrDefault();
if (last != null)
ScrollTo.Handle(last).Wait();
})
.DisposeWith(Disposables);
}
public Interaction<LogItem, Unit> ScrollTo { get; set; }
public SourceList<LogItem> LogsSource { get; set; }
private ReadOnlyObservableCollection<LogItem> _logsList;
public ReadOnlyObservableCollection<LogItem> LogsList => _logsList;
public ReactiveCommand<Unit, LogItem[]> UpdateCommand { get; set; }
public long? LastId { get; private set; }
public ShowModel Model => _model;
public ReactiveCommand<Unit, Unit> StartCommand { get; set; }
public ReactiveCommand<Unit, Unit> StopCommand { get; set; }
private LogItem[] OnUpdate()
{
var req = new ELogRequest
{
LastID = LastId,
Level = _model.Level == LevelType.None ? null : (byte?) _model.Level,
SeverityCutoff =
_model.SeverityCutoff == SeverityCutoffType.None ? null : (byte?) _model.SeverityCutoff,
Top = _model.Top == TopType.None ? null : (byte?) _model.Top,
Groups = _model.Groups.ToArray(),
Instances = _model.Instances.ToArray()
};
ELog_[] response;
try
{
response = _model.Cache.Service.GetLogs(req);
}
catch
{
return new[] {new LogItem {Body = "INTERNAL ERROR", Created = DateTime.Now}};
}
if (response.Length > 0)
LastId = response.Max(x => x.ID);
IEnumerable<ELog_> groupedRequest;
if (_model.GroupDuplicatingItems)
groupedRequest = GroupDuplicatingLogs(response).OrderBy(x => x.ID);
else
groupedRequest = response;
var result = groupedRequest.Select(x =>
{
var created = x.Created.ToLocalTime();
return new LogItem
{
ID = x.ID,
Created = created,
CreatedStr = created.ToString(x.Doubled ? _model.DuplicatedDateTimeFormat : _model.DateTimeFormat),
Received = x.Received.ToLocalTime(),
ReceivedStr = x.Received.ToLocalTime().ToString(_model.DateTimeFormat),
Level = x.Level,
Severity = x.Severity,
Instance = _model.Cache.GetInstance(x.InstanceID),
Body = x.Body.Replace(Environment.NewLine, "")
};
});
return result.ToArray();
}
private IEnumerable<ELog_> GroupDuplicatingLogs(ELog_[] response)
{
var result = response?.GroupBy(r => new {r.InstanceID, r.Body, r.Severity, r.Level}).SelectMany(g =>
{
var min = g.Min(r => r.Created);
var firstIn5Sec = g.GroupBy(r =>
{
var totalSeconds = (r.Created - min).TotalSeconds;
var rez = totalSeconds - totalSeconds % _model.RefreshSec;
return rez;
})
.Select(inner =>
{
var eLog = inner.First();
if (inner.Count() > 1)
eLog.Doubled = true;
return eLog;
}).ToArray();
return firstIn5Sec;
});
return result;
}
protected override void DisposeInternals()
{
base.DisposeInternals();
_updateExecutor?.Dispose();
}
}
} | 37.064356 | 120 | 0.501937 | [
"MIT"
] | Totopolis/monik.desktop | MonikDesktopSolution/MonikDesktop/ViewModels/LogsViewModel.cs | 7,489 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using Enterspeed.Source.Sdk.Api.Models.Properties;
using Enterspeed.Source.SitecoreCms.V9.Extensions;
using Enterspeed.Source.SitecoreCms.V9.Models.Configuration;
using Enterspeed.Source.SitecoreCms.V9.Services.DataProperties;
using Enterspeed.Source.SitecoreCms.V9.Services.DataProperties.Formatters;
using Sitecore;
using Sitecore.Abstractions;
using Sitecore.Data.Items;
using Sitecore.Globalization;
using Sitecore.Layouts;
using Sitecore.Security.AccessControl;
using Sitecore.Security.Accounts;
using Version = Sitecore.Data.Version;
namespace Enterspeed.Source.SitecoreCms.V9.Services
{
public class EnterspeedPropertyService : IEnterspeedPropertyService
{
private const string MetaData = "metaData";
private const string Renderings = "renderings";
private readonly IEnterspeedConfigurationService _enterspeedConfigurationService;
private readonly IEnterspeedIdentityService _identityService;
private readonly EnterspeedDateFormatter _dateFormatter;
private readonly IEnumerable<IEnterspeedFieldValueConverter> _fieldValueConverters;
private readonly IEnterspeedFieldConverter _fieldConverter;
private readonly BaseItemManager _itemManager;
private readonly BaseUserManager _userManager;
private readonly BaseAccessRightManager _accessRightManager;
private readonly BaseRolesInRolesManager _rolesInRolesManager;
public EnterspeedPropertyService(
IEnterspeedConfigurationService enterspeedConfigurationService,
IEnterspeedIdentityService identityService,
EnterspeedDateFormatter dateFormatter,
IEnumerable<IEnterspeedFieldValueConverter> fieldValueConverters,
IEnterspeedFieldConverter fieldConverter,
BaseItemManager itemManager,
BaseUserManager userManager,
BaseAccessRightManager accessRightManager,
BaseRolesInRolesManager rolesInRolesManager)
{
_enterspeedConfigurationService = enterspeedConfigurationService;
_identityService = identityService;
_dateFormatter = dateFormatter;
_fieldValueConverters = fieldValueConverters;
_fieldConverter = fieldConverter;
_itemManager = itemManager;
_userManager = userManager;
_accessRightManager = accessRightManager;
_rolesInRolesManager = rolesInRolesManager;
}
public IDictionary<string, IEnterspeedProperty> GetProperties(Item item)
{
if (item.IsDictionaryItem())
{
IDictionary<string, IEnterspeedProperty> dictionaryProperties = _fieldConverter.ConvertFields(item, null, _fieldValueConverters.ToList());
return dictionaryProperties;
}
EnterspeedSiteInfo siteOfItem = _enterspeedConfigurationService
.GetConfiguration()
.GetSite(item);
if (siteOfItem == null)
{
return null;
}
IDictionary<string, IEnterspeedProperty> properties = _fieldConverter.ConvertFields(item, siteOfItem, _fieldValueConverters.ToList());
properties.Add(MetaData, CreateMetaData(item));
IEnterspeedProperty renderings = CreateRenderings(item);
if (renderings != null)
{
properties.Add(Renderings, renderings);
}
return properties;
}
public IDictionary<string, IEnterspeedProperty> GetProperties(RenderingItem item)
{
IDictionary<string, IEnterspeedProperty> properties = _fieldConverter.ConvertFields(item.InnerItem, null, _fieldValueConverters.ToList());
return properties;
}
private static List<Guid> GetContentPathIds(Item item)
{
List<Guid> ids = item
.Paths
.LongID
.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
.Select(Guid.Parse)
.Where(x => x != ItemIDs.RootID.Guid && x != ItemIDs.ContentRoot.Guid)
.ToList();
return ids;
}
private IEnterspeedProperty CreateMetaData(Item item)
{
int level = GetContentPathIds(item).IndexOf(item.ID.Guid);
var metaData = new Dictionary<string, IEnterspeedProperty>
{
["name"] = new StringEnterspeedProperty("name", item.Name),
["displayName"] = new StringEnterspeedProperty("displayName", item.DisplayName),
["language"] = new StringEnterspeedProperty("language", item.Language.Name),
["sortOrder"] = new NumberEnterspeedProperty("sortOrder", item.Appearance.Sortorder),
["level"] = new NumberEnterspeedProperty("level", level),
["createDate"] = new StringEnterspeedProperty("createDate", _dateFormatter.FormatDate(item.Statistics.Created)),
["updateDate"] = new StringEnterspeedProperty("updateDate", _dateFormatter.FormatDate(item.Statistics.Updated)),
["updatedBy"] = new StringEnterspeedProperty("updatedBy", item.Statistics.UpdatedBy),
["fullPath"] = new ArrayEnterspeedProperty("fullPath", GetItemFullPath(item)),
["languages"] = new ArrayEnterspeedProperty("languages", GetAvailableLanguagesOfItem(item)),
["isAccessRestricted"] = GetIsAccessRestricted(item),
["accessRestrictions"] = GetAccessRestrictions(item)
};
return new ObjectEnterspeedProperty(MetaData, metaData);
}
private IEnterspeedProperty CreateRenderings(Item item)
{
var renderingReferences = new List<ObjectEnterspeedProperty>();
RenderingReference[] renderings = item.Visualization.GetRenderings(DeviceItem.ResolveDevice(item.Database), false);
foreach (RenderingReference renderingReference in renderings)
{
if (renderingReference.RenderingItem == null)
{
continue;
}
if (renderingReference.RenderingID.Guid == Guid.Empty)
{
continue;
}
string placeholder;
if (!string.IsNullOrEmpty(renderingReference.Placeholder))
{
placeholder = renderingReference.Placeholder;
}
else
{
placeholder = renderingReference.RenderingItem.Placeholder;
}
if (string.IsNullOrEmpty(placeholder))
{
// We cannot continue not knowing the placeholder
continue;
}
var renderingProperties = new Dictionary<string, IEnterspeedProperty>
{
["name"] = new StringEnterspeedProperty("name", renderingReference.RenderingItem.Name),
["placeholder"] = new StringEnterspeedProperty("placeholder", placeholder)
};
if (!string.IsNullOrEmpty(renderingReference.Settings.Parameters))
{
NameValueCollection parameters = HttpUtility.ParseQueryString(renderingReference.Settings.Parameters);
var parameterItems = new List<StringEnterspeedProperty>();
foreach (string key in parameters)
{
if (string.IsNullOrEmpty(key))
{
continue;
}
string value = parameters[key];
if (string.IsNullOrEmpty(value))
{
continue;
}
parameterItems.Add(new StringEnterspeedProperty(key, value));
}
if (parameters.Count > 0 && parameterItems.Count > 0)
{
renderingProperties.Add("parameters", new ArrayEnterspeedProperty("parameters", parameterItems.ToArray()));
}
}
if (!string.IsNullOrEmpty(renderingReference.Settings.DataSource))
{
Item datasourceItem = item.Database.GetItem(renderingReference.Settings.DataSource, item.Language, Version.Latest);
if (datasourceItem != null && datasourceItem.Versions.Count > 0)
{
renderingProperties.Add("datasource", new StringEnterspeedProperty("datasource", _identityService.GetId(datasourceItem)));
}
}
renderingReferences.Add(new ObjectEnterspeedProperty(null, renderingProperties));
}
if (!renderingReferences.Any())
{
return null;
}
return new ArrayEnterspeedProperty(Renderings, renderingReferences.ToArray());
}
private IEnterspeedProperty[] GetItemFullPath(Item item)
{
List<Guid> ids = GetContentPathIds(item);
var properties = ids
.Select(x => new StringEnterspeedProperty(null, _identityService.GetId(x, item.Language)))
.ToArray();
return properties;
}
private IEnterspeedProperty[] GetAvailableLanguagesOfItem(Item item)
{
var languages = new List<StringEnterspeedProperty>();
foreach (Language language in item.Languages)
{
Item itemInLanguage = _itemManager.GetItem(item.ID, language, Version.Latest, item.Database);
if (itemInLanguage == null ||
itemInLanguage.Versions.Count == 0)
{
continue;
}
languages.Add(new StringEnterspeedProperty(null, language.Name));
}
return languages.ToArray();
}
private IEnterspeedProperty GetIsAccessRestricted(Item item)
{
bool isAccessRestricted;
var allUsers = _userManager.GetUsers().ToList();
var anonymous = allUsers.Single(x => x.Name.Equals("extranet\\anonymous", StringComparison.OrdinalIgnoreCase));
using (new UserSwitcher(anonymous))
{
isAccessRestricted = !item.Access.CanRead();
}
return new BooleanEnterspeedProperty("isAccessRestricted", isAccessRestricted);
}
private IEnterspeedProperty GetAccessRestrictions(Item item)
{
var readAccess = new Dictionary<string, bool>();
foreach (var user in _userManager.GetUsers())
{
using (new UserSwitcher(user))
{
var canRead = item.Access.CanRead();
var userName = user.LocalName.ToLower();
if (readAccess.ContainsKey(userName))
{
readAccess[userName] = canRead;
}
else
{
readAccess.Add(userName, canRead);
}
}
}
var accessRestrictionItems = new List<BooleanEnterspeedProperty>();
if (readAccess.Any(x => !x.Value))
{
var usersWithRestrictedAccess = readAccess.Where(x => !x.Value).ToList();
accessRestrictionItems.AddRange(usersWithRestrictedAccess.Select(x => new BooleanEnterspeedProperty(x.Key, x.Value)));
}
return new ArrayEnterspeedProperty("accessRestrictions", accessRestrictionItems.ToArray());
}
}
} | 40.076667 | 154 | 0.596939 | [
"MIT"
] | enterspeedhq/enterspeed-source-sitecore-cms | src/Enterspeed.Source.SitecoreCms.V9/Services/EnterspeedPropertyService.cs | 12,025 | C# |
namespace AppCore.Enums
{
public enum Status { ToDo, Doing, Done }
} | 18.25 | 44 | 0.684932 | [
"MIT"
] | javier-de-lamo/Example_Kanban | AppCore/Enums/Status.cs | 75 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InmobiliariaLogicLayer.Persistence;
using InmobiliariaDataLayer.Connection;
using InmobiliariaViewModels.Cuotas;
namespace InmobiliariaDataLayer.Pagos
{
public class DBCalcMora: ISelectForId, ISave
{
private PostConnection db;
public DBCalcMora()
{
this.db = new PostConnection();
}
public object FindForId(int id)
{
var paramsMora = new CalcularMoraViewModels();
string query = "SELECT saldo, fecha, cuota, mora FROM calc_demorados WHERE venta_id = @venta_id"
+ " ORDER BY fecha DESC LIMIT 1";
using (var connection = PostConnection.Connection())
{
using (var command = db.Command(query))
{
try
{
connection.Open();
command.Parameters.AddWithValue("@venta_id", id);
command.Connection = connection;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
paramsMora.Saldo = Convert.ToDouble(reader["saldo"]);
paramsMora.Fecha = Convert.ToDateTime(reader["fecha"]);
paramsMora.Cuota = Convert.ToDouble(reader["cuota"]);
paramsMora.TasaMora = Convert.ToDouble(reader["mora"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
DateTime fechaUltimaMora = FechaUltimaMora(id);
paramsMora.Fecha = paramsMora.Fecha < fechaUltimaMora ? fechaUltimaMora : paramsMora.Fecha;
return paramsMora;
}
private DateTime FechaUltimaMora(int id)
{
DateTime fechaUltimaMora = new DateTime();
string query = "SELECT fecha FROM moras WHERE venta_id = @venta_id" +
" ORDER BY fecha DESC LIMIT 1";
using (var connection = PostConnection.Connection())
{
using (var command = db.Command(query))
{
try
{
connection.Open();
command.Parameters.AddWithValue("@venta_id", id);
command.Connection = connection;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
fechaUltimaMora = Convert.ToDateTime(reader["fecha"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
return fechaUltimaMora;
}
public int Save(object data)
{
int estado = -1;
var mora = (MoraViewModels)data;
string query = "INSERT INTO moras VALUES(null, @monto, @fecha, @estado, @venta_id)";
var command = db.Command(query);
command.Parameters.AddWithValue("@monto", mora.Monto);
command.Parameters.AddWithValue("@fecha", mora.Fecha);
command.Parameters.AddWithValue("@estado", 0);
command.Parameters.AddWithValue("@venta_id", mora.VentaId);
estado = db.Command(command);
return estado;
}
}
}
| 36.780952 | 108 | 0.474107 | [
"MIT"
] | djosuhe/cake | InmobiliariaDataLayer/Pagos/DBCalcMora.cs | 3,864 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeQuality;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.CSharp.MakeStructFieldsWritable
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpMakeStructFieldsWritableDiagnosticAnalyzer : AbstractCodeQualityDiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor s_diagnosticDescriptor = CreateDescriptor(
IDEDiagnosticIds.MakeStructFieldsWritable,
new LocalizableResourceString(nameof(FeaturesResources.Make_readonly_fields_writable), FeaturesResources.ResourceManager, typeof(FeaturesResources)),
new LocalizableResourceString(nameof(FeaturesResources.Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable), FeaturesResources.ResourceManager, typeof(FeaturesResources)),
isUnnecessary: false);
public CSharpMakeStructFieldsWritableDiagnosticAnalyzer()
: base(ImmutableArray.Create(s_diagnosticDescriptor), GeneratedCodeAnalysisFlags.ReportDiagnostics)
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
protected override void InitializeWorker(AnalysisContext context)
{
context.RegisterCompilationStartAction(compilationStartContext
=> SymbolAnalyzer.CreateAndRegisterActions(compilationStartContext));
}
private sealed class SymbolAnalyzer
{
private readonly INamedTypeSymbol _namedTypeSymbol;
private bool _hasTypeInstanceAssigment;
private SymbolAnalyzer(INamedTypeSymbol namedTypeSymbol)
=> _namedTypeSymbol = namedTypeSymbol;
public static void CreateAndRegisterActions(CompilationStartAnalysisContext compilationStartContext)
{
compilationStartContext.RegisterSymbolStartAction(symbolStartContext =>
{
// We report diagnostic only if these requirements are met:
// 1. The type is struct
// 2. Struct contains at least one 'readonly' field
// 3. Struct contains assignment to 'this' outside the scope of constructor
var namedTypeSymbol = (INamedTypeSymbol)symbolStartContext.Symbol;
// We are only interested in struct declarations
if (namedTypeSymbol.TypeKind != TypeKind.Struct)
{
return;
}
//We check if struct contains any 'readonly' fields
if (!HasReadonlyField(namedTypeSymbol))
{
return;
}
var symbolAnalyzer = new SymbolAnalyzer(namedTypeSymbol);
symbolAnalyzer.RegisterActions(symbolStartContext);
}, SymbolKind.NamedType);
}
private static bool HasReadonlyField(INamedTypeSymbol namedTypeSymbol)
{
return namedTypeSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(field => field.AssociatedSymbol == null)
.Any(field => field.IsReadOnly);
}
private void RegisterActions(SymbolStartAnalysisContext symbolStartContext)
{
symbolStartContext.RegisterOperationBlockStartAction(blockAction =>
{
var isConstructor = blockAction.OwningSymbol is IMethodSymbol method &&
method.MethodKind == MethodKind.Constructor;
blockAction.RegisterOperationAction(
operationAction => AnalyzeAssignment(operationAction, isConstructor), OperationKind.SimpleAssignment);
});
symbolStartContext.RegisterSymbolEndAction(SymbolEndAction);
}
private void AnalyzeAssignment(OperationAnalysisContext operationContext, bool isConstructor)
{
// We are looking for assignment to 'this' outside the constructor scope
if (isConstructor)
{
return;
}
var operationAssigmnent = (IAssignmentOperation)operationContext.Operation;
_hasTypeInstanceAssigment |= operationAssigmnent.Target is IInstanceReferenceOperation instance &&
instance.ReferenceKind == InstanceReferenceKind.ContainingTypeInstance;
}
private void SymbolEndAction(SymbolAnalysisContext symbolEndContext)
{
if (_hasTypeInstanceAssigment)
{
var diagnostic = Diagnostic.Create(
s_diagnosticDescriptor,
_namedTypeSymbol.Locations[0]);
symbolEndContext.ReportDiagnostic(diagnostic);
}
}
}
}
}
| 46.161017 | 219 | 0.630255 | [
"MIT"
] | douglasg14b/roslyn | src/Features/CSharp/Portable/MakeStructFieldsWritable/CSharpMakeStructFieldsWritableDiagnosticAnalyzer.cs | 5,449 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
public class NetworkTransmitter : NetworkBehaviour {
private static readonly string LOG_PREFIX = "[" + typeof(NetworkTransmitter).Name + "]: ";
private const int RELIABLE_SEQUENCED_CHANNEL = CaptainsMessNetworkManager.ChannelReliableSequenced;
private static int defaultBufferSize = 1024; //max ethernet MTU is ~1400
private class TransmissionData{
public int curDataIndex; //current position in the array of data already received.
public byte[] data;
public TransmissionData(byte[] _data){
curDataIndex = 0;
data = _data;
}
}
//list of transmissions currently going on. a transmission id is used to uniquely identify to which transmission a received byte[] belongs to.
List<int> serverTransmissionIds = new List<int>();
//maps the transmission id to the data being received.
Dictionary<int, TransmissionData> clientTransmissionData = new Dictionary<int,TransmissionData>();
//callbacks which are invoked on the respective events. int = transmissionId. byte[] = data sent or received.
public event UnityAction<int, byte[]> OnDataComepletelySent;
public event UnityAction<int, byte[]> OnDataFragmentSent;
public event UnityAction<int, byte[]> OnDataFragmentReceived;
public event UnityAction<int, byte[]> OnDataCompletelyReceived;
[Server]
public void SendBytesToClients(int transmissionId, byte[] data)
{
Debug.Assert(!serverTransmissionIds.Contains(transmissionId));
StartCoroutine(SendBytesToClientsRoutine(transmissionId, data));
}
[Server]
public IEnumerator SendBytesToClientsRoutine(int transmissionId, byte[] data)
{
Debug.Assert(!serverTransmissionIds.Contains(transmissionId));
Debug.Log(LOG_PREFIX + "SendBytesToClients processId=" + transmissionId + " | datasize=" + data.Length);
//tell client that he is going to receive some data and tell him how much it will be.
RpcPrepareToReceiveBytes(transmissionId, data.Length);
yield return null;
//begin transmission of data. send chunks of 'bufferSize' until completely transmitted.
serverTransmissionIds.Add(transmissionId);
TransmissionData dataToTransmit = new TransmissionData(data);
int bufferSize = defaultBufferSize;
while (dataToTransmit.curDataIndex < dataToTransmit.data.Length-1)
{
//determine the remaining amount of bytes, still need to be sent.
int remaining = dataToTransmit.data.Length - dataToTransmit.curDataIndex;
if (remaining < bufferSize)
bufferSize = remaining;
//prepare the chunk of data which will be sent in this iteration
byte[] buffer = new byte[bufferSize];
System.Array.Copy(dataToTransmit.data, dataToTransmit.curDataIndex, buffer, 0, bufferSize);
//send the chunk
RpcReceiveBytes(transmissionId, buffer);
dataToTransmit.curDataIndex += bufferSize;
yield return null;
if (null != OnDataFragmentSent)
OnDataFragmentSent.Invoke(transmissionId, buffer);
}
//transmission complete.
serverTransmissionIds.Remove(transmissionId);
if (null != OnDataComepletelySent)
OnDataComepletelySent.Invoke(transmissionId, dataToTransmit.data);
}
[ClientRpc]
private void RpcPrepareToReceiveBytes(int transmissionId, int expectedSize)
{
if (clientTransmissionData.ContainsKey(transmissionId))
return;
//prepare data array which will be filled chunk by chunk by the received data
TransmissionData receivingData = new TransmissionData(new byte[expectedSize]);
clientTransmissionData.Add(transmissionId, receivingData);
}
//use reliable sequenced channel to ensure bytes are sent in correct order
[ClientRpc(channel = RELIABLE_SEQUENCED_CHANNEL)]
private void RpcReceiveBytes(int transmissionId, byte[] recBuffer)
{
//already completely received or not prepared?
if (!clientTransmissionData.ContainsKey(transmissionId))
return;
//copy received data into prepared array and remember current dataposition
TransmissionData dataToReceive = clientTransmissionData[transmissionId];
System.Array.Copy(recBuffer, 0, dataToReceive.data, dataToReceive.curDataIndex, recBuffer.Length);
dataToReceive.curDataIndex += recBuffer.Length;
if (null != OnDataFragmentReceived)
OnDataFragmentReceived(transmissionId, recBuffer);
if (dataToReceive.curDataIndex < dataToReceive.data.Length - 1)
//current data not completely received
return;
//current data completely received
Debug.Log(LOG_PREFIX + "Completely Received Data at transmissionId=" + transmissionId);
clientTransmissionData.Remove(transmissionId);
if (null != OnDataCompletelyReceived)
OnDataCompletelyReceived.Invoke(transmissionId, dataToReceive.data);
}
} | 44.737705 | 148 | 0.67369 | [
"MIT"
] | oliverellmers/SharedSpheres | Assets/CaptainsMess/Example/NetworkTransmitter.cs | 5,460 | C# |
using MBBSEmu.Extensions;
using System;
using Xunit;
namespace MBBSEmu.Tests.Extensions
{
public class Ushort_Tests
{
[Theory]
[InlineData(2020, 01, 01, 20513)]
[InlineData(1980, 01, 01, 33)]
[InlineData(2022, 06, 04, 21700)]
[InlineData(2010, 12, 31, 15775)]
[InlineData(2000, 04, 03, 10371)]
public void ToDosDate_Test(ushort srcYr, ushort srcMo, ushort srcDay, ushort expectedDosDate)
{
var sourceDate = new DateTime(srcYr, srcMo, srcDay);
//Verify Results
Assert.Equal(expectedDosDate, sourceDate.ToDosDate());
}
[Theory]
[InlineData(20513, 2020, 01, 01)]
[InlineData(33, 1980, 01, 01)]
[InlineData(21700, 2022, 06, 04)]
[InlineData(15775, 2010, 12, 31)]
[InlineData(10371, 2000, 04, 03)]
public void FromDosDate_Test(ushort srcDosDate, ushort expYr, ushort expMo, ushort expDay)
{
var expectedDate = new DateTime(expYr, expMo, expDay);
//Verify Results
Assert.Equal(expectedDate, srcDosDate.FromDosDate());
}
}
}
| 30.605263 | 101 | 0.588994 | [
"MIT"
] | enusbaum/MBBSEmu | MBBSEmu.Tests/Extensions/Ushort_Tests.cs | 1,165 | C# |
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.WindowsAzure.Storage.Table;
namespace Microsoft.UnifiedPlatform.Service.Common.Storage
{
public interface ITableReader<TEntity> where TEntity: ITableEntity
{
Task<TEntity> Get(string partitionKey, string rowKey, string transactionId, string correlationId);
Task<List<TEntity>> QueryAll(string partitionKey, string transactionId, string correlationId);
}
}
| 35.846154 | 106 | 0.781116 | [
"MIT"
] | microsoft/UnifiedRedisPlatform.Core | src/service/Microsoft.UnifiedRedisPlatform.Service/SharedKernel/Common/Storage/ITableReader.cs | 468 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ShapeUp.Model.Models
{
public class MProizvodi
{
public int Id { get; set; }
public string Naziv { get; set; }
public string Opis { get; set; }
public decimal? ProsjecnaOcjena { get; set; }
public bool? Slika { get; set; }
public decimal? Cijena { get; set; }
public int? KategorijaProizvodaId { get; set; }
}
}
| 25.5 | 55 | 0.6122 | [
"MIT"
] | neiraomerika/Seminarski-ShapeUp | ShapeUp/ShapeUp.Model/Models/MProizvodi.cs | 461 | C# |
// <copyright file="WLANConfiguration.cs" company="ContextQuickie">
// MIT License
//
// Copyright (c) 2018
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </copyright>
namespace FritzControl.Soap.LANDevice
{
/// <summary>
/// Wrapper for the service urn:dslforum-org:service:WLANConfiguration:3.
/// </summary>
public class WLANConfiguration : BaseService
{
/// <inheritdoc/>
protected override string ServiceType { get; } = "urn:dslforum-org:service:WLANConfiguration:3";
/// <summary>
/// Wrapper for the action SetEnable.
/// </summary>
/// <param name="newEnable">The SOAP parameter NewEnable.</param>
public void SetEnable(bool newEnable)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewEnable", newEnable);
this.SendRequest("SetEnable", arguments);
}
/// <summary>
/// Wrapper for the action GetInfo.
/// </summary>
/// <returns>The result (WLANConfigurationGetInfoResult) of the action.</returns>
public WLANConfigurationGetInfoResult GetInfo()
{
return this.SendRequest<WLANConfigurationGetInfoResult>("GetInfo");
}
/// <summary>
/// Wrapper for the action SetConfig.
/// </summary>
/// <param name="newMaxBitRate">The SOAP parameter NewMaxBitRate.</param>
/// <param name="newChannel">The SOAP parameter NewChannel.</param>
/// <param name="newSSID">The SOAP parameter NewSSID.</param>
/// <param name="newBeaconType">The SOAP parameter NewBeaconType.</param>
/// <param name="newMACAddressControlEnabled">The SOAP parameter NewMACAddressControlEnabled.</param>
/// <param name="newBasicEncryptionModes">The SOAP parameter NewBasicEncryptionModes.</param>
/// <param name="newBasicAuthenticationMode">The SOAP parameter NewBasicAuthenticationMode.</param>
public void SetConfig(string newMaxBitRate, byte newChannel, string newSSID, string newBeaconType, bool newMACAddressControlEnabled, string newBasicEncryptionModes, string newBasicAuthenticationMode)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewMaxBitRate", newMaxBitRate);
arguments.Add("NewChannel", newChannel);
arguments.Add("NewSSID", newSSID);
arguments.Add("NewBeaconType", newBeaconType);
arguments.Add("NewMACAddressControlEnabled", newMACAddressControlEnabled);
arguments.Add("NewBasicEncryptionModes", newBasicEncryptionModes);
arguments.Add("NewBasicAuthenticationMode", newBasicAuthenticationMode);
this.SendRequest("SetConfig", arguments);
}
/// <summary>
/// Wrapper for the action SetSecurityKeys.
/// </summary>
/// <param name="newWEPKey0">The SOAP parameter NewWEPKey0.</param>
/// <param name="newWEPKey1">The SOAP parameter NewWEPKey1.</param>
/// <param name="newWEPKey2">The SOAP parameter NewWEPKey2.</param>
/// <param name="newWEPKey3">The SOAP parameter NewWEPKey3.</param>
/// <param name="newPreSharedKey">The SOAP parameter NewPreSharedKey.</param>
/// <param name="newKeyPassphrase">The SOAP parameter NewKeyPassphrase.</param>
public void SetSecurityKeys(string newWEPKey0, string newWEPKey1, string newWEPKey2, string newWEPKey3, string newPreSharedKey, string newKeyPassphrase)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewWEPKey0", newWEPKey0);
arguments.Add("NewWEPKey1", newWEPKey1);
arguments.Add("NewWEPKey2", newWEPKey2);
arguments.Add("NewWEPKey3", newWEPKey3);
arguments.Add("NewPreSharedKey", newPreSharedKey);
arguments.Add("NewKeyPassphrase", newKeyPassphrase);
this.SendRequest("SetSecurityKeys", arguments);
}
/// <summary>
/// Wrapper for the action GetSecurityKeys.
/// </summary>
/// <returns>The result (WLANConfigurationGetSecurityKeysResult) of the action.</returns>
public WLANConfigurationGetSecurityKeysResult GetSecurityKeys()
{
return this.SendRequest<WLANConfigurationGetSecurityKeysResult>("GetSecurityKeys");
}
/// <summary>
/// Wrapper for the action SetDefaultWEPKeyIndex.
/// </summary>
/// <param name="newDefaultWEPKeyIndex">The SOAP parameter NewDefaultWEPKeyIndex.</param>
public void SetDefaultWEPKeyIndex(byte newDefaultWEPKeyIndex)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewDefaultWEPKeyIndex", newDefaultWEPKeyIndex);
this.SendRequest("SetDefaultWEPKeyIndex", arguments);
}
/// <summary>
/// Wrapper for the action GetDefaultWEPKeyIndex.
/// </summary>
/// <returns>The result (NewDefaultWEPKeyIndex) of the action.</returns>
public byte GetDefaultWEPKeyIndex()
{
return this.SendRequest<byte>("GetDefaultWEPKeyIndex");
}
/// <summary>
/// Wrapper for the action SetBasBeaconSecurityProperties.
/// </summary>
/// <param name="newBasicEncryptionModes">The SOAP parameter NewBasicEncryptionModes.</param>
/// <param name="newBasicAuthenticationMode">The SOAP parameter NewBasicAuthenticationMode.</param>
public void SetBasBeaconSecurityProperties(string newBasicEncryptionModes, string newBasicAuthenticationMode)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewBasicEncryptionModes", newBasicEncryptionModes);
arguments.Add("NewBasicAuthenticationMode", newBasicAuthenticationMode);
this.SendRequest("SetBasBeaconSecurityProperties", arguments);
}
/// <summary>
/// Wrapper for the action GetBasBeaconSecurityProperties.
/// </summary>
/// <returns>The result (WLANConfigurationGetBasBeaconSecurityPropertiesResult) of the action.</returns>
public WLANConfigurationGetBasBeaconSecurityPropertiesResult GetBasBeaconSecurityProperties()
{
return this.SendRequest<WLANConfigurationGetBasBeaconSecurityPropertiesResult>("GetBasBeaconSecurityProperties");
}
/// <summary>
/// Wrapper for the action GetStatistics.
/// </summary>
/// <returns>The result (WLANConfigurationGetStatisticsResult) of the action.</returns>
public WLANConfigurationGetStatisticsResult GetStatistics()
{
return this.SendRequest<WLANConfigurationGetStatisticsResult>("GetStatistics");
}
/// <summary>
/// Wrapper for the action GetPacketStatistics.
/// </summary>
/// <returns>The result (WLANConfigurationGetPacketStatisticsResult) of the action.</returns>
public WLANConfigurationGetPacketStatisticsResult GetPacketStatistics()
{
return this.SendRequest<WLANConfigurationGetPacketStatisticsResult>("GetPacketStatistics");
}
/// <summary>
/// Wrapper for the action GetBSSID.
/// </summary>
/// <returns>The result (NewBSSID) of the action.</returns>
public string GetBSSID()
{
return this.SendRequest<string>("GetBSSID");
}
/// <summary>
/// Wrapper for the action GetSSID.
/// </summary>
/// <returns>The result (NewSSID) of the action.</returns>
public string GetSSID()
{
return this.SendRequest<string>("GetSSID");
}
/// <summary>
/// Wrapper for the action SetSSID.
/// </summary>
/// <param name="newSSID">The SOAP parameter NewSSID.</param>
public void SetSSID(string newSSID)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewSSID", newSSID);
this.SendRequest("SetSSID", arguments);
}
/// <summary>
/// Wrapper for the action GetBeaconType.
/// </summary>
/// <returns>The result (NewBeaconType) of the action.</returns>
public string GetBeaconType()
{
return this.SendRequest<string>("GetBeaconType");
}
/// <summary>
/// Wrapper for the action SetBeaconType.
/// </summary>
/// <param name="newBeaconType">The SOAP parameter NewBeaconType.</param>
public void SetBeaconType(string newBeaconType)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewBeaconType", newBeaconType);
this.SendRequest("SetBeaconType", arguments);
}
/// <summary>
/// Wrapper for the action GetChannelInfo.
/// </summary>
/// <returns>The result (WLANConfigurationGetChannelInfoResult) of the action.</returns>
public WLANConfigurationGetChannelInfoResult GetChannelInfo()
{
return this.SendRequest<WLANConfigurationGetChannelInfoResult>("GetChannelInfo");
}
/// <summary>
/// Wrapper for the action SetChannel.
/// </summary>
/// <param name="newChannel">The SOAP parameter NewChannel.</param>
public void SetChannel(byte newChannel)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewChannel", newChannel);
this.SendRequest("SetChannel", arguments);
}
/// <summary>
/// Wrapper for the action GetBeaconAdvertisement.
/// </summary>
/// <returns>The result (NewBeaconAdvertisementEnabled) of the action.</returns>
public bool GetBeaconAdvertisement()
{
return this.SendRequest<bool>("GetBeaconAdvertisement");
}
/// <summary>
/// Wrapper for the action SetBeaconAdvertisement.
/// </summary>
/// <param name="newBeaconAdvertisementEnabled">The SOAP parameter NewBeaconAdvertisementEnabled.</param>
public void SetBeaconAdvertisement(bool newBeaconAdvertisementEnabled)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewBeaconAdvertisementEnabled", newBeaconAdvertisementEnabled);
this.SendRequest("SetBeaconAdvertisement", arguments);
}
/// <summary>
/// Wrapper for the action GetTotalAssociations.
/// </summary>
/// <returns>The result (NewTotalAssociations) of the action.</returns>
public ushort GetTotalAssociations()
{
return this.SendRequest<ushort>("GetTotalAssociations");
}
/// <summary>
/// Wrapper for the action GetGenericAssociatedDeviceInfo.
/// </summary>
/// <param name="newAssociatedDeviceIndex">The SOAP parameter NewAssociatedDeviceIndex.</param>
/// <returns>The result (WLANConfigurationGetGenericAssociatedDeviceInfoResult) of the action.</returns>
public WLANConfigurationGetGenericAssociatedDeviceInfoResult GetGenericAssociatedDeviceInfo(ushort newAssociatedDeviceIndex)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewAssociatedDeviceIndex", newAssociatedDeviceIndex);
return this.SendRequest<WLANConfigurationGetGenericAssociatedDeviceInfoResult>("GetGenericAssociatedDeviceInfo", arguments);
}
/// <summary>
/// Wrapper for the action GetSpecificAssociatedDeviceInfo.
/// </summary>
/// <param name="newAssociatedDeviceMACAddress">The SOAP parameter NewAssociatedDeviceMACAddress.</param>
/// <returns>The result (WLANConfigurationGetSpecificAssociatedDeviceInfoResult) of the action.</returns>
public WLANConfigurationGetSpecificAssociatedDeviceInfoResult GetSpecificAssociatedDeviceInfo(string newAssociatedDeviceMACAddress)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewAssociatedDeviceMACAddress", newAssociatedDeviceMACAddress);
return this.SendRequest<WLANConfigurationGetSpecificAssociatedDeviceInfoResult>("GetSpecificAssociatedDeviceInfo", arguments);
}
/// <summary>
/// Wrapper for the action X_AVM-DE_GetSpecificAssociatedDeviceInfoByIp.
/// </summary>
/// <param name="newAssociatedDeviceIPAddress">The SOAP parameter NewAssociatedDeviceIPAddress.</param>
/// <returns>The result (WLANConfigurationX_AVM_DE_GetSpecificAssociatedDeviceInfoByIpResult) of the action.</returns>
public WLANConfigurationX_AVM_DE_GetSpecificAssociatedDeviceInfoByIpResult X_AVM_DE_GetSpecificAssociatedDeviceInfoByIp(string newAssociatedDeviceIPAddress)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewAssociatedDeviceIPAddress", newAssociatedDeviceIPAddress);
return this.SendRequest<WLANConfigurationX_AVM_DE_GetSpecificAssociatedDeviceInfoByIpResult>("X_AVM-DE_GetSpecificAssociatedDeviceInfoByIp", arguments);
}
/// <summary>
/// Wrapper for the action X_AVM-DE_SetStickSurfEnable.
/// </summary>
/// <param name="newStickSurfEnable">The SOAP parameter NewStickSurfEnable.</param>
public void X_AVM_DE_SetStickSurfEnable(bool newStickSurfEnable)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewStickSurfEnable", newStickSurfEnable);
this.SendRequest("X_AVM-DE_SetStickSurfEnable", arguments);
}
/// <summary>
/// Wrapper for the action X_AVM-DE_GetIPTVOptimized.
/// </summary>
/// <returns>The result (NewX_AVM-DE_IPTVoptimize) of the action.</returns>
public bool X_AVM_DE_GetIPTVOptimized()
{
return this.SendRequest<bool>("X_AVM-DE_GetIPTVOptimized");
}
/// <summary>
/// Wrapper for the action X_AVM-DE_SetIPTVOptimized.
/// </summary>
/// <param name="newX_AVM_DE_IPTVoptimize">The SOAP parameter NewX_AVM-DE_IPTVoptimize.</param>
public void X_AVM_DE_SetIPTVOptimized(bool newX_AVM_DE_IPTVoptimize)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewX_AVM-DE_IPTVoptimize", newX_AVM_DE_IPTVoptimize);
this.SendRequest("X_AVM-DE_SetIPTVOptimized", arguments);
}
/// <summary>
/// Wrapper for the action X_AVM-DE_GetNightControl.
/// </summary>
/// <returns>The result (WLANConfigurationX_AVM_DE_GetNightControlResult) of the action.</returns>
public WLANConfigurationX_AVM_DE_GetNightControlResult X_AVM_DE_GetNightControl()
{
return this.SendRequest<WLANConfigurationX_AVM_DE_GetNightControlResult>("X_AVM-DE_GetNightControl");
}
/// <summary>
/// Wrapper for the action X_AVM-DE_GetWLANHybridMode.
/// </summary>
/// <returns>The result (WLANConfigurationX_AVM_DE_GetWLANHybridModeResult) of the action.</returns>
public WLANConfigurationX_AVM_DE_GetWLANHybridModeResult X_AVM_DE_GetWLANHybridMode()
{
return this.SendRequest<WLANConfigurationX_AVM_DE_GetWLANHybridModeResult>("X_AVM-DE_GetWLANHybridMode");
}
/// <summary>
/// Wrapper for the action X_AVM-DE_SetWLANHybridMode.
/// </summary>
/// <param name="newEnable">The SOAP parameter NewEnable.</param>
/// <param name="newBeaconType">The SOAP parameter NewBeaconType.</param>
/// <param name="newKeyPassphrase">The SOAP parameter NewKeyPassphrase.</param>
/// <param name="newSSID">The SOAP parameter NewSSID.</param>
/// <param name="newBSSID">The SOAP parameter NewBSSID.</param>
/// <param name="newTrafficMode">The SOAP parameter NewTrafficMode.</param>
/// <param name="newManualSpeed">The SOAP parameter NewManualSpeed.</param>
/// <param name="newMaxSpeedDS">The SOAP parameter NewMaxSpeedDS.</param>
/// <param name="newMaxSpeedUS">The SOAP parameter NewMaxSpeedUS.</param>
public void X_AVM_DE_SetWLANHybridMode(bool newEnable, string newBeaconType, string newKeyPassphrase, string newSSID, string newBSSID, string newTrafficMode, bool newManualSpeed, uint newMaxSpeedDS, uint newMaxSpeedUS)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewEnable", newEnable);
arguments.Add("NewBeaconType", newBeaconType);
arguments.Add("NewKeyPassphrase", newKeyPassphrase);
arguments.Add("NewSSID", newSSID);
arguments.Add("NewBSSID", newBSSID);
arguments.Add("NewTrafficMode", newTrafficMode);
arguments.Add("NewManualSpeed", newManualSpeed);
arguments.Add("NewMaxSpeedDS", newMaxSpeedDS);
arguments.Add("NewMaxSpeedUS", newMaxSpeedUS);
this.SendRequest("X_AVM-DE_SetWLANHybridMode", arguments);
}
/// <summary>
/// Wrapper for the action X_AVM-DE_GetWLANExtInfo.
/// </summary>
/// <returns>The result (WLANConfigurationX_AVM_DE_GetWLANExtInfoResult) of the action.</returns>
public WLANConfigurationX_AVM_DE_GetWLANExtInfoResult X_AVM_DE_GetWLANExtInfo()
{
return this.SendRequest<WLANConfigurationX_AVM_DE_GetWLANExtInfoResult>("X_AVM-DE_GetWLANExtInfo");
}
/// <summary>
/// Wrapper for the action X_AVM-DE_GetWPSInfo.
/// </summary>
/// <returns>The result (WLANConfigurationX_AVM_DE_GetWPSInfoResult) of the action.</returns>
public WLANConfigurationX_AVM_DE_GetWPSInfoResult X_AVM_DE_GetWPSInfo()
{
return this.SendRequest<WLANConfigurationX_AVM_DE_GetWPSInfoResult>("X_AVM-DE_GetWPSInfo");
}
/// <summary>
/// Wrapper for the action X_AVM-DE_SetWPSConfig.
/// </summary>
/// <param name="newX_AVM_DE_WPSMode">The SOAP parameter NewX_AVM-DE_WPSMode.</param>
/// <param name="newX_AVM_DE_WPSClientPIN">The SOAP parameter NewX_AVM-DE_WPSClientPIN.</param>
/// <returns>The result (WLANConfigurationX_AVM_DE_SetWPSConfigResult) of the action.</returns>
public WLANConfigurationX_AVM_DE_SetWPSConfigResult X_AVM_DE_SetWPSConfig(string newX_AVM_DE_WPSMode, string newX_AVM_DE_WPSClientPIN)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewX_AVM-DE_WPSMode", newX_AVM_DE_WPSMode);
arguments.Add("NewX_AVM-DE_WPSClientPIN", newX_AVM_DE_WPSClientPIN);
return this.SendRequest<WLANConfigurationX_AVM_DE_SetWPSConfigResult>("X_AVM-DE_SetWPSConfig", arguments);
}
/// <summary>
/// Wrapper for the action X_AVM-DE_SetWLANGlobalEnable.
/// </summary>
/// <param name="newX_AVM_DE_WLANGlobalEnable">The SOAP parameter NewX_AVM-DE_WLANGlobalEnable.</param>
public void X_AVM_DE_SetWLANGlobalEnable(bool newX_AVM_DE_WLANGlobalEnable)
{
System.Collections.Generic.Dictionary<string, object> arguments = new System.Collections.Generic.Dictionary<string, object>();
arguments.Add("NewX_AVM-DE_WLANGlobalEnable", newX_AVM_DE_WLANGlobalEnable);
this.SendRequest("X_AVM-DE_SetWLANGlobalEnable", arguments);
}
}
}
| 48.17381 | 222 | 0.733208 | [
"MIT"
] | ContextQuickie/HomeAutomation | Source/FritzControl/Soap/LANDevice/WLANConfiguration.cs | 20,233 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchemaForge.Crucible.Extensions
{
/// <summary>
/// Contains extensions to the <see cref="Array"/> class for ease-of-use in SchemaForge.
/// </summary>
public static class ArrayExtensions
{
/// <summary>
/// Shallow copies the <paramref name="source"/> array.
/// </summary>
/// <typeparam name="T">Type of the data contained in the array.</typeparam>
/// <param name="source">Source array to be shallow copied.</param>
/// <returns>Copy of the <paramref name="source"/> array.</returns>
public static T[] CloneArray<T>(this T[] source)
{
_ = source ?? throw new ArgumentNullException(nameof(source));
return (T[])source.Clone();
}
/// <summary>
/// Performs an in-place reversal on the <paramref name="source"/>
/// and returns it.
/// </summary>
/// <typeparam name="T">Type of the data contained in the array.</typeparam>
/// <param name="source">Source array, modified in place.</param>
/// <exception cref="ArgumentNullException">
/// If the <paramref name="source"/> array is null.
/// </exception>
/// <returns>The <paramref name="source"/> array.</returns>
public static T[] Reverse<T>(this T[] source)
{
Array.Reverse(source);
return source;
}
}
}
| 32.790698 | 90 | 0.639007 | [
"MIT"
] | schema-forge/crucible-dotnet | Crucible/Extensions/ArrayExtensions.cs | 1,412 | C# |
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Boogie;
using Microsoft.Basetypes;
using Bpl = Microsoft.Boogie;
using System;
using System.Diagnostics.Contracts;
namespace Microsoft.Boogie {
public class Parser {
public const int _EOF = 0;
public const int _ident = 1;
public const int _bvlit = 2;
public const int _digits = 3;
public const int _string = 4;
public const int _decimal = 5;
public const int _dec_float = 6;
public const int _float = 7;
public const int maxT = 107;
const bool _T = true;
const bool _x = false;
const int minErrDist = 2;
public Scanner/*!*/ scanner;
public Errors/*!*/ errors;
public Token/*!*/ t; // last recognized token
public Token/*!*/ la; // lookahead token
int errDist = minErrDist;
readonly Program/*!*/ Pgm;
readonly Expr/*!*/ dummyExpr;
readonly Cmd/*!*/ dummyCmd;
readonly Block/*!*/ dummyBlock;
readonly Bpl.Type/*!*/ dummyType;
readonly List<Expr>/*!*/ dummyExprSeq;
readonly TransferCmd/*!*/ dummyTransferCmd;
readonly StructuredCmd/*!*/ dummyStructuredCmd;
///<summary>
///Returns the number of parsing errors encountered. If 0, "program" returns as
///the parsed program.
///</summary>
public static int Parse (string/*!*/ filename, /*maybe null*/ List<string/*!*/> defines, out /*maybe null*/ Program program, bool useBaseName=false) /* throws System.IO.IOException */ {
Contract.Requires(filename != null);
Contract.Requires(cce.NonNullElements(defines,true));
if (defines == null) {
defines = new List<string/*!*/>();
}
if (filename == "stdin.bpl") {
var s = ParserHelper.Fill(Console.In, defines);
return Parse(s, filename, out program, useBaseName);
} else {
FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
var s = ParserHelper.Fill(stream, defines);
var ret = Parse(s, filename, out program, useBaseName);
stream.Close();
return ret;
}
}
public static int Parse (string s, string/*!*/ filename, out /*maybe null*/ Program program, bool useBaseName=false) /* throws System.IO.IOException */ {
Contract.Requires(s != null);
Contract.Requires(filename != null);
byte[]/*!*/ buffer = cce.NonNull(UTF8Encoding.Default.GetBytes(s));
MemoryStream ms = new MemoryStream(buffer,false);
Errors errors = new Errors();
Scanner scanner = new Scanner(ms, errors, filename, useBaseName);
Parser parser = new Parser(scanner, errors, false);
parser.Parse();
if (errors.count == 0)
{
parser.Pgm.ProcessDatatypeConstructors(errors);
}
if (errors.count == 0)
{
program = parser.Pgm;
} else
{
program = null;
}
return errors.count;
}
public Parser(Scanner/*!*/ scanner, Errors/*!*/ errors, bool disambiguation)
: this(scanner, errors)
{
// initialize readonly fields
Pgm = new Program();
dummyExpr = new LiteralExpr(Token.NoToken, false);
dummyCmd = new AssumeCmd(Token.NoToken, dummyExpr);
dummyBlock = new Block(Token.NoToken, "dummyBlock", new List<Cmd>(), new ReturnCmd(Token.NoToken));
dummyType = new BasicType(Token.NoToken, SimpleType.Bool);
dummyExprSeq = new List<Expr> ();
dummyTransferCmd = new ReturnCmd(Token.NoToken);
dummyStructuredCmd = new BreakCmd(Token.NoToken, null);
}
// Class to represent the bounds of a bitvector expression t[a:b].
// Objects of this class only exist during parsing and are directly
// turned into BvExtract before they get anywhere else
private class BvBounds : Expr {
public BigNum Lower;
public BigNum Upper;
public BvBounds(IToken/*!*/ tok, BigNum lower, BigNum upper)
: base(tok, /*immutable=*/ false) {
Contract.Requires(tok != null);
this.Lower = lower;
this.Upper = upper;
}
public override Bpl.Type/*!*/ ShallowType { get {Contract.Ensures(Contract.Result<Bpl.Type>() != null); return Bpl.Type.Int; } }
public override void Resolve(ResolutionContext/*!*/ rc) {
// Contract.Requires(rc != null);
rc.Error(this, "bitvector bounds in illegal position");
}
public override void Emit(TokenTextWriter/*!*/ stream,
int contextBindingStrength, bool fragileContext) {
Contract.Assert(false);throw new cce.UnreachableException();
}
public override void ComputeFreeVariables(GSet<object>/*!*/ freeVars) { Contract.Assert(false);throw new cce.UnreachableException(); }
public override int ComputeHashCode()
{
return base.GetHashCode();
}
}
/*--------------------------------------------------------------------------*/
public Parser(Scanner/*!*/ scanner, Errors/*!*/ errors) {
this.scanner = scanner;
this.errors = errors;
Token/*!*/ tok = new Token();
tok.val = "";
this.la = tok;
this.t = new Token(); // just to satisfy its non-null constraint
}
void SynErr (int n) {
if (errDist >= minErrDist) errors.SynErr(la.filename, la.line, la.col, n);
errDist = 0;
}
public void SemErr (string/*!*/ msg) {
Contract.Requires(msg != null);
if (errDist >= minErrDist) errors.SemErr(t, msg);
errDist = 0;
}
public void SemErr(IToken/*!*/ tok, string/*!*/ msg) {
Contract.Requires(tok != null);
Contract.Requires(msg != null);
errors.SemErr(tok, msg);
}
void Get () {
for (;;) {
t = la;
la = scanner.Scan();
if (la.kind <= maxT) { ++errDist; break; }
la = t;
}
}
void Expect (int n) {
if (la.kind==n) Get(); else { SynErr(n); }
}
bool StartOf (int s) {
return set[s, la.kind];
}
void ExpectWeak (int n, int follow) {
if (la.kind == n) Get();
else {
SynErr(n);
while (!StartOf(follow)) Get();
}
}
bool WeakSeparator(int n, int syFol, int repFol) {
int kind = la.kind;
if (kind == n) {Get(); return true;}
else if (StartOf(repFol)) {return false;}
else {
SynErr(n);
while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) {
Get();
kind = la.kind;
}
return StartOf(syFol);
}
}
void BoogiePL() {
List<Variable>/*!*/ vs;
List<Declaration>/*!*/ ds;
Axiom/*!*/ ax;
List<Declaration/*!*/>/*!*/ ts;
Procedure/*!*/ pr;
Implementation im;
Implementation/*!*/ nnim;
while (StartOf(1)) {
switch (la.kind) {
case 22: {
Consts(out vs);
foreach(Bpl.Variable/*!*/ v in vs){
Contract.Assert(v != null);
Pgm.AddTopLevelDeclaration(v);
}
break;
}
case 26: {
Function(out ds);
foreach(Bpl.Declaration/*!*/ d in ds){
Contract.Assert(d != null);
Pgm.AddTopLevelDeclaration(d);
}
break;
}
case 30: {
Axiom(out ax);
Pgm.AddTopLevelDeclaration(ax);
break;
}
case 31: {
UserDefinedTypes(out ts);
foreach(Declaration/*!*/ td in ts){
Contract.Assert(td != null);
Pgm.AddTopLevelDeclaration(td);
}
break;
}
case 8: {
GlobalVars(out vs);
foreach(Bpl.Variable/*!*/ v in vs){
Contract.Assert(v != null);
Pgm.AddTopLevelDeclaration(v);
}
break;
}
case 33: {
Procedure(out pr, out im);
Pgm.AddTopLevelDeclaration(pr);
if (im != null) {
Pgm.AddTopLevelDeclaration(im);
}
break;
}
case 34: {
Implementation(out nnim);
Pgm.AddTopLevelDeclaration(nnim);
break;
}
}
}
Expect(0);
}
void Consts(out List<Variable>/*!*/ ds) {
Contract.Ensures(Contract.ValueAtReturn(out ds) != null); IToken/*!*/ y; List<TypedIdent>/*!*/ xs;
ds = new List<Variable>();
bool u = false; QKeyValue kv = null;
bool ChildrenComplete = false;
List<ConstantParent/*!*/> Parents = null;
Expect(22);
y = t;
while (la.kind == 28) {
Attribute(ref kv);
}
if (la.kind == 23) {
Get();
u = true;
}
IdsType(out xs);
if (la.kind == 24) {
OrderSpec(out ChildrenComplete, out Parents);
}
bool makeClone = false;
foreach(TypedIdent/*!*/ x in xs){
Contract.Assert(x != null);
// ensure that no sharing is introduced
List<ConstantParent/*!*/> ParentsClone;
if (makeClone && Parents != null) {
ParentsClone = new List<ConstantParent/*!*/> ();
foreach (ConstantParent/*!*/ p in Parents){
Contract.Assert(p != null);
ParentsClone.Add(new ConstantParent (
new IdentifierExpr (p.Parent.tok, p.Parent.Name),
p.Unique));}
} else {
ParentsClone = Parents;
}
makeClone = true;
ds.Add(new Constant(y, x, u, ParentsClone, ChildrenComplete, kv));
}
Expect(9);
}
void Function(out List<Declaration>/*!*/ ds) {
Contract.Ensures(Contract.ValueAtReturn(out ds) != null);
ds = new List<Declaration>(); IToken/*!*/ z;
IToken/*!*/ typeParamTok;
var typeParams = new List<TypeVariable>();
var arguments = new List<Variable>();
TypedIdent/*!*/ tyd;
TypedIdent retTyd = null;
Bpl.Type/*!*/ retTy;
QKeyValue argKv = null;
QKeyValue kv = null;
Expr definition = null;
Expr/*!*/ tmp;
Expect(26);
while (la.kind == 28) {
Attribute(ref kv);
}
Ident(out z);
if (la.kind == 20) {
TypeParams(out typeParamTok, out typeParams);
}
Expect(10);
if (StartOf(2)) {
VarOrType(out tyd, out argKv);
arguments.Add(new Formal(tyd.tok, tyd, true, argKv));
while (la.kind == 13) {
Get();
VarOrType(out tyd, out argKv);
arguments.Add(new Formal(tyd.tok, tyd, true, argKv));
}
}
Expect(11);
argKv = null;
if (la.kind == 27) {
Get();
Expect(10);
VarOrType(out retTyd, out argKv);
Expect(11);
} else if (la.kind == 12) {
Get();
Type(out retTy);
retTyd = new TypedIdent(retTy.tok, TypedIdent.NoName, retTy);
} else SynErr(108);
if (la.kind == 28) {
Get();
Expression(out tmp);
definition = tmp;
Expect(29);
} else if (la.kind == 9) {
Get();
} else SynErr(109);
if (retTyd == null) {
// construct a dummy type for the case of syntax error
retTyd = new TypedIdent(t, TypedIdent.NoName, new BasicType(t, SimpleType.Int));
}
Function/*!*/ func = new Function(z, z.val, typeParams, arguments,
new Formal(retTyd.tok, retTyd, false, argKv), null, kv);
Contract.Assert(func != null);
ds.Add(func);
bool allUnnamed = true;
foreach(Formal/*!*/ f in arguments){
Contract.Assert(f != null);
if (f.TypedIdent.HasName) {
allUnnamed = false;
break;
}
}
if (!allUnnamed) {
Bpl.Type prevType = null;
for (int i = arguments.Count; 0 <= --i; ) {
TypedIdent/*!*/ curr = cce.NonNull(arguments[i]).TypedIdent;
if (curr.HasName) {
// the argument was given as both an identifier and a type
prevType = curr.Type;
} else {
// the argument was given as just one "thing", which syntactically parsed as a type
if (prevType == null) {
this.errors.SemErr(curr.tok, "the type of the last parameter is unspecified");
break;
}
Bpl.Type ty = curr.Type;
var uti = ty as UnresolvedTypeIdentifier;
if (uti != null && uti.Arguments.Count == 0) {
// the given "thing" was just an identifier, so let's use it as the name of the parameter
curr.Name = uti.Name;
curr.Type = prevType;
} else {
this.errors.SemErr(curr.tok, "expecting an identifier as parameter name");
}
}
}
}
if (definition != null) {
// generate either an axiom or a function body
if (QKeyValue.FindBoolAttribute(kv, "inline")) {
func.Body = definition;
} else {
ds.Add(func.CreateDefinitionAxiom(definition, kv));
}
}
}
void Axiom(out Axiom/*!*/ m) {
Contract.Ensures(Contract.ValueAtReturn(out m) != null); Expr/*!*/ e; QKeyValue kv = null;
Expect(30);
while (la.kind == 28) {
Attribute(ref kv);
}
IToken/*!*/ x = t;
Proposition(out e);
Expect(9);
m = new Axiom(x,e, null, kv);
}
void UserDefinedTypes(out List<Declaration/*!*/>/*!*/ ts) {
Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out ts))); Declaration/*!*/ decl; QKeyValue kv = null; ts = new List<Declaration/*!*/> ();
Expect(31);
while (la.kind == 28) {
Attribute(ref kv);
}
UserDefinedType(out decl, kv);
ts.Add(decl);
while (la.kind == 13) {
Get();
UserDefinedType(out decl, kv);
ts.Add(decl);
}
Expect(9);
}
void GlobalVars(out List<Variable>/*!*/ ds) {
Contract.Ensures(Contract.ValueAtReturn(out ds) != null);
QKeyValue kv = null;
ds = new List<Variable>();
var dsx = ds;
Expect(8);
while (la.kind == 28) {
Attribute(ref kv);
}
IdsTypeWheres(true, "global variables", delegate(TypedIdent tyd) { dsx.Add(new GlobalVariable(tyd.tok, tyd, kv)); } );
Expect(9);
}
void Procedure(out Procedure/*!*/ proc, out /*maybe null*/ Implementation impl) {
Contract.Ensures(Contract.ValueAtReturn(out proc) != null); IToken/*!*/ x;
List<TypeVariable>/*!*/ typeParams;
List<Variable>/*!*/ ins, outs;
List<Requires>/*!*/ pre = new List<Requires>();
List<IdentifierExpr>/*!*/ mods = new List<IdentifierExpr>();
List<Ensures>/*!*/ post = new List<Ensures>();
List<Variable>/*!*/ locals = new List<Variable>();
StmtList/*!*/ stmtList;
QKeyValue kv = null;
impl = null;
Expect(33);
ProcSignature(true, out x, out typeParams, out ins, out outs, out kv);
if (la.kind == 9) {
Get();
while (StartOf(3)) {
Spec(pre, mods, post);
}
} else if (StartOf(4)) {
while (StartOf(3)) {
Spec(pre, mods, post);
}
ImplBody(out locals, out stmtList);
impl = new Implementation(x, x.val, typeParams,
Formal.StripWhereClauses(ins), Formal.StripWhereClauses(outs), locals, stmtList, kv == null ? null : (QKeyValue)kv.Clone(), this.errors);
} else SynErr(110);
proc = new Procedure(x, x.val, typeParams, ins, outs, pre, mods, post, kv);
}
void Implementation(out Implementation/*!*/ impl) {
Contract.Ensures(Contract.ValueAtReturn(out impl) != null); IToken/*!*/ x;
List<TypeVariable>/*!*/ typeParams;
List<Variable>/*!*/ ins, outs;
List<Variable>/*!*/ locals;
StmtList/*!*/ stmtList;
QKeyValue kv;
Expect(34);
ProcSignature(false, out x, out typeParams, out ins, out outs, out kv);
ImplBody(out locals, out stmtList);
impl = new Implementation(x, x.val, typeParams, ins, outs, locals, stmtList, kv, this.errors);
}
void Attribute(ref QKeyValue kv) {
Trigger trig = null;
AttributeOrTrigger(ref kv, ref trig);
if (trig != null) this.SemErr("only attributes, not triggers, allowed here");
}
void IdsTypeWheres(bool allowWhereClauses, string context, System.Action<TypedIdent> action ) {
IdsTypeWhere(allowWhereClauses, context, action);
while (la.kind == 13) {
Get();
IdsTypeWhere(allowWhereClauses, context, action);
}
}
void LocalVars(List<Variable>/*!*/ ds) {
Contract.Ensures(Contract.ValueAtReturn(out ds) != null);
QKeyValue kv = null;
Expect(8);
while (la.kind == 28) {
Attribute(ref kv);
}
IdsTypeWheres(true, "local variables", delegate(TypedIdent tyd) { ds.Add(new LocalVariable(tyd.tok, tyd, kv)); } );
Expect(9);
}
void ProcFormals(bool incoming, bool allowWhereClauses, out List<Variable>/*!*/ ds) {
Contract.Ensures(Contract.ValueAtReturn(out ds) != null);
ds = new List<Variable>();
var dsx = ds;
var context = allowWhereClauses ? "procedure formals" : "the 'implementation' copies of formals";
Expect(10);
if (la.kind == 1 || la.kind == 28) {
AttrsIdsTypeWheres(allowWhereClauses, allowWhereClauses, context, delegate(TypedIdent tyd, QKeyValue kv) { dsx.Add(new Formal(tyd.tok, tyd, incoming, kv)); });
}
Expect(11);
}
void AttrsIdsTypeWheres(bool allowAttributes, bool allowWhereClauses, string context, System.Action<TypedIdent, QKeyValue> action ) {
AttributesIdsTypeWhere(allowAttributes, allowWhereClauses, context, action);
while (la.kind == 13) {
Get();
AttributesIdsTypeWhere(allowAttributes, allowWhereClauses, context, action);
}
}
void BoundVars(out List<Variable>/*!*/ ds) {
Contract.Ensures(Contract.ValueAtReturn(out ds) != null);
List<TypedIdent>/*!*/ tyds = new List<TypedIdent>();
ds = new List<Variable>();
var dsx = ds;
AttrsIdsTypeWheres(true, false, "bound variables", delegate(TypedIdent tyd, QKeyValue kv) { dsx.Add(new BoundVariable(tyd.tok, tyd, kv)); } );
}
void IdsType(out List<TypedIdent>/*!*/ tyds) {
Contract.Ensures(Contract.ValueAtReturn(out tyds) != null); List<IToken>/*!*/ ids; Bpl.Type/*!*/ ty;
Idents(out ids);
Expect(12);
Type(out ty);
tyds = new List<TypedIdent>();
foreach(Token/*!*/ id in ids){
Contract.Assert(id != null);
tyds.Add(new TypedIdent(id, id.val, ty, null));
}
}
void Idents(out List<IToken>/*!*/ xs) {
Contract.Ensures(Contract.ValueAtReturn(out xs) != null); IToken/*!*/ id; xs = new List<IToken>();
Ident(out id);
xs.Add(id);
while (la.kind == 13) {
Get();
Ident(out id);
xs.Add(id);
}
}
void Type(out Bpl.Type/*!*/ ty) {
Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken/*!*/ tok; ty = dummyType;
if (StartOf(5)) {
TypeAtom(out ty);
} else if (la.kind == 1) {
Ident(out tok);
List<Bpl.Type>/*!*/ args = new List<Bpl.Type> ();
if (StartOf(6)) {
TypeArgs(args);
}
ty = new UnresolvedTypeIdentifier (tok, tok.val, args);
} else if (la.kind == 18 || la.kind == 20) {
MapType(out ty);
} else SynErr(111);
}
void AttributesIdsTypeWhere(bool allowAttributes, bool allowWhereClauses, string context, System.Action<TypedIdent, QKeyValue> action ) {
QKeyValue kv = null;
while (la.kind == 28) {
Attribute(ref kv);
if (!allowAttributes) {
kv = null;
this.SemErr("attributes are not allowed on " + context);
}
}
IdsTypeWhere(allowWhereClauses, context, delegate(TypedIdent tyd) { action(tyd, kv); });
}
void IdsTypeWhere(bool allowWhereClauses, string context, System.Action<TypedIdent> action ) {
List<IToken>/*!*/ ids; Bpl.Type/*!*/ ty; Expr wh = null; Expr/*!*/ nne;
Idents(out ids);
Expect(12);
Type(out ty);
if (la.kind == 14) {
Get();
Expression(out nne);
if (!allowWhereClauses) {
this.SemErr("where clause not allowed on " + context);
} else {
wh = nne;
}
}
foreach(Token/*!*/ id in ids){
Contract.Assert(id != null);
action(new TypedIdent(id, id.val, ty, wh));
}
}
void Expression(out Expr/*!*/ e0) {
Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1;
ImpliesExpression(false, out e0);
while (la.kind == 56 || la.kind == 57) {
EquivOp();
x = t;
ImpliesExpression(false, out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.Iff, e0, e1);
}
}
void TypeAtom(out Bpl.Type/*!*/ ty) {
Contract.Ensures(Contract.ValueAtReturn(out ty) != null); ty = dummyType;
if (la.kind == 15) {
Get();
ty = new BasicType(t, SimpleType.Int);
} else if (la.kind == 16) {
Get();
ty = new BasicType(t, SimpleType.Real);
} else if (la.kind == 17) {
Get();
ty = new BasicType(t, SimpleType.Bool);
} else if (la.kind == 10) {
Get();
Type(out ty);
Expect(11);
} else SynErr(112);
}
void Ident(out IToken/*!*/ x) {
Contract.Ensures(Contract.ValueAtReturn(out x) != null);
Expect(1);
x = t;
if (x.val.StartsWith("\\"))
x.val = x.val.Substring(1);
}
void TypeArgs(List<Bpl.Type>/*!*/ ts) {
Contract.Requires(ts != null); IToken/*!*/ tok; Bpl.Type/*!*/ ty;
if (StartOf(5)) {
TypeAtom(out ty);
ts.Add(ty);
if (StartOf(6)) {
TypeArgs(ts);
}
} else if (la.kind == 1) {
Ident(out tok);
List<Bpl.Type>/*!*/ args = new List<Bpl.Type> ();
ts.Add(new UnresolvedTypeIdentifier (tok, tok.val, args));
if (StartOf(6)) {
TypeArgs(ts);
}
} else if (la.kind == 18 || la.kind == 20) {
MapType(out ty);
ts.Add(ty);
} else SynErr(113);
}
void MapType(out Bpl.Type/*!*/ ty) {
Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken tok = null;
IToken/*!*/ nnTok;
List<Bpl.Type>/*!*/ arguments = new List<Bpl.Type>();
Bpl.Type/*!*/ result;
List<TypeVariable>/*!*/ typeParameters = new List<TypeVariable>();
if (la.kind == 20) {
TypeParams(out nnTok, out typeParameters);
tok = nnTok;
}
Expect(18);
if (tok == null) tok = t;
if (StartOf(6)) {
Types(arguments);
}
Expect(19);
Type(out result);
ty = new MapType(tok, typeParameters, arguments, result);
}
void TypeParams(out IToken/*!*/ tok, out List<TypeVariable>/*!*/ typeParams) {
Contract.Ensures(Contract.ValueAtReturn(out tok) != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); List<IToken>/*!*/ typeParamToks;
Expect(20);
tok = t;
Idents(out typeParamToks);
Expect(21);
typeParams = new List<TypeVariable> ();
foreach(Token/*!*/ id in typeParamToks){
Contract.Assert(id != null);
typeParams.Add(new TypeVariable(id, id.val));}
}
void Types(List<Bpl.Type>/*!*/ ts) {
Contract.Requires(ts != null); Bpl.Type/*!*/ ty;
Type(out ty);
ts.Add(ty);
while (la.kind == 13) {
Get();
Type(out ty);
ts.Add(ty);
}
}
void OrderSpec(out bool ChildrenComplete, out List<ConstantParent/*!*/> Parents) {
Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out Parents),true)); ChildrenComplete = false;
Parents = null;
bool u;
IToken/*!*/ parent;
Expect(24);
Parents = new List<ConstantParent/*!*/> ();
u = false;
if (la.kind == 1 || la.kind == 23) {
if (la.kind == 23) {
Get();
u = true;
}
Ident(out parent);
Parents.Add(new ConstantParent (
new IdentifierExpr(parent, parent.val), u));
while (la.kind == 13) {
Get();
u = false;
if (la.kind == 23) {
Get();
u = true;
}
Ident(out parent);
Parents.Add(new ConstantParent (
new IdentifierExpr(parent, parent.val), u));
}
}
if (la.kind == 25) {
Get();
ChildrenComplete = true;
}
}
void VarOrType(out TypedIdent/*!*/ tyd, out QKeyValue kv) {
Contract.Ensures(Contract.ValueAtReturn(out tyd) != null);
string/*!*/ varName = TypedIdent.NoName;
Bpl.Type/*!*/ ty;
IToken/*!*/ tok;
kv = null;
while (la.kind == 28) {
Attribute(ref kv);
}
Type(out ty);
tok = ty.tok;
if (la.kind == 12) {
Get();
var uti = ty as UnresolvedTypeIdentifier;
if (uti != null && uti.Arguments.Count == 0) {
varName = uti.Name;
} else {
this.SemErr("expected identifier before ':'");
}
Type(out ty);
}
tyd = new TypedIdent(tok, varName, ty);
}
void Proposition(out Expr/*!*/ e) {
Contract.Ensures(Contract.ValueAtReturn(out e) != null);
Expression(out e);
}
void UserDefinedType(out Declaration/*!*/ decl, QKeyValue kv) {
Contract.Ensures(Contract.ValueAtReturn(out decl) != null); IToken/*!*/ id; List<IToken>/*!*/ paramTokens = new List<IToken> ();
Bpl.Type/*!*/ body = dummyType; bool synonym = false;
Ident(out id);
if (la.kind == 1) {
WhiteSpaceIdents(out paramTokens);
}
if (la.kind == 32) {
Get();
Type(out body);
synonym = true;
}
if (synonym) {
List<TypeVariable>/*!*/ typeParams = new List<TypeVariable>();
foreach(Token/*!*/ t in paramTokens){
Contract.Assert(t != null);
typeParams.Add(new TypeVariable(t, t.val));}
decl = new TypeSynonymDecl(id, id.val, typeParams, body, kv);
} else {
decl = new TypeCtorDecl(id, id.val, paramTokens.Count, kv);
}
}
void WhiteSpaceIdents(out List<IToken>/*!*/ xs) {
Contract.Ensures(Contract.ValueAtReturn(out xs) != null); IToken/*!*/ id; xs = new List<IToken>();
Ident(out id);
xs.Add(id);
while (la.kind == 1) {
Ident(out id);
xs.Add(id);
}
}
void ProcSignature(bool allowWhereClausesOnFormals, out IToken/*!*/ name, out List<TypeVariable>/*!*/ typeParams,
out List<Variable>/*!*/ ins, out List<Variable>/*!*/ outs, out QKeyValue kv) {
Contract.Ensures(Contract.ValueAtReturn(out name) != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); Contract.Ensures(Contract.ValueAtReturn(out ins) != null); Contract.Ensures(Contract.ValueAtReturn(out outs) != null);
IToken/*!*/ typeParamTok; typeParams = new List<TypeVariable>();
outs = new List<Variable>(); kv = null;
while (la.kind == 28) {
Attribute(ref kv);
}
Ident(out name);
if (la.kind == 20) {
TypeParams(out typeParamTok, out typeParams);
}
ProcFormals(true, allowWhereClausesOnFormals, out ins);
if (la.kind == 27) {
Get();
ProcFormals(false, allowWhereClausesOnFormals, out outs);
}
}
void Spec(List<Requires>/*!*/ pre, List<IdentifierExpr>/*!*/ mods, List<Ensures>/*!*/ post) {
Contract.Requires(pre != null); Contract.Requires(mods != null); Contract.Requires(post != null); List<IToken>/*!*/ ms;
if (la.kind == 35) {
Get();
if (la.kind == 1) {
Idents(out ms);
foreach(IToken/*!*/ m in ms){
Contract.Assert(m != null);
mods.Add(new IdentifierExpr(m, m.val));
}
}
Expect(9);
} else if (la.kind == 36) {
Get();
SpecPrePost(true, pre, post);
} else if (la.kind == 37 || la.kind == 38) {
SpecPrePost(false, pre, post);
} else SynErr(114);
}
void ImplBody(out List<Variable>/*!*/ locals, out StmtList/*!*/ stmtList) {
Contract.Ensures(Contract.ValueAtReturn(out locals) != null); Contract.Ensures(Contract.ValueAtReturn(out stmtList) != null); locals = new List<Variable>();
Expect(28);
while (la.kind == 8) {
LocalVars(locals);
}
StmtList(out stmtList);
}
void SpecPrePost(bool free, List<Requires>/*!*/ pre, List<Ensures>/*!*/ post) {
Contract.Requires(pre != null); Contract.Requires(post != null); Expr/*!*/ e; Token tok = null; QKeyValue kv = null;
if (la.kind == 37) {
Get();
tok = t;
while (la.kind == 28) {
Attribute(ref kv);
}
Proposition(out e);
Expect(9);
pre.Add(new Requires(tok, free, e, null, kv));
} else if (la.kind == 38) {
Get();
tok = t;
while (la.kind == 28) {
Attribute(ref kv);
}
Proposition(out e);
Expect(9);
post.Add(new Ensures(tok, free, e, null, kv));
} else SynErr(115);
}
void StmtList(out StmtList/*!*/ stmtList) {
Contract.Ensures(Contract.ValueAtReturn(out stmtList) != null); List<BigBlock/*!*/> bigblocks = new List<BigBlock/*!*/>();
/* built-up state for the current BigBlock: */
IToken startToken = null; string currentLabel = null;
List<Cmd> cs = null; /* invariant: startToken != null ==> cs != null */
/* temporary variables: */
IToken label; Cmd c; BigBlock b;
StructuredCmd ec = null; StructuredCmd/*!*/ ecn;
TransferCmd tc = null; TransferCmd/*!*/ tcn;
while (StartOf(7)) {
if (StartOf(8)) {
LabelOrCmd(out c, out label);
if (c != null) {
// LabelOrCmd read a Cmd
Contract.Assert(label == null);
if (startToken == null) { startToken = c.tok; cs = new List<Cmd>(); }
Contract.Assert(cs != null);
cs.Add(c);
} else {
// LabelOrCmd read a label
Contract.Assert(label != null);
if (startToken != null) {
Contract.Assert(cs != null);
// dump the built-up state into a BigBlock
b = new BigBlock(startToken, currentLabel, cs, null, null);
bigblocks.Add(b);
cs = null;
}
startToken = label;
currentLabel = label.val;
cs = new List<Cmd>();
}
} else if (la.kind == 41 || la.kind == 43 || la.kind == 46) {
StructuredCmd(out ecn);
ec = ecn;
if (startToken == null) { startToken = ec.tok; cs = new List<Cmd>(); }
Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, ec, null);
bigblocks.Add(b);
startToken = null; currentLabel = null; cs = null;
} else {
TransferCmd(out tcn);
tc = tcn;
if (startToken == null) { startToken = tc.tok; cs = new List<Cmd>(); }
Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, null, tc);
bigblocks.Add(b);
startToken = null; currentLabel = null; cs = null;
}
}
Expect(29);
IToken/*!*/ endCurly = t;
if (startToken == null && bigblocks.Count == 0) {
startToken = t; cs = new List<Cmd>();
}
if (startToken != null) {
Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, null, null);
bigblocks.Add(b);
}
stmtList = new StmtList(bigblocks, endCurly);
}
void LabelOrCmd(out Cmd c, out IToken label) {
IToken/*!*/ x; Expr/*!*/ e;
List<IToken>/*!*/ xs;
List<IdentifierExpr> ids;
c = dummyCmd; label = null;
Cmd/*!*/ cn;
QKeyValue kv = null;
switch (la.kind) {
case 1: {
LabelOrAssign(out c, out label);
break;
}
case 47: {
Get();
x = t;
while (la.kind == 28) {
Attribute(ref kv);
}
Proposition(out e);
c = new AssertCmd(x, e, kv);
Expect(9);
break;
}
case 48: {
Get();
x = t;
while (la.kind == 28) {
Attribute(ref kv);
}
Proposition(out e);
c = new AssumeCmd(x, e, kv);
Expect(9);
break;
}
case 49: {
Get();
x = t;
Idents(out xs);
Expect(9);
ids = new List<IdentifierExpr>();
foreach(IToken/*!*/ y in xs){
Contract.Assert(y != null);
ids.Add(new IdentifierExpr(y, y.val));
}
c = new HavocCmd(x,ids);
break;
}
case 36: case 52: case 53: {
CallCmd(out cn);
Expect(9);
c = cn;
break;
}
case 54: {
ParCallCmd(out cn);
c = cn;
break;
}
case 50: {
Get();
x = t;
Expect(9);
c = new YieldCmd(x);
break;
}
default: SynErr(116); break;
}
}
void StructuredCmd(out StructuredCmd/*!*/ ec) {
Contract.Ensures(Contract.ValueAtReturn(out ec) != null); ec = dummyStructuredCmd; Contract.Assume(cce.IsPeerConsistent(ec));
IfCmd/*!*/ ifcmd; WhileCmd/*!*/ wcmd; BreakCmd/*!*/ bcmd;
if (la.kind == 41) {
IfCmd(out ifcmd);
ec = ifcmd;
} else if (la.kind == 43) {
WhileCmd(out wcmd);
ec = wcmd;
} else if (la.kind == 46) {
BreakCmd(out bcmd);
ec = bcmd;
} else SynErr(117);
}
void TransferCmd(out TransferCmd/*!*/ tc) {
Contract.Ensures(Contract.ValueAtReturn(out tc) != null); tc = dummyTransferCmd;
Token y; List<IToken>/*!*/ xs;
List<String> ss = new List<String>();
if (la.kind == 39) {
Get();
y = t;
Idents(out xs);
foreach(IToken/*!*/ s in xs){
Contract.Assert(s != null);
ss.Add(s.val); }
tc = new GotoCmd(y, ss);
} else if (la.kind == 40) {
Get();
tc = new ReturnCmd(t);
} else SynErr(118);
Expect(9);
}
void IfCmd(out IfCmd/*!*/ ifcmd) {
Contract.Ensures(Contract.ValueAtReturn(out ifcmd) != null); IToken/*!*/ x;
Expr guard;
StmtList/*!*/ thn;
IfCmd/*!*/ elseIf; IfCmd elseIfOption = null;
StmtList/*!*/ els; StmtList elseOption = null;
Expect(41);
x = t;
Guard(out guard);
Expect(28);
StmtList(out thn);
if (la.kind == 42) {
Get();
if (la.kind == 41) {
IfCmd(out elseIf);
elseIfOption = elseIf;
} else if (la.kind == 28) {
Get();
StmtList(out els);
elseOption = els;
} else SynErr(119);
}
ifcmd = new IfCmd(x, guard, thn, elseIfOption, elseOption);
}
void WhileCmd(out WhileCmd/*!*/ wcmd) {
Contract.Ensures(Contract.ValueAtReturn(out wcmd) != null); IToken/*!*/ x; Token z;
Expr guard; Expr/*!*/ e; bool isFree;
List<PredicateCmd/*!*/> invariants = new List<PredicateCmd/*!*/>();
StmtList/*!*/ body;
QKeyValue kv = null;
Expect(43);
x = t;
Guard(out guard);
Contract.Assume(guard == null || cce.Owner.None(guard));
while (la.kind == 36 || la.kind == 44) {
isFree = false; z = la/*lookahead token*/;
if (la.kind == 36) {
Get();
isFree = true;
}
Expect(44);
while (la.kind == 28) {
Attribute(ref kv);
}
Expression(out e);
if (isFree) {
invariants.Add(new AssumeCmd(z, e, kv));
} else {
invariants.Add(new AssertCmd(z, e, kv));
}
kv = null;
Expect(9);
}
Expect(28);
StmtList(out body);
wcmd = new WhileCmd(x, guard, invariants, body);
}
void BreakCmd(out BreakCmd/*!*/ bcmd) {
Contract.Ensures(Contract.ValueAtReturn(out bcmd) != null); IToken/*!*/ x; IToken/*!*/ y;
string breakLabel = null;
Expect(46);
x = t;
if (la.kind == 1) {
Ident(out y);
breakLabel = y.val;
}
Expect(9);
bcmd = new BreakCmd(x, breakLabel);
}
void Guard(out Expr e) {
Expr/*!*/ ee; e = null;
Expect(10);
if (la.kind == 45) {
Get();
e = null;
} else if (StartOf(9)) {
Expression(out ee);
e = ee;
} else SynErr(120);
Expect(11);
}
void LabelOrAssign(out Cmd c, out IToken label) {
IToken/*!*/ id; IToken/*!*/ x, y; Expr/*!*/ e0;
c = dummyCmd; label = null;
AssignLhs/*!*/ lhs;
List<AssignLhs/*!*/>/*!*/ lhss;
List<Expr/*!*/>/*!*/ rhss;
List<Expr/*!*/>/*!*/ indexes;
QKeyValue kv = null;
Ident(out id);
x = t;
if (la.kind == 12) {
Get();
c = null; label = x;
} else if (la.kind == 13 || la.kind == 18 || la.kind == 51) {
lhss = new List<AssignLhs/*!*/>();
lhs = new SimpleAssignLhs(id, new IdentifierExpr(id, id.val));
while (la.kind == 18) {
MapAssignIndex(out y, out indexes);
lhs = new MapAssignLhs(y, lhs, indexes);
}
lhss.Add(lhs);
while (la.kind == 13) {
Get();
Ident(out id);
lhs = new SimpleAssignLhs(id, new IdentifierExpr(id, id.val));
while (la.kind == 18) {
MapAssignIndex(out y, out indexes);
lhs = new MapAssignLhs(y, lhs, indexes);
}
lhss.Add(lhs);
}
Expect(51);
x = t; /* use location of := */
while (la.kind == 28) {
Attribute(ref kv);
}
Expression(out e0);
rhss = new List<Expr/*!*/> ();
rhss.Add(e0);
while (la.kind == 13) {
Get();
Expression(out e0);
rhss.Add(e0);
}
Expect(9);
c = new AssignCmd(x, lhss, rhss, kv);
} else SynErr(121);
}
void CallCmd(out Cmd c) {
Contract.Ensures(Contract.ValueAtReturn(out c) != null);
IToken x;
bool isAsync = false;
bool isFree = false;
QKeyValue kv = null;
c = null;
if (la.kind == 52) {
Get();
isAsync = true;
}
if (la.kind == 36) {
Get();
isFree = true;
}
Expect(53);
x = t;
while (la.kind == 28) {
Attribute(ref kv);
}
CallParams(isAsync, isFree, kv, x, out c);
}
void ParCallCmd(out Cmd d) {
Contract.Ensures(Contract.ValueAtReturn(out d) != null);
IToken x;
QKeyValue kv = null;
Cmd c = null;
List<CallCmd> callCmds = new List<CallCmd>();
Expect(54);
x = t;
while (la.kind == 28) {
Attribute(ref kv);
}
CallParams(false, false, kv, x, out c);
callCmds.Add((CallCmd)c);
while (la.kind == 55) {
Get();
CallParams(false, false, kv, x, out c);
callCmds.Add((CallCmd)c);
}
Expect(9);
d = new ParCallCmd(x, callCmds, kv);
}
void MapAssignIndex(out IToken/*!*/ x, out List<Expr/*!*/>/*!*/ indexes) {
Contract.Ensures(Contract.ValueAtReturn(out x) != null); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out indexes))); indexes = new List<Expr/*!*/> ();
Expr/*!*/ e;
Expect(18);
x = t;
if (StartOf(9)) {
Expression(out e);
indexes.Add(e);
while (la.kind == 13) {
Get();
Expression(out e);
indexes.Add(e);
}
}
Expect(19);
}
void CallParams(bool isAsync, bool isFree, QKeyValue kv, IToken x, out Cmd c) {
List<IdentifierExpr> ids = new List<IdentifierExpr>();
List<Expr> es = new List<Expr>();
Expr en;
IToken first;
IToken p;
c = null;
Ident(out first);
if (la.kind == 10) {
Get();
if (StartOf(9)) {
Expression(out en);
es.Add(en);
while (la.kind == 13) {
Get();
Expression(out en);
es.Add(en);
}
}
Expect(11);
c = new CallCmd(x, first.val, es, ids, kv); ((CallCmd) c).IsFree = isFree; ((CallCmd) c).IsAsync = isAsync;
} else if (la.kind == 13 || la.kind == 51) {
ids.Add(new IdentifierExpr(first, first.val));
if (la.kind == 13) {
Get();
Ident(out p);
ids.Add(new IdentifierExpr(p, p.val));
while (la.kind == 13) {
Get();
Ident(out p);
ids.Add(new IdentifierExpr(p, p.val));
}
}
Expect(51);
Ident(out first);
Expect(10);
if (StartOf(9)) {
Expression(out en);
es.Add(en);
while (la.kind == 13) {
Get();
Expression(out en);
es.Add(en);
}
}
Expect(11);
c = new CallCmd(x, first.val, es, ids, kv); ((CallCmd) c).IsFree = isFree; ((CallCmd) c).IsAsync = isAsync;
} else SynErr(122);
}
void Expressions(out List<Expr>/*!*/ es) {
Contract.Ensures(Contract.ValueAtReturn(out es) != null); Expr/*!*/ e; es = new List<Expr>();
Expression(out e);
es.Add(e);
while (la.kind == 13) {
Get();
Expression(out e);
es.Add(e);
}
}
void ImpliesExpression(bool noExplies, out Expr/*!*/ e0) {
Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1;
LogicalExpression(out e0);
if (StartOf(10)) {
if (la.kind == 58 || la.kind == 59) {
ImpliesOp();
x = t;
ImpliesExpression(true, out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.Imp, e0, e1);
} else {
ExpliesOp();
if (noExplies)
this.SemErr("illegal mixture of ==> and <==, use parentheses to disambiguate");
x = t;
LogicalExpression(out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.Imp, e1, e0);
while (la.kind == 60 || la.kind == 61) {
ExpliesOp();
x = t;
LogicalExpression(out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.Imp, e1, e0);
}
}
}
}
void EquivOp() {
if (la.kind == 56) {
Get();
} else if (la.kind == 57) {
Get();
} else SynErr(123);
}
void LogicalExpression(out Expr/*!*/ e0) {
Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1;
RelationalExpression(out e0);
if (StartOf(11)) {
if (la.kind == 62 || la.kind == 63) {
AndOp();
x = t;
RelationalExpression(out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.And, e0, e1);
while (la.kind == 62 || la.kind == 63) {
AndOp();
x = t;
RelationalExpression(out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.And, e0, e1);
}
} else {
OrOp();
x = t;
RelationalExpression(out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.Or, e0, e1);
while (la.kind == 64 || la.kind == 65) {
OrOp();
x = t;
RelationalExpression(out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.Or, e0, e1);
}
}
}
}
void ImpliesOp() {
if (la.kind == 58) {
Get();
} else if (la.kind == 59) {
Get();
} else SynErr(124);
}
void ExpliesOp() {
if (la.kind == 60) {
Get();
} else if (la.kind == 61) {
Get();
} else SynErr(125);
}
void RelationalExpression(out Expr/*!*/ e0) {
Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op;
BvTerm(out e0);
if (StartOf(12)) {
RelOp(out x, out op);
BvTerm(out e1);
e0 = Expr.Binary(x, op, e0, e1);
}
}
void AndOp() {
if (la.kind == 62) {
Get();
} else if (la.kind == 63) {
Get();
} else SynErr(126);
}
void OrOp() {
if (la.kind == 64) {
Get();
} else if (la.kind == 65) {
Get();
} else SynErr(127);
}
void BvTerm(out Expr/*!*/ e0) {
Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1;
Term(out e0);
while (la.kind == 74) {
Get();
x = t;
Term(out e1);
e0 = new BvConcatExpr(x, e0, e1);
}
}
void RelOp(out IToken/*!*/ x, out BinaryOperator.Opcode op) {
Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
switch (la.kind) {
case 66: {
Get();
x = t; op=BinaryOperator.Opcode.Eq;
break;
}
case 20: {
Get();
x = t; op=BinaryOperator.Opcode.Lt;
break;
}
case 21: {
Get();
x = t; op=BinaryOperator.Opcode.Gt;
break;
}
case 67: {
Get();
x = t; op=BinaryOperator.Opcode.Le;
break;
}
case 68: {
Get();
x = t; op=BinaryOperator.Opcode.Ge;
break;
}
case 69: {
Get();
x = t; op=BinaryOperator.Opcode.Neq;
break;
}
case 70: {
Get();
x = t; op=BinaryOperator.Opcode.Subtype;
break;
}
case 71: {
Get();
x = t; op=BinaryOperator.Opcode.Neq;
break;
}
case 72: {
Get();
x = t; op=BinaryOperator.Opcode.Le;
break;
}
case 73: {
Get();
x = t; op=BinaryOperator.Opcode.Ge;
break;
}
default: SynErr(128); break;
}
}
void Term(out Expr/*!*/ e0) {
Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op;
Factor(out e0);
while (la.kind == 75 || la.kind == 76) {
AddOp(out x, out op);
Factor(out e1);
e0 = Expr.Binary(x, op, e0, e1);
}
}
void Factor(out Expr/*!*/ e0) {
Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op;
Power(out e0);
while (StartOf(13)) {
MulOp(out x, out op);
Power(out e1);
e0 = Expr.Binary(x, op, e0, e1);
}
}
void AddOp(out IToken/*!*/ x, out BinaryOperator.Opcode op) {
Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
if (la.kind == 75) {
Get();
x = t; op=BinaryOperator.Opcode.Add;
} else if (la.kind == 76) {
Get();
x = t; op=BinaryOperator.Opcode.Sub;
} else SynErr(129);
}
void Power(out Expr/*!*/ e0) {
Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1;
UnaryExpression(out e0);
if (la.kind == 80) {
Get();
x = t;
Power(out e1);
e0 = Expr.Binary(x, BinaryOperator.Opcode.Pow, e0, e1);
}
}
void MulOp(out IToken/*!*/ x, out BinaryOperator.Opcode op) {
Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
if (la.kind == 45) {
Get();
x = t; op=BinaryOperator.Opcode.Mul;
} else if (la.kind == 77) {
Get();
x = t; op=BinaryOperator.Opcode.Div;
} else if (la.kind == 78) {
Get();
x = t; op=BinaryOperator.Opcode.Mod;
} else if (la.kind == 79) {
Get();
x = t; op=BinaryOperator.Opcode.RealDiv;
} else SynErr(130);
}
void UnaryExpression(out Expr/*!*/ e) {
Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
e = dummyExpr;
if (la.kind == 76) {
Get();
x = t;
UnaryExpression(out e);
e = Expr.Unary(x, UnaryOperator.Opcode.Neg, e);
} else if (la.kind == 81 || la.kind == 82) {
NegOp();
x = t;
UnaryExpression(out e);
e = Expr.Unary(x, UnaryOperator.Opcode.Not, e);
} else if (StartOf(14)) {
CoercionExpression(out e);
} else SynErr(131);
}
void NegOp() {
if (la.kind == 81) {
Get();
} else if (la.kind == 82) {
Get();
} else SynErr(132);
}
void CoercionExpression(out Expr/*!*/ e) {
Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
Bpl.Type/*!*/ coercedTo;
BigNum bn;
ArrayExpression(out e);
while (la.kind == 12) {
Get();
x = t;
if (StartOf(6)) {
Type(out coercedTo);
e = Expr.CoerceType(x, e, coercedTo);
} else if (la.kind == 3) {
Nat(out bn);
if (!(e is LiteralExpr) || !((LiteralExpr)e).isBigNum) {
this.SemErr("arguments of extract need to be integer literals");
e = new BvBounds(x, bn, BigNum.ZERO);
} else {
e = new BvBounds(x, bn, ((LiteralExpr)e).asBigNum);
}
} else SynErr(133);
}
}
void ArrayExpression(out Expr/*!*/ e) {
Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
Expr/*!*/ index0 = dummyExpr; Expr/*!*/ e1;
bool store; bool bvExtract;
List<Expr>/*!*/ allArgs = dummyExprSeq;
AtomExpression(out e);
while (la.kind == 18) {
Get();
x = t; allArgs = new List<Expr> ();
allArgs.Add(e);
store = false; bvExtract = false;
if (StartOf(15)) {
if (StartOf(9)) {
Expression(out index0);
if (index0 is BvBounds)
bvExtract = true;
else
allArgs.Add(index0);
while (la.kind == 13) {
Get();
Expression(out e1);
if (bvExtract || e1 is BvBounds)
this.SemErr("bitvectors only have one dimension");
allArgs.Add(e1);
}
if (la.kind == 51) {
Get();
Expression(out e1);
if (bvExtract || e1 is BvBounds)
this.SemErr("assignment to bitvectors is not possible");
allArgs.Add(e1); store = true;
}
} else {
Get();
Expression(out e1);
allArgs.Add(e1); store = true;
}
}
Expect(19);
if (store)
e = new NAryExpr(x, new MapStore(x, allArgs.Count - 2), allArgs);
else if (bvExtract)
e = new BvExtractExpr(x, e,
((BvBounds)index0).Upper.ToIntSafe,
((BvBounds)index0).Lower.ToIntSafe);
else
e = new NAryExpr(x, new MapSelect(x, allArgs.Count - 1), allArgs);
}
}
void Nat(out BigNum n) {
Expect(3);
try {
n = BigNum.FromString(t.val);
} catch (FormatException) {
this.SemErr("incorrectly formatted number");
n = BigNum.ZERO;
}
}
void AtomExpression(out Expr/*!*/ e) {
Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; int n; BigNum bn; BigDec bd; BigFloat bf;
List<Expr>/*!*/ es; List<Variable>/*!*/ ds; Trigger trig;
List<TypeVariable>/*!*/ typeParams;
IdentifierExpr/*!*/ id;
QKeyValue kv;
e = dummyExpr;
List<Variable>/*!*/ locals;
List<Block/*!*/>/*!*/ blocks;
switch (la.kind) {
case 83: {
Get();
e = new LiteralExpr(t, false);
break;
}
case 84: {
Get();
e = new LiteralExpr(t, true);
break;
}
case 85: case 86: {
if (la.kind == 85) {
Get();
} else {
Get();
}
e = new LiteralExpr(t, RoundingMode.RNE);
break;
}
case 87: case 88: {
if (la.kind == 87) {
Get();
} else {
Get();
}
e = new LiteralExpr(t, RoundingMode.RNA);
break;
}
case 89: case 90: {
if (la.kind == 89) {
Get();
} else {
Get();
}
e = new LiteralExpr(t, RoundingMode.RTP);
break;
}
case 91: case 92: {
if (la.kind == 91) {
Get();
} else {
Get();
}
e = new LiteralExpr(t, RoundingMode.RTN);
break;
}
case 93: case 94: {
if (la.kind == 93) {
Get();
} else {
Get();
}
e = new LiteralExpr(t, RoundingMode.RTZ);
break;
}
case 3: {
Nat(out bn);
e = new LiteralExpr(t, bn);
break;
}
case 5: case 6: {
Dec(out bd);
e = new LiteralExpr(t, bd);
break;
}
case 7: {
Float(out bf);
e = new LiteralExpr(t, bf);
break;
}
case 2: {
BvLit(out bn, out n);
e = new LiteralExpr(t, bn, n);
break;
}
case 1: {
Ident(out x);
id = new IdentifierExpr(x, x.val); e = id;
if (la.kind == 10) {
Get();
if (StartOf(9)) {
Expressions(out es);
e = new NAryExpr(x, new FunctionCall(id), es);
} else if (la.kind == 11) {
e = new NAryExpr(x, new FunctionCall(id), new List<Expr>());
} else SynErr(134);
Expect(11);
}
break;
}
case 95: {
Get();
x = t;
Expect(10);
Expression(out e);
Expect(11);
e = new OldExpr(x, e);
break;
}
case 15: {
Get();
x = t;
Expect(10);
Expression(out e);
Expect(11);
e = new NAryExpr(x, new ArithmeticCoercion(x, ArithmeticCoercion.CoercionType.ToInt), new List<Expr>{ e });
break;
}
case 16: {
Get();
x = t;
Expect(10);
Expression(out e);
Expect(11);
e = new NAryExpr(x, new ArithmeticCoercion(x, ArithmeticCoercion.CoercionType.ToReal), new List<Expr>{ e });
break;
}
case 10: {
Get();
if (StartOf(9)) {
Expression(out e);
if (e is BvBounds)
this.SemErr("parentheses around bitvector bounds " +
"are not allowed");
} else if (la.kind == 99 || la.kind == 100) {
Forall();
x = t;
QuantifierBody(x, out typeParams, out ds, out kv, out trig, out e);
if (typeParams.Count + ds.Count > 0)
e = new ForallExpr(x, typeParams, ds, kv, trig, e);
} else if (la.kind == 101 || la.kind == 102) {
Exists();
x = t;
QuantifierBody(x, out typeParams, out ds, out kv, out trig, out e);
if (typeParams.Count + ds.Count > 0)
e = new ExistsExpr(x, typeParams, ds, kv, trig, e);
} else if (la.kind == 103 || la.kind == 104) {
Lambda();
x = t;
QuantifierBody(x, out typeParams, out ds, out kv, out trig, out e);
if (trig != null)
SemErr("triggers not allowed in lambda expressions");
if (typeParams.Count + ds.Count > 0)
e = new LambdaExpr(x, typeParams, ds, kv, e);
} else if (la.kind == 8) {
LetExpr(out e);
} else SynErr(135);
Expect(11);
break;
}
case 41: {
IfThenElseExpression(out e);
break;
}
case 96: {
CodeExpression(out locals, out blocks);
e = new CodeExpr(locals, blocks);
break;
}
default: SynErr(136); break;
}
}
void Dec(out BigDec n) {
string s = "";
if (la.kind == 5) {
Get();
s = t.val;
} else if (la.kind == 6) {
Get();
s = t.val;
} else SynErr(137);
try {
n = BigDec.FromString(s);
} catch (FormatException) {
this.SemErr("incorrectly formatted number");
n = BigDec.ZERO;
}
}
void Float(out BigFloat n) {
string s = "";
Expect(7);
s = t.val;
try {
n = BigFloat.FromString(s);
} catch (FormatException e) {
this.SemErr("incorrectly formatted floating point, " + e.Message);
n = BigFloat.ZERO;
}
}
void BvLit(out BigNum n, out int m) {
Expect(2);
int pos = t.val.IndexOf("bv");
string a = t.val.Substring(0, pos);
string b = t.val.Substring(pos + 2);
try {
n = BigNum.FromString(a);
m = Convert.ToInt32(b);
} catch (FormatException) {
this.SemErr("incorrectly formatted bitvector");
n = BigNum.ZERO;
m = 0;
}
}
void Forall() {
if (la.kind == 99) {
Get();
} else if (la.kind == 100) {
Get();
} else SynErr(138);
}
void QuantifierBody(IToken/*!*/ q, out List<TypeVariable>/*!*/ typeParams, out List<Variable>/*!*/ ds,
out QKeyValue kv, out Trigger trig, out Expr/*!*/ body) {
Contract.Requires(q != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); Contract.Ensures(Contract.ValueAtReturn(out ds) != null); Contract.Ensures(Contract.ValueAtReturn(out body) != null);
trig = null; typeParams = new List<TypeVariable> ();
IToken/*!*/ tok;
kv = null;
ds = new List<Variable> ();
if (la.kind == 20) {
TypeParams(out tok, out typeParams);
if (la.kind == 1 || la.kind == 28) {
BoundVars(out ds);
}
} else if (la.kind == 1 || la.kind == 28) {
BoundVars(out ds);
} else SynErr(139);
QSep();
while (la.kind == 28) {
AttributeOrTrigger(ref kv, ref trig);
}
Expression(out body);
}
void Exists() {
if (la.kind == 101) {
Get();
} else if (la.kind == 102) {
Get();
} else SynErr(140);
}
void Lambda() {
if (la.kind == 103) {
Get();
} else if (la.kind == 104) {
Get();
} else SynErr(141);
}
void LetExpr(out Expr/*!*/ letexpr) {
IToken tok;
Variable v;
var ds = new List<Variable>();
Expr e0;
var rhss = new List<Expr>();
QKeyValue kv = null;
Expr body;
Expect(8);
tok = t;
LetVar(out v);
ds.Add(v);
while (la.kind == 13) {
Get();
LetVar(out v);
ds.Add(v);
}
Expect(51);
Expression(out e0);
rhss.Add(e0);
while (la.kind == 13) {
Get();
Expression(out e0);
rhss.Add(e0);
}
Expect(9);
while (la.kind == 28) {
Attribute(ref kv);
}
Expression(out body);
letexpr = new LetExpr(tok, ds, rhss, kv, body);
}
void IfThenElseExpression(out Expr/*!*/ e) {
Contract.Ensures(Contract.ValueAtReturn(out e) != null);
IToken/*!*/ tok;
Expr/*!*/ e0, e1, e2;
e = dummyExpr;
Expect(41);
tok = t;
Expression(out e0);
Expect(98);
Expression(out e1);
Expect(42);
Expression(out e2);
e = new NAryExpr(tok, new IfThenElse(tok), new List<Expr>{ e0, e1, e2 });
}
void CodeExpression(out List<Variable>/*!*/ locals, out List<Block/*!*/>/*!*/ blocks) {
Contract.Ensures(Contract.ValueAtReturn(out locals) != null); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out blocks))); locals = new List<Variable>(); Block/*!*/ b;
blocks = new List<Block/*!*/>();
Expect(96);
while (la.kind == 8) {
LocalVars(locals);
}
SpecBlock(out b);
blocks.Add(b);
while (la.kind == 1) {
SpecBlock(out b);
blocks.Add(b);
}
Expect(97);
}
void SpecBlock(out Block/*!*/ b) {
Contract.Ensures(Contract.ValueAtReturn(out b) != null); IToken/*!*/ x; IToken/*!*/ y;
Cmd c; IToken label;
List<Cmd> cs = new List<Cmd>();
List<IToken>/*!*/ xs;
List<String> ss = new List<String>();
b = dummyBlock;
Expr/*!*/ e;
Ident(out x);
Expect(12);
while (StartOf(8)) {
LabelOrCmd(out c, out label);
if (c != null) {
Contract.Assert(label == null);
cs.Add(c);
} else {
Contract.Assert(label != null);
SemErr("SpecBlock's can only have one label");
}
}
if (la.kind == 39) {
Get();
y = t;
Idents(out xs);
foreach(IToken/*!*/ s in xs){
Contract.Assert(s != null);
ss.Add(s.val); }
b = new Block(x,x.val,cs,new GotoCmd(y,ss));
} else if (la.kind == 40) {
Get();
Expression(out e);
b = new Block(x,x.val,cs,new ReturnExprCmd(t,e));
} else SynErr(142);
Expect(9);
}
void AttributeOrTrigger(ref QKeyValue kv, ref Trigger trig) {
IToken/*!*/ tok; Expr/*!*/ e; List<Expr>/*!*/ es;
string key;
List<object/*!*/> parameters; object/*!*/ param;
Expect(28);
tok = t;
if (la.kind == 12) {
Get();
Expect(1);
key = t.val; parameters = new List<object/*!*/>();
if (StartOf(16)) {
AttributeParameter(out param);
parameters.Add(param);
while (la.kind == 13) {
Get();
AttributeParameter(out param);
parameters.Add(param);
}
}
if (key == "nopats") {
if (parameters.Count == 1 && parameters[0] is Expr) {
e = (Expr)parameters[0];
if(trig==null){
trig = new Trigger(tok, false, new List<Expr> { e }, null);
} else {
trig.AddLast(new Trigger(tok, false, new List<Expr> { e }, null));
}
} else {
this.SemErr("the 'nopats' quantifier attribute expects a string-literal parameter");
}
} else {
if (kv==null) {
kv = new QKeyValue(tok, key, parameters, null);
} else {
kv.AddLast(new QKeyValue(tok, key, parameters, null));
}
}
} else if (StartOf(9)) {
Expression(out e);
es = new List<Expr> { e };
while (la.kind == 13) {
Get();
Expression(out e);
es.Add(e);
}
if (trig==null) {
trig = new Trigger(tok, true, es, null);
} else {
trig.AddLast(new Trigger(tok, true, es, null));
}
} else SynErr(143);
Expect(29);
}
void AttributeParameter(out object/*!*/ o) {
Contract.Ensures(Contract.ValueAtReturn(out o) != null);
o = "error";
Expr/*!*/ e;
if (la.kind == 4) {
Get();
o = t.val.Substring(1, t.val.Length-2);
} else if (StartOf(9)) {
Expression(out e);
o = e;
} else SynErr(144);
}
void QSep() {
if (la.kind == 105) {
Get();
} else if (la.kind == 106) {
Get();
} else SynErr(145);
}
void LetVar(out Variable/*!*/ v) {
QKeyValue kv = null;
IToken id;
while (la.kind == 28) {
Attribute(ref kv);
}
Ident(out id);
var tyd = new TypedIdent(id, id.val, dummyType/*will be replaced during type checking*/, null);
v = new BoundVariable(tyd.tok, tyd, kv);
}
public void Parse() {
la = new Token();
la.val = "";
Get();
BoogiePL();
Expect(0);
Expect(0);
}
static readonly bool[,]/*!*/ set = {
{_T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_x,_x,_x, _x,_x,_x,_x, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_T,_x, _x,_x,_T,_x, _x,_x,_T,_T, _x,_T,_T,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_T,_x, _x,_x,_x,_T, _T,_T,_T,_x, _T,_x,_x,_x, _x,_x,_x,_x, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_T, _T,_T,_T,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _T,_x,_x,_x, _x,_x,_x,_T, _T,_T,_T,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_T,_x, _x,_x,_x,_T, _T,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_T,_x, _x,_x,_x,_T, _T,_T,_T,_x, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _T,_x,_x,_T, _T,_T,_x,_T, _x,_x,_T,_T, _T,_T,_T,_x, _T,_T,_T,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_T, _T,_T,_T,_x, _T,_T,_T,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_T,_T, _x,_T,_T,_T, _x,_x,_T,_x, _x,_x,_x,_T, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _T,_x,_x,_x, _x,_T,_T,_T, _T,_T,_T,_T, _T,_T,_T,_T, _T,_T,_T,_T, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_T,_T, _T,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_T,_T, _T,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _T,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_T,_T, _T,_T,_T,_T, _T,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_T,_T,_T, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_T,_T, _x,_T,_T,_T, _x,_x,_T,_x, _x,_x,_x,_T, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_T, _T,_T,_T,_T, _T,_T,_T,_T, _T,_T,_T,_T, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_T,_T, _x,_T,_T,_T, _x,_x,_T,_x, _x,_x,_x,_T, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_T, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _T,_x,_x,_x, _x,_T,_T,_T, _T,_T,_T,_T, _T,_T,_T,_T, _T,_T,_T,_T, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x},
{_x,_T,_T,_T, _T,_T,_T,_T, _x,_x,_T,_x, _x,_x,_x,_T, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_T,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _T,_x,_x,_x, _x,_T,_T,_T, _T,_T,_T,_T, _T,_T,_T,_T, _T,_T,_T,_T, _T,_x,_x,_x, _x,_x,_x,_x, _x,_x,_x,_x, _x}
};
} // end Parser
public class Errors {
public int count = 0; // number of errors detected
public System.IO.TextWriter/*!*/ errorStream = Console.Out; // error messages go to this stream
public string errMsgFormat = "{0}({1},{2}): error: {3}"; // 0=filename, 1=line, 2=column, 3=text
public string warningMsgFormat = "{0}({1},{2}): warning: {3}"; // 0=filename, 1=line, 2=column, 3=text
public void SynErr(string filename, int line, int col, int n) {
SynErr(filename, line, col, GetSyntaxErrorString(n));
}
public virtual void SynErr(string filename, int line, int col, string/*!*/ msg) {
Contract.Requires(msg != null);
errorStream.WriteLine(errMsgFormat, filename, line, col, msg);
count++;
}
string GetSyntaxErrorString(int n) {
string s;
switch (n) {
case 0: s = "EOF expected"; break;
case 1: s = "ident expected"; break;
case 2: s = "bvlit expected"; break;
case 3: s = "digits expected"; break;
case 4: s = "string expected"; break;
case 5: s = "decimal expected"; break;
case 6: s = "dec_float expected"; break;
case 7: s = "float expected"; break;
case 8: s = "\"var\" expected"; break;
case 9: s = "\";\" expected"; break;
case 10: s = "\"(\" expected"; break;
case 11: s = "\")\" expected"; break;
case 12: s = "\":\" expected"; break;
case 13: s = "\",\" expected"; break;
case 14: s = "\"where\" expected"; break;
case 15: s = "\"int\" expected"; break;
case 16: s = "\"real\" expected"; break;
case 17: s = "\"bool\" expected"; break;
case 18: s = "\"[\" expected"; break;
case 19: s = "\"]\" expected"; break;
case 20: s = "\"<\" expected"; break;
case 21: s = "\">\" expected"; break;
case 22: s = "\"const\" expected"; break;
case 23: s = "\"unique\" expected"; break;
case 24: s = "\"extends\" expected"; break;
case 25: s = "\"complete\" expected"; break;
case 26: s = "\"function\" expected"; break;
case 27: s = "\"returns\" expected"; break;
case 28: s = "\"{\" expected"; break;
case 29: s = "\"}\" expected"; break;
case 30: s = "\"axiom\" expected"; break;
case 31: s = "\"type\" expected"; break;
case 32: s = "\"=\" expected"; break;
case 33: s = "\"procedure\" expected"; break;
case 34: s = "\"implementation\" expected"; break;
case 35: s = "\"modifies\" expected"; break;
case 36: s = "\"free\" expected"; break;
case 37: s = "\"requires\" expected"; break;
case 38: s = "\"ensures\" expected"; break;
case 39: s = "\"goto\" expected"; break;
case 40: s = "\"return\" expected"; break;
case 41: s = "\"if\" expected"; break;
case 42: s = "\"else\" expected"; break;
case 43: s = "\"while\" expected"; break;
case 44: s = "\"invariant\" expected"; break;
case 45: s = "\"*\" expected"; break;
case 46: s = "\"break\" expected"; break;
case 47: s = "\"assert\" expected"; break;
case 48: s = "\"assume\" expected"; break;
case 49: s = "\"havoc\" expected"; break;
case 50: s = "\"yield\" expected"; break;
case 51: s = "\":=\" expected"; break;
case 52: s = "\"async\" expected"; break;
case 53: s = "\"call\" expected"; break;
case 54: s = "\"par\" expected"; break;
case 55: s = "\"|\" expected"; break;
case 56: s = "\"<==>\" expected"; break;
case 57: s = "\"\\u21d4\" expected"; break;
case 58: s = "\"==>\" expected"; break;
case 59: s = "\"\\u21d2\" expected"; break;
case 60: s = "\"<==\" expected"; break;
case 61: s = "\"\\u21d0\" expected"; break;
case 62: s = "\"&&\" expected"; break;
case 63: s = "\"\\u2227\" expected"; break;
case 64: s = "\"||\" expected"; break;
case 65: s = "\"\\u2228\" expected"; break;
case 66: s = "\"==\" expected"; break;
case 67: s = "\"<=\" expected"; break;
case 68: s = "\">=\" expected"; break;
case 69: s = "\"!=\" expected"; break;
case 70: s = "\"<:\" expected"; break;
case 71: s = "\"\\u2260\" expected"; break;
case 72: s = "\"\\u2264\" expected"; break;
case 73: s = "\"\\u2265\" expected"; break;
case 74: s = "\"++\" expected"; break;
case 75: s = "\"+\" expected"; break;
case 76: s = "\"-\" expected"; break;
case 77: s = "\"div\" expected"; break;
case 78: s = "\"mod\" expected"; break;
case 79: s = "\"/\" expected"; break;
case 80: s = "\"**\" expected"; break;
case 81: s = "\"!\" expected"; break;
case 82: s = "\"\\u00ac\" expected"; break;
case 83: s = "\"false\" expected"; break;
case 84: s = "\"true\" expected"; break;
case 85: s = "\"roundNearestTiesToEven\" expected"; break;
case 86: s = "\"RNE\" expected"; break;
case 87: s = "\"roundNearestTiesToAway\" expected"; break;
case 88: s = "\"RNA\" expected"; break;
case 89: s = "\"roundTowardPositive\" expected"; break;
case 90: s = "\"RTP\" expected"; break;
case 91: s = "\"roundTowardNegative\" expected"; break;
case 92: s = "\"RTN\" expected"; break;
case 93: s = "\"roundTowardZero\" expected"; break;
case 94: s = "\"RTZ\" expected"; break;
case 95: s = "\"old\" expected"; break;
case 96: s = "\"|{\" expected"; break;
case 97: s = "\"}|\" expected"; break;
case 98: s = "\"then\" expected"; break;
case 99: s = "\"forall\" expected"; break;
case 100: s = "\"\\u2200\" expected"; break;
case 101: s = "\"exists\" expected"; break;
case 102: s = "\"\\u2203\" expected"; break;
case 103: s = "\"lambda\" expected"; break;
case 104: s = "\"\\u03bb\" expected"; break;
case 105: s = "\"::\" expected"; break;
case 106: s = "\"\\u2022\" expected"; break;
case 107: s = "??? expected"; break;
case 108: s = "invalid Function"; break;
case 109: s = "invalid Function"; break;
case 110: s = "invalid Procedure"; break;
case 111: s = "invalid Type"; break;
case 112: s = "invalid TypeAtom"; break;
case 113: s = "invalid TypeArgs"; break;
case 114: s = "invalid Spec"; break;
case 115: s = "invalid SpecPrePost"; break;
case 116: s = "invalid LabelOrCmd"; break;
case 117: s = "invalid StructuredCmd"; break;
case 118: s = "invalid TransferCmd"; break;
case 119: s = "invalid IfCmd"; break;
case 120: s = "invalid Guard"; break;
case 121: s = "invalid LabelOrAssign"; break;
case 122: s = "invalid CallParams"; break;
case 123: s = "invalid EquivOp"; break;
case 124: s = "invalid ImpliesOp"; break;
case 125: s = "invalid ExpliesOp"; break;
case 126: s = "invalid AndOp"; break;
case 127: s = "invalid OrOp"; break;
case 128: s = "invalid RelOp"; break;
case 129: s = "invalid AddOp"; break;
case 130: s = "invalid MulOp"; break;
case 131: s = "invalid UnaryExpression"; break;
case 132: s = "invalid NegOp"; break;
case 133: s = "invalid CoercionExpression"; break;
case 134: s = "invalid AtomExpression"; break;
case 135: s = "invalid AtomExpression"; break;
case 136: s = "invalid AtomExpression"; break;
case 137: s = "invalid Dec"; break;
case 138: s = "invalid Forall"; break;
case 139: s = "invalid QuantifierBody"; break;
case 140: s = "invalid Exists"; break;
case 141: s = "invalid Lambda"; break;
case 142: s = "invalid SpecBlock"; break;
case 143: s = "invalid AttributeOrTrigger"; break;
case 144: s = "invalid AttributeParameter"; break;
case 145: s = "invalid QSep"; break;
default: s = "error " + n; break;
}
return s;
}
public void SemErr(IToken/*!*/ tok, string/*!*/ msg) { // semantic errors
Contract.Requires(tok != null);
Contract.Requires(msg != null);
SemErr(tok.filename, tok.line, tok.col, msg);
}
public virtual void SemErr(string filename, int line, int col, string/*!*/ msg) {
Contract.Requires(msg != null);
errorStream.WriteLine(errMsgFormat, filename, line, col, msg);
count++;
}
public void Warning(IToken/*!*/ tok, string/*!*/ msg) { // warnings
Contract.Requires(tok != null);
Contract.Requires(msg != null);
Warning(tok.filename, tok.line, tok.col, msg);
}
public virtual void Warning(string filename, int line, int col, string msg) {
Contract.Requires(msg != null);
errorStream.WriteLine(warningMsgFormat, filename, line, col, msg);
}
} // Errors
public class FatalError: Exception {
public FatalError(string m): base(m) {}
}
} | 29.879901 | 359 | 0.572038 | [
"MIT"
] | alexanderjsummers/boogie | Source/Core/Parser.cs | 69,977 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.Identity.Core.Cache;
namespace Microsoft.Identity.Core
{
/// <summary>
/// Common operations for extracting platform / operating system specifics
/// </summary>
internal interface IPlatformProxy
{
/// <summary>
/// Gets the device model. On some TFMs this is not returned for security reasonons.
/// </summary>
/// <returns>device model or null</returns>
string GetDeviceModel();
string GetEnvironmentVariable(string variable);
string GetOperatingSystem();
string GetProcessorArchitecture();
/// <summary>
/// Gets the upn of the user currently logged into the OS
/// </summary>
/// <returns></returns>
Task<string> GetUserPrincipalNameAsync();
/// <summary>
/// Returns true if the current OS logged in user is AD or AAD joined.
/// </summary>
/// <returns></returns>
bool IsDomainJoined();
Task<bool> IsUserLocalAsync(RequestContext requestContext);
/// <summary>
/// Returns the name of the calling assembly
/// </summary>
/// <returns></returns>
string GetCallingApplicationName();
/// <summary>
/// Returns the version of the calling assembly
/// </summary>
/// <returns></returns>
string GetCallingApplicationVersion();
/// <summary>
/// Returns a device identifier. Varies by platform.
/// </summary>
/// <returns></returns>
string GetDeviceId();
/// <summary>
/// Get the redirect Uri as string, or the a broker specified value
/// </summary>
string GetBrokerOrRedirectUri(Uri redirectUri);
/// <summary>
/// Gets the default redirect uri for the platform, which sometimes includes the clientId
/// </summary>
string GetDefaultRedirectUri(string clientId);
string GetProductName();
ILegacyCachePersistence CreateLegacyCachePersistence();
ITokenCacheAccessor CreateTokenCacheAccessor();
ICryptographyManager CryptographyManager { get; }
}
}
| 29.666667 | 97 | 0.60764 | [
"MIT"
] | AaronPatterson/azure-activedirectory-library-for-dotnet | src/Microsoft.IdentityModel.Clients.ActiveDirectory/Core/IPlatformProxy.cs | 2,227 | C# |
using System.IO;
using System.Runtime.CompilerServices;
namespace Mirror.SimpleWeb
{
public static class MessageProcessor
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static byte FirstLengthByte(byte[] buffer) => (byte)(buffer[1] & 0b0111_1111);
public static bool NeedToReadShortLength(byte[] buffer)
{
byte lenByte = FirstLengthByte(buffer);
return lenByte >= Constants.UshortPayloadLength;
}
public static int GetOpcode(byte[] buffer)
{
return buffer[0] & 0b0000_1111;
}
public static int GetPayloadLength(byte[] buffer)
{
byte lenByte = FirstLengthByte(buffer);
return GetMessageLength(buffer, 0, lenByte);
}
public static void ValidateHeader(byte[] buffer, int maxLength, bool expectMask)
{
bool finished = (buffer[0] & 0b1000_0000) != 0; // has full message been sent
bool hasMask = (buffer[1] & 0b1000_0000) != 0; // true from clients, false from server, "All messages from the client to the server have this bit set"
int opcode = buffer[0] & 0b0000_1111; // expecting 1 - text message
byte lenByte = FirstLengthByte(buffer);
ThrowIfNotFinished(finished);
ThrowIfMaskNotExpected(hasMask, expectMask);
ThrowIfBadOpCode(opcode);
int msglen = GetMessageLength(buffer, 0, lenByte);
ThrowIfLengthZero(msglen);
ThrowIfMsgLengthTooLong(msglen, maxLength);
}
public static void ToggleMask(byte[] src, int sourceOffset, int messageLength, byte[] maskBuffer, int maskOffset)
{
ToggleMask(src, sourceOffset, src, sourceOffset, messageLength, maskBuffer, maskOffset);
}
public static void ToggleMask(byte[] src, int sourceOffset, ArrayBuffer dst, int messageLength, byte[] maskBuffer, int maskOffset)
{
ToggleMask(src, sourceOffset, dst.array, 0, messageLength, maskBuffer, maskOffset);
dst.count = messageLength;
}
public static void ToggleMask(byte[] src, int srcOffset, byte[] dst, int dstOffset, int messageLength, byte[] maskBuffer, int maskOffset)
{
for (int i = 0; i < messageLength; i++)
{
byte maskByte = maskBuffer[maskOffset + i % Constants.MaskSize];
dst[dstOffset + i] = (byte)(src[srcOffset + i] ^ maskByte);
}
}
/// <exception cref="InvalidDataException"></exception>
static int GetMessageLength(byte[] buffer, int offset, byte lenByte)
{
if (lenByte == Constants.UshortPayloadLength)
{
// header is 4 bytes long
ushort value = 0;
value |= (ushort)(buffer[offset + 2] << 8);
value |= buffer[offset + 3];
return value;
}
else if (lenByte == Constants.UlongPayloadLength)
{
throw new InvalidDataException("Max length is longer than allowed in a single message");
}
else // is less than 126
{
// header is 2 bytes long
return lenByte;
}
}
/// <exception cref="InvalidDataException"></exception>
static void ThrowIfNotFinished(bool finished)
{
if (!finished)
{
throw new InvalidDataException("Full message should have been sent, if the full message wasn't sent it wasn't sent from this trasnport");
}
}
/// <exception cref="InvalidDataException"></exception>
static void ThrowIfMaskNotExpected(bool hasMask, bool expectMask)
{
if (hasMask != expectMask)
{
throw new InvalidDataException($"Message expected mask to be {expectMask} but was {hasMask}");
}
}
/// <exception cref="InvalidDataException"></exception>
static void ThrowIfBadOpCode(int opcode)
{
// 2 = binary
// 8 = close
if (opcode != 2 && opcode != 8)
{
throw new InvalidDataException("Expected opcode to be binary or close");
}
}
/// <exception cref="InvalidDataException"></exception>
static void ThrowIfLengthZero(int msglen)
{
if (msglen == 0)
{
throw new InvalidDataException("Message length was zero");
}
}
/// <summary>
/// need to check this so that data from previous buffer isnt used
/// </summary>
/// <exception cref="InvalidDataException"></exception>
static void ThrowIfMsgLengthTooLong(int msglen, int maxLength)
{
if (msglen > maxLength)
{
throw new InvalidDataException("Message length is greater than max length");
}
}
}
}
| 35.829787 | 162 | 0.569279 | [
"MIT"
] | 28raining/Mirror | Assets/Mirror/Runtime/Transport/SimpleWebTransport/Common/MessageProcessor.cs | 5,052 | C# |
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebVella.Erp.Exceptions;
using WebVella.Erp.Web.Models;
using WebVella.Erp.Web.Services;
using WebVella.Erp.Web.Utils;
using WebVella.TagHelpers.Models;
namespace WebVella.Erp.Web.Components
{
[PageComponent(Label = "Field Data Csv", Library = "WebVella", Description = "field for submitting CSV data", Version = "0.0.1", IconClass = "fas fa-table")]
public class PcFieldDataCsv : PcFieldBase
{
protected ErpRequestContext ErpRequestContext { get; set; }
public PcFieldDataCsv([FromServices]ErpRequestContext coreReqCtx)
{
ErpRequestContext = coreReqCtx;
}
public class PcFieldDataCsvOptions : PcFieldBaseOptions
{
[JsonProperty(PropertyName = "height")]
public string Height { get; set; } = "";
[JsonProperty(PropertyName = "delimiter_value_ds")]
public string DelimiterValueDs { get; set; } = "comma";
[JsonProperty(PropertyName = "delimiter_field_name")]
public string DelimiterFieldName { get; set; } = "";
[JsonProperty(PropertyName = "has_header_value_ds")]
public string HasHeaderValueDs { get; set; } = "true";
[JsonProperty(PropertyName = "has_header_field_name")]
public string HasHeaderFieldName { get; set; } = "";
[JsonProperty(PropertyName = "has_header_column_value_ds")]
public string HasHeaderColumnValueDs { get; set; } = "false";
[JsonProperty(PropertyName = "has_header_column_field_name")]
public string HasHeaderColumnFieldName { get; set; } = "";
[JsonProperty(PropertyName = "lang_ds")]
public string LangDs { get; set; } = "en";
public static PcFieldDataCsvOptions CopyFromBaseOptions(PcFieldBaseOptions input)
{
return new PcFieldDataCsvOptions
{
IsVisible = input.IsVisible,
LabelMode = input.LabelMode,
LabelText = input.LabelText,
Mode = input.Mode,
Name = input.Name,
Height = "",
DelimiterValueDs = "",
HasHeaderValueDs = "",
HasHeaderColumnValueDs = "",
DelimiterFieldName = "",
HasHeaderFieldName = "",
HasHeaderColumnFieldName = "",
LangDs = "en",
};
}
}
public async Task<IViewComponentResult> InvokeAsync(PageComponentContext context)
{
ErpPage currentPage = null;
try
{
#region << Init >>
if (context.Node == null)
{
return await Task.FromResult<IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component"));
}
var pageFromModel = context.DataModel.GetProperty("Page");
if (pageFromModel is ErpPage)
{
currentPage = (ErpPage)pageFromModel;
}
else
{
return await Task.FromResult<IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type"));
}
if (currentPage == null)
{
return await Task.FromResult<IViewComponentResult>(Content("Error: The page Id is required to be set as query parameter 'pid', when requesting this component"));
}
var baseOptions = InitPcFieldBaseOptions(context);
var options = PcFieldDataCsvOptions.CopyFromBaseOptions(baseOptions);
if (context.Options != null)
{
options = JsonConvert.DeserializeObject<PcFieldDataCsvOptions>(context.Options.ToString());
}
var modelFieldLabel = "";
var model = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
if (String.IsNullOrWhiteSpace(options.LabelText) && context.Mode != ComponentMode.Options)
{
options.LabelText = modelFieldLabel;
}
ViewBag.LabelMode = options.LabelMode;
ViewBag.Mode = options.Mode;
if (options.LabelMode == WvLabelRenderMode.Undefined && baseOptions.LabelMode != WvLabelRenderMode.Undefined)
ViewBag.LabelMode = baseOptions.LabelMode;
if (options.Mode == WvFieldRenderMode.Undefined && baseOptions.Mode != WvFieldRenderMode.Undefined)
ViewBag.Mode = baseOptions.Mode;
var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as WvFieldAccess?;
if(accessOverride != null){
model.Access = accessOverride.Value;
}
var requiredOverride = context.DataModel.GetPropertyValueByDataSource(options.RequiredOverrideDs) as bool?;
if(requiredOverride != null){
model.Required = requiredOverride.Value;
}
else{
if(!String.IsNullOrWhiteSpace(options.RequiredOverrideDs)){
if(options.RequiredOverrideDs.ToLowerInvariant() == "true"){
model.Required = true;
}
else if(options.RequiredOverrideDs.ToLowerInvariant() == "false"){
model.Required = false;
}
}
}
#endregion
ViewBag.Options = options;
ViewBag.Model = model;
ViewBag.Node = context.Node;
ViewBag.ComponentMeta = componentMeta;
ViewBag.RequestContext = ErpRequestContext;
ViewBag.AppContext = ErpAppContext.Current;
ViewBag.ComponentContext = context;
ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;
if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
{
var isVisible = true;
var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
{
if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
{
isVisible = outBool;
}
}
else if (isVisibleDS is Boolean)
{
isVisible = (bool)isVisibleDS;
}
ViewBag.IsVisible = isVisible;
model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);
var delimiter = context.DataModel.GetPropertyValueByDataSource(options.DelimiterValueDs) as string;
var lang = context.DataModel.GetPropertyValueByDataSource(options.LangDs) as string;
var hasHeader = context.DataModel.GetPropertyValueByDataSource(options.HasHeaderValueDs) as bool?;
var hasHeaderColumn = context.DataModel.GetPropertyValueByDataSource(options.HasHeaderColumnValueDs) as bool?;
ViewBag.Delimiter = WvCsvDelimiterType.COMMA;
if (!String.IsNullOrWhiteSpace(delimiter) && delimiter == "tab") {
ViewBag.Delimiter = WvCsvDelimiterType.TAB;
}
ViewBag.Lang = "en";
if (!String.IsNullOrWhiteSpace(lang))
{
ViewBag.Lang = lang;
}
ViewBag.HasHeader = true;
if (hasHeader != null)
{
ViewBag.HasHeader = hasHeader;
}
ViewBag.HasHeaderColumn = false;
if (hasHeaderColumn != null)
{
ViewBag.HasHeaderColumn = hasHeaderColumn;
}
}
switch (context.Mode)
{
case ComponentMode.Display:
return await Task.FromResult<IViewComponentResult>(View("Display"));
case ComponentMode.Design:
return await Task.FromResult<IViewComponentResult>(View("Design"));
case ComponentMode.Options:
return await Task.FromResult<IViewComponentResult>(View("Options"));
case ComponentMode.Help:
return await Task.FromResult<IViewComponentResult>(View("Help"));
default:
ViewBag.Error = new ValidationException()
{
Message = "Unknown component mode"
};
return await Task.FromResult<IViewComponentResult>(View("Error"));
}
}
catch (ValidationException ex)
{
ViewBag.Error = ex;
return await Task.FromResult<IViewComponentResult>(View("Error"));
}
catch (Exception ex)
{
ViewBag.Error = new ValidationException()
{
Message = ex.Message
};
return await Task.FromResult<IViewComponentResult>(View("Error"));
}
}
}
}
| 32.873418 | 166 | 0.70145 | [
"Apache-2.0"
] | 628426/WebVella-ERP | WebVella.Erp.Web/Components/PcFieldDataCsv/PcFieldDataCsv.cs | 7,793 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GoogleAnalytics
{
/// <summary>
/// Dimensions in pixels.
/// </summary>
public struct Dimensions
{
/// <summary>
/// Creates a new object to store dimensions.
/// </summary>
/// <param name="width">The width in pixels.</param>
/// <param name="height">The height in pixels.</param>
public Dimensions(int width, int height)
{
Width = width;
Height = height;
}
/// <summary>
/// Gets the width in pixels.
/// </summary>
public int Width { get; private set; }
/// <summary>
/// Gets the height in pixels.
/// </summary>
public int Height { get; private set; }
}
}
| 24.111111 | 62 | 0.543779 | [
"MIT"
] | Lyoware/wpf-windows-sdk-for-google-analytics | GoogleAnalytics.SDK/Dimensions.cs | 870 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ModuleInitializer.cs" company="WildGums">
// Copyright (c) 2008 - 2019 WildGums. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using Catel.IoC;
using Catel.MVVM;
using Catel.Services;
using Orc.DataAccess.Controls;
/// <summary>
/// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded.
/// </summary>
public static class ModuleInitializer
{
/// <summary>
/// Initializes the module.
/// </summary>
public static void Initialize()
{
var serviceLocator = ServiceLocator.Default;
var viewModelLocator = serviceLocator.ResolveType<IViewModelLocator>();
viewModelLocator.Register(typeof(ConnectionStringEditWindow), typeof(ConnectionStringEditViewModel));
viewModelLocator.Register(typeof(ConnectionStringAdvancedOptionsWindow), typeof(ConnectionStringAdvancedOptionsViewModel));
viewModelLocator.Register(typeof(DbConnectionProviderListWindow), typeof(DbConnectionProviderListViewModel));
var languageService = serviceLocator.ResolveType<ILanguageService>();
languageService.RegisterLanguageSource(new LanguageResourceSource("Orc.DataAccess", "Orc.DataAccess.Properties", "Resources"));
}
}
| 44.969697 | 135 | 0.626011 | [
"MIT"
] | WildGums/Orc.DataAccess | src/Orc.DataAccess.Xaml/ModuleInitializer.cs | 1,486 | C# |
namespace Jeelu.SimplusD.Client.Win
{
partial class Department
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.lblDep = new System.Windows.Forms.Label();
this.tbxLinkEmail = new System.Windows.Forms.TextBox();
this.lblLinkEmail = new System.Windows.Forms.Label();
this.tbxLinkPostCode = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.tbxLinkFax = new System.Windows.Forms.TextBox();
this.lblLinkFax = new System.Windows.Forms.Label();
this.tbxLinkAddress = new System.Windows.Forms.TextBox();
this.lblLinkAddress = new System.Windows.Forms.Label();
this.tbxLinkPhone = new System.Windows.Forms.TextBox();
this.lblLinkPhone = new System.Windows.Forms.Label();
this.tbxLinkMan = new System.Windows.Forms.TextBox();
this.lblLinkMan = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tbxPhone = new System.Windows.Forms.TextBox();
this.btnUserAdd = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(66, 6);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(115, 20);
this.comboBox1.TabIndex = 0;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// lblDep
//
this.lblDep.AutoSize = true;
this.lblDep.Location = new System.Drawing.Point(5, 10);
this.lblDep.Name = "lblDep";
this.lblDep.Size = new System.Drawing.Size(59, 12);
this.lblDep.TabIndex = 0;
this.lblDep.Text = "部门名称:";
//
// tbxLinkEmail
//
this.tbxLinkEmail.Location = new System.Drawing.Point(66, 56);
this.tbxLinkEmail.Name = "tbxLinkEmail";
this.tbxLinkEmail.Size = new System.Drawing.Size(150, 21);
this.tbxLinkEmail.TabIndex = 3;
this.tbxLinkEmail.TextChanged += new System.EventHandler(this.tbxLinkEmail_TextChanged);
//
// lblLinkEmail
//
this.lblLinkEmail.AutoSize = true;
this.lblLinkEmail.Location = new System.Drawing.Point(5, 60);
this.lblLinkEmail.Name = "lblLinkEmail";
this.lblLinkEmail.Size = new System.Drawing.Size(59, 12);
this.lblLinkEmail.TabIndex = 24;
this.lblLinkEmail.Text = "电子邮箱:";
//
// tbxLinkPostCode
//
this.tbxLinkPostCode.Location = new System.Drawing.Point(66, 78);
this.tbxLinkPostCode.Name = "tbxLinkPostCode";
this.tbxLinkPostCode.Size = new System.Drawing.Size(150, 21);
this.tbxLinkPostCode.TabIndex = 5;
this.tbxLinkPostCode.TextChanged += new System.EventHandler(this.tbxLinkPostCode_TextChanged);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(5, 82);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(59, 12);
this.label7.TabIndex = 17;
this.label7.Text = "邮 编:";
//
// tbxLinkFax
//
this.tbxLinkFax.Location = new System.Drawing.Point(283, 78);
this.tbxLinkFax.Name = "tbxLinkFax";
this.tbxLinkFax.Size = new System.Drawing.Size(150, 21);
this.tbxLinkFax.TabIndex = 6;
this.tbxLinkFax.TextChanged += new System.EventHandler(this.tbxLinkFax_TextChanged);
//
// lblLinkFax
//
this.lblLinkFax.AutoSize = true;
this.lblLinkFax.Location = new System.Drawing.Point(222, 82);
this.lblLinkFax.Name = "lblLinkFax";
this.lblLinkFax.Size = new System.Drawing.Size(59, 12);
this.lblLinkFax.TabIndex = 18;
this.lblLinkFax.Text = "传 真:";
//
// tbxLinkAddress
//
this.tbxLinkAddress.Location = new System.Drawing.Point(66, 101);
this.tbxLinkAddress.Name = "tbxLinkAddress";
this.tbxLinkAddress.Size = new System.Drawing.Size(367, 21);
this.tbxLinkAddress.TabIndex = 7;
this.tbxLinkAddress.TextChanged += new System.EventHandler(this.tbxLinkAddress_TextChanged);
//
// lblLinkAddress
//
this.lblLinkAddress.AutoSize = true;
this.lblLinkAddress.Location = new System.Drawing.Point(5, 105);
this.lblLinkAddress.Name = "lblLinkAddress";
this.lblLinkAddress.Size = new System.Drawing.Size(59, 12);
this.lblLinkAddress.TabIndex = 15;
this.lblLinkAddress.Text = "地 址:";
//
// tbxLinkPhone
//
this.tbxLinkPhone.Location = new System.Drawing.Point(283, 34);
this.tbxLinkPhone.Name = "tbxLinkPhone";
this.tbxLinkPhone.Size = new System.Drawing.Size(150, 21);
this.tbxLinkPhone.TabIndex = 2;
this.tbxLinkPhone.TextChanged += new System.EventHandler(this.tbxLinkPhone_TextChanged);
//
// lblLinkPhone
//
this.lblLinkPhone.AutoSize = true;
this.lblLinkPhone.Location = new System.Drawing.Point(222, 38);
this.lblLinkPhone.Name = "lblLinkPhone";
this.lblLinkPhone.Size = new System.Drawing.Size(59, 12);
this.lblLinkPhone.TabIndex = 16;
this.lblLinkPhone.Text = "固定电话:";
//
// tbxLinkMan
//
this.tbxLinkMan.Location = new System.Drawing.Point(66, 34);
this.tbxLinkMan.Name = "tbxLinkMan";
this.tbxLinkMan.Size = new System.Drawing.Size(150, 21);
this.tbxLinkMan.TabIndex = 1;
this.tbxLinkMan.TextChanged += new System.EventHandler(this.tbxLinkMan_TextChanged);
//
// lblLinkMan
//
this.lblLinkMan.AutoSize = true;
this.lblLinkMan.Location = new System.Drawing.Point(5, 38);
this.lblLinkMan.Name = "lblLinkMan";
this.lblLinkMan.Size = new System.Drawing.Size(59, 12);
this.lblLinkMan.TabIndex = 14;
this.lblLinkMan.Text = "联 系 人:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(222, 60);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(59, 12);
this.label1.TabIndex = 26;
this.label1.Text = "移动电话:";
//
// tbxPhone
//
this.tbxPhone.Location = new System.Drawing.Point(283, 56);
this.tbxPhone.Name = "tbxPhone";
this.tbxPhone.Size = new System.Drawing.Size(150, 21);
this.tbxPhone.TabIndex = 4;
this.tbxPhone.TextChanged += new System.EventHandler(this.tbxPhone_TextChanged);
//
// btnUserAdd
//
this.btnUserAdd.Location = new System.Drawing.Point(187, 4);
this.btnUserAdd.Name = "btnUserAdd";
this.btnUserAdd.Size = new System.Drawing.Size(63, 23);
this.btnUserAdd.TabIndex = 27;
this.btnUserAdd.Text = "自定义";
this.btnUserAdd.UseVisualStyleBackColor = true;
this.btnUserAdd.Click += new System.EventHandler(this.btnUserAdd_Click);
//
// Department
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.btnUserAdd);
this.Controls.Add(this.tbxPhone);
this.Controls.Add(this.label1);
this.Controls.Add(this.tbxLinkEmail);
this.Controls.Add(this.lblLinkEmail);
this.Controls.Add(this.tbxLinkPostCode);
this.Controls.Add(this.label7);
this.Controls.Add(this.tbxLinkFax);
this.Controls.Add(this.lblLinkFax);
this.Controls.Add(this.tbxLinkAddress);
this.Controls.Add(this.lblLinkAddress);
this.Controls.Add(this.tbxLinkPhone);
this.Controls.Add(this.lblLinkPhone);
this.Controls.Add(this.tbxLinkMan);
this.Controls.Add(this.lblLinkMan);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.lblDep);
this.Name = "Department";
this.Size = new System.Drawing.Size(444, 126);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label lblDep;
private System.Windows.Forms.TextBox tbxLinkEmail;
private System.Windows.Forms.Label lblLinkEmail;
private System.Windows.Forms.TextBox tbxLinkPostCode;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox tbxLinkFax;
private System.Windows.Forms.Label lblLinkFax;
private System.Windows.Forms.TextBox tbxLinkAddress;
private System.Windows.Forms.Label lblLinkAddress;
private System.Windows.Forms.TextBox tbxLinkPhone;
private System.Windows.Forms.Label lblLinkPhone;
private System.Windows.Forms.TextBox tbxLinkMan;
private System.Windows.Forms.Label lblLinkMan;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbxPhone;
private System.Windows.Forms.Button btnUserAdd;
}
}
| 44.340081 | 112 | 0.578159 | [
"Apache-2.0"
] | xknife-erian/nknife.jeelusrc | NKnife.App.WebsiteBuilder/SimplusD/Client/Win/Common/CustomControls/PageEditControl/Department.Designer.cs | 11,160 | C# |
// ***********************************************************************
// <copyright file="IDataProviderWithCategories.cs" company="Alchiweb.fr">
// Copyright MIT License / 2015 Alchiweb.fr
// </copyright>
// <summary>
// Added by CategoriesForAppStudio
// Created by Hervé PHILIPPE
// alchiweb@live.fr / alchiweb.fr
// </summary>
// ***********************************************************************
namespace AppStudio.DataProviders
{
public enum VisibleItemsType
{
CurrentLevel,
All,
AllForCurrentCategory
}
public enum VisibleCategoriesType
{
CurrentLevel,
All,
NotEmpty
}
public interface IDataProviderWithCategories<T> where T : SchemaBase, ICategories, IHierarchical
{
IParserWithCategories<T> Parser { get; }
VisibleItemsType VisibleItems { get; set; }
VisibleCategoriesType VisibleCategories { get; set; }
}
}
| 28.058824 | 100 | 0.554507 | [
"MIT"
] | alchiweb/CategoriesForAppStudio | Install_CategoriesForAppStudio/[WAS_APP_NAME].W10/AppStudio.DataProviders/IDataProviderWithCategories.cs | 955 | C# |
using System;
using System.Threading.Tasks;
using Autofac;
using MiningCore.Blockchain.Bitcoin;
using MiningCore.Blockchain.Bitcoin.DaemonResponses;
using MiningCore.Blockchain.ZCash.DaemonResponses;
using MiningCore.Contracts;
using MiningCore.DaemonInterface;
using MiningCore.Time;
namespace MiningCore.Blockchain.ZCash
{
public class ZCashJobManager : BitcoinJobManager<ZCashJob, ZCashBlockTemplate>
{
public ZCashJobManager(
IComponentContext ctx,
IMasterClock clock,
BitcoinExtraNonceProvider extraNonceProvider) : base(ctx, clock, extraNonceProvider)
{
getBlockTemplateParams = new object[]
{
new
{
capabilities = new[] { "coinbasetxn", "workid", "coinbase/append" },
}
};
}
public override async Task<bool> ValidateAddressAsync(string address)
{
Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(address), $"{nameof(address)} must not be empty");
// handle t-addr
if (address.Length == 36)
return await base.ValidateAddressAsync(address);
// handle z-addr
if (address.Length == 96)
{
var result = await daemon.ExecuteCmdAnyAsync<ValidateAddressResponse>(
ZCashCommands.ZValidateAddress, new[] {address});
return result.Response != null && result.Response.IsValid;
}
return false;
}
protected override async Task<DaemonResponse<ZCashBlockTemplate>> GetBlockTemplateAsync()
{
var subsidyResponse = await daemon.ExecuteCmdAnyAsync<ZCashBlockSubsidy>(BitcoinCommands.GetBlockSubsidy);
var result = await daemon.ExecuteCmdAnyAsync<ZCashBlockTemplate>(
BitcoinCommands.GetBlockTemplate, getBlockTemplateParams);
if (subsidyResponse.Error == null && result.Error == null && result.Response != null)
result.Response.Subsidy = subsidyResponse.Response;
return result;
}
}
}
| 34.888889 | 122 | 0.616924 | [
"MIT"
] | SolarPool/miningcore_ella | src/MiningCore/Blockchain/ZCash/ZCashJobManager.cs | 2,200 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Viewer.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.296296 | 151 | 0.579642 | [
"BSD-3-Clause"
] | Jamaika1/charls | samples/viewer/Properties/Settings.Designer.cs | 1,063 | C# |
/*
Copyright 2007-2017 The NGenerics Team
(https://github.com/ngenerics/ngenerics/wiki/Team)
This program is licensed under the MIT License. You should
have received a copy of the license along with the source code. If not, an online copy
of the license can be found at https://opensource.org/licenses/MIT.
*/
using NGenerics.DataStructures.Mathematical;
using NUnit.Framework;
namespace NGenerics.Tests.DataStructures.Mathematical.Vector3DTests
{
[TestFixture]
public class Negate
{
[Test]
public void Simple()
{
var vector = new Vector3D(1, 2, -5);
vector.Negate();
Assert.AreEqual(-1, vector.X);
Assert.AreEqual(-2, vector.Y);
Assert.AreEqual(5, vector.Z);
}
}
} | 24.71875 | 88 | 0.647282 | [
"MIT"
] | ngenerics/ngenerics | src/NGenerics.Tests/DataStructures/Mathematical/Vector3DTests/Negate.cs | 791 | C# |
using System;
namespace Ultraviolet.SDL2
{
/// <summary>
/// Represents the configuration information for SDL2 windows.
/// </summary>
public sealed class SDL2PlatformConfiguration
{
/// <summary>
/// Gets or sets the rendering API which will be used by the application.
/// </summary>
public SDL2PlatformRenderingAPI RenderingAPI { get; set; }
/// <summary>
/// Gets the number of buffers used for multisample anti-aliasing.
/// </summary>
public Int32 MultiSampleBuffers { get; set; }
/// <summary>
/// Gets the number of samples around the current pixel used for multisample anti-aliasing.
/// </summary>
public Int32 MultiSampleSamples { get; set; }
/// <summary>
/// Gets or sets a value indicating whether SRGB encoding should be enabled for
/// textures and render buffers if it is supported.
/// </summary>
public Boolean SrgbBuffersEnabled { get; set; }
}
}
| 32.25 | 99 | 0.616279 | [
"Apache-2.0",
"MIT"
] | Spool5520/ultraviolet | Source/Ultraviolet.SDL2/Shared/SDL2PlatformConfiguration.cs | 1,034 | C# |
using Microsoft.EntityFrameworkCore;
namespace NChista.StoredProcedureCore.Extensions
{
/// <summary>
/// Stored procedure extension method for <see cref="DbContext"/> that allows executing a specific stored procedure.
/// </summary>
public static class DbContextExtensions
{
/// <summary>
/// Initializes a new instance of the <see cref="NChista.StoredProcedureCore.StoredProcedure"/> class.
/// </summary>
/// <param name="dbContext">The context being used to execute the stored procedure.</param>
/// <param name="name">The name of the stored procedure.</param>
/// <returns>An <see cref="IStoredProcedure"/>.</returns>
public static IStoredProcedure StoredProcedure(this DbContext dbContext, string name)
{
return new StoredProcedure(dbContext, name);
}
}
}
| 39.636364 | 120 | 0.665138 | [
"MIT"
] | MohsenNouriG/NChista.StoredProcedureCore | NChista.StoredProcedureCore/Extensions/DbContextExtensions.cs | 874 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PUBGSDK {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class URL {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal URL() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PUBGSDK.URL", typeof(URL).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to shards/.
/// </summary>
internal static string base_extension {
get {
return ResourceManager.GetString("base_extension", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to https://api.playbattlegrounds.com/.
/// </summary>
internal static string base_url {
get {
return ResourceManager.GetString("base_url", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to matches/.
/// </summary>
internal static string match {
get {
return ResourceManager.GetString("match", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to players/.
/// </summary>
internal static string player {
get {
return ResourceManager.GetString("player", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to players?filter[playerIds]=.
/// </summary>
internal static string player_ids {
get {
return ResourceManager.GetString("player_ids", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to players?filter[playerNames]=.
/// </summary>
internal static string player_names {
get {
return ResourceManager.GetString("player_names", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to status.
/// </summary>
internal static string status {
get {
return ResourceManager.GetString("status", resourceCulture);
}
}
}
}
| 37.503937 | 150 | 0.562041 | [
"MIT"
] | Scarjit/PUBGSDK | PUBGSDK/URL.Designer.cs | 4,765 | C# |
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
namespace SmartHouse.Domain.Core
{
public class MongoBase
{
[BsonId]
[Required]
[JsonProperty(Required = Required.Always)]
public string Id { get; set; }
[BsonElement("categoryName")]
[BsonRepresentation(BsonType.String)]
public string CategoryName { get; set; }
}
} | 24.736842 | 50 | 0.67234 | [
"MIT"
] | JeanRasin/SmartHouse | SmartHouse.Domain.Core/MongoBase.cs | 472 | C# |
public class BoosterInfo
{
public string id {get;}
public int index {get;}
public float barSize1 {get;}
public float barSize2 {get;}
public float barSize3 {get;}
public float spd1 {get;}
public float spd2 {get;}
public float spd3 {get;}
public BoosterInfo(BoosterTableData _data)
{
this.id = _data.BID;
this.index = _data.Index;
this.barSize1 = _data.Barsize1;
this.barSize2 = _data.Barsize2;
this.barSize3 = _data.Barsize3;
this.spd1 = _data.Spd1;
this.spd2 = _data.Spd2;
this.spd3 = _data.Spd3;
}
}
| 24.692308 | 47 | 0.580997 | [
"MIT"
] | HEE-SUK/Country_Road | Assets/GameResources/Scripts/InfoTable/BoosterInfo.cs | 644 | C# |
using Etsy.Resources;
namespace Etsy.Services
{
public class Listing : RestBase
{
public Listing(SessionInfo session)
{
base.info = session;
}
// listings
public Resources.Listing createListing(int quantity, string title, string description, decimal price,
string tags, long shipping_template_id, string materials = "", long? shop_section_id = null)
{
method = "POST";
URI = "/listings";
var parameters = new Parameters();
parameters.AddParameter("quantity", quantity.ToString());
parameters.AddParameter("title", title);
parameters.AddParameter("description", description);
parameters.AddParameter("price", price.ToString());
parameters.AddParameter("tags", tags);
parameters.AddParameter("shipping_template_id", shipping_template_id.ToString());
if (!string.IsNullOrEmpty(materials))
{
parameters.AddParameter("materials", materials);
}
if (shop_section_id.HasValue)
{
parameters.AddParameter("shop_section_id", shop_section_id.Value.ToString());
}
var response = SendRequest<Resources.Listing>(parameters);
return response == null ? null : response.results[0];
}
public void deleteListing(long listing_id)
{
method = "DELETE";
URI = "/listings/:listing_id";
id.listing_id = listing_id.ToString();
var parameters = new Parameters();
SendRequest<Resources.Listing>(parameters);
}
public Resources.Listing getListing(long listing_id, string fields = null, string includes = null)
{
method = "GET";
URI = "/listings/:listing_id";
id.listing_id = listing_id.ToString();
var parameters = new Parameters();
parameters.AddParameter("fields", fields);
parameters.AddParameter("includes", includes);
var response = SendRequest<Resources.Listing>(parameters);
return response == null ? null : response.results[0];
}
public Resources.Listing updateListing(long listing_id, bool renew, int quantity, string title, string description, decimal price,
string tags, long? shipping_template_id = null, string materials = "", long? shop_section_id = null, string state = "active")
{
method = "PUT";
URI = "/listings/:listing_id";
id.listing_id = listing_id.ToString();
var parameters = new Parameters();
parameters.AddParameter("renew", renew?"true":"false");
parameters.AddParameter("state", state);
parameters.AddParameter("quantity", quantity.ToString());
parameters.AddParameter("title", title);
parameters.AddParameter("description", description);
parameters.AddParameter("price", price.ToString());
parameters.AddParameter("tags", tags);
parameters.AddParameter("shipping_template_id", shipping_template_id.ToString());
parameters.AddParameter("materials", materials);
parameters.AddParameter("shop_section_id", shop_section_id.ToString());
var response = SendRequest<Resources.Listing>(parameters);
return response == null ? null : response.results[0];
}
public ListingImage uploadListingImage(string listing_id, string path)
{
method = "POST";
URI = "/listings/:listing_id/images";
id.listing_id = listing_id;
filePath = path;
var parameters = new Parameters();
var response = SendRequest<ListingImage>(parameters, true);
return response == null ? null : response.results[0];
}
// shipping templates
public ShippingTemplate createShippingTemplate(string title, int origin_country_id, int? destination_country_id,
decimal primary_cost, decimal secondary_cost, int? destination_region_id)
{
method = "POST";
URI = "shipping/templates";
var parameters = new Parameters();
parameters.AddParameter("title", title);
parameters.AddParameter("origin_country_id", origin_country_id.ToString());
parameters.AddParameter("destination_country_id", destination_country_id.ToString());
parameters.AddParameter("primary_cost", primary_cost.ToString());
parameters.AddParameter("secondary_cost", secondary_cost.ToString());
parameters.AddParameter("destination_region_id", destination_region_id.ToString());
var data = SendRequest<ShippingTemplate>(parameters);
return data == null? null: data.results[0];
}
public ShippingTemplateEntry createShippingTemplateEntry(long shipping_template_id, int? destination_country_id,
decimal primary_cost, decimal secondary_cost, int? destination_region_id)
{
method = "POST";
URI = "shipping/templates/entries";
var parameters = new Parameters();
parameters.AddParameter("shipping_template_id", shipping_template_id.ToString());
parameters.AddParameter("destination_country_id", destination_country_id.ToString());
parameters.AddParameter("primary_cost", primary_cost.ToString());
parameters.AddParameter("secondary_cost", secondary_cost.ToString());
parameters.AddParameter("destination_region_id", destination_region_id.ToString());
var data = SendRequest<ShippingTemplateEntry>(parameters);
return data == null ? null : data.results[0];
}
}
}
| 45.898438 | 138 | 0.625532 | [
"Apache-2.0"
] | seanlinmt/tradelr | Etsy/Services/Listing.cs | 5,877 | C# |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using DotNetNuke.UI.Skins;
#endregion
namespace DotNetNuke.Services.Installer.Installers
{
/// -----------------------------------------------------------------------------
/// <summary>
/// The ContainerInstaller installs Container Components to a DotNetNuke site
/// </summary>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
public class ContainerInstaller : SkinInstaller
{
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets the name of the Collection Node ("containerFiles")
/// </summary>
/// <value>A String</value>
/// -----------------------------------------------------------------------------
protected override string CollectionNodeName
{
get
{
return "containerFiles";
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets the name of the Item Node ("containerFile")
/// </summary>
/// <value>A String</value>
/// -----------------------------------------------------------------------------
protected override string ItemNodeName
{
get
{
return "containerFile";
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets the name of the SkinName Node ("containerName")
/// </summary>
/// <value>A String</value>
/// -----------------------------------------------------------------------------
protected override string SkinNameNodeName
{
get
{
return "containerName";
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets the RootName of the Skin
/// </summary>
/// <value>A String</value>
/// -----------------------------------------------------------------------------
protected override string SkinRoot
{
get
{
return SkinController.RootContainer;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets the Type of the Skin
/// </summary>
/// <value>A String</value>
/// -----------------------------------------------------------------------------
protected override string SkinType
{
get
{
return "Container";
}
}
}
}
| 32.462366 | 101 | 0.319311 | [
"MIT"
] | CMarius94/Dnn.Platform | DNN Platform/Library/Services/Installer/Installers/ContainerInstaller.cs | 3,021 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
/// <summary>
/// Example script to test toggling the gaze provider source from platform-specific overrides to the default camera frame center.
/// </summary>
public class ToggleGazeSource : MonoBehaviour
{
private IMixedRealityGazeProviderHeadOverride GazeProvider => gazeProvider ?? (gazeProvider = CoreServices.InputSystem?.GazeProvider as IMixedRealityGazeProviderHeadOverride);
private IMixedRealityGazeProviderHeadOverride gazeProvider = null;
/// <summary>
/// Toggles the value of IMixedRealityGazeProviderWithOverride's UseHeadGazeOverride.
/// </summary>
public void ToggleGazeOverride()
{
if (GazeProvider != null)
{
GazeProvider.UseHeadGazeOverride = !GazeProvider.UseHeadGazeOverride;
}
}
}
}
| 37.034483 | 184 | 0.679702 | [
"MIT"
] | Argylebuild/aad-hololens | Assets/MRTK/Examples/Demos/HandTracking/Scripts/ToggleGazeSource.cs | 1,076 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Win.Pizzeria
{
public partial class FormPerecederos : Form
{
public FormPerecederos()
{
InitializeComponent();
}
}
}
| 19.571429 | 48 | 0.664234 | [
"MIT"
] | AdanTorres21/Pizza-Ordenes | FormPerecederos.cs | 413 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Bakery.Models;
namespace BakeryTests
{
[TestClass]
public class PastryTests
{
[TestMethod]
public void Constructor_BuildPastryOrder_True()
{
Pastry testPastry = new Pastry(17);
Assert.AreEqual(17, testPastry.Count);
}
[TestMethod]
public void CalculatePrice_CalculatesPastryPrice_True()
{
Pastry testPastry = new Pastry(17);
testPastry.CalculatePrice();
Assert.AreEqual(29, testPastry.Price);
}
}
} | 22.958333 | 60 | 0.667877 | [
"MIT"
] | TJEverett/Pierre_Bakery | BakeryTests/ModelsTests/PastryTests.cs | 551 | C# |
using ReturnTrue.QueryBuilder.Enums;
using ReturnTrue.QueryBuilder.Modifiers;
using ReturnTrue.QueryBuilder.Renderers;
using ReturnTrue.QueryBuilder.Select;
using ReturnTrue.QueryBuilder.Select.OrderBy;
using System;
using System.Collections.Generic;
namespace ReturnTrue.QueryBuilder.Elements
{
public class Column : IQueryValueExpression
{
public string Name { get; private set; }
public Table Table { get; private set; }
public Column(string name)
: this(name, null)
{
}
public Column(string name, Table table)
{
Name = name;
Table = table;
}
public virtual string Render(IRenderer renderer)
{
return renderer.Render(this);
}
public PatternPredicate IsLike(string pattern)
{
return new PatternPredicate(this, new StringLiteralValue(pattern));
}
public PatternPredicate IsNotLike(string pattern)
{
return new PatternPredicate(this, new NotModifier(), new StringLiteralValue(pattern));
}
public MembershipPredicate IsIn(IQueryMembership membership)
{
return new MembershipPredicate(this, membership);
}
public MembershipPredicate IsIn(IEnumerable<int> membership)
{
return new MembershipPredicate(this, new IntegerLiteralArray(membership));
}
public MembershipPredicate IsNotIn(IQueryMembership membership)
{
return new MembershipPredicate(this, new NotModifier(), membership);
}
public MembershipPredicate IsNotIn(string membership)
{
return new MembershipPredicate(this, new NotModifier(), new StringLiteralValue(membership));
}
public RangePredicate IsInRange(IQueryValueExpression middleExpression, IQueryValueExpression rightExpression)
{
return new RangePredicate(this, middleExpression, rightExpression);
}
public RangePredicate IsNotInRange(IQueryValueExpression middleExpression, IQueryValueExpression rightExpression)
{
return new RangePredicate(this, new NotModifier(), middleExpression, rightExpression);
}
public NullPredicate IsNull()
{
return new NullPredicate(this);
}
public NullPredicate IsNotNull()
{
return new NullPredicate(this, new NotModifier());
}
public AggregateFunction Count()
{
return new AggregateFunction(FunctionType.Count, this);
}
public AggregateFunction Sum()
{
return new AggregateFunction(FunctionType.Sum, this);
}
public AggregateFunction Avg()
{
return new AggregateFunction(FunctionType.Avg, this);
}
public AggregateFunction Max()
{
return new AggregateFunction(FunctionType.Max, this);
}
public AggregateFunction Min()
{
return new AggregateFunction(FunctionType.Min, this);
}
public DatePartFunction DatePart(DatePartType partType)
{
return new DatePartFunction(partType, this);
}
public UpperFunction ToUpper()
{
return new UpperFunction(this);
}
public LowerFunction ToLower()
{
return new LowerFunction(this);
}
public OrderByClause Asc()
{
return new OrderByClause(this, OrderType.Ascending);
}
public OrderByClause Desc()
{
return new OrderByClause(this, OrderType.Descending);
}
public static OrderByClause operator +(Column column)
{
return new OrderByClause(column, OrderType.Ascending);
}
public static OrderByClause operator -(Column column)
{
return new OrderByClause(column, OrderType.Descending);
}
public static ComparisonPredicate operator ==(Column leftColumn, bool literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.Equals, new BooleanLiteralValue(literalValue));
}
public static ComparisonPredicate operator ==(Column leftColumn, DateTime literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.Equals, new DateTimeLiteralValue(literalValue));
}
public static ComparisonPredicate operator ==(Column leftColumn, int literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.Equals, new IntegerLiteralValue(literalValue));
}
public static ComparisonPredicate operator ==(Column leftColumn, double literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.Equals, new DecimalLiteralValue(literalValue));
}
public static ComparisonPredicate operator ==(Column leftColumn, string literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.Equals, new StringLiteralValue(literalValue));
}
public static ComparisonPredicate operator ==(Column leftColumn, Column rightColumn)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.Equals, rightColumn);
}
public static ComparisonPredicate operator ==(Column leftColumn, SelectQuery query)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.Equals, query);
}
public static ComparisonPredicate operator !=(Column leftColumn, bool literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.NotEquals, new BooleanLiteralValue(literalValue));
}
public static ComparisonPredicate operator !=(Column leftColumn, DateTime literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.NotEquals, new DateTimeLiteralValue(literalValue));
}
public static ComparisonPredicate operator !=(Column leftColumn, int literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.NotEquals, new IntegerLiteralValue(literalValue));
}
public static ComparisonPredicate operator !=(Column leftColumn, double literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.NotEquals, new DecimalLiteralValue(literalValue));
}
public static ComparisonPredicate operator !=(Column leftColumn, string literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.NotEquals, new StringLiteralValue(literalValue));
}
public static ComparisonPredicate operator !=(Column leftColumn, Column rightColumn)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.NotEquals, rightColumn);
}
public static ComparisonPredicate operator !=(Column leftColumn, SelectQuery query)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.NotEquals, query);
}
public static ComparisonPredicate operator <(Column leftColumn, bool literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessThan, new BooleanLiteralValue(literalValue));
}
public static ComparisonPredicate operator <(Column leftColumn, DateTime literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessThan, new DateTimeLiteralValue(literalValue));
}
public static ComparisonPredicate operator <(Column leftColumn, int literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessThan, new IntegerLiteralValue(literalValue));
}
public static ComparisonPredicate operator <(Column leftColumn, double literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessThan, new DecimalLiteralValue(literalValue));
}
public static ComparisonPredicate operator <(Column leftColumn, string literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessThan, new StringLiteralValue(literalValue));
}
public static ComparisonPredicate operator <(Column leftColumn, Column rightColumn)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessThan, rightColumn);
}
public static ComparisonPredicate operator <(Column leftColumn, SelectQuery query)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessThan, query);
}
public static ComparisonPredicate operator >(Column leftColumn, bool literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterThan, new BooleanLiteralValue(literalValue));
}
public static ComparisonPredicate operator >(Column leftColumn, DateTime literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterThan, new DateTimeLiteralValue(literalValue));
}
public static ComparisonPredicate operator >(Column leftColumn, int literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterThan, new IntegerLiteralValue(literalValue));
}
public static ComparisonPredicate operator >(Column leftColumn, double literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterThan, new DecimalLiteralValue(literalValue));
}
public static ComparisonPredicate operator >(Column leftColumn, string literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterThan, new StringLiteralValue(literalValue));
}
public static ComparisonPredicate operator >(Column leftColumn, Column rightColumn)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterThan, rightColumn);
}
public static ComparisonPredicate operator >(Column leftColumn, SelectQuery query)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterThan, query);
}
public static ComparisonPredicate operator >=(Column leftColumn, bool literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterOrEqualsThan, new BooleanLiteralValue(literalValue));
}
public static ComparisonPredicate operator >=(Column leftColumn, DateTime literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterOrEqualsThan, new DateTimeLiteralValue(literalValue));
}
public static ComparisonPredicate operator >=(Column leftColumn, int literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterOrEqualsThan, new IntegerLiteralValue(literalValue));
}
public static ComparisonPredicate operator >=(Column leftColumn, double literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterOrEqualsThan, new DecimalLiteralValue(literalValue));
}
public static ComparisonPredicate operator >=(Column leftColumn, string literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterOrEqualsThan, new StringLiteralValue(literalValue));
}
public static ComparisonPredicate operator >=(Column leftColumn, Column rightColumn)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterOrEqualsThan, rightColumn);
}
public static ComparisonPredicate operator >=(Column leftColumn, SelectQuery query)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.GreaterOrEqualsThan, query);
}
public static ComparisonPredicate operator <=(Column leftColumn, bool literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessOrEqualsThan, new BooleanLiteralValue(literalValue));
}
public static ComparisonPredicate operator <=(Column leftColumn, DateTime literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessOrEqualsThan, new DateTimeLiteralValue(literalValue));
}
public static ComparisonPredicate operator <=(Column leftColumn, int literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessOrEqualsThan, new IntegerLiteralValue(literalValue));
}
public static ComparisonPredicate operator <=(Column leftColumn, double literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessOrEqualsThan, new DecimalLiteralValue(literalValue));
}
public static ComparisonPredicate operator <=(Column leftColumn, string literalValue)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessOrEqualsThan, new StringLiteralValue(literalValue));
}
public static ComparisonPredicate operator <=(Column leftColumn, Column rightColumn)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessOrEqualsThan, rightColumn);
}
public static ComparisonPredicate operator <=(Column leftColumn, SelectQuery query)
{
return new ComparisonPredicate(leftColumn, ComparisonPredicateType.LessOrEqualsThan, query);
}
}
} | 39.846591 | 140 | 0.690289 | [
"MIT"
] | aleripe/QueryBuilder | QueryBuilder/Elements/Column.cs | 14,028 | C# |
using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.CSharp.SmartMarkers
{
public class UsingHTMLProperty
{
public static void Run()
{
// ExStart:1
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Workbook workbook = new Workbook();
WorkbookDesigner designer = new WorkbookDesigner();
designer.Workbook = workbook;
workbook.Worksheets[0].Cells["A1"].PutValue("&=$VariableArray(HTML)");
designer.SetDataSource("VariableArray", new String[] { "Hello <b>World</b>", "Arabic", "Hindi", "Urdu", "French" });
designer.Process();
workbook.Save(dataDir + "output.xls");
// ExEnd:1
}
}
} | 33.615385 | 128 | 0.606407 | [
"MIT"
] | Aspose/Aspose.Cells-for-.NET | Examples/CSharp/SmartMarkers/UsingHTMLProperty.cs | 874 | C# |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Blumind.Configuration;
using Blumind.Controls;
using Blumind.Core;
using Blumind.Globalization;
using Blumind.Model;
using Blumind.Model.Widgets;
namespace Blumind.Dialogs
{
class RemarkDialog : BaseDialog, IWidgetEditDialog
{
public const string RemarkDialogSize = "RemarkDialogSize";
HtmlEditor htmlEditor;
Button btnEdit;
Button btnSave;
Button btnCancelEdit;
Button btnClose;
bool _IsEditMode;
IRemark _RemarkObject;
public RemarkDialog()
{
InitializeComponent();
AfterInitialize();
}
void InitializeComponent()
{
htmlEditor = new HtmlEditor();
htmlEditor.ReadOnly = ReadOnly;
btnEdit = new Button();
btnEdit.Text = "Edit";
btnEdit.Click += btnEdit_Click;
btnSave = new Button();
btnSave.Text = "Accept Changes";
btnSave.Width = 120;
btnSave.Click += btnAcceptChanges_Click;
btnCancelEdit = new Button();
btnCancelEdit.Text = "Cancel";
btnCancelEdit.Click += btnCancelEdit_Click;
btnClose = new Button();
btnClose.Text = "Close";
btnClose.Click += btnClose_Click;
SuspendLayout();
FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
CancelButton = btnClose;
Controls.AddRange(new Control[] { htmlEditor, btnEdit, btnSave, btnCancelEdit, btnClose });
MinimumSize = new Size(400, 300);
if (Options.Current.Contains(RemarkDialogSize))
Size = Options.Current.GetValue(RemarkDialogSize, Size);
ResumeLayout(false);
}
public string Remark
{
get { return htmlEditor.Text; }
set { htmlEditor.Text = value; }
}
public bool IsEditMode
{
get { return _IsEditMode; }
set
{
if (_IsEditMode != value)
{
_IsEditMode = value;
OnIsEditModeChanged();
}
}
}
[DefaultValue(null)]
public IRemark RemarkObject
{
get { return _RemarkObject; }
set
{
if (_RemarkObject != value)
{
var ce = new CancelEventArgs();
OnRemarkObjectChanging(_RemarkObject, value, ce);
if (ce.Cancel)
return;
_RemarkObject = value;
OnRemarkObjectChanged();
}
}
}
Widget IWidgetEditDialog.Widget
{
get
{
return RemarkObject as Widget;
}
set
{
RemarkObject = value;
}
}
protected override bool ShowButtonArea
{
get
{
return true;
}
}
void OnIsEditModeChanged()
{
if (!IsEditMode && htmlEditor.ViewType != HtmlEditorViewType.Design)
htmlEditor.ViewType = HtmlEditorViewType.Design;
RefreshViewStatus();
}
protected override void OnCurrentLanguageChanged()
{
base.OnCurrentLanguageChanged();
Text = Lang._("Remark");
btnEdit.Text = Lang._("Edit");
btnSave.Text = Lang._("Accept Changes");
btnCancelEdit.Text = Lang._("Cancel");
btnClose.Text = Lang._("Close");
}
void RefreshViewStatus()
{
var readOnly = !IsEditMode || ReadOnly;
htmlEditor.ReadOnly = readOnly;
btnSave.Visible = btnSave.Enabled = !ReadOnly && IsEditMode;
btnCancelEdit.Visible = btnCancelEdit.Enabled = !ReadOnly && IsEditMode;
btnEdit.Visible = btnEdit.Enabled = !ReadOnly && !IsEditMode;
}
protected override void OnReadOnlyChanged()
{
base.OnReadOnlyChanged();
RefreshViewStatus();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!DesignMode)
{
RefreshViewStatus();
}
}
protected override void OnLayout(LayoutEventArgs e)
{
base.OnLayout(e);
if (htmlEditor != null)
{
htmlEditor.Bounds = this.ControlsRectangle;
}
if (btnEdit != null)
{
LocateButtonsLeft(new Control[] { btnEdit, btnSave, btnCancelEdit });
}
if (btnClose != null)
{
LocateButtonsRight(new Control[] { btnClose });
}
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
base.OnFormClosed(e);
Options.Current.SetValue(RemarkDialogSize, Size);
}
void btnEdit_Click(object sender, EventArgs e)
{
if (!ReadOnly)
{
IsEditMode = true;
}
}
void btnCancelEdit_Click(object sender, EventArgs e)
{
IsEditMode = false;
}
void btnAcceptChanges_Click(object sender, EventArgs e)
{
if (RemarkObject != null && IsEditMode)
{
htmlEditor.EndEdit();
if (htmlEditor.Modified)
{
RemarkObject.Remark = Remark;
}
}
IsEditMode = false;
}
void btnClose_Click(object sender, EventArgs e)
{
Close();
}
void OnRemarkObjectChanging(IRemark oldValue, IRemark newValue, CancelEventArgs e)
{
if (oldValue != null && IsEditMode)
{
htmlEditor.EndEdit();
if (htmlEditor.Modified)
{
var msg = Lang._("The content has changed, do you want to accept the changes?");
var dr = this.ShowMessage(msg, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
switch (dr)
{
case System.Windows.Forms.DialogResult.Yes:
oldValue.Remark = Remark;
break;
case System.Windows.Forms.DialogResult.No:
break;
case System.Windows.Forms.DialogResult.Cancel:
e.Cancel = true;
break;
}
}
}
}
void OnRemarkObjectChanged()
{
if (RemarkObject != null)
Remark = RemarkObject.Remark;
else
Remark = null;
IsEditMode = false;
}
public void ShowDialog(IRemark remarkObject, bool readOnly)
{
this.RemarkObject = remarkObject;
this.ReadOnly = readOnly;
if (remarkObject != null)
{
if (!Visible)
this.Show(Program.MainForm);
}
else
{
if (Visible)
this.Hide();
}
}
#region GlobalRemarkDialog
static RemarkDialog _Global;
public static RemarkDialog Global
{
get
{
if (_Global == null || _Global.IsDisposed)
_Global = new RemarkDialog();
return _Global;
}
}
#endregion
}
}
| 27.177474 | 107 | 0.483235 | [
"MIT"
] | Darkxiete/Blumind | Code/Blumind/Dialogs/RemarkDialog.cs | 7,965 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02.CompareArrays")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.CompareArrays")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b722e8ac-184e-4464-ae52-fe2309924574")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.972973 | 84 | 0.745196 | [
"MIT"
] | SHAMMY1/Telerik-Academy | Homeworks/CSharpPartTwo/01.Arrays/Arrays-Homework/02.CompareArrays/Properties/AssemblyInfo.cs | 1,408 | 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 auditmanager-2017-07-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AuditManager.Model
{
/// <summary>
/// Container for the parameters to the BatchCreateDelegationByAssessment operation.
/// Create a batch of delegations for a specified assessment in AWS Audit Manager.
/// </summary>
public partial class BatchCreateDelegationByAssessmentRequest : AmazonAuditManagerRequest
{
private string _assessmentId;
private List<CreateDelegationRequest> _createDelegationRequests = new List<CreateDelegationRequest>();
/// <summary>
/// Gets and sets the property AssessmentId.
/// <para>
/// The identifier for the specified assessment.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=36, Max=36)]
public string AssessmentId
{
get { return this._assessmentId; }
set { this._assessmentId = value; }
}
// Check to see if AssessmentId property is set
internal bool IsSetAssessmentId()
{
return this._assessmentId != null;
}
/// <summary>
/// Gets and sets the property CreateDelegationRequests.
/// <para>
/// The API request to batch create delegations in AWS Audit Manager.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=50)]
public List<CreateDelegationRequest> CreateDelegationRequests
{
get { return this._createDelegationRequests; }
set { this._createDelegationRequests = value; }
}
// Check to see if CreateDelegationRequests property is set
internal bool IsSetCreateDelegationRequests()
{
return this._createDelegationRequests != null && this._createDelegationRequests.Count > 0;
}
}
} | 35.164557 | 111 | 0.643269 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/AuditManager/Generated/Model/BatchCreateDelegationByAssessmentRequest.cs | 2,778 | C# |
using System;
using System.Runtime.CompilerServices;
namespace NetFabric.Hyperlinq
{
public static partial class ArrayExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Count<TSource>(this Memory<TSource> source)
=> source.Length;
}
}
| 22 | 69 | 0.707792 | [
"MIT"
] | manofstick/NetFabric.Hyperlinq | NetFabric.Hyperlinq/Aggregation/Count/Count.Memory.cs | 308 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
namespace AppManagementTool
{
public partial class CreatePackageForm : Form
{
private string appId;
public CreatePackageForm(string title, string id, string file)
{
InitializeComponent();
this.titleLabel.Text = title;
this.appId = id;
this.mainDllTextBox.Text = Path.GetDirectoryName(file);
this.BrowseFolder(this.mainDllTextBox.Text);
}
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
if (folderBrowserDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.mainDllTextBox.Text = folderBrowserDlg.SelectedPath;
this.BrowseFolder(folderBrowserDlg.SelectedPath);
}
}
private void BrowseFolder(string folder)
{
DirectoryInfo di = new DirectoryInfo(folder);
foreach (DirectoryInfo subDi in di.GetDirectories())
{
this.BrowseFolder(subDi.FullName);
}
foreach (FileInfo fi in di.GetFiles())
{
this.fileListBox.Items.Add(fi.FullName);
}
}
private void startButton_Click(object sender, EventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
DirectoryInfo di = new DirectoryInfo(System.IO.Path.GetDirectoryName(assembly.Location));
string packFile = Path.Combine(di.FullName, "AppPackages");
if (!Directory.Exists(packFile))
Directory.CreateDirectory(packFile);
packFile = Path.Combine(packFile, this.appId + ".zip");
{
FileStream fs = File.OpenWrite(packFile);
// Header
this.WriteString(fs, "{B5F6844E-984C-4129-8D19-79FDEFBDD5DC}");
// Title
this.WriteString(fs, this.titleLabel.Text);
// AppId
this.WriteString(fs, this.appId);
this.WriteString(fs, this.fileListBox.Items.Count.ToString());
foreach (string file in this.fileListBox.Items)
{
string fileName = file.Remove(0, this.mainDllTextBox.Text.Length);
this.WriteString(fs, fileName);
this.WriteBytes(fs, File.ReadAllBytes(file));
}
fs.Close();
}
}
private void WriteString(Stream stream, string text)
{
byte[] textData = Encoding.UTF8.GetBytes(text);
byte[] textDataLength = BitConverter.GetBytes(textData.Length);
stream.Write(textDataLength, 0, 4);
stream.Write(textData, 0, textData.Length);
}
private void WriteBytes(Stream stream, byte[] bytes)
{
byte[] byteLen = BitConverter.GetBytes(bytes.Length);
stream.Write(byteLen, 0, 4);
stream.Write(bytes, 0, bytes.Length);
}
}
}
| 32.666667 | 101 | 0.579232 | [
"MIT"
] | LigangSun/AppCenter | source/Tools/AppManagementTool/CreatePackageForm.cs | 3,334 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace TreinaWeb.CSharpAvancado.CadastroPessoas.WPF
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 19.888889 | 54 | 0.723464 | [
"MIT"
] | ariele-fatima/C_Sharp_Avancado_2 | TreinaWeb.CSharpAvancado.CadastroPessoas/TreinaWeb.CSharpAvancado.CadastroPessoas.WPF/App.xaml.cs | 360 | C# |
/*
* Accounting API
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 2.0.0
* Contact: api@xero.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Xero.NetStandard.OAuth2.Api;
using Xero.NetStandard.OAuth2.Model;
using Xero.NetStandard.OAuth2.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Xero.NetStandard.OAuth2.Test.Model.Accounting
{
/// <summary>
/// Class for testing TaxRate
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class TaxRateTests : IDisposable
{
// TODO uncomment below to declare an instance variable for TaxRate
//private TaxRate instance;
public TaxRateTests()
{
// TODO uncomment below to create an instance of TaxRate
//instance = new TaxRate();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of TaxRate
/// </summary>
[Fact]
public void TaxRateInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" TaxRate
//Assert.IsInstanceOfType<TaxRate> (instance, "variable 'instance' is a TaxRate");
}
/// <summary>
/// Test the property 'Name'
/// </summary>
[Fact]
public void NameTest()
{
// TODO unit test for the property 'Name'
}
/// <summary>
/// Test the property 'TaxType'
/// </summary>
[Fact]
public void TaxTypeTest()
{
// TODO unit test for the property 'TaxType'
}
/// <summary>
/// Test the property 'TaxComponents'
/// </summary>
[Fact]
public void TaxComponentsTest()
{
// TODO unit test for the property 'TaxComponents'
}
/// <summary>
/// Test the property 'Status'
/// </summary>
[Fact]
public void StatusTest()
{
// TODO unit test for the property 'Status'
}
/// <summary>
/// Test the property 'ReportTaxType'
/// </summary>
[Fact]
public void ReportTaxTypeTest()
{
// TODO unit test for the property 'ReportTaxType'
}
/// <summary>
/// Test the property 'CanApplyToAssets'
/// </summary>
[Fact]
public void CanApplyToAssetsTest()
{
// TODO unit test for the property 'CanApplyToAssets'
}
/// <summary>
/// Test the property 'CanApplyToEquity'
/// </summary>
[Fact]
public void CanApplyToEquityTest()
{
// TODO unit test for the property 'CanApplyToEquity'
}
/// <summary>
/// Test the property 'CanApplyToExpenses'
/// </summary>
[Fact]
public void CanApplyToExpensesTest()
{
// TODO unit test for the property 'CanApplyToExpenses'
}
/// <summary>
/// Test the property 'CanApplyToLiabilities'
/// </summary>
[Fact]
public void CanApplyToLiabilitiesTest()
{
// TODO unit test for the property 'CanApplyToLiabilities'
}
/// <summary>
/// Test the property 'CanApplyToRevenue'
/// </summary>
[Fact]
public void CanApplyToRevenueTest()
{
// TODO unit test for the property 'CanApplyToRevenue'
}
/// <summary>
/// Test the property 'DisplayTaxRate'
/// </summary>
[Fact]
public void DisplayTaxRateTest()
{
// TODO unit test for the property 'DisplayTaxRate'
}
/// <summary>
/// Test the property 'EffectiveRate'
/// </summary>
[Fact]
public void EffectiveRateTest()
{
// TODO unit test for the property 'EffectiveRate'
}
}
}
| 27.41875 | 109 | 0.547299 | [
"MIT"
] | AlbertGromek/Xero-NetStandard | Xero.NetStandard.OAuth2.Test/Model/Accounting/TaxRateTests.cs | 4,387 | 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.SecurityInsights.Outputs
{
/// <summary>
/// GetInsights Query Errors.
/// </summary>
[OutputType]
public sealed class GetInsightsErrorResponse
{
/// <summary>
/// the error message
/// </summary>
public readonly string ErrorMessage;
/// <summary>
/// the query kind
/// </summary>
public readonly string Kind;
/// <summary>
/// the query id
/// </summary>
public readonly string? QueryId;
[OutputConstructor]
private GetInsightsErrorResponse(
string errorMessage,
string kind,
string? queryId)
{
ErrorMessage = errorMessage;
Kind = kind;
QueryId = queryId;
}
}
}
| 24.434783 | 81 | 0.585409 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/SecurityInsights/Outputs/GetInsightsErrorResponse.cs | 1,124 | C# |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Northwind.EF.Persistence.MSSQL.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Category",
columns: table => new
{
CategoryID = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CategoryName = table.Column<string>(maxLength: 15, nullable: false),
Description = table.Column<string>(type: "ntext", nullable: true),
Picture = table.Column<byte[]>(type: "image", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Category", x => x.CategoryID);
});
migrationBuilder.CreateTable(
name: "Customer",
columns: table => new
{
CustomerID = table.Column<string>(maxLength: 5, nullable: false),
CompanyName = table.Column<string>(maxLength: 40, nullable: false),
ContactName = table.Column<string>(maxLength: 30, nullable: true),
ContactTitle = table.Column<string>(maxLength: 30, nullable: true),
Address = table.Column<string>(maxLength: 60, nullable: true),
City = table.Column<string>(maxLength: 15, nullable: true),
Region = table.Column<string>(maxLength: 15, nullable: true),
PostalCode = table.Column<string>(maxLength: 10, nullable: true),
Country = table.Column<string>(maxLength: 15, nullable: true),
Phone = table.Column<string>(maxLength: 24, nullable: true),
Fax = table.Column<string>(maxLength: 24, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Customer", x => x.CustomerID);
});
migrationBuilder.CreateTable(
name: "Employee",
columns: table => new
{
EmployeeID = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
LastName = table.Column<string>(maxLength: 20, nullable: false),
FirstName = table.Column<string>(maxLength: 10, nullable: false),
Title = table.Column<string>(maxLength: 30, nullable: true),
TitleOfCourtesy = table.Column<string>(maxLength: 25, nullable: true),
BirthDate = table.Column<DateTime>(type: "datetime", nullable: true),
HireDate = table.Column<DateTime>(type: "datetime", nullable: true),
Address = table.Column<string>(maxLength: 60, nullable: true),
City = table.Column<string>(maxLength: 15, nullable: true),
Region = table.Column<string>(maxLength: 15, nullable: true),
PostalCode = table.Column<string>(maxLength: 10, nullable: true),
Country = table.Column<string>(maxLength: 15, nullable: true),
HomePhone = table.Column<string>(maxLength: 24, nullable: true),
Extension = table.Column<string>(maxLength: 4, nullable: true),
Photo = table.Column<byte[]>(type: "image", nullable: true),
Notes = table.Column<string>(type: "ntext", nullable: true),
ReportsTo = table.Column<int>(nullable: true),
PhotoPath = table.Column<string>(maxLength: 255, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Employee", x => x.EmployeeID);
table.ForeignKey(
name: "FK_Employees_Employees",
column: x => x.ReportsTo,
principalTable: "Employee",
principalColumn: "EmployeeID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Region",
columns: table => new
{
RegionID = table.Column<int>(nullable: false),
RegionDescription = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Region", x => x.RegionID);
});
migrationBuilder.CreateTable(
name: "Shipper",
columns: table => new
{
ShipperID = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CompanyName = table.Column<string>(maxLength: 40, nullable: false),
Phone = table.Column<string>(maxLength: 24, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Shipper", x => x.ShipperID);
});
migrationBuilder.CreateTable(
name: "Supplier",
columns: table => new
{
SupplierID = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CompanyName = table.Column<string>(maxLength: 40, nullable: false),
ContactName = table.Column<string>(maxLength: 30, nullable: true),
ContactTitle = table.Column<string>(maxLength: 30, nullable: true),
Address = table.Column<string>(maxLength: 60, nullable: true),
City = table.Column<string>(maxLength: 15, nullable: true),
Region = table.Column<string>(maxLength: 15, nullable: true),
PostalCode = table.Column<string>(maxLength: 10, nullable: true),
Country = table.Column<string>(maxLength: 15, nullable: true),
Phone = table.Column<string>(maxLength: 24, nullable: true),
Fax = table.Column<string>(maxLength: 24, nullable: true),
HomePage = table.Column<string>(type: "ntext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Supplier", x => x.SupplierID);
});
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
AdAccount_Domain = table.Column<string>(nullable: true),
AdAccount_Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Territory",
columns: table => new
{
TerritoryID = table.Column<string>(maxLength: 20, nullable: false),
TerritoryDescription = table.Column<string>(maxLength: 50, nullable: false),
RegionID = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Territory", x => x.TerritoryID);
table.ForeignKey(
name: "FK_Territories_Region",
column: x => x.RegionID,
principalTable: "Region",
principalColumn: "RegionID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Order",
columns: table => new
{
OrderID = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CustomerID = table.Column<string>(maxLength: 5, nullable: true),
EmployeeID = table.Column<int>(nullable: true),
OrderDate = table.Column<DateTime>(type: "datetime", nullable: true),
RequiredDate = table.Column<DateTime>(type: "datetime", nullable: true),
ShippedDate = table.Column<DateTime>(type: "datetime", nullable: true),
ShipVia = table.Column<int>(nullable: true),
Freight = table.Column<decimal>(type: "money", nullable: true, defaultValueSql: "((0))"),
ShipName = table.Column<string>(maxLength: 40, nullable: true),
ShipAddress = table.Column<string>(maxLength: 60, nullable: true),
ShipCity = table.Column<string>(maxLength: 15, nullable: true),
ShipRegion = table.Column<string>(maxLength: 15, nullable: true),
ShipPostalCode = table.Column<string>(maxLength: 10, nullable: true),
ShipCountry = table.Column<string>(maxLength: 15, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Order", x => x.OrderID);
table.ForeignKey(
name: "FK_Orders_Customers",
column: x => x.CustomerID,
principalTable: "Customer",
principalColumn: "CustomerID",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Orders_Employees",
column: x => x.EmployeeID,
principalTable: "Employee",
principalColumn: "EmployeeID",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Orders_Shippers",
column: x => x.ShipVia,
principalTable: "Shipper",
principalColumn: "ShipperID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Product",
columns: table => new
{
ProductID = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ProductName = table.Column<string>(maxLength: 40, nullable: false),
SupplierID = table.Column<int>(nullable: true),
CategoryID = table.Column<int>(nullable: true),
QuantityPerUnit = table.Column<string>(maxLength: 20, nullable: true),
UnitPrice = table.Column<decimal>(type: "money", nullable: true, defaultValueSql: "((0))"),
UnitsInStock = table.Column<short>(nullable: true, defaultValueSql: "((0))"),
UnitsOnOrder = table.Column<short>(nullable: true, defaultValueSql: "((0))"),
ReorderLevel = table.Column<short>(nullable: true, defaultValueSql: "((0))"),
Discontinued = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Product", x => x.ProductID);
table.ForeignKey(
name: "FK_Products_Categories",
column: x => x.CategoryID,
principalTable: "Category",
principalColumn: "CategoryID",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Products_Suppliers",
column: x => x.SupplierID,
principalTable: "Supplier",
principalColumn: "SupplierID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "EmployeeTerritory",
columns: table => new
{
EmployeeID = table.Column<int>(nullable: false),
TerritoryID = table.Column<string>(maxLength: 20, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_EmployeeTerritory", x => new { x.EmployeeID, x.TerritoryID });
table.ForeignKey(
name: "FK_EmployeeTerritories_Employees",
column: x => x.EmployeeID,
principalTable: "Employee",
principalColumn: "EmployeeID",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_EmployeeTerritories_Territories",
column: x => x.TerritoryID,
principalTable: "Territory",
principalColumn: "TerritoryID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Order Details",
columns: table => new
{
OrderID = table.Column<int>(nullable: false),
ProductID = table.Column<int>(nullable: false),
UnitPrice = table.Column<decimal>(type: "money", nullable: false),
Quantity = table.Column<short>(nullable: false, defaultValueSql: "((1))"),
Discount = table.Column<float>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Order Details", x => new { x.OrderID, x.ProductID });
table.ForeignKey(
name: "FK_Order_Details_Orders",
column: x => x.OrderID,
principalTable: "Order",
principalColumn: "OrderID",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Order_Details_Products",
column: x => x.ProductID,
principalTable: "Product",
principalColumn: "ProductID",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Employee_ReportsTo",
table: "Employee",
column: "ReportsTo");
migrationBuilder.CreateIndex(
name: "IX_EmployeeTerritory_TerritoryID",
table: "EmployeeTerritory",
column: "TerritoryID");
migrationBuilder.CreateIndex(
name: "IX_Order_CustomerID",
table: "Order",
column: "CustomerID");
migrationBuilder.CreateIndex(
name: "IX_Order_EmployeeID",
table: "Order",
column: "EmployeeID");
migrationBuilder.CreateIndex(
name: "IX_Order_ShipVia",
table: "Order",
column: "ShipVia");
migrationBuilder.CreateIndex(
name: "IX_Order Details_ProductID",
table: "Order Details",
column: "ProductID");
migrationBuilder.CreateIndex(
name: "IX_Product_CategoryID",
table: "Product",
column: "CategoryID");
migrationBuilder.CreateIndex(
name: "IX_Product_SupplierID",
table: "Product",
column: "SupplierID");
migrationBuilder.CreateIndex(
name: "IX_Territory_RegionID",
table: "Territory",
column: "RegionID");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "EmployeeTerritory");
migrationBuilder.DropTable(
name: "Order Details");
migrationBuilder.DropTable(
name: "User");
migrationBuilder.DropTable(
name: "Territory");
migrationBuilder.DropTable(
name: "Order");
migrationBuilder.DropTable(
name: "Product");
migrationBuilder.DropTable(
name: "Region");
migrationBuilder.DropTable(
name: "Customer");
migrationBuilder.DropTable(
name: "Employee");
migrationBuilder.DropTable(
name: "Shipper");
migrationBuilder.DropTable(
name: "Category");
migrationBuilder.DropTable(
name: "Supplier");
}
}
}
| 47.546419 | 122 | 0.501199 | [
"Apache-2.0"
] | DavidSilwal/Northwind-EFCore3 | Northwind.EF.Persistence.MSSQL/Migrations/20190729151924_InitialCreate.cs | 17,927 | C# |
using Moralis.Platform.Objects;
namespace Moralis.Platform.Abstractions
{
/// <summary>
/// A unit that can generate a relative path to a persistent storage file.
/// </summary>
public interface IRelativeCacheLocationGenerator
{
/// <summary>
/// The corresponding relative path generated by this <see cref="IRelativeCacheLocationGenerator"/>.
/// </summary>
string GetRelativeCacheFilePath<TUser>(IServiceHub<TUser> serviceHub) where TUser : MoralisUser;
}
}
| 31.470588 | 109 | 0.66729 | [
"MIT"
] | rahul0tripathi/MetaNox | Assets/MoralisWeb3ApiSdk/Moralis/MoralisDotNet/Platform/Abstractions/IRelativeCacheLocationGenerator.cs | 537 | C# |
using System;
using HanumanInstitute.OntraportApi.Models;
using HanumanInstitute.OntraportApi.IdentityCore;
using System.Threading.Tasks;
using Xunit;
using HanumanInstitute.Validators;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Identity;
using System.Net.Http;
using Xunit.Abstractions;
namespace HanumanInstitute.OntraportApi.IntegrationTests.IdentityCore
{
public class UserManagerTests
{
private readonly ITestOutputHelper _output;
public UserManagerTests(ITestOutputHelper output = null)
{
_output = output;
}
private readonly string[] _roles = new[] { "Admin", "Manager" };
//private readonly string[] _roleAdmin = new[] { "Admin" };
private const int ContactIdWithPassword = 118;
private const int ContactIdNoPassword = 115;
private const int ContactIdInvalid = 116;
private const string ContactEmailWithPassword = "identity_withpass@test.com";
private const string ContactEmailNoPassword = "identity_nopass@test.com";
private const string ContactEmailInvalid = "identity_invalid@test.com";
private const string Password = "bingo";
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("abc")]
[InlineData("-----")]
[InlineData("0.5")]
public async Task FindByIdAsync_InvalidInt_ThrowsException(string contactId)
{
using var c = new UserManagerContext(_roles, _output);
Task<OntraportIdentityUser> Act() => c.UserManager.FindByIdAsync(contactId.ToStringInvariant());
await Assert.ThrowsAsync<ArgumentException>(Act);
}
[Theory]
[InlineData(ContactIdNoPassword)]
[InlineData(ContactIdInvalid)]
public async Task FindByIdAsync_NoPassword_ReturnsNull(int contactId)
{
using var c = new UserManagerContext(_roles, _output);
var result = await c.UserManager.FindByIdAsync(contactId.ToStringInvariant()).ConfigureAwait(false);
Assert.Null(result);
}
[Theory]
[InlineData(ContactIdWithPassword)]
public async Task FindByIdAsync_WithPassword_ReturnsIdentity(int contactId)
{
using var c = new UserManagerContext(_roles, _output);
var result = await c.UserManager.FindByIdAsync(contactId.ToStringInvariant()).ConfigureAwait(false);
Assert.NotNull(result);
}
[Theory]
[InlineData(ContactEmailNoPassword)]
[InlineData(ContactEmailInvalid)]
public async Task FindByNameAsync_EmailNoPassword_ReturnsNull(string email)
{
using var c = new UserManagerContext(_roles, _output);
var result = await c.UserManager.FindByNameAsync(email).ConfigureAwait(false);
Assert.Null(result);
}
[Theory]
[InlineData(ContactEmailWithPassword)]
public async Task FindByNameAsync_EmailWithPassword_ReturnsIdentity(string email)
{
using var c = new UserManagerContext(_roles, _output);
var result = await c.UserManager.FindByNameAsync(email).ConfigureAwait(false);
Assert.NotNull(result);
}
[Theory]
[InlineData(ContactEmailWithPassword)]
public async Task FindByNameAsync_UpperCaseEmailWithPassword_ReturnsIdentity(string email)
{
using var c = new UserManagerContext(_roles, _output);
var result = await c.UserManager.FindByNameAsync(email.ToUpperInvariant()).ConfigureAwait(false);
Assert.NotNull(result);
}
[Theory]
[InlineData(ContactEmailNoPassword)]
[InlineData(ContactEmailInvalid)]
public async Task FindByEmailAsync_EmailNoPassword_ReturnsNull(string email)
{
using var c = new UserManagerContext(_roles, _output);
var result = await c.UserManager.FindByEmailAsync(email).ConfigureAwait(false);
Assert.Null(result);
}
[Theory]
[InlineData(ContactEmailWithPassword)]
public async Task FindByEmailAsync_EmailWithPassword_ReturnsIdentity(string email)
{
using var c = new UserManagerContext(_roles, _output);
var result = await c.UserManager.FindByEmailAsync(email).ConfigureAwait(false);
Assert.NotNull(result);
}
[Theory]
[InlineData(ContactEmailWithPassword)]
public async Task FindByEmailAsync_UpperCaseEmailWithPassword_ReturnsIdentity(string email)
{
using var c = new UserManagerContext(_roles, _output);
var result = await c.UserManager.FindByEmailAsync(email.ToUpperInvariant()).ConfigureAwait(false);
Assert.NotNull(result);
}
[Fact]
public async Task CreateAsync_NewEmail_IdReturned()
{
const string NewEmail = "CreateAsyncTest@test.com";
using var c = new UserManagerContext(_roles, _output);
var exist = await c.UserManager.FindByNameAsync(NewEmail);
if (exist != null)
{
await c.UserManager.DeleteAsync(exist);
}
var user = new OntraportIdentityUser()
{
UserName = NewEmail,
Email = NewEmail
};
var result = await c.UserManager.CreateAsync(user, Password);
Assert.True(result.Succeeded);
Assert.True(user.Id > 0);
}
[Fact]
public async Task CreateAsync_ExistingEmail_ReturnsFailure()
{
const string NewEmail = "CreateAsyncDuplicate@test.com";
using var c = new UserManagerContext(_roles, _output);
var user = new OntraportIdentityUser()
{
UserName = NewEmail,
Email = NewEmail
};
var result = await c.UserManager.CreateAsync(user, Password);
Assert.False(result.Succeeded);
}
[Fact]
public async Task DeleteAsync_ValidId_LeaveContactAndRemovePassword()
{
const string NewEmail = "DeleteAsync@test.com";
using var c = new UserManagerContext(_roles, _output);
var user = await c.FindOrCreateUserAsync(NewEmail, Password);
var result = await c.UserManager.DeleteAsync(user);
Assert.True(result.Succeeded);
var exist = await c.OntraportContacts.SelectAsync(user.Id);
Assert.NotNull(exist);
Assert.Empty(exist.IdentityPasswordHash);
}
[Fact]
public async Task DeleteAsync_InvalidId_ThrowsException()
{
const string NewEmail = "DeleteInvalid@test.com";
using var c = new UserManagerContext(_roles, _output);
var user = new OntraportIdentityUser()
{
Id = int.MaxValue,
UserName = NewEmail,
Email = NewEmail
};
Task<IdentityResult> Act() => c.UserManager.DeleteAsync(user);
await Assert.ThrowsAsync<HttpRequestException>(Act);
}
[Fact]
public async Task UpdateAsync_ExistingEmail_ReturnsFailure()
{
const string NewEmail = "UpdateAsync@test.com";
using var c = new UserManagerContext(_roles, _output);
var user = await c.FindOrCreateUserAsync(NewEmail, Password);
await c.UserManager.ChangePasswordAsync(user, Password, Password);
var result = await c.UserManager.UpdateAsync(user);
Assert.True(result.Succeeded);
}
[Theory]
[InlineData("Admin")]
[InlineData("MANAGER")]
public async Task AddToRoleAsync_Valid_IsInRole(string role)
{
const string NewEmail = "AddToRoleAsync@test.com";
using var c = new UserManagerContext(_roles, _output);
var user = await c.FindOrCreateUserAsync(NewEmail, Password);
var result = await c.UserManager.AddToRoleAsync(user, role);
Assert.True(await c.UserManager.IsInRoleAsync(user, role));
await c.UserManager.DeleteAsync(user);
Assert.True(result.Succeeded);
}
[Theory]
[InlineData("aaa")]
public async Task AddToRoleAsync_Invalid_IsInRole(string role)
{
const string NewEmail = "AddToRoleAsync@test.com";
using var c = new UserManagerContext(_roles, _output);
var user = await c.FindOrCreateUserAsync(NewEmail, Password);
Task Act() => c.UserManager.AddToRoleAsync(user, role);
await Assert.ThrowsAsync<ArgumentException>(Act);
}
[Theory]
[InlineData("Admin")]
[InlineData("MANAGER")]
public async Task RemoveFromRoleAsync_Valid_IsInRole(string role)
{
const string NewEmail = "AddToRoleAsync@test.com";
using var c = new UserManagerContext(_roles, _output);
var user = await c.FindOrCreateUserAsync(NewEmail, Password);
await c.UserManager.AddToRoleAsync(user, role);
var result = await c.UserManager.RemoveFromRoleAsync(user, role);
Assert.False(await c.UserManager.IsInRoleAsync(user, role));
await c.UserManager.DeleteAsync(user);
Assert.True(result.Succeeded);
}
[Fact]
public async Task GetRolesAsync_TwoRoles_ReturnsBoth()
{
const string NewEmail = "AddToRoleAsync@test.com";
using var c = new UserManagerContext(_roles, _output);
var user = await c.FindOrCreateUserAsync(NewEmail, Password);
await c.UserManager.AddToRoleAsync(user, _roles[0]);
await c.UserManager.AddToRoleAsync(user, _roles[1]);
var result = await c.UserManager.GetRolesAsync(user);
Assert.Contains(_roles[0], result);
Assert.Contains(_roles[1], result);
await c.UserManager.DeleteAsync(user);
}
}
}
| 35.454545 | 112 | 0.628698 | [
"BSD-2-Clause"
] | mysteryx93/OntraportApi.NET | OntraportApi.IntegrationTests/IdentityCore/UserManagerTests.cs | 10,142 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CatClock.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CatClock.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 35.896552 | 84 | 0.739673 | [
"Apache-2.0"
] | 15217711253/xamarin-forms-samples | CatClock/CatClock/CatClock.UWP/Properties/AssemblyInfo.cs | 1,044 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker
{
public sealed class TaskManagerL0
{
private Mock<IJobServer> _jobServer;
private Mock<ITaskServer> _taskServer;
private Mock<IConfigurationStore> _configurationStore;
private Mock<IExecutionContext> _ec;
private TaskManager _taskManager;
private string _workFolder;
//Test the cancellation flow: interrupt download task via HostContext cancellation token.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void BubblesCancellation()
{
try
{
//Arrange
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
var bingTask = new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = "Bing",
Version = "0.1.2",
Id = Guid.NewGuid()
}
};
var pingTask = new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = "Ping",
Version = "0.1.1",
Id = Guid.NewGuid()
}
};
var bingVersion = new TaskVersion(bingTask.Reference.Version);
var pingVersion = new TaskVersion(pingTask.Reference.Version);
_taskServer
.Setup(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()))
.Returns((Guid taskId, TaskVersion taskVersion, CancellationToken token) =>
{
tokenSource.Cancel();
tokenSource.Token.ThrowIfCancellationRequested();
return null;
});
var tasks = new List<Pipelines.TaskStep>(new Pipelines.TaskStep[] { bingTask, pingTask });
//Act
//should initiate a download with a mocked IJobServer, which sets a cancellation token and
//download task is expected to be in cancelled state
Task downloadTask = _taskManager.DownloadAsync(_ec.Object, tasks);
Task[] taskToWait = { downloadTask, Task.Delay(2000) };
//wait for the task to be cancelled to exit
await Task.WhenAny(taskToWait);
//Assert
//verify task completed in less than 2sec and it is in cancelled state
Assert.True(downloadTask.IsCompleted, $"{nameof(_taskManager.DownloadAsync)} timed out.");
Assert.True(!downloadTask.IsFaulted, downloadTask.Exception?.ToString());
Assert.True(downloadTask.IsCanceled);
//check if the task.json was not downloaded for ping and bing tasks
Assert.Equal(
0,
Directory.GetFiles(_hc.GetDirectory(WellKnownDirectory.Tasks), "*", SearchOption.AllDirectories).Length);
//assert download was invoked only once, because the first task cancelled the second task download
_taskServer
.Verify(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()), Times.Once());
}
}
finally
{
Teardown();
}
}
//Test how exceptions are propagated to the caller.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void RetryNetworkException()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
var pingTask = new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = "Ping",
Version = "0.1.1",
Id = Guid.NewGuid()
}
};
var pingVersion = new TaskVersion(pingTask.Reference.Version);
Exception expectedException = new System.Net.Http.HttpRequestException("simulated network error");
_taskServer
.Setup(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()))
.Returns((Guid taskId, TaskVersion taskVersion, CancellationToken token) =>
{
throw expectedException;
});
var tasks = new List<Pipelines.TaskStep>(new Pipelines.TaskStep[] { pingTask });
//Act
Exception actualException = null;
try
{
await _taskManager.DownloadAsync(_ec.Object, tasks);
}
catch (Exception ex)
{
actualException = ex;
}
//Assert
//verify task completed in less than 2sec and it is in failed state state
Assert.Equal(expectedException, actualException);
//assert download was invoked 3 times, because we retry on task download
_taskServer
.Verify(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()), Times.Exactly(3));
//see if the task.json was not downloaded
Assert.Equal(
0,
Directory.GetFiles(_hc.GetDirectory(WellKnownDirectory.Tasks), "*", SearchOption.AllDirectories).Length);
}
}
finally
{
Teardown();
}
}
//Test how exceptions are propagated to the caller.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void RetryStreamException()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
var pingTask = new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = "Ping",
Version = "0.1.1",
Id = Guid.NewGuid()
}
};
var pingVersion = new TaskVersion(pingTask.Reference.Version);
Exception expectedException = new System.Net.Http.HttpRequestException("simulated network error");
_taskServer
.Setup(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()))
.Returns((Guid taskId, TaskVersion taskVersion, CancellationToken token) =>
{
return Task.FromResult<Stream>(new ExceptionStream());
});
var tasks = new List<Pipelines.TaskStep>(new Pipelines.TaskStep[] { pingTask });
//Act
Exception actualException = null;
try
{
await _taskManager.DownloadAsync(_ec.Object, tasks);
}
catch (Exception ex)
{
actualException = ex;
}
//Assert
//verify task completed in less than 2sec and it is in failed state state
Assert.Equal("NotImplementedException", actualException.GetType().Name);
//assert download was invoked 3 times, because we retry on task download
_taskServer
.Verify(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()), Times.Exactly(3));
//see if the task.json was not downloaded
Assert.Equal(
0,
Directory.GetFiles(_hc.GetDirectory(WellKnownDirectory.Tasks), "*", SearchOption.AllDirectories).Length);
}
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DeserializesPlatformSupportedHandlersOnly()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
// Prepare the content.
const string Content = @"
{
""execution"": {
""Node"": { },
""Process"": { },
}
}";
// Write the task.json to disk.
Pipelines.TaskStep instance;
string directory;
CreateTask(jsonContent: Content, instance: out instance, directory: out directory);
// Act.
Definition definition = _taskManager.Load(instance);
// Assert.
Assert.NotNull(definition);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Execution);
Assert.NotNull(definition.Data.Execution.Node);
if (TestUtil.IsWindows())
{
Assert.NotNull(definition.Data.Execution.Process);
}
else
{
Assert.Null(definition.Data.Execution.Process);
}
}
}
finally
{
Teardown();
}
}
//Test the normal flow, which downloads a few tasks and skips disabled, duplicate and cached tasks.
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void DownloadsTasks()
{
try
{
//Arrange
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
var bingGuid = Guid.NewGuid();
string bingTaskName = "Bing";
string bingVersion = "1.21.2";
var tasks = new List<Pipelines.TaskStep>
{
new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = bingTaskName,
Version = bingVersion,
Id = bingGuid
}
},
new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = bingTaskName,
Version = bingVersion,
Id = bingGuid
}
}
};
using (var stream = GetZipStream())
{
_taskServer
.Setup(x => x.GetTaskContentZipAsync(
bingGuid,
It.Is<TaskVersion>(y => string.Equals(y.ToString(), bingVersion, StringComparison.Ordinal)),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<Stream>(stream));
//Act
//first invocation will download and unzip the task from mocked IJobServer
await _taskManager.DownloadAsync(_ec.Object, tasks);
//second and third invocations should find the task in the cache and do nothing
await _taskManager.DownloadAsync(_ec.Object, tasks);
await _taskManager.DownloadAsync(_ec.Object, tasks);
//Assert
//see if the task.json was downloaded
string destDirectory = Path.Combine(
_hc.GetDirectory(WellKnownDirectory.Tasks),
$"{bingTaskName}_{bingGuid}",
bingVersion);
Assert.True(File.Exists(Path.Combine(destDirectory, Constants.Path.TaskJsonFile)));
//assert download has happened only once, because disabled, duplicate and cached tasks are not downloaded
_taskServer
.Verify(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()), Times.Once());
}
}
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public async void PreservesTaskZipTaskWhenInSignatureVerificationMode()
{
try
{
//Arrange
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource, signatureVerificationEnabled: true))
{
var bingGuid = Guid.NewGuid();
string bingTaskName = "Bing";
string bingVersion = "1.21.2";
var tasks = new List<Pipelines.TaskStep>
{
new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = bingTaskName,
Version = bingVersion,
Id = bingGuid
}
},
new Pipelines.TaskStep()
{
Enabled = true,
Reference = new Pipelines.TaskStepDefinitionReference()
{
Name = bingTaskName,
Version = bingVersion,
Id = bingGuid
}
}
};
using (var stream = GetZipStream())
{
_taskServer
.Setup(x => x.GetTaskContentZipAsync(
bingGuid,
It.Is<TaskVersion>(y => string.Equals(y.ToString(), bingVersion, StringComparison.Ordinal)),
It.IsAny<CancellationToken>()))
.Returns(Task.FromResult<Stream>(stream));
//Act
//first invocation will download and unzip the task from mocked IJobServer
await _taskManager.DownloadAsync(_ec.Object, tasks);
//second and third invocations should find the task in the cache and do nothing
await _taskManager.DownloadAsync(_ec.Object, tasks);
await _taskManager.DownloadAsync(_ec.Object, tasks);
//Assert
//see if the task.json was downloaded
string destDirectory = Path.Combine(
_hc.GetDirectory(WellKnownDirectory.Tasks),
$"{bingTaskName}_{bingGuid}",
bingVersion);
string zipDestDirectory = Path.Combine(_hc.GetDirectory(WellKnownDirectory.TaskZips), $"{bingTaskName}_{bingGuid}_{bingVersion}.zip");
// task.json should exist since we need it for JobExtension.InitializeJob
Assert.True(File.Exists(Path.Combine(destDirectory, Constants.Path.TaskJsonFile)));
// the zip for the task should exist on disk
Assert.True(File.Exists(zipDestDirectory));
//assert download has happened only once, because disabled, duplicate and cached tasks are not downloaded
_taskServer
.Verify(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), It.IsAny<CancellationToken>()), Times.Once());
}
}
}
finally
{
Teardown();
}
}
// TODO: Add test for Extract
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ExtractsAnAlreadyDownloadedZipToTheCorrectLocation()
{
try
{
// Arrange
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource, signatureVerificationEnabled: true))
{
var bingGuid = Guid.NewGuid();
string bingTaskName = "Bing";
string bingVersion = "1.21.2";
var taskStep = new Pipelines.TaskStep
{
Name = bingTaskName,
Reference = new Pipelines.TaskStepDefinitionReference
{
Id = bingGuid,
Name = bingTaskName,
Version = bingVersion
}
};
string zipDestDirectory = Path.Combine(_hc.GetDirectory(WellKnownDirectory.TaskZips), $"{bingTaskName}_{bingGuid}_{bingVersion}.zip");
Directory.CreateDirectory(_hc.GetDirectory(WellKnownDirectory.TaskZips));
// write stream to file
using (Stream zipStream = GetZipStream())
using (var fileStream = new FileStream(zipDestDirectory, FileMode.Create, FileAccess.Write))
{
zipStream.CopyTo(fileStream);
}
// Act
_taskManager.Extract(_ec.Object, taskStep);
// Assert
string destDirectory = Path.Combine(
_hc.GetDirectory(WellKnownDirectory.Tasks),
$"{bingTaskName}_{bingGuid}",
bingVersion);
Assert.True(File.Exists(Path.Combine(destDirectory, Constants.Path.TaskJsonFile)));
}
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatchPlatform()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
HandlerData data = new NodeHandlerData() { Platforms = new string[] { "nosuch" } };
// Act/Assert.
Assert.False(data.PreferredOnPlatform(PlatformUtil.OS.Windows));
Assert.False(data.PreferredOnPlatform(PlatformUtil.OS.Linux));
Assert.False(data.PreferredOnPlatform(PlatformUtil.OS.OSX));
}
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void LoadsDefinition()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
// Prepare the task.json content.
const string Content = @"
{
""inputs"": [
{
""extraInputKey"": ""Extra input value"",
""name"": ""someFilePathInput"",
""type"": ""filePath"",
""label"": ""Some file path input label"",
""defaultValue"": ""Some default file path"",
""required"": true,
""helpMarkDown"": ""Some file path input markdown""
},
{
""name"": ""someStringInput"",
""type"": ""string"",
""label"": ""Some string input label"",
""defaultValue"": ""Some default string"",
""helpMarkDown"": ""Some string input markdown"",
""required"": false,
""groupName"": ""advanced""
}
],
""execution"": {
""Node"": {
""target"": ""Some Node target"",
""extraNodeArg"": ""Extra node arg value""
},
""Node10"": {
""target"": ""Some Node10 target"",
""extraNodeArg"": ""Extra node10 arg value""
},
""Process"": {
""target"": ""Some process target"",
""argumentFormat"": ""Some process argument format"",
""workingDirectory"": ""Some process working directory"",
""extraProcessArg"": ""Some extra process arg"",
""platforms"": [
""windows""
]
},
""NoSuchHandler"": {
""target"": ""no such target""
}
},
""someExtraSection"": {
""someExtraKey"": ""Some extra value""
}
}";
// Write the task.json to disk.
Pipelines.TaskStep instance;
string directory;
CreateTask(jsonContent: Content, instance: out instance, directory: out directory);
// Act.
Definition definition = _taskManager.Load(instance);
// Assert.
Assert.NotNull(definition);
Assert.Equal(directory, definition.Directory);
Assert.NotNull(definition.Data);
Assert.NotNull(definition.Data.Inputs); // inputs
Assert.Equal(2, definition.Data.Inputs.Length);
Assert.Equal("someFilePathInput", definition.Data.Inputs[0].Name);
Assert.Equal("Some default file path", definition.Data.Inputs[0].DefaultValue);
Assert.Equal("someStringInput", definition.Data.Inputs[1].Name);
Assert.Equal("Some default string", definition.Data.Inputs[1].DefaultValue);
Assert.NotNull(definition.Data.Execution); // execution
if (TestUtil.IsWindows())
{
// Process handler should only be deserialized on Windows.
Assert.Equal(3, definition.Data.Execution.All.Count);
}
else
{
// Only the Node and Node10 handlers should be deserialized on non-Windows.
Assert.Equal(2, definition.Data.Execution.All.Count);
}
// Node handler should always be deserialized.
Assert.NotNull(definition.Data.Execution.Node); // execution.Node
Assert.Equal(definition.Data.Execution.Node, definition.Data.Execution.All[0]);
Assert.Equal("Some Node target", definition.Data.Execution.Node.Target);
// Node10 handler should always be deserialized.
Assert.NotNull(definition.Data.Execution.Node10); // execution.Node10
Assert.Equal(definition.Data.Execution.Node10, definition.Data.Execution.All[1]);
Assert.Equal("Some Node10 target", definition.Data.Execution.Node10.Target);
if (TestUtil.IsWindows())
{
// Process handler should only be deserialized on Windows.
Assert.NotNull(definition.Data.Execution.Process); // execution.Process
Assert.Equal(definition.Data.Execution.Process, definition.Data.Execution.All[2]);
Assert.Equal("Some process argument format", definition.Data.Execution.Process.ArgumentFormat);
Assert.NotNull(definition.Data.Execution.Process.Platforms);
Assert.Equal(1, definition.Data.Execution.Process.Platforms.Length);
Assert.Equal("windows", definition.Data.Execution.Process.Platforms[0]);
Assert.Equal("Some process target", definition.Data.Execution.Process.Target);
Assert.Equal("Some process working directory", definition.Data.Execution.Process.WorkingDirectory);
}
}
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
[Trait("SkipOn", "darwin")]
[Trait("SkipOn", "linux")]
public void MatchesPlatform()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
HandlerData data = new NodeHandlerData() { Platforms = new[] { "WiNdOwS" } };
// Act/Assert.
Assert.True(data.PreferredOnPlatform(PlatformUtil.OS.Windows));
Assert.False(data.PreferredOnPlatform(PlatformUtil.OS.Linux));
Assert.False(data.PreferredOnPlatform(PlatformUtil.OS.OSX));
}
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ReplacesMacros()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
const string Directory = "Some directory";
Definition definition = new Definition() { Directory = Directory };
NodeHandlerData node = new NodeHandlerData()
{
Target = @"$(CuRrEnTdIrEcToRy)\Some node target",
WorkingDirectory = @"$(CuRrEnTdIrEcToRy)\Some node working directory",
};
ProcessHandlerData process = new ProcessHandlerData()
{
ArgumentFormat = @"$(CuRrEnTdIrEcToRy)\Some process argument format",
Target = @"$(CuRrEnTdIrEcToRy)\Some process target",
WorkingDirectory = @"$(CuRrEnTdIrEcToRy)\Some process working directory",
};
// Act.
node.ReplaceMacros(_hc, definition);
process.ReplaceMacros(_hc, definition);
// Assert.
Assert.Equal($@"{Directory}\Some node target", node.Target);
Assert.Equal($@"{Directory}\Some node working directory", node.WorkingDirectory);
Assert.Equal($@"{Directory}\Some process argument format", process.ArgumentFormat);
Assert.Equal($@"{Directory}\Some process target", process.Target);
Assert.Equal($@"{Directory}\Some process working directory", process.WorkingDirectory);
}
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ReplacesMacrosAndPreventsInfiniteRecursion()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
string directory = "$(currentdirectory)$(currentdirectory)";
Definition definition = new Definition() { Directory = directory };
NodeHandlerData node = new NodeHandlerData()
{
Target = @"$(currentDirectory)\Some node target",
};
// Act.
node.ReplaceMacros(_hc, definition);
// Assert.
Assert.Equal($@"{directory}\Some node target", node.Target);
}
}
finally
{
Teardown();
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void ReplacesMultipleMacroInstances()
{
try
{
// Arrange.
using (var tokenSource = new CancellationTokenSource())
using (var _hc = Setup(tokenSource))
{
const string Directory = "Some directory";
Definition definition = new Definition() { Directory = Directory };
NodeHandlerData node = new NodeHandlerData()
{
Target = @"$(CuRrEnTdIrEcToRy)$(CuRrEnTdIrEcToRy)\Some node target",
};
// Act.
node.ReplaceMacros(_hc, definition);
// Assert.
Assert.Equal($@"{Directory}{Directory}\Some node target", node.Target);
}
}
finally
{
Teardown();
}
}
private void CreateTask(string jsonContent, out Pipelines.TaskStep instance, out string directory)
{
const string TaskName = "SomeTask";
const string TaskVersion = "1.2.3";
Guid taskGuid = Guid.NewGuid();
directory = Path.Combine(_workFolder, Constants.Path.TasksDirectory, $"{TaskName}_{taskGuid}", TaskVersion);
string file = Path.Combine(directory, Constants.Path.TaskJsonFile);
Directory.CreateDirectory(Path.GetDirectoryName(file));
File.WriteAllText(file, jsonContent);
instance = new Pipelines.TaskStep()
{
Reference = new Pipelines.TaskStepDefinitionReference()
{
Id = taskGuid,
Name = TaskName,
Version = TaskVersion,
}
};
}
private Stream GetZipStream()
{
// Locate the test data folder containing the task.json.
string sourceFolder = Path.Combine(TestUtil.GetTestDataPath(), nameof(TaskManagerL0));
Assert.True(Directory.Exists(sourceFolder), $"Directory does not exist: {sourceFolder}");
Assert.True(File.Exists(Path.Combine(sourceFolder, Constants.Path.TaskJsonFile)));
// Create the zip file under the work folder so it gets cleaned up.
string zipFile = Path.Combine(
_workFolder,
$"{Guid.NewGuid()}.zip");
Directory.CreateDirectory(_workFolder);
ZipFile.CreateFromDirectory(sourceFolder, zipFile, CompressionLevel.Fastest, includeBaseDirectory: false);
return new FileStream(zipFile, FileMode.Open);
}
private TestHostContext Setup(CancellationTokenSource _ecTokenSource, [CallerMemberName] string name = "", bool signatureVerificationEnabled = false)
{
// Mocks.
_jobServer = new Mock<IJobServer>();
_taskServer = new Mock<ITaskServer>();
_ec = new Mock<IExecutionContext>();
_ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
// Test host context.
var _hc = new TestHostContext(this, name);
// Random work folder.
_workFolder = _hc.GetDirectory(WellKnownDirectory.Work);
_hc.SetSingleton<IJobServer>(_jobServer.Object);
_hc.SetSingleton<ITaskServer>(_taskServer.Object);
String fingerprint = String.Empty;
if (signatureVerificationEnabled)
{
fingerprint = "FAKEFINGERPRINT";
}
_configurationStore = new Mock<IConfigurationStore>();
_configurationStore
.Setup(x => x.GetSettings())
.Returns(
new AgentSettings
{
Fingerprint = fingerprint,
WorkFolder = _workFolder
});
_hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
// Instance to test.
_taskManager = new TaskManager();
_taskManager.Initialize(_hc);
Environment.SetEnvironmentVariable("VSTS_TASK_DOWNLOAD_NO_BACKOFF", "1");
return _hc;
}
private void Teardown()
{
if (!string.IsNullOrEmpty(_workFolder) && Directory.Exists(_workFolder))
{
Directory.Delete(_workFolder, recursive: true);
}
}
private class ExceptionStream : Stream
{
public override bool CanRead => throw new NotImplementedException();
public override bool CanSeek => throw new NotImplementedException();
public override bool CanWrite => throw new NotImplementedException();
public override long Length => throw new NotImplementedException();
public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override void Flush()
{
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
}
}
| 41.667797 | 158 | 0.480421 | [
"MIT"
] | AzureMentor/azure-pipelines-agent | src/Test/L0/Worker/TaskManagerL0.cs | 36,876 | C# |
using System.Collections.Generic;
using Microsoft.AspNet.Identity;
namespace Luma.SmartHub.Web.ViewModels.Manage
{
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
}
| 21.789474 | 56 | 0.657005 | [
"Apache-2.0"
] | czesiu/Luma.SmartHub.Web | src/Luma.SmartHub.Web/ViewModels/Manage/IndexViewModel.cs | 416 | C# |
using BusinessLogicLayer;
using Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace OnlineAssessmentSystem.Controllers
{
public class HomeController : Controller
{
IBLLService bllService;
public HomeController()
{
bllService = new BLLService();
}
public HomeController(IBLLService bService)
{
bllService = bService;
}
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
public IEnumerable<category> Get()
{
return bllService.GetCategories();
}
}
}
| 19.702703 | 51 | 0.589849 | [
"MIT"
] | virtualghostmck/OAS | BackEnd/OnlineAssessmentSystem/OnlineAssessmentSystem/Controllers/HomeController.cs | 731 | C# |
using System;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Core.Domain
{
/// <summary>
/// AlipayMarketingCampaignPrizepoolPrizeDeleteModel Data Structure.
/// </summary>
[Serializable]
public class AlipayMarketingCampaignPrizepoolPrizeDeleteModel : AopObject
{
/// <summary>
/// 外部业务流水号,用来标识唯 一的业务动作,用于幂等
/// </summary>
[XmlElement("out_biz_id")]
public string OutBizId { get; set; }
/// <summary>
/// 奖品池id,使用前请联系业务 对接同学提供
/// </summary>
[XmlElement("pool_id")]
public string PoolId { get; set; }
/// <summary>
/// 奖品id,从奖品池内删除的奖品标识
/// </summary>
[XmlElement("prize_id")]
public string PrizeId { get; set; }
/// <summary>
/// 表示业务来源,由营销技术提 供具体值
/// </summary>
[XmlElement("source")]
public string Source { get; set; }
/// <summary>
/// PRIZE_PAUSED("PRIZE_PAUSED", "暂停状态"), PRIZE_CLOSED("PRIZE_CLOSED", "关闭状态"); 参数为空,默认暂停状态
/// </summary>
[XmlElement("status")]
public string Status { get; set; }
}
}
| 26.697674 | 99 | 0.560105 | [
"MIT"
] | leixf2005/Alipay.AopSdk.Core | Alipay.AopSdk.Core/Domain/AlipayMarketingCampaignPrizepoolPrizeDeleteModel.cs | 1,334 | C# |
#pragma checksum "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Home\Privacy.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d8ddb6bffa5a9b264bf8f89038bf03c234083fd3"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Home_Privacy), @"mvc.1.0.view", @"/Views/Home/Privacy.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\_ViewImports.cshtml"
using MVC_CoreProject;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\_ViewImports.cshtml"
using MVC_CoreProject.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d8ddb6bffa5a9b264bf8f89038bf03c234083fd3", @"/Views/Home/Privacy.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"489d51d8aff94f7b19f5c397c763638bcd9574ac", @"/Views/_ViewImports.cshtml")]
public class Views_Home_Privacy : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Home\Privacy.cshtml"
ViewData["Title"] = "Privacy Policy";
#line default
#line hidden
#nullable disable
WriteLiteral("<h1>");
#nullable restore
#line 4 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Home\Privacy.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral("</h1>\r\n\r\n<p>Use this page to detail your site\'s privacy policy.</p>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 46.5 | 190 | 0.763125 | [
"MIT"
] | batuhansariikaya/MVC_CoreBlogProject | CoreProject_MVC/CoreProject_MVC/obj/Debug/net5.0/Razor/Views/Home/Privacy.cshtml.g.cs | 3,162 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace _03._Word_Count
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> wordCount = new Dictionary<string, int>();
List<string> words = new List<string>();
string wordsPath = "../Resources/words.txt";
string textPath = "../Resources/text.txt";
string resultsPath = "../Output/03/result.txt";
using(StreamReader readerWords = new StreamReader(wordsPath))
{
string word;
while((word = readerWords.ReadLine()) != null)
{
wordCount.Add(word, 0);
words.Add(word);
}
}
using(StreamReader readerText = new StreamReader(textPath))
{
string line;
while((line = readerText.ReadLine()) != null)
{
foreach(string word in words)
{
string pattern = $"(?<=[^a-zA-Z]){word}(?=[^a-zA-Z])";
int count = Regex.Matches(line, pattern, RegexOptions.IgnoreCase).Count;
wordCount[word] += count;
}
}
}
using(StreamWriter writer = new StreamWriter(resultsPath))
{
foreach(var word in wordCount.Keys.OrderByDescending(x => wordCount[x]))
{
writer.WriteLine($"{word} - {wordCount[word]}");
}
}
}
}
}
| 30.981818 | 96 | 0.475939 | [
"MIT"
] | Javorov1103/SoftUni-Course | C# Advanced/03. Streams and Files Exercises/03. Word Count/Program.cs | 1,706 | C# |
namespace Farm
{
public class StartUp
{
public static void Main()
{
Dog dog = new Dog();
dog.Bark();
dog.Eat();
}
}
}
| 14.692308 | 33 | 0.397906 | [
"MIT"
] | A-Manev/SoftUni-CSharp-Advanced-january-2020 | CSharp OOP/Inheritance - Lab/01. Single Inheritance/StartUp.cs | 193 | C# |
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.
using static TorchSharp.torch;
namespace TorchSharp
{
public partial class torchaudio
{
public interface ITransform
{
Tensor forward(Tensor input);
}
}
}
| 22.333333 | 130 | 0.668657 | [
"MIT"
] | dayo05/TorchSharp | src/TorchSharp/TorchAudio/ITransform.cs | 335 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Xml.Linq;
namespace Microsoft.AspNetCore.DataProtection
{
/// <summary>
/// Contains XLinq constants.
/// </summary>
internal static class XmlConstants
{
/// <summary>
/// The root namespace used for all DataProtection-specific XML elements and attributes.
/// </summary>
private static readonly XNamespace RootNamespace = XNamespace.Get(
"http://schemas.asp.net/2015/03/dataProtection"
);
/// <summary>
/// Represents the type of decryptor that can be used when reading 'encryptedSecret' elements.
/// </summary>
internal static readonly XName DecryptorTypeAttributeName = "decryptorType";
/// <summary>
/// Elements with this attribute will be read with the specified deserializer type.
/// </summary>
internal static readonly XName DeserializerTypeAttributeName = "deserializerType";
/// <summary>
/// Elements with this name will be automatically decrypted when read by the XML key manager.
/// </summary>
internal static readonly XName EncryptedSecretElementName = RootNamespace.GetName(
"encryptedSecret"
);
/// <summary>
/// Elements where this attribute has a value of 'true' should be encrypted before storage.
/// </summary>
internal static readonly XName RequiresEncryptionAttributeName = RootNamespace.GetName(
"requiresEncryption"
);
}
}
| 36.847826 | 111 | 0.655457 | [
"Apache-2.0"
] | belav/aspnetcore | src/DataProtection/DataProtection/src/XmlConstants.cs | 1,695 | C# |
namespace UnKnownName.Patches
{
using HarmonyLib;
[HarmonyPatch(typeof(KnownTech), nameof(KnownTech.Analyze))]
public class KnownTech_Analyze
{
[HarmonyPrefix]
public static bool Prefix(TechType techType, bool verbose)
{
if(Main.Config.Hardcore)
{
var entryData = PDAScanner.GetEntryData(techType);
return !verbose || entryData == null || (entryData != null && PDAScanner.ContainsCompleteEntry(techType));
}
return true;
}
}
} | 26.761905 | 122 | 0.588968 | [
"MIT"
] | MrPurple6411/Subnautica-Mods | UnkownName/Patches/KnownTech_Analyze.cs | 564 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
namespace System.Globalization.Tests
{
public enum IdnaTestResultType
{
ToUnicode,
ToAscii
}
public class ConformanceIdnaTestResult
{
/// <summary>
/// Determines if the intended result is a success or failure
/// </summary>
public bool Success { get; private set; }
/// <summary>
/// If Success is true, then the value shows the expected value of the test
/// If Success is false, then the value shows the conversion steps that have issues
///
/// For details, see the explanation in IdnaTest.txt for the Unicode version being tested
/// </summary>
public string Value { get; private set; }
public IdnaTestResultType ResultType { get; private set; }
public string StatusValue { get; private set; }
public ConformanceIdnaTestResult(
string entry,
string fallbackValue,
IdnaTestResultType resultType = IdnaTestResultType.ToAscii
) : this(entry, fallbackValue, null, null, useValueForStatus: true, resultType) { }
public ConformanceIdnaTestResult(
string entry,
string fallbackValue,
string statusValue,
string statusFallbackValue,
IdnaTestResultType resultType = IdnaTestResultType.ToAscii
)
: this(
entry,
fallbackValue,
statusValue,
statusFallbackValue,
useValueForStatus: false,
resultType
) { }
private ConformanceIdnaTestResult(
string entry,
string fallbackValue,
string statusValue,
string statusFallbackValue,
bool useValueForStatus,
IdnaTestResultType resultType
)
{
ResultType = resultType;
SetValue(string.IsNullOrEmpty(entry.Trim()) ? fallbackValue : entry);
SetSuccess(
useValueForStatus
? Value
: string.IsNullOrEmpty(statusValue.Trim())
? statusFallbackValue
: statusValue
);
}
private void SetValue(string entry)
{
Value = entry.Trim();
}
private void SetSuccess(string statusValue)
{
StatusValue = statusValue.Trim();
Success = true;
if (StatusValue.StartsWith('[') && StatusValue != "[]")
{
if (StatusValue == Value)
{
Success = false;
return;
}
string[] statusCodes = StatusValue[1..^1].Split(',');
for (int i = 0; i < statusCodes.Length; i++)
{
if (!IsIgnoredError(statusCodes[i].Trim()))
{
Success = false;
break;
}
}
}
}
private bool IsIgnoredError(string statusCode)
{
// We don't validate for BIDI rule so we can ignore BIDI codes
// If we're validating ToAscii we ignore rule V2 (UIDNA_ERROR_HYPHEN_3_4) for compatibility with windows.
return statusCode.StartsWith('B')
|| (ResultType == IdnaTestResultType.ToAscii && statusCode == "V2");
}
}
}
| 31.594828 | 117 | 0.533697 | [
"MIT"
] | belav/runtime | src/libraries/System.Globalization.Extensions/tests/IdnMapping/Data/ConformanceIdnaTestResult.cs | 3,665 | C# |
using System.IO;
using System.Threading.Tasks;
namespace MS2Lib
{
public interface IMS2FileInfoCrypto
{
Task<IMS2FileInfo> ReadAsync(TextReader textReader);
Task WriteAsync(TextWriter textWriter, IMS2FileInfo fileInfo);
}
}
| 21.166667 | 70 | 0.728346 | [
"MIT"
] | Miyuyami/MS2Lib | MS2Lib/CryptoRepository/Contracts/IMS2FileInfoCrypto.cs | 256 | C# |
//
// Mono.Cairo.LinearGradient.cs
//
// Author: Jordi Mas (jordi@ximian.com)
// Hisham Mardam Bey (hisham.mardambey@gmail.com)
// (C) Ximian Inc, 2004.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// 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 Drawing2D;
namespace Crow.CairoBackend {
public class LinearGradient : Gradient
{
internal LinearGradient (IntPtr handle, bool owned) : base (handle, owned)
{
}
public LinearGradient (double x0, double y0, double x1, double y1)
: base (NativeMethods.cairo_pattern_create_linear (x0, y0, x1, y1), true)
{
}
public PointD[] LinearPoints {
get {
double x0, y0, x1, y1;
PointD[] points = new PointD [2];
NativeMethods.cairo_pattern_get_linear_points (handle, out x0, out y0, out x1, out y1);
points[0] = new PointD (x0, y0);
points[1] = new PointD (x1, y1);
return points;
}
}
}
}
| 32.131148 | 91 | 0.716327 | [
"MIT"
] | jpbruyere/Crow | Backends/CairoBackend/src/LinearGradient.cs | 1,960 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Framework.Tests.Visual.UserInterface
{
public class TestSceneFocusedOverlayContainer : ManualInputManagerTestScene
{
private TestFocusedOverlayContainer overlayContainer;
private ParentContainer parentContainer;
[Test]
public void TestClickDismiss()
{
AddStep("create container", () => { Child = overlayContainer = new TestFocusedOverlayContainer(); });
AddStep("show", () => overlayContainer.Show());
AddAssert("has focus", () => overlayContainer.HasFocus);
AddStep("click inside", () =>
{
InputManager.MoveMouseTo(overlayContainer.ScreenSpaceDrawQuad.Centre);
InputManager.PressButton(MouseButton.Left);
InputManager.ReleaseButton(MouseButton.Left);
});
AddAssert("still has focus", () => overlayContainer.HasFocus);
AddStep("click outside", () =>
{
InputManager.MoveMouseTo(overlayContainer.ScreenSpaceDrawQuad.TopLeft - new Vector2(20));
InputManager.PressButton(MouseButton.Left);
InputManager.ReleaseButton(MouseButton.Left);
});
AddAssert("lost focus", () => !overlayContainer.HasFocus);
AddAssert("not visible", () => overlayContainer.State.Value == Visibility.Hidden);
}
[TestCase(true)]
[TestCase(false)]
public void TestScrollBlocking(bool isBlocking)
{
AddStep("create container", () =>
{
Child = parentContainer = new ParentContainer
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
overlayContainer = new TestFocusedOverlayContainer(blockScrollInput: isBlocking)
}
};
});
AddStep("show", () => overlayContainer.Show());
AddAssert("has focus", () => overlayContainer.HasFocus);
int initialScrollCount = 0;
AddStep("scroll inside", () =>
{
initialScrollCount = parentContainer.ScrollReceived;
InputManager.MoveMouseTo(overlayContainer.ScreenSpaceDrawQuad.Centre);
InputManager.ScrollVerticalBy(1);
});
if (isBlocking)
AddAssert("scroll not received by parent", () => parentContainer.ScrollReceived == initialScrollCount);
else
AddAssert("scroll received by parent", () => parentContainer.ScrollReceived == ++initialScrollCount);
AddStep("scroll outside", () =>
{
InputManager.MoveMouseTo(overlayContainer.ScreenSpaceDrawQuad.TopLeft - new Vector2(20));
InputManager.ScrollVerticalBy(1);
});
AddAssert("scroll received by parent", () => parentContainer.ScrollReceived == ++initialScrollCount);
}
private class TestFocusedOverlayContainer : FocusedOverlayContainer
{
protected override bool StartHidden { get; }
protected override bool BlockPositionalInput => true;
protected override bool BlockNonPositionalInput => false;
protected override bool BlockScrollInput { get; }
public TestFocusedOverlayContainer(bool startHidden = true, bool blockScrollInput = true)
{
BlockScrollInput = blockScrollInput;
StartHidden = startHidden;
Size = new Vector2(0.5f);
RelativeSizeAxes = Axes.Both;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Children = new Drawable[]
{
new Box
{
Colour = Color4.Cyan,
RelativeSizeAxes = Axes.Both,
},
};
State.ValueChanged += e => FireCount++;
}
public int FireCount { get; private set; }
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;
protected override bool OnClick(ClickEvent e)
{
if (!base.ReceivePositionalInputAt(e.ScreenSpaceMousePosition))
{
Hide();
return true;
}
return true;
}
protected override bool OnMouseDown(MouseDownEvent e)
{
base.OnMouseDown(e);
return true;
}
protected override void PopIn()
{
this.FadeIn(1000, Easing.OutQuint);
this.ScaleTo(1, 1000, Easing.OutElastic);
base.PopIn();
}
protected override void PopOut()
{
this.FadeOut(1000, Easing.OutQuint);
this.ScaleTo(0.4f, 1000, Easing.OutQuint);
base.PopOut();
}
}
}
public class ParentContainer : Container
{
public int ScrollReceived;
protected override bool OnScroll(ScrollEvent e)
{
ScrollReceived++;
return base.OnScroll(e);
}
}
}
| 33.587571 | 120 | 0.537258 | [
"MIT"
] | ATiltedTree/osu-framework | osu.Framework.Tests/Visual/UserInterface/TestSceneFocusedOverlayContainer.cs | 5,769 | C# |
using System;
using System.Windows;
using Messaging.RabbitMq;
namespace Messaging.Publisher
{
public partial class MainWindow : Window
{
private RabbitMqPublisher _publisher;
public MainWindow()
{
InitializeComponent();
_publisher = new RabbitMqPublisher();
}
private void ButtonClick(object sender, RoutedEventArgs e)
{
var message = $"Button clicked at {DateTime.Now:hh:mm:ss.fff}";
_publisher.Publish(message);
}
}
}
| 18.16 | 66 | 0.726872 | [
"MIT"
] | asa-hmb/MessagingTalk | Messaging.Publisher/MainWindow.xaml.cs | 456 | C# |
using System.Web.Mvc;
namespace GroupDocsConversionMVCDemoWithProgress
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | 23.583333 | 81 | 0.657244 | [
"MIT"
] | atirtahirgroupdocs/GroupDocs.Conversion-for-.NET | Showcases/GroupDocsConversionMVCDemoWithProgress/App_Start/FilterConfig.cs | 285 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using ComposeTestEnvironment.xUnit.Infrastructure;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
// ReSharper disable StaticMemberInGenericType
namespace ComposeTestEnvironment.xUnit
{
public class DockerComposeEnvironmentFixture<TDescriptor> : IAsyncLifetime
where TDescriptor : DockerComposeDescriptor, new()
{
private const string ComposeExe = @"docker-compose";
private static readonly TimeSpan _startTimeout = TimeSpan.FromSeconds(10);
private static readonly object _syncRoot = new();
private static Task<Discovery>? _initializeAsync;
private readonly IMessageSink _output;
private readonly List<string> _outputStrings = new();
private readonly DisposableList _disposables = new();
public DockerComposeEnvironmentFixture(IMessageSink output)
{
_output = output;
Discovery = null !; // This class is available only after InitializeAsync. So Discovery will be initialized
}
public Discovery Discovery { get; private set; }
protected TDescriptor Descriptor { get; } = new();
protected virtual ValueTask AfterInitializeAsync()
{
return default;
}
protected virtual ValueTask BeforeDisposeAsync()
{
return default;
}
protected virtual ValueTask BeforeSingleTimeInitialize()
{
return default;
}
protected virtual ValueTask AfterSingleTimeInitialize(Discovery discovery, bool usedExistingEnvironment)
{
return default;
}
protected void RegisterGlobalDisposable(IDisposable disposable)
{
_disposables.Add(disposable);
}
protected ValueTask RegisterGlobalDisposableAsync(IAsyncDisposable disposable)
{
return _disposables.AddAsync(disposable);
}
protected virtual Task<bool> IsEnvironmentUp(Discovery discovery)
{
return Task.FromResult(true);
}
async Task IAsyncLifetime.InitializeAsync()
{
if (_initializeAsync == null)
{
lock (_syncRoot)
{
_initializeAsync ??= InitializeCoreAsync();
}
}
Discovery = await _initializeAsync.ConfigureAwait(false);
await AfterInitializeAsync().ConfigureAwait(false);
}
async Task IAsyncLifetime.DisposeAsync()
{
await BeforeDisposeAsync().ConfigureAwait(false);
}
private async Task<Discovery> InitializeCoreAsync()
{
TestFramework.RegisterDisposable(_disposables);
await BeforeSingleTimeInitialize().ConfigureAwait(false);
Discovery discovery;
bool existingEnv = false;
if (Descriptor.IsUnderCompose)
{
if (Descriptor.WaitForPortsListen)
{
var listening = Descriptor.Ports
.SelectMany(x => x.Value.Select(port => new {Service = x.Key, Port = port}))
.Where(x => !Descriptor.IgnoreWaitForPortListening.TryGetValue(x.Service, out var prohibitedPorts) ||
!prohibitedPorts.Contains(x.Port))
.Select(x => new UriBuilder("tcp://", x.Service, x.Port).Uri)
.ToList();
await WaitForListeningPorts(listening).ConfigureAwait(false);
}
discovery = new Discovery(
Descriptor.Ports.ToDictionary(
item => new HostSubstitution(item.Key, item.Key),
item => (IReadOnlyList<PortSubstitution>)item.Value.Select(port => new PortSubstitution(port, port)).ToList()));
}
else if (Descriptor.IsExternalCompose)
{
if (Descriptor.WaitForPortsListen)
{
var listening = Descriptor.Ports
.SelectMany(x => x.Value.Select(port => new {Service = x.Key, Port = port}))
.Where(x => !Descriptor.IgnoreWaitForPortListening.TryGetValue(x.Service, out var prohibitedPorts) ||
!prohibitedPorts.Contains(x.Port))
.Select(x => new UriBuilder("tcp://", Descriptor.DockerHost, x.Port).Uri)
.ToList();
await WaitForListeningPorts(listening).ConfigureAwait(false);
}
discovery = new Discovery(
Descriptor.Ports.ToDictionary(
item => new HostSubstitution(item.Key, Descriptor.DockerHost),
item => (IReadOnlyList<PortSubstitution>)item.Value.Select(port => new PortSubstitution(port, port)).ToList()));
}
else
{
(discovery, existingEnv) = await InitializeComposeEnvironmentAsync().ConfigureAwait(false);
}
await Descriptor.WaitForReady(discovery).ConfigureAwait(false);
await AfterSingleTimeInitialize(discovery, existingEnv).ConfigureAwait(false);
return discovery;
}
private async Task<(Discovery Discovery, bool ExistingEnvironment)> InitializeComposeEnvironmentAsync()
{
using var composeFileStream = File.OpenRead(FindFile(Descriptor.ComposeFileName));
var composeFile = ComposeFile.Parse(composeFileStream);
await AssignExposedPorts(composeFile, Descriptor.PortRenter).ConfigureAwait(false);
var (discovery, portMappings) = PortMappings(composeFile);
if (Descriptor.TryFindExistingEnvironment)
{
if (await ArePortsOpened(portMappings).ConfigureAwait(false) &&
await IsEnvironmentUp(discovery).ConfigureAwait(false))
{
return (discovery, true);
}
}
await ApplyEnvironmentChanges(composeFile, discovery);
var generatedFilePath = GenerateComposeFileWithExposedPorts(composeFile);
var projectName = Descriptor.ProjectName;
if (Descriptor.DownOnComplete)
{
var downProcess = ComposeDown(generatedFilePath, projectName);
_disposables.Add(downProcess);
await _disposables.AddAsync(async () =>
{
WriteMessage("Stopping compose...");
await downProcess.Start(_startTimeout).ConfigureAwait(false);
await downProcess.WaitForExit().WithTimeout(Descriptor.StopTimeout).ConfigureAwait(false);
}).ConfigureAwait(false);
}
var downBeforeCreate = ComposeDown(generatedFilePath, projectName);
_disposables.Add(downBeforeCreate);
await downBeforeCreate.Start(_startTimeout).ConfigureAwait(false);
await downBeforeCreate.WaitForExit().ConfigureAwait(false);
var pullProcess = ComposePull(generatedFilePath, projectName);
_disposables.Add(pullProcess);
await pullProcess.Start(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
await pullProcess.WaitForExit().ConfigureAwait(false);
var process = new ProcessHelper(ComposeExe)
.Argument("-f", generatedFilePath)
.Argument("-p", projectName)
.Argument("up")
.CollectOutput(WriteMessage);
if (!Descriptor.GenerateImageBasedCompose)
{
process.Argument("--build");
}
foreach (var message in Descriptor.StartedMessageMarkers)
{
process.WaitForMessageInOutput(message);
}
_disposables.Add(process);
try
{
await process.Start(Descriptor.StartTimeout).ConfigureAwait(false);
}
catch (OperationCanceledException ex)
{
var processOutput = string.Join(Environment.NewLine, _outputStrings);
if (_outputStrings.Any(x => x.Contains("No space left on device", StringComparison.Ordinal)))
{
throw new InvalidOperationException("No space left on device. Try to clean volumes via: 'docker volume prune' command.\r\n\r\n", ex);
}
throw new OperationCanceledException($"Timeout, docker output:\r\n {processOutput}", ex);
}
await WaitForListeningPorts(portMappings);
return (discovery, false);
}
private async Task WaitForListeningPorts(Dictionary<string, IReadOnlyList<DockerPort>> portMappings)
{
if (Descriptor.WaitForPortsListen)
{
using var cancellationTokenSource = new CancellationTokenSource(Descriptor.StartTimeout);
var listening = GetListeningUrls(portMappings);
await Task.WhenAll(listening.Select(x => Connect(x, cancellationTokenSource.Token)));
}
}
private async Task<bool> ArePortsOpened(Dictionary<string, IReadOnlyList<DockerPort>> portMappings)
{
if (Descriptor.WaitForPortsListen)
{
using var cancellationTokenSource = new CancellationTokenSource(Descriptor.StartTimeout);
var listening = GetListeningUrls(portMappings);
var results = await Task.WhenAll(listening.Select(x => CanConnect(x, cancellationTokenSource.Token)))!;
return results.All(x => x);
}
return true;
}
private List<Uri> GetListeningUrls(Dictionary<string, IReadOnlyList<DockerPort>> portMappings)
{
return portMappings
.SelectMany(x => x.Value.Select(y => new {Service = x.Key, Port = y}))
.Where(x => string.IsNullOrEmpty(x.Port.Protocol) || x.Port.Protocol == "tcp")
.Where(x => !Descriptor.IgnoreWaitForPortListening.TryGetValue(x.Service, out var prohibitedPorts) ||
!prohibitedPorts.Contains(x.Port.ExposedPort))
.Select(x => x.Port)
.Select(x => new UriBuilder("tcp://", Descriptor.DockerHost, x.PublicPort).Uri)
.ToList();
}
private (Discovery discovery, Dictionary<string, IReadOnlyList<DockerPort>> portMappings) PortMappings(
ComposeFile composeFile)
{
var portMappings = composeFile.Services
.Where(service =>
service.Image != null &&
Descriptor.Ports.ContainsKey(service.ServiceName))
.ToDictionary(x => x.ServiceName, x => x.PortMappings);
var discovery = new Discovery(
portMappings.ToDictionary(
item => new HostSubstitution(item.Key, Descriptor.DockerHost),
item => (IReadOnlyList<PortSubstitution>)item.Value
.Select(port => new PortSubstitution(port.ExposedPort, port.PublicPort)).ToList()));
return (discovery, portMappings);
}
private async Task ApplyEnvironmentChanges(ComposeFile composeFile, Discovery discovery)
{
foreach (var service in composeFile.Services)
{
var existing = service.GetEnvironment();
var overrides = await Descriptor.GetEnvironment(service.ServiceName, existing, discovery);
service.SetEnvironment(overrides);
}
}
protected virtual async Task WaitForListeningPorts(IReadOnlyList<Uri> listening)
{
using var cancellationTokenSource = new CancellationTokenSource(Descriptor.StartTimeout);
var tasks = listening.Select(uri => Connect(uri, cancellationTokenSource.Token));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
protected virtual void WriteMessage(string message)
{
_outputStrings.Add(message);
_output.OnMessage(new DiagnosticMessage(message));
}
private async Task Connect(Uri uri, CancellationToken cancellation)
{
try
{
while (!cancellation.IsCancellationRequested)
{
var canConnect = await CanConnect(uri, cancellation).ConfigureAwait(false);
if (canConnect)
{
return;
}
await Task.Delay(TimeSpan.FromMilliseconds(50), cancellation).ConfigureAwait(false);
}
}
catch (OperationCanceledException ex)
{
throw new OperationCanceledException($"Unable to connect to {uri}", ex);
}
}
private async Task<bool> CanConnect(Uri uri, CancellationToken cancellation)
{
using var client = new TcpClient();
try
{
#if NET5_0
await client.ConnectAsync(uri.Host, uri.Port, cancellation).ConfigureAwait(false);
#else
await client.ConnectAsync(uri.Host, uri.Port).ConfigureAwait(false);
#endif
if (client.Connected)
{
return true;
}
}
catch (SocketException)
{
}
return false;
}
private ProcessHelper ComposeDown(string composeFile, string projectName)
{
var downProcess = new ProcessHelper(ComposeExe)
.Argument("-f", composeFile)
.Argument("-p", projectName)
.Argument("down")
.Argument("--remove-orphans")
.Argument("--volumes") // Remove volumes on down to do not eat the space
.CollectOutput(line => WriteMessage("down: " + line));
return downProcess;
}
private ProcessHelper ComposePull(string composeFile, string projectName)
{
var downProcess = new ProcessHelper(ComposeExe)
.Argument("-f", composeFile)
.Argument("-p", projectName)
.Argument("pull")
.CollectOutput(line => WriteMessage("pull: " + line));
return downProcess;
}
private string GenerateComposeFileWithExposedPorts(ComposeFile composeFile)
{
var generatedComposeFile = GetTempFile();
_disposables.Add(() =>
{
try
{
File.Delete(generatedComposeFile);
}
catch (IOException)
{
}
});
if (Descriptor.GenerateImageBasedCompose)
{
var nonImageServices = composeFile.Services
.Where(service => service.Image == null)
.Select(service => service.ServiceName)
.ToList();
composeFile.RemoveServices(nonImageServices);
}
composeFile.RemoveServices(Descriptor.ServicesToRemove);
using (var tempStream = File.OpenWrite(generatedComposeFile))
{
composeFile.Save(tempStream);
}
return generatedComposeFile;
}
private async Task AssignExposedPorts(ComposeFile composeFile, IPortRenter portRenter)
{
var docker = new DockerFacade();
foreach (var service in composeFile.Services)
{
if (service.Image == null)
{
continue;
}
if (!Descriptor.Ports.TryGetValue(service.ServiceName, out var discoveryPorts))
{
continue;
}
var imageExposedPorts = await docker.GetExposedPortsAsync(service.Image).ConfigureAwait(false);
var publicPorts = portRenter.Rent(service.ServiceName, discoveryPorts.Length);
var portMapping = discoveryPorts
.Select((port, index) =>
{
// Expose only necessary ports, dont expose all ports from image
var imagePort = imageExposedPorts.FirstOrDefault(x => x.PortNumber == port);
if (imagePort != default)
{
return new DockerPort(imagePort.PortNumber, publicPorts[index], imagePort.Protocol);
}
return new DockerPort((ushort)port, publicPorts[index], string.Empty);
})
.ToList();
service.SetPortMapping(portMapping);
}
}
private string GetTempFile()
{
var random = new Random();
string fileName;
do
{
var prefix = random.Next().ToString("x8");
fileName = $"~{Descriptor.ProjectName}{prefix}.tmp.yml";
} while (File.Exists(fileName));
return fileName;
}
private static string FindFile(string name)
{
var dir = AppContext.BaseDirectory;
var fileName = Path.Combine(dir, name);
while (!File.Exists(fileName))
{
var parent = Directory.GetParent(dir);
if (parent == null)
{
return Path.Combine(AppContext.BaseDirectory, name);
}
dir = parent.FullName;
fileName = Path.Combine(dir, name);
}
return fileName;
}
}
}
| 36.35 | 153 | 0.562201 | [
"MIT"
] | MaxShoshin/TestCompose | ComposeTestEnvironment.xUnit/DockerComposeEnvironmentFixture.cs | 18,177 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
public ActiveListenerComponent activeListener { get { return (ActiveListenerComponent)GetComponent(GameComponentsLookup.ActiveListener); } }
public bool hasActiveListener { get { return HasComponent(GameComponentsLookup.ActiveListener); } }
public void AddActiveListener(System.Collections.Generic.List<IActiveListener> newValue) {
var index = GameComponentsLookup.ActiveListener;
var component = (ActiveListenerComponent)CreateComponent(index, typeof(ActiveListenerComponent));
component.value = newValue;
AddComponent(index, component);
}
public void ReplaceActiveListener(System.Collections.Generic.List<IActiveListener> newValue) {
var index = GameComponentsLookup.ActiveListener;
var component = (ActiveListenerComponent)CreateComponent(index, typeof(ActiveListenerComponent));
component.value = newValue;
ReplaceComponent(index, component);
}
public void RemoveActiveListener() {
RemoveComponent(GameComponentsLookup.ActiveListener);
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameMatcher {
static Entitas.IMatcher<GameEntity> _matcherActiveListener;
public static Entitas.IMatcher<GameEntity> ActiveListener {
get {
if (_matcherActiveListener == null) {
var matcher = (Entitas.Matcher<GameEntity>)Entitas.Matcher<GameEntity>.AllOf(GameComponentsLookup.ActiveListener);
matcher.componentNames = GameComponentsLookup.componentNames;
_matcherActiveListener = matcher;
}
return _matcherActiveListener;
}
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.EventEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
public void AddActiveListener(IActiveListener value) {
var listeners = hasActiveListener
? activeListener.value
: new System.Collections.Generic.List<IActiveListener>();
listeners.Add(value);
ReplaceActiveListener(listeners);
}
public void RemoveActiveListener(IActiveListener value, bool removeComponentWhenEmpty = true) {
var listeners = activeListener.value;
listeners.Remove(value);
if (removeComponentWhenEmpty && listeners.Count == 0) {
RemoveActiveListener();
} else {
ReplaceActiveListener(listeners);
}
}
}
| 41.430233 | 144 | 0.612405 | [
"MIT"
] | et9930/ECS-Game | Assets/Script/Generated/Game/Components/GameActiveListenerComponent.cs | 3,563 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901
{
using static Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Extensions;
/// <summary>
/// Information about a service principal identity for the cluster to use for manipulating Azure APIs.
/// </summary>
public partial class ManagedClusterServicePrincipalProfile :
Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterServicePrincipalProfile,
Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterServicePrincipalProfileInternal
{
/// <summary>Backing field for <see cref="ClientId" /> property.</summary>
private string _clientId;
/// <summary>The ID for the service principal.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)]
public string ClientId { get => this._clientId; set => this._clientId = value; }
/// <summary>Backing field for <see cref="Secret" /> property.</summary>
private string _secret;
/// <summary>The secret password associated with the service principal in plain text.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Aks.Origin(Microsoft.Azure.PowerShell.Cmdlets.Aks.PropertyOrigin.Owned)]
public string Secret { get => this._secret; set => this._secret = value; }
/// <summary>Creates an new <see cref="ManagedClusterServicePrincipalProfile" /> instance.</summary>
public ManagedClusterServicePrincipalProfile()
{
}
}
/// Information about a service principal identity for the cluster to use for manipulating Azure APIs.
public partial interface IManagedClusterServicePrincipalProfile :
Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.IJsonSerializable
{
/// <summary>The ID for the service principal.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The ID for the service principal.",
SerializedName = @"clientId",
PossibleTypes = new [] { typeof(string) })]
string ClientId { get; set; }
/// <summary>The secret password associated with the service principal in plain text.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The secret password associated with the service principal in plain text.",
SerializedName = @"secret",
PossibleTypes = new [] { typeof(string) })]
string Secret { get; set; }
}
/// Information about a service principal identity for the cluster to use for manipulating Azure APIs.
internal partial interface IManagedClusterServicePrincipalProfileInternal
{
/// <summary>The ID for the service principal.</summary>
string ClientId { get; set; }
/// <summary>The secret password associated with the service principal in plain text.</summary>
string Secret { get; set; }
}
} | 48.6 | 117 | 0.679329 | [
"MIT"
] | Amrinder-Singh29/azure-powershell | src/Aks/Aks.Autorest/generated/api/Models/Api20200901/ManagedClusterServicePrincipalProfile.cs | 3,095 | C# |
using System;
namespace EnvironmentBusinessLayer
{
public interface IEnvironment
{
string MachineName();
}
}
| 14 | 35 | 0.628571 | [
"MIT"
] | Vitalii-Misechko/dot-net-dependency-injection | ModulesFeature/EnvironmentBusinessLayer/IEnvironment.cs | 142 | C# |
using System.Collections.Generic;
using System.Linq;
using DRMFSS.BLL.Interfaces;
using DRMFSS.BLL.MetaModels;
using System.ComponentModel.DataAnnotations;
using System;
using DRMFSS.Web.Models;
namespace DRMFSS.BLL.Repository
{
/// <summary>
///
/// </summary>
public partial class DispatchDetailRepository :GenericRepository<CTSContext,DispatchDetail>, IDispatchDetailRepository
{
public DispatchDetailRepository(CTSContext _db, IUnitOfWork uow)
{
db = _db;
repository = uow;
}
/// <summary>
/// Gets the dispatch detail list.
/// </summary>
/// <param name="dispatchId">The dispatch id.</param>
/// <returns></returns>
public List<BLL.DispatchDetail> GetDispatchDetail(int partitionID, Guid dispatchId)
{
return (from p in db.DispatchDetails
where ( p.DispatchID == dispatchId)
select p).ToList();
}
public List<DispatchDetail> GetDispatchDetail(Guid dispatchId)
{
return (from p in db.DispatchDetails
where (p.DispatchID == dispatchId)
select p).ToList();
}
public List<DispatchDetailModelDto> ByDispatchIDetached(Guid dispatchId, string PreferedWeightMeasurment)
{
List<DispatchDetailModelDto> dispatchDetais = new List<DispatchDetailModelDto>();
var query = (from rD in db.DispatchDetails
where rD.DispatchID == dispatchId
select rD);
foreach (var dispatchDetail in query)
{
var DDMD = new DispatchDetailModelDto();
DDMD.DispatchID = dispatchDetail.DispatchID;
DDMD.DispatchDetailID = dispatchDetail.DispatchDetailID;
DDMD.CommodityName = dispatchDetail.Commodity.Name;
DDMD.UnitName = dispatchDetail.Unit.Name;
DDMD.RequestedQuantityInUnit = Math.Abs(dispatchDetail.RequestedQunatityInUnit);
DDMD.DispatchedQuantityInUnit = Math.Abs(dispatchDetail.DispatchedQuantityInUnit);
if (PreferedWeightMeasurment.ToUpperInvariant() == "QN")
{
DDMD.RequestedQuantityMT = Math.Abs(dispatchDetail.RequestedQuantityInMT)*10;
DDMD.DispatchedQuantityMT = Math.Abs(dispatchDetail.DispatchedQuantityInMT)*10;
}
else
{
DDMD.RequestedQuantityMT = Math.Abs(dispatchDetail.RequestedQuantityInMT);
DDMD.DispatchedQuantityMT = Math.Abs(dispatchDetail.DispatchedQuantityInMT);
}
dispatchDetais.Add(DDMD);
}
return dispatchDetais;
}
public bool DeleteByID(int id)
{
var original = FindById(id);
if (original == null) return false;
db.DispatchDetails.Remove(original);
return true;
}
public bool DeleteByID(System.Guid id)
{
return false;
}
public DispatchDetail FindById(int id)
{
return null;
}
public DispatchDetail FindById(System.Guid id)
{
return db.DispatchDetails.FirstOrDefault(t => t.DispatchDetailID == id);
}
}
}
| 33.048077 | 122 | 0.581903 | [
"MIT"
] | aliostad/deep-learning-lang-detection | data/train/csharp/49e42d3621b87b038703665f7f956b6311fb98d7DispatchDetailRepository.cs | 3,437 | C# |
using System.Xml;
using System.Text;
using BepInEx.Logging;
using HarmonyLib;
using Hacknet;
using Pathfinder.Util;
using Pathfinder.Util.XML;
namespace Pathfinder.Administrator
{
public abstract class BaseAdministrator : Hacknet.Administrator
{
protected Computer computer;
protected OS opSystem;
public BaseAdministrator(Computer computer, OS opSystem) : base()
{
this.computer = computer;
this.opSystem = opSystem;
}
}
}
| 21.826087 | 73 | 0.679283 | [
"MIT"
] | 4310V343k/Hacknet-Pathfinder | PathfinderAPI/Administrator/BaseAdministrator.cs | 502 | C# |
namespace Febraban240
{
public class HeaderLote040
{
public GrupoControle Controle = new GrupoControle();
public class GrupoControle
{
public Campo Banco = new CampoNumerico(1, 3, 0, "G001");
public Campo Lote = new CampoNumerico(4, 7, 0, "G002");
public Campo Registro = new CampoNumerico(8, 8, 0, "G003", "1");
}
public GrupoServico Servico = new GrupoServico();
public class GrupoServico
{
public Campo Operacao = new CampoAlfanumerico(9, 9, "G028", "C");
public Campo Servico = new CampoAlfanumerico(10, 11, "G025");
public Campo FormaLancamento = new CampoAlfanumerico(12, 13, "G029");
public Campo LayoutLote = new CampoAlfanumerico(14, 16, "G030", "046");
}
public Campo Cnab1 = new CampoAlfanumerico(17, 17, "G004");
public GrupoEmpresa Empresa = new GrupoEmpresa();
public class GrupoEmpresa
{
public GrupoInscricao Inscricao = new GrupoInscricao();
public class GrupoInscricao
{
public Campo Tipo = new CampoNumerico(18, 18, 0, "G005");
public Campo Numero = new CampoNumerico(19, 32, 0, "G006");
}
public Campo Convenio = new CampoAlfanumerico(33, 52, "G007");
public GrupoContaCorrente ContaCorrente = new GrupoContaCorrente();
public class GrupoContaCorrente
{
public GrupoAgencia Agencia = new GrupoAgencia();
public class GrupoAgencia
{
public Campo Codigo = new CampoNumerico(53, 57, 0, "G008");
public Campo DV = new CampoAlfanumerico(58, 58, "G009");
}
public GrupoConta Conta = new GrupoConta();
public class GrupoConta
{
public Campo Numero = new CampoNumerico(59, 70, 0, "G010");
public Campo DV = new CampoAlfanumerico(71, 71, "G011");
}
public Campo DV = new CampoAlfanumerico(72, 72, "G012");
}
public Campo Nome = new CampoAlfanumerico(73, 102, "G013");
}
public Campo Informacao1 = new CampoAlfanumerico(103, 142, "G031");
public GrupoEnderecoEmpresa EnderecoEmpresa = new GrupoEnderecoEmpresa();
public class GrupoEnderecoEmpresa
{
public Campo Logradouro = new CampoAlfanumerico(143, 172, "G032");
public Campo Numero = new CampoAlfanumerico(173, 177, "G032");
public Campo Complemento = new CampoAlfanumerico(178, 192, "G032");
public Campo Cidade = new CampoAlfanumerico(193, 212, "G033");
public Campo CEP = new CampoAlfanumerico(213, 217, "G034");
public Campo ComplementoCEP = new CampoAlfanumerico(218, 220, "G035");
public Campo Estado = new CampoAlfanumerico(221, 222, "G036");
}
public Campo Cnab2 = new CampoAlfanumerico(223, 230, "G004");
public Campo Ocorrencias = new CampoAlfanumerico(231, 240, "G059");
}
}
| 47.984848 | 83 | 0.581939 | [
"MIT"
] | rafaelsolli/Febraban240 | Geral/HeaderLote040.cs | 3,169 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using InSituVisualization.Model;
using InSituVisualization.Predictions;
using InSituVisualization.TelemetryCollector;
using Microsoft.CodeAnalysis;
namespace InSituVisualization.TelemetryMapper
{
// ReSharper disable once ClassNeverInstantiated.Global Justification: IoC
internal class TelemetryDataMapper : ITelemetryDataMapper
{
private readonly IPredictionEngine _predictionEngine;
private readonly ITelemetryProvider _telemetryProvider;
private readonly Dictionary<string, MethodPerformanceInfo> _methodPerformancInfoCache = new Dictionary<string, MethodPerformanceInfo>();
public TelemetryDataMapper(ITelemetryProvider telemetryProvider, IPredictionEngine predictionEngine)
{
_predictionEngine = predictionEngine ?? throw new ArgumentNullException(nameof(predictionEngine));
_telemetryProvider = telemetryProvider ?? throw new ArgumentNullException(nameof(telemetryProvider));
}
public async Task<MethodPerformanceInfo> GetMethodPerformanceInfoAsync(IMethodSymbol methodSymbol)
{
var documentationCommentId = methodSymbol.GetDocumentationCommentId();
if (_methodPerformancInfoCache.TryGetValue(documentationCommentId, out var existingMethodPerformanceInfo))
{
return existingMethodPerformanceInfo;
}
// TODO RR: Use SyntaxAnnotation https://joshvarty.wordpress.com/2015/09/18/learn-roslyn-now-part-13-keeping-track-of-syntax-nodes-with-syntax-annotations/
// TODO RR: Do one Dictionary per Class/File
var methodTelemetry = await _telemetryProvider.GetTelemetryDataAsync(documentationCommentId).ConfigureAwait(false);
if (methodTelemetry == null)
{
return null;
}
var performanceInfo = new MethodPerformanceInfo(_predictionEngine, methodSymbol, methodTelemetry);
_methodPerformancInfoCache.Add(documentationCommentId, performanceInfo);
return performanceInfo;
}
}
}
| 43.16 | 167 | 0.73494 | [
"Apache-2.0"
] | sealuzh/visual-studio-perfviz | InSituVisualization/TelemetryMapper/TelemetryDataMapper.cs | 2,160 | C# |
using System;
using Newtonsoft.Json;
using SeafClient.Converters;
namespace SeafClient.Types
{
/// <summary>
/// Represents a shared library
/// </summary>
public class SeafSharedLibrary : SeafLibrary
{
[JsonProperty("repo_id")]
public override string Id { get; set; }
[JsonProperty("repo_name")]
public override string Name { get; set; }
[JsonProperty("repo_desc")]
public override string Description { get; set; }
[JsonProperty("user")]
public override string Owner { get; set; }
[JsonProperty("last_modified")]
[JsonConverter(typeof(SeafTimestampConverter))]
public override DateTime? Timestamp { get; set; }
}
} | 26.321429 | 57 | 0.626866 | [
"MIT"
] | AKrasheninnikov/SeafClient | SeafClient/Types/SeafSharedLibrary.cs | 739 | C# |
using Newtonsoft.Json;
namespace SendPulse.SDK.Models
{
public class EmailData : EmailBase
{
[JsonProperty("html")]
public string HTML { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
}
| 18.285714 | 40 | 0.589844 | [
"MIT"
] | iodes/SendPulse | SendPulse.SDK/Models/EmailData.cs | 258 | C# |
namespace CodingMilitia.PlayBall.GroupManagement.Data.Entities
{
public class GroupEntity
{
public long Id { get; set; }
public string Name { get; set; }
public uint RowVersion { get; set; }
}
} | 25.555556 | 62 | 0.630435 | [
"MIT"
] | romanolester/GroupManagement | src/CodingMilitia.PlayBall.GroupManagement.Data/Entities/GroupEntity.cs | 230 | C# |
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/8/8
* Time: 19:32
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using Lextm.SharpSnmpLib.Security;
using Xunit;
#pragma warning disable 1591, 0618
namespace Lextm.SharpSnmpLib.Messaging.Tests
{
public class MessageFactoryTestFixture
{
[Fact]
public void TrapV1InSNMPV2()
{
var data = "30 42 02 01 01 04 06 70 75 62 6C 69 63 A4 35 06 08 2B 06 01 04 01 81 AB 34 40 04 C0 A8 01 14 02 01 06 02 02 03 E8 43 04 00 00 03 63 30 16 30 14 06 0C 2B 06 01 04 01 81 AB 34 02 01 01 00 02 04 00 00 00 01";
var bytes = ByteTool.Convert(data);
Assert.Throws<SnmpException>(() => MessageFactory.ParseMessages(bytes, new UserRegistry()));
}
#if !NETSTANDARD
[Fact]
public void TestReportFailure()
{
const string data = "30 70 02 01 03 30"+
"11 02 04 76 EB 6A 22 02 03 00 FF F0 04 01 01 02 01 03 04 33 30 31 04 09"+
"80 00 05 23 01 C1 4D BB 83 02 01 5B 02 03 1C 93 9D 04 0C 4D 44 35 5F 44"+
"45 53 5F 55 73 65 72 04 0C E5 C7 C5 2E 17 7E 87 62 AB 56 D6 C7 04 00 30"+
"23 04 00 04 00 A8 1D 02 01 00 02 01 00 02 01 00 30 12 30 10 06 0A 2B 06"+
"01 06 03 0F 01 01 02 00 41 02 05 EE";
var bytes = ByteTool.Convert(data);
const string userName = "MD5_DES_User";
const string phrase = "AuthPassword";
const string privatePhrase = "PrivPassword";
IAuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString(phrase));
IPrivacyProvider priv = new DESPrivacyProvider(new OctetString(privatePhrase), auth);
var users = new UserRegistry();
users.Add(new User(new OctetString(userName), priv));
var messages = MessageFactory.ParseMessages(bytes, users);
Assert.Equal(1, messages.Count);
var message = messages[0];
Assert.Equal(1, message.Variables().Count);
}
#endif
[Fact]
public void TestReportFailure2()
{
const string data = "30780201033010020462d4a37602020578040101020103042f302d040b800000090340f4ecf2b113020124020200a4040762696c6c696e67040c62bc133ef237922dfa8ca39a04003030040b800000090340f4ecf2b1130400a81f02049d2b5c8c0201000201003011300f060a2b060106030f01010200410105";
var bytes = ByteTool.Convert(data);
const string userName = "billing";
IAuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString("testing345"));
IPrivacyProvider priv = new DefaultPrivacyProvider(auth);
var users = new UserRegistry();
users.Add(new User(new OctetString(userName), priv));
var messages = MessageFactory.ParseMessages(bytes, users);
Assert.Equal(1, messages.Count);
var message = messages[0];
Assert.Equal(1, message.Variables().Count);
Assert.Equal("not in time window", message.Variables()[0].Id.GetErrorMessage());
}
[Fact]
public void TestInform()
{
byte[] data = new byte[] { 0x30, 0x5d, 0x02, 0x01, 0x01, 0x04, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0xa6, 0x50, 0x02, 0x01, 0x01, 0x02, 0x01,
0x00, 0x02, 0x01, 0x00, 0x30, 0x45, 0x30, 0x0e, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x02, 0x01, 0x01, 0x03, 0x00, 0x43, 0x02,
0x3f, 0xe0, 0x30, 0x18, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x06, 0x03, 0x01, 0x01, 0x04, 0x01, 0x00, 0x06, 0x0a, 0x2b, 0x06,
0x01, 0x04, 0x01, 0x90, 0x72, 0x87, 0x68, 0x02, 0x30, 0x19, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x90, 0x72, 0x87,
0x69, 0x15, 0x00, 0x04, 0x0a, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x54, 0x65, 0x73, 0x74 };
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(data, new UserRegistry());
Assert.Equal(SnmpType.InformRequestPdu, messages[0].TypeCode());
}
[Fact]
public void TestString()
{
string bytes = "30 29 02 01 00 04 06 70 75 62 6c 69 63 a0 1c 02 04 4f 89 fb dd" + Environment.NewLine +
"02 01 00 02 01 00 30 0e 30 0c 06 08 2b 06 01 02 01 01 05 00 05 00";
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, new UserRegistry());
Assert.Equal(1, messages.Count);
GetRequestMessage m = (GetRequestMessage)messages[0];
Variable v = m.Variables()[0];
string i = v.Id.ToString();
Assert.Equal(".1.3.6.1.2.1.1.5.0", i);
}
[Fact]
public void TestBrokenString()
{
bool hasException = false;
try
{
const string bytes = "30 39 02 01 01 04 06 70 75 62 6C 69 63 A7 2C 02 01 01 02 01 00 02 01 00 30 21 30 0D 06 08 2B 06 01 02 01 01";
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, new UserRegistry());
Assert.Equal(1, messages.Count);
}
catch (Exception)
{
hasException = true;
}
Assert.True(hasException);
}
[Fact]
public void TestDiscovery()
{
const string bytes = "30 3A 02 01 03 30 0F 02 02 6A 09 02 03 00 FF E3" +
"04 01 04 02 01 03 04 10 30 0E 04 00 02 01 00 02" +
"01 00 04 00 04 00 04 00 30 12 04 00 04 00 A0 0C" +
"02 02 2C 6B 02 01 00 02 01 00 30 00";
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, new UserRegistry());
Assert.Equal(1, messages.Count);
Assert.Equal(OctetString.Empty, messages[0].Parameters.UserName);
}
[Fact]
public void TestGetV3()
{
const string bytes = "30 68 02 01 03 30 0F 02 02 6A 08 02 03 00 FF E3" +
"04 01 04 02 01 03 04 23 30 21 04 0D 80 00 1F 88" +
"80 E9 63 00 00 D6 1F F4 49 02 01 05 02 02 0F 1B" +
"04 05 6C 65 78 74 6D 04 00 04 00 30 2D 04 0D 80" +
"00 1F 88 80 E9 63 00 00 D6 1F F4 49 04 00 A0 1A" +
"02 02 2C 6A 02 01 00 02 01 00 30 0E 30 0C 06 08" +
"2B 06 01 02 01 01 03 00 05 00";
UserRegistry registry = new UserRegistry();
registry.Add(new OctetString("lextm"), DefaultPrivacyProvider.DefaultPair);
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
GetRequestMessage get = (GetRequestMessage)messages[0];
Assert.Equal(27144, get.MessageId());
//Assert.Equal(SecurityLevel.None | SecurityLevel.Reportable, get.Level);
Assert.Equal("lextm", get.Community().ToString());
}
#if !NETSTANDARD
[Fact]
public void TestGetRequestV3AuthPriv()
{
const string bytes = "30 81 80 02 01 03 30 0F 02 02 6C 99 02 03 00 FF" +
"E3 04 01 07 02 01 03 04 38 30 36 04 0D 80 00 1F" +
"88 80 E9 63 00 00 D6 1F F4 49 02 01 14 02 01 35" +
"04 07 6C 65 78 6D 61 72 6B 04 0C 80 50 D9 A1 E7" +
"81 B6 19 80 4F 06 C0 04 08 00 00 00 01 44 2C A3" +
"B5 04 30 4B 4F 10 3B 73 E1 E4 BD 91 32 1B CB 41" +
"1B A1 C1 D1 1D 2D B7 84 16 CA 41 BF B3 62 83 C4" +
"29 C5 A4 BC 32 DA 2E C7 65 A5 3D 71 06 3C 5B 56" +
"FB 04 A4";
MD5AuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString("testpass"));
var registry = new UserRegistry();
registry.Add(new OctetString("lexmark"), new DefaultPrivacyProvider(auth));
var messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
Assert.Equal(SnmpType.Unknown, messages[0].TypeCode());
//registry.Add(new OctetString("lexmark"),
// new DESPrivacyProvider(
// new OctetString("veryverylonglongago"),
// auth));
//Assert.Throws<SnmpException>(() => MessageFactory.ParseMessages(bytes, registry));
registry.Add(new OctetString("lexmark"), new DESPrivacyProvider(new OctetString("passtest"), auth));
messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
GetRequestMessage get = (GetRequestMessage)messages[0];
Assert.Equal(27801, get.MessageId());
//Assert.Equal(SecurityLevel.None | SecurityLevel.Reportable, get.Level);
Assert.Equal("lexmark", get.Community().ToString());
//OctetString digest = new MD5AuthenticationProvider(new OctetString("testpass")).ComputeHash(get);
//Assert.Equal(digest, get.Parameters.AuthenticationParameters);
}
#endif
[Fact]
public void TestGetRequestV3Auth()
{
const string bytes = "30 73" +
"02 01 03 " +
"30 0F " +
"02 02 35 41 " +
"02 03 00 FF E3" +
"04 01 05" +
"02 01 03" +
"04 2E " +
"30 2C" +
"04 0D 80 00 1F 88 80 E9 63 00 00 D6 1F F4 49 " +
"02 01 0D " +
"02 01 57 " +
"04 05 6C 65 78 6C 69 " +
"04 0C 1C 6D 67 BF B2 38 ED 63 DF 0A 05 24 " +
"04 00 " +
"30 2D " +
"04 0D 80 00 1F 88 80 E9 63 00 00 D6 1F F4 49 " +
"04 00 " +
"A0 1A 02 02 01 AF 02 01 00 02 01 00 30 0E 30 0C 06 08 2B 06 01 02 01 01 03 00 05 00";
UserRegistry registry = new UserRegistry();
registry.Add(new OctetString("lexli"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("testpass"))));
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
GetRequestMessage get = (GetRequestMessage)messages[0];
Assert.Equal(13633, get.MessageId());
//Assert.Equal(SecurityLevel.None | SecurityLevel.Reportable, get.Level);
Assert.Equal("lexli", get.Community().ToString());
//OctetString digest = new MD5AuthenticationProvider(new OctetString("testpass")).ComputeHash(get);
//Assert.Equal(digest, get.Parameters.AuthenticationParameters);
}
#if !NETSTANDARD
[Fact]
public void TestResponseV1()
{
ISnmpMessage message = MessageFactory.ParseMessages(Properties.Resources.getresponse, new UserRegistry())[0];
Assert.Equal(SnmpType.ResponsePdu, message.TypeCode());
ISnmpPdu pdu = message.Pdu();
Assert.Equal(SnmpType.ResponsePdu, pdu.TypeCode);
ResponsePdu response = (ResponsePdu)pdu;
Assert.Equal(Integer32.Zero, response.ErrorStatus);
Assert.Equal(0, response.ErrorIndex.ToInt32());
Assert.Equal(1, response.Variables.Count);
Variable v = response.Variables[0];
Assert.Equal(new uint[] { 1, 3, 6, 1, 2, 1, 1, 6, 0 }, v.Id.ToNumerical());
Assert.Equal("Shanghai", v.Data.ToString());
}
#endif
[Fact]
public void TestGetResponseV3Error()
{
// TODO: make use of this test case.
const string bytes = "30 77 02 01 03 30 11 02 04 1A AE F6 91 02 03 00" +
"FF E3 04 01 04 02 01 03 04 29 30 27 04 0F 04 0D" +
"80 00 1F 88 80 E9 63 00 00 D6 1F F4 49 02 01 00" +
"02 04 01 5C DE E9 04 07 6E 65 69 74 68 65 72 04" +
"00 04 00 30 34 04 0F 04 0D 80 00 1F 88 80 E9 63" +
"00 00 D6 1F F4 49 04 00 A2 1F 02 04 1A AE F6 9E" +
"02 01 00 02 01 00 30 11 30 0F 06 08 2B 06 01 02" +
"01 01 02 00 06 03 2B 06 01";
UserRegistry registry = new UserRegistry();
registry.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
ISnmpMessage message = messages[0];
Assert.Equal("040D80001F8880E9630000D61FF449", message.Parameters.EngineId.ToHexString());
Assert.Equal(0, message.Parameters.EngineBoots.ToInt32());
Assert.Equal(22863593, message.Parameters.EngineTime.ToInt32());
Assert.Equal("neither", message.Parameters.UserName.ToString());
Assert.Equal("", message.Parameters.AuthenticationParameters.ToHexString());
Assert.Equal("", message.Parameters.PrivacyParameters.ToHexString());
Assert.Equal("040D80001F8880E9630000D61FF449", message.Scope.ContextEngineId.ToHexString());
Assert.Equal("", message.Scope.ContextName.ToHexString());
}
[Fact]
public void TestException()
{
Assert.Throws<ArgumentNullException>(() => MessageFactory.ParseMessages((byte[])null, null));
Assert.Throws<ArgumentNullException>(() => MessageFactory.ParseMessages(new byte[0], null));
Assert.Throws<ArgumentNullException>(() => MessageFactory.ParseMessages((string)null, null));
Assert.Throws<ArgumentNullException>(() => MessageFactory.ParseMessages(string.Empty, null));
Assert.Throws<ArgumentNullException>(() => MessageFactory.ParseMessages(null, 0, 0, null));
Assert.Throws<ArgumentNullException>(() => MessageFactory.ParseMessages(new byte[0], 0, 0, null));
}
[Fact]
public void TestGetResponseV3()
{
const string bytes = "30 6B 02 01 03 30 0F 02 02 6A 08 02 03 00 FF E3" +
"04 01 00 02 01 03 04 23 30 21 04 0D 80 00 1F 88" +
"80 E9 63 00 00 D6 1F F4 49 02 01 05 02 02 0F 1C" +
"04 05 6C 65 78 74 6D 04 00 04 00 30 30 04 0D 80" +
"00 1F 88 80 E9 63 00 00 D6 1F F4 49 04 00 A2 1D" +
"02 02 2C 6A 02 01 00 02 01 00 30 11 30 0F 06 08" +
"2B 06 01 02 01 01 03 00 43 03 05 E7 14";
UserRegistry registry = new UserRegistry();
var messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
Assert.Equal(SnmpType.Unknown, messages[0].TypeCode());
registry.Add(new OctetString("lextm"), DefaultPrivacyProvider.DefaultPair);
messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
ISnmpMessage message = messages[0];
Assert.Equal("80001F8880E9630000D61FF449", message.Parameters.EngineId.ToHexString());
Assert.Equal(5, message.Parameters.EngineBoots.ToInt32());
Assert.Equal(3868, message.Parameters.EngineTime.ToInt32());
Assert.Equal("lextm", message.Parameters.UserName.ToString());
Assert.Equal("", message.Parameters.AuthenticationParameters.ToHexString());
Assert.Equal("", message.Parameters.PrivacyParameters.ToHexString());
Assert.Equal("80001F8880E9630000D61FF449", message.Scope.ContextEngineId.ToHexString());
Assert.Equal("", message.Scope.ContextName.ToHexString());
}
[Fact]
public void TestDiscoveryResponse()
{
const string bytes = "30 66 02 01 03 30 0F 02 02 6A 09 02 03 00 FF E3" +
"04 01 00 02 01 03 04 1E 30 1C 04 0D 80 00 1F 88" +
"80 E9 63 00 00 D6 1F F4 49 02 01 05 02 02 0F 1B" +
"04 00 04 00 04 00 30 30 04 0D 80 00 1F 88 80 E9" +
"63 00 00 D6 1F F4 49 04 00 A8 1D 02 02 2C 6B 02" +
"01 00 02 01 00 30 11 30 0F 06 0A 2B 06 01 06 03" +
"0F 01 01 04 00 41 01 03";
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, new UserRegistry());
Assert.Equal(1, messages.Count);
Assert.Equal(5, messages[0].Parameters.EngineBoots.ToInt32());
Assert.Equal("80001F8880E9630000D61FF449", messages[0].Parameters.EngineId.ToHexString());
Assert.Equal(3867, messages[0].Parameters.EngineTime.ToInt32());
Assert.Equal(ErrorCode.NoError, messages[0].Pdu().ErrorStatus.ToErrorCode());
Assert.Equal(1, messages[0].Pdu().Variables.Count);
Variable v = messages[0].Pdu().Variables[0];
Assert.Equal(".1.3.6.1.6.3.15.1.1.4.0", v.Id.ToString());
ISnmpData data = v.Data;
Assert.Equal(SnmpType.Counter32, data.TypeCode);
Assert.Equal(3U, ((Counter32)data).ToUInt32());
Assert.Equal("80001F8880E9630000D61FF449", messages[0].Scope.ContextEngineId.ToHexString());
Assert.Equal("", messages[0].Scope.ContextName.ToHexString());
}
#if !NETSTANDARD
[Fact]
public void TestTrapV3()
{
byte[] bytes = Properties.Resources.trapv3;
UserRegistry registry = new UserRegistry();
registry.Add(new OctetString("lextm"), DefaultPrivacyProvider.DefaultPair);
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
ISnmpMessage message = messages[0];
Assert.Equal("80001F8880E9630000D61FF449", message.Parameters.EngineId.ToHexString());
Assert.Equal(0, message.Parameters.EngineBoots.ToInt32());
Assert.Equal(0, message.Parameters.EngineTime.ToInt32());
Assert.Equal("lextm", message.Parameters.UserName.ToString());
Assert.Equal("", message.Parameters.AuthenticationParameters.ToHexString());
Assert.Equal("", message.Parameters.PrivacyParameters.ToHexString());
Assert.Equal("", message.Scope.ContextEngineId.ToHexString()); // SNMP#NET returns string.Empty here.
Assert.Equal("", message.Scope.ContextName.ToHexString());
Assert.Equal(528732060, message.MessageId());
Assert.Equal(1905687779, message.RequestId());
Assert.Equal(".1.3.6", ((TrapV2Message)message).Enterprise.ToString());
}
[Fact]
public void TestTrapV3Auth()
{
byte[] bytes = Properties.Resources.trapv3auth;
UserRegistry registry = new UserRegistry();
registry.Add(new OctetString("lextm"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
ISnmpMessage message = messages[0];
Assert.Equal("80001F8880E9630000D61FF449", message.Parameters.EngineId.ToHexString());
Assert.Equal(0, message.Parameters.EngineBoots.ToInt32());
Assert.Equal(0, message.Parameters.EngineTime.ToInt32());
Assert.Equal("lextm", message.Parameters.UserName.ToString());
Assert.Equal("84433969457707152C289A3E", message.Parameters.AuthenticationParameters.ToHexString());
Assert.Equal("", message.Parameters.PrivacyParameters.ToHexString());
Assert.Equal("", message.Scope.ContextEngineId.ToHexString()); // SNMP#NET returns string.Empty here.
Assert.Equal("", message.Scope.ContextName.ToHexString());
Assert.Equal(318463383, message.MessageId());
Assert.Equal(1276263065, message.RequestId());
}
[Fact]
public void TestTrapV3AuthBytes()
{
byte[] bytes = Properties.Resources.v3authNoPriv_BER_Issue;
UserRegistry registry = new UserRegistry();
SHA1AuthenticationProvider authen = new SHA1AuthenticationProvider(new OctetString("testpass"));
registry.Add(new OctetString("test"), new DefaultPrivacyProvider(authen));
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
ISnmpMessage message = messages[0];
Assert.Equal("80001299030005B706CF69", message.Parameters.EngineId.ToHexString());
Assert.Equal(41, message.Parameters.EngineBoots.ToInt32());
Assert.Equal(877, message.Parameters.EngineTime.ToInt32());
Assert.Equal("test", message.Parameters.UserName.ToString());
Assert.Equal("C107F9DAA3FC552960E38936", message.Parameters.AuthenticationParameters.ToHexString());
Assert.Equal("", message.Parameters.PrivacyParameters.ToHexString());
Assert.Equal("80001299030005B706CF69", message.Scope.ContextEngineId.ToHexString()); // SNMP#NET returns string.Empty here.
Assert.Equal("", message.Scope.ContextName.ToHexString());
Assert.Equal(681323585, message.MessageId());
Assert.Equal(681323584, message.RequestId());
Assert.Equal(bytes, message.ToBytes());
}
[Fact]
public void TestTrapV3AuthPriv()
{
// The message body generated by snmp#net is problematic.
byte[] bytes = Properties.Resources.trapv3authpriv;
UserRegistry registry = new UserRegistry();
registry.Add(new OctetString("lextm"), new DESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
Assert.Equal(1, messages.Count);
ISnmpMessage message = messages[0];
Assert.Equal("80001F8880E9630000D61FF449", message.Parameters.EngineId.ToHexString());
Assert.Equal(0, message.Parameters.EngineBoots.ToInt32());
Assert.Equal(0, message.Parameters.EngineTime.ToInt32());
Assert.Equal("lextm", message.Parameters.UserName.ToString());
Assert.Equal("89D351891A55829243617F2C", message.Parameters.AuthenticationParameters.ToHexString());
Assert.Equal("0000000069D39B2A", message.Parameters.PrivacyParameters.ToHexString());
Assert.Equal("", message.Scope.ContextEngineId.ToHexString()); // SNMP#NET returns string.Empty here.
Assert.Equal("", message.Scope.ContextName.ToHexString());
Assert.Equal(0, message.Scope.Pdu.Variables.Count);
Assert.Equal(1004947569, message.MessageId());
Assert.Equal(234419641, message.RequestId());
}
#endif
[Fact]
public void TestBadResponseFromPrinter()
{
// #7241
var data = "30 2B 02 01 00 04 06 70 75 62 6C 69 63 A2 1E 02 04 32 FA 7A 02 02 01 00 02 01 00 30 10 30 0E 06 0A 2B 06 01 02 01 02 02 01 16 01 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";
var bytes = ByteTool.Convert(data);
var exception = Assert.Throws<SnmpException>(() => MessageFactory.ParseMessages(bytes, new UserRegistry()));
Assert.Equal(string.Format("length cannot be 0{0}Parameter name: length", Environment.NewLine), exception.InnerException.Message);
}
}
}
#pragma warning restore 1591, 0618
| 112.9447 | 24,601 | 0.622832 | [
"MIT"
] | AwsomeCode/sharpsnmplib | Tests/Messaging/Tests/MessageFactoryTestFixture.cs | 49,018 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("2020052101CS_7zip")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("2020052101CS_7zip")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("58b0e081-4720-4b1d-8679-335e48ab7b7a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.891892 | 84 | 0.749643 | [
"MIT"
] | AungWinnHtut/POL | C#/2020052101CS_7zip/Properties/AssemblyInfo.cs | 1,405 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// This C# code was generated by XmlSchemaClassGenerator version 1.0.0.0.
namespace Models.XsdConvert.genericRailML
{
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
[System.CodeDom.Compiler.GeneratedCodeAttribute("XmlSchemaClassGenerator", "1.0.0.0")]
internal partial interface IAEpsgCode
{
string Default
{
get;
set;
}
string ExtraHeight
{
get;
set;
}
}
}
| 26.527778 | 90 | 0.504712 | [
"Apache-2.0"
] | LightosLimited/RailML | v3.1/Models/XsdConvert/genericRailML/IAEpsgCode.cs | 955 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AdaptiveCards;
using Luis;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Choices;
using Microsoft.Bot.Builder.Solutions.Authentication;
using Microsoft.Bot.Builder.Solutions.Extensions;
using Microsoft.Bot.Builder.Solutions.Prompts;
using Microsoft.Bot.Builder.Solutions.Resources;
using Microsoft.Bot.Builder.Solutions.Responses;
using Microsoft.Bot.Builder.Solutions.Skills;
using Microsoft.Bot.Builder.Solutions.Telemetry;
using Microsoft.Bot.Builder.Solutions.Util;
using Microsoft.Bot.Schema;
using Microsoft.Recognizers.Text;
using Newtonsoft.Json.Linq;
using ToDoSkill.Dialogs.AddToDo.Resources;
using ToDoSkill.Dialogs.DeleteToDo.Resources;
using ToDoSkill.Dialogs.MarkToDo.Resources;
using ToDoSkill.Dialogs.Shared.Cards;
using ToDoSkill.Dialogs.Shared.DialogOptions;
using ToDoSkill.Dialogs.Shared.Resources;
using ToDoSkill.Dialogs.ShowToDo.Resources;
using ToDoSkill.Models;
using ToDoSkill.ServiceClients;
using static ToDoSkill.Dialogs.Shared.ServiceProviderTypes;
namespace ToDoSkill.Dialogs.Shared
{
public class ToDoSkillDialog : ComponentDialog
{
// Constants
public const string SkillModeAuth = "SkillAuth";
public ToDoSkillDialog(
string dialogId,
SkillConfigurationBase services,
ResponseManager responseManager,
IStatePropertyAccessor<ToDoSkillState> toDoStateAccessor,
IStatePropertyAccessor<ToDoSkillUserState> userStateAccessor,
IServiceManager serviceManager,
IBotTelemetryClient telemetryClient)
: base(dialogId)
{
Services = services;
ResponseManager = responseManager;
ToDoStateAccessor = toDoStateAccessor;
UserStateAccessor = userStateAccessor;
ServiceManager = serviceManager;
TelemetryClient = telemetryClient;
if (!Services.AuthenticationConnections.Any())
{
throw new Exception("You must configure an authentication connection in your bot file before using this component.");
}
AddDialog(new EventPrompt(SkillModeAuth, "tokens/response", TokenResponseValidator));
AddDialog(new MultiProviderAuthDialog(services));
AddDialog(new TextPrompt(Action.Prompt));
AddDialog(new ConfirmPrompt(Action.ConfirmPrompt, null, Culture.English) { Style = ListStyle.SuggestedAction });
}
protected SkillConfigurationBase Services { get; set; }
protected IStatePropertyAccessor<ToDoSkillState> ToDoStateAccessor { get; set; }
protected IStatePropertyAccessor<ToDoSkillUserState> UserStateAccessor { get; set; }
protected IServiceManager ServiceManager { get; set; }
protected ResponseManager ResponseManager { get; set; }
protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext dc, object options, CancellationToken cancellationToken = default(CancellationToken))
{
await DigestToDoLuisResult(dc);
return await base.OnBeginDialogAsync(dc, options, cancellationToken);
}
protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
{
await DigestToDoLuisResult(dc);
return await base.OnContinueDialogAsync(dc, cancellationToken);
}
protected override Task<DialogTurnResult> EndComponentAsync(DialogContext outerDc, object result, CancellationToken cancellationToken)
{
var resultString = result?.ToString();
if (!string.IsNullOrWhiteSpace(resultString) && resultString.Equals(CommonUtil.DialogTurnResultCancelAllDialogs, StringComparison.InvariantCultureIgnoreCase))
{
return outerDc.CancelAllDialogsAsync();
}
else
{
return base.EndComponentAsync(outerDc, result, cancellationToken);
}
}
// Shared steps
protected async Task<DialogTurnResult> GetAuthToken(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var skillOptions = (ToDoSkillDialogOptions)sc.Options;
// If in Skill mode we ask the calling Bot for the token
if (skillOptions != null && skillOptions.SkillMode)
{
// We trigger a Token Request from the Parent Bot by sending a "TokenRequest" event back and then waiting for a "TokenResponse"
// TODO Error handling - if we get a new activity that isn't an event
var response = sc.Context.Activity.CreateReply();
response.Type = ActivityTypes.Event;
response.Name = "tokens/request";
// Send the tokens/request Event
await sc.Context.SendActivityAsync(response);
// Wait for the tokens/response event
return await sc.PromptAsync(SkillModeAuth, new PromptOptions());
}
else
{
return await sc.PromptAsync(nameof(MultiProviderAuthDialog), new PromptOptions() { RetryPrompt = ResponseManager.GetResponse(ToDoSharedResponses.NoAuth) });
}
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AfterGetAuthToken(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
// When the user authenticates interactively we pass on the tokens/Response event which surfaces as a JObject
// When the token is cached we get a TokenResponse object.
var skillOptions = (ToDoSkillDialogOptions)sc.Options;
ProviderTokenResponse providerTokenResponse;
if (skillOptions != null && skillOptions.SkillMode)
{
var resultType = sc.Context.Activity.Value.GetType();
if (resultType == typeof(ProviderTokenResponse))
{
providerTokenResponse = sc.Context.Activity.Value as ProviderTokenResponse;
}
else
{
var tokenResponseObject = sc.Context.Activity.Value as JObject;
providerTokenResponse = tokenResponseObject?.ToObject<ProviderTokenResponse>();
}
}
else
{
providerTokenResponse = sc.Result as ProviderTokenResponse;
}
if (providerTokenResponse != null)
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
state.MsGraphToken = providerTokenResponse.TokenResponse.Token;
}
return await sc.NextAsync();
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> ClearContext(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
var topIntent = state.LuisResult?.TopIntent().intent;
var generalTopIntent = state.GeneralLuisResult?.TopIntent().intent;
if (topIntent == ToDoLU.Intent.ShowToDo)
{
state.ShowTaskPageIndex = 0;
state.Tasks = new List<TaskItem>();
state.AllTasks = new List<TaskItem>();
state.ListType = null;
state.GoBackToStart = false;
await DigestToDoLuisResult(sc);
}
else if (topIntent == ToDoLU.Intent.ShowNextPage || generalTopIntent == General.Intent.ShowNext)
{
state.IsLastPage = false;
if ((state.ShowTaskPageIndex + 1) * state.PageSize < state.AllTasks.Count)
{
state.ShowTaskPageIndex++;
}
else
{
state.IsLastPage = true;
}
}
else if (topIntent == ToDoLU.Intent.ShowPreviousPage || generalTopIntent == General.Intent.ShowPrevious)
{
state.IsFirstPage = false;
if (state.ShowTaskPageIndex > 0)
{
state.ShowTaskPageIndex--;
}
else
{
state.IsFirstPage = true;
}
}
else if (topIntent == ToDoLU.Intent.AddToDo)
{
state.TaskContentPattern = null;
state.TaskContentML = null;
state.TaskContent = null;
state.FoodOfGrocery = null;
state.ShopContent = null;
state.HasShopVerb = false;
state.ListType = null;
await DigestToDoLuisResult(sc);
}
else if (topIntent == ToDoLU.Intent.MarkToDo || topIntent == ToDoLU.Intent.DeleteToDo)
{
state.TaskIndexes = new List<int>();
state.MarkOrDeleteAllTasksFlag = false;
state.TaskContentPattern = null;
state.TaskContentML = null;
state.TaskContent = null;
state.CollectIndexRetry = false;
await DigestToDoLuisResult(sc);
}
return await sc.NextAsync();
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> InitAllTasks(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
// LastListType is used to switch between list types in DeleteToDoItemDialog and MarkToDoItemDialog.
if (!state.ListTypeIds.ContainsKey(state.ListType)
|| state.ListType != state.LastListType)
{
var service = await InitListTypeIds(sc);
state.AllTasks = await service.GetTasksAsync(state.ListType);
state.ShowTaskPageIndex = 0;
var rangeCount = Math.Min(state.PageSize, state.AllTasks.Count);
state.Tasks = state.AllTasks.GetRange(0, rangeCount);
}
if (state.AllTasks.Count <= 0)
{
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.NoTasksInList));
return await sc.EndDialogAsync(true);
}
else
{
return await sc.NextAsync();
}
}
catch (SkillException ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
// Validators
protected Task<bool> TokenResponseValidator(PromptValidatorContext<Activity> pc, CancellationToken cancellationToken)
{
var activity = pc.Recognized.Value;
if (activity != null && activity.Type == ActivityTypes.Event)
{
return Task.FromResult(true);
}
else
{
return Task.FromResult(false);
}
}
protected Task<bool> AuthPromptValidator(PromptValidatorContext<TokenResponse> promptContext, CancellationToken cancellationToken)
{
var token = promptContext.Recognized.Value;
if (token != null)
{
return Task.FromResult(true);
}
else
{
return Task.FromResult(false);
}
}
// Helpers
protected async Task DigestToDoLuisResult(DialogContext dc)
{
try
{
var state = await ToDoStateAccessor.GetAsync(dc.Context);
var luisResult = state.LuisResult;
var entities = luisResult.Entities;
if (entities.ContainsAll != null)
{
state.MarkOrDeleteAllTasksFlag = true;
}
if (entities.ordinal != null || entities.number != null)
{
var indexOfOrdinal = entities.ordinal == null ? 0 : (int)entities.ordinal[0];
var indexOfNumber = entities.number == null ? 0 : (int)entities.number[0];
var index = 0;
if (indexOfOrdinal > 0 && indexOfOrdinal <= state.PageSize)
{
index = indexOfOrdinal;
}
else if (indexOfNumber > 0 && indexOfNumber <= state.PageSize)
{
index = indexOfNumber;
}
if (index > 0 && index <= state.PageSize)
{
if (state.TaskIndexes.Count > 0)
{
state.TaskIndexes[0] = index - 1;
}
else
{
state.TaskIndexes.Add(index - 1);
}
}
}
if (entities.ListType != null)
{
if (ToDoStrings.GrocerySynonym.Contains(entities.ListType[0], StringComparison.InvariantCultureIgnoreCase))
{
state.ListType = ToDoStrings.Grocery;
}
else if (ToDoStrings.ShoppingSynonym.Contains(entities.ListType[0], StringComparison.InvariantCultureIgnoreCase))
{
state.ListType = ToDoStrings.Shopping;
}
else
{
state.ListType = ToDoStrings.ToDo;
}
}
if (entities.FoodOfGrocery != null)
{
state.FoodOfGrocery = entities.FoodOfGrocery[0][0];
}
if (entities.ShopVerb != null && (entities.ShopContent != null || entities.FoodOfGrocery != null))
{
state.HasShopVerb = true;
}
if (entities.ShopContent != null)
{
state.ShopContent = entities.ShopContent[0];
}
if (entities.TaskContentPattern != null)
{
state.TaskContentPattern = entities.TaskContentPattern[0];
}
if (entities.TaskContentML != null)
{
state.TaskContentML = entities.TaskContentML[0];
}
}
catch
{
// ToDo
}
}
protected Activity ToAdaptiveCardForShowToDos(
List<TaskItem> todos,
int allTasksCount,
string listType)
{
var cardReply = BuildTodoCard(null, todos, allTasksCount, listType);
ResponseTemplate response;
var speakText = string.Empty;
var showText = string.Empty;
if (allTasksCount <= todos.Count)
{
if (todos.Count == 1)
{
response = ResponseManager.GetResponseTemplate(ShowToDoResponses.LatestTask);
speakText = response.Reply.Speak;
}
else if (todos.Count >= 2)
{
response = ResponseManager.GetResponseTemplate(ShowToDoResponses.LatestTasks);
speakText = response.Reply.Speak;
}
}
else
{
if (todos.Count == 1)
{
response = ResponseManager.GetResponseTemplate(ToDoSharedResponses.CardSummaryMessageForSingleTask);
}
else
{
response = ResponseManager.GetResponseTemplate(ToDoSharedResponses.CardSummaryMessageForMultipleTasks);
}
speakText = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "taskCount", allTasksCount.ToString() }, { "listType", listType } });
showText = speakText;
response = ResponseManager.GetResponseTemplate(ShowToDoResponses.MostRecentTasks);
var mostRecentTasksString = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "taskCount", todos.Count.ToString() } });
speakText += mostRecentTasksString;
}
speakText += todos.ToSpeechString(CommonStrings.And, li => li.Topic);
cardReply.Speak = speakText;
cardReply.Text = showText;
return cardReply;
}
protected Activity ToAdaptiveCardForReadMore(
List<TaskItem> todos,
int allTasksCount,
string listType)
{
var cardReply = BuildTodoCard(null, todos, allTasksCount, listType);
// Build up speach
var speakText = string.Empty;
var response = new ResponseTemplate();
if (todos.Count == 1)
{
response = ResponseManager.GetResponseTemplate(ShowToDoResponses.NextTask);
speakText = response.Reply.Speak;
}
else if (todos.Count >= 2)
{
response = ResponseManager.GetResponseTemplate(ShowToDoResponses.NextTasks);
speakText = response.Reply.Speak;
}
speakText += todos.ToSpeechString(CommonStrings.And, li => li.Topic);
cardReply.Speak = speakText;
return cardReply;
}
protected Activity ToAdaptiveCardForPreviousPage(
List<TaskItem> todos,
int allTasksCount,
bool isFirstPage,
string listType)
{
var cardReply = BuildTodoCard(ToDoSharedResponses.CardSummaryMessageForMultipleTasks, todos, allTasksCount, listType);
var response = ResponseManager.GetResponseTemplate(ShowToDoResponses.PreviousTasks);
var speakText = response.Reply.Speak;
if (isFirstPage)
{
if (todos.Count == 1)
{
response = ResponseManager.GetResponseTemplate(ShowToDoResponses.PreviousFirstSingleTask);
}
else
{
response = ResponseManager.GetResponseTemplate(ShowToDoResponses.PreviousFirstTasks);
}
speakText = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "taskCount", todos.Count.ToString() } });
}
speakText += todos.ToSpeechString(CommonStrings.And, li => li.Topic);
cardReply.Speak = speakText;
return cardReply;
}
protected Activity ToAdaptiveCardForTaskAddedFlow(
List<TaskItem> todos,
string taskContent,
int allTasksCount,
string listType)
{
var cardReply = BuildTodoCard(null, todos, allTasksCount, listType);
var response = ResponseManager.GetResponseTemplate(AddToDoResponses.AfterTaskAdded);
cardReply.Text = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "taskContent", taskContent }, { "listType", listType } });
cardReply.Speak = cardReply.Text;
return cardReply;
}
protected Activity ToAdaptiveCardForTaskCompletedFlow(
List<TaskItem> todos,
int allTasksCount,
string taskContent,
string listType,
bool isCompleteAll)
{
var cardReply = BuildTodoCard(null, todos, allTasksCount, listType);
var response = new ResponseTemplate();
if (isCompleteAll)
{
response = ResponseManager.GetResponseTemplate(MarkToDoResponses.AfterAllTasksCompleted);
cardReply.Speak = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "listType", listType } });
}
else
{
response = ResponseManager.GetResponseTemplate(MarkToDoResponses.AfterTaskCompleted);
cardReply.Speak = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "taskContent", taskContent }, { "listType", listType } });
}
if (allTasksCount == 1)
{
response = ResponseManager.GetResponseTemplate(ToDoSharedResponses.CardSummaryMessageForSingleTask);
}
else
{
response = ResponseManager.GetResponseTemplate(ToDoSharedResponses.CardSummaryMessageForMultipleTasks);
}
var showText = ResponseManager.Format(response.Reply.Text, new StringDictionary() { { "taskCount", allTasksCount.ToString() }, { "listType", listType } });
cardReply.Text = showText;
return cardReply;
}
protected Activity ToAdaptiveCardForTaskDeletedFlow(
List<TaskItem> todos,
int allTasksCount,
string taskContent,
string listType,
bool isDeleteAll)
{
var cardReply = BuildTodoCard(null, todos, allTasksCount, listType);
var response = new ResponseTemplate();
if (isDeleteAll)
{
response = ResponseManager.GetResponseTemplate(DeleteToDoResponses.AfterAllTasksDeleted);
cardReply.Speak = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "listType", listType } });
}
else
{
response = ResponseManager.GetResponseTemplate(DeleteToDoResponses.AfterTaskDeleted);
cardReply.Speak = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "taskContent", taskContent }, { "listType", listType } });
}
cardReply.Text = cardReply.Speak;
return cardReply;
}
protected Activity ToAdaptiveCardForDeletionRefusedFlow(
List<TaskItem> todos,
int allTasksCount,
string listType)
{
var cardReply = BuildTodoCard(null, todos, allTasksCount, listType);
var response = ResponseManager.GetResponseTemplate(DeleteToDoResponses.DeletionAllConfirmationRefused);
cardReply.Speak = ResponseManager.Format(response.Reply.Speak, new StringDictionary() { { "taskCount", allTasksCount.ToString() }, { "listType", listType } });
cardReply.Text = cardReply.Speak;
return cardReply;
}
private Activity BuildTodoCard(
string tempId,
List<TaskItem> todos,
int allTasksCount,
string listType)
{
var tokens = new StringDictionary()
{
{ "taskCount", allTasksCount.ToString() },
{ "listType", listType },
};
var showTodoListData = new TodoListData
{
Title = string.Format(ToDoStrings.CardTitle, listType),
TotalNumber = allTasksCount > 1 ? string.Format(ToDoStrings.CardMultiNumber, allTasksCount.ToString()) : string.Format(ToDoStrings.CardOneNumber, allTasksCount.ToString())
};
List<Card> todoItems = new List<Card>();
int index = 0;
foreach (var todo in todos)
{
todoItems.Add(new Card("ShowTodoItem", new TodoItemData
{
CheckIconUrl = todo.IsCompleted ? IconImageSource.CheckIconSource : IconImageSource.UncheckIconSource,
Topic = todo.Topic
}));
index++;
}
var cardReply = ResponseManager.GetCardResponse(
tempId,
new Card("ShowTodoCard", showTodoListData),
tokens,
"items",
todoItems);
return cardReply;
}
// This method is called by any waterfall step that throws an exception to ensure consistency
protected async Task HandleDialogExceptions(WaterfallStepContext sc, Exception ex)
{
// send trace back to emulator
var trace = new Activity(type: ActivityTypes.Trace, text: $"DialogException: {ex.Message}, StackTrace: {ex.StackTrace}");
await sc.Context.SendActivityAsync(trace);
// log exception
TelemetryClient.TrackExceptionEx(ex, sc.Context.Activity, sc.ActiveDialog?.Id);
// send error message to bot user
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.ToDoErrorMessage));
// clear state
var state = await ToDoStateAccessor.GetAsync(sc.Context);
state.Clear();
}
// This method is called by any waterfall step that throws a SkillException to ensure consistency
protected async Task HandleDialogExceptions(WaterfallStepContext sc, SkillException ex)
{
// send trace back to emulator
var trace = new Activity(type: ActivityTypes.Trace, text: $"DialogException: {ex.Message}, StackTrace: {ex.StackTrace}");
await sc.Context.SendActivityAsync(trace);
// log exception
TelemetryClient.TrackExceptionEx(ex, sc.Context.Activity, sc.ActiveDialog?.Id);
// send error message to bot user
if (ex.ExceptionType == SkillExceptionType.APIAccessDenied)
{
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.ToDoErrorMessageBotProblem));
}
else if (ex.ExceptionType == SkillExceptionType.AccountNotActivated)
{
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.ToDoErrorMessageAccountProblem));
}
else
{
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.ToDoErrorMessage));
}
// clear state
var state = await ToDoStateAccessor.GetAsync(sc.Context);
state.Clear();
}
protected async Task<ITaskService> InitListTypeIds(WaterfallStepContext sc)
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
if (!state.ListTypeIds.ContainsKey(state.ListType))
{
var emailService = ServiceManager.InitMailService(state.MsGraphToken);
var senderMailAddress = await emailService.GetSenderMailAddressAsync();
state.UserStateId = senderMailAddress;
var recovered = await RecoverListTypeIdsAsync(sc);
if (!recovered)
{
var taskServiceInit = ServiceManager.InitTaskService(state.MsGraphToken, state.ListTypeIds, state.TaskServiceType);
if (taskServiceInit.IsListCreated)
{
if (state.TaskServiceType == ProviderTypes.OneNote)
{
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.SettingUpOneNoteMessage));
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.AfterOneNoteSetupMessage));
}
else
{
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.SettingUpOutlookMessage));
await sc.Context.SendActivityAsync(ResponseManager.GetResponse(ToDoSharedResponses.AfterOutlookSetupMessage));
}
var taskWebLink = await taskServiceInit.GetTaskWebLink();
var emailContent = string.Format(ToDoStrings.EmailContent, taskWebLink, taskWebLink);
await emailService.SendMessageAsync(emailContent, ToDoStrings.EmailSubject);
}
await StoreListTypeIdsAsync(sc);
return taskServiceInit;
}
}
var taskService = ServiceManager.InitTaskService(state.MsGraphToken, state.ListTypeIds, state.TaskServiceType);
await StoreListTypeIdsAsync(sc);
return taskService;
}
private async Task<bool> RecoverListTypeIdsAsync(DialogContext dc)
{
var userState = await UserStateAccessor.GetAsync(dc.Context, () => new ToDoSkillUserState());
var state = await ToDoStateAccessor.GetAsync(dc.Context, () => new ToDoSkillState());
var senderMailAddress = state.UserStateId;
if (userState.ListTypeIds.ContainsKey(senderMailAddress)
&& state.ListTypeIds.Count <= 0
&& userState.ListTypeIds[senderMailAddress].Count > 0)
{
foreach (var listType in userState.ListTypeIds[senderMailAddress])
{
state.ListTypeIds.Add(listType.Key, listType.Value);
}
return true;
}
return false;
}
private async Task StoreListTypeIdsAsync(DialogContext dc)
{
var userState = await UserStateAccessor.GetAsync(dc.Context, () => new ToDoSkillUserState());
var state = await ToDoStateAccessor.GetAsync(dc.Context, () => new ToDoSkillState());
var senderMailAddress = state.UserStateId;
if (!userState.ListTypeIds.ContainsKey(senderMailAddress))
{
userState.ListTypeIds.Add(senderMailAddress, new Dictionary<string, string>());
foreach (var listType in state.ListTypeIds)
{
userState.ListTypeIds[senderMailAddress].Add(listType.Key, listType.Value);
}
}
else
{
foreach (var listType in state.ListTypeIds)
{
if (userState.ListTypeIds[senderMailAddress].ContainsKey(listType.Key))
{
userState.ListTypeIds[senderMailAddress][listType.Key] = listType.Value;
}
else
{
userState.ListTypeIds[senderMailAddress].Add(listType.Key, listType.Value);
}
}
}
}
}
} | 41.926829 | 187 | 0.567374 | [
"MIT"
] | garypretty/AI | solutions/Virtual-Assistant/src/csharp/skills/todoskill/todoskill/Dialogs/Shared/ToDoSkillDialog.cs | 32,663 | C# |
using UnityEngine;
using System.Collections;
[AddComponentMenu("Interactivity-Controls/Input Orbit")]
public class InputOrbit : MonoBehaviour
{
public Transform target;
public float distance = 50.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;
public float ScrollSpeed = 20.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float distanceMin = 5f;
public float distanceMax = 100f;
float x = 0.0f;
float y = 0.0f;
private static float ClampAngle(float angle, float min, float max)
{
if( angle < -360f ) angle += 360f;
if( angle > 360f ) angle -= 360f;
return Mathf.Clamp(angle, min, max);
}
void Start()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
// Make the rigid body not change rotation
if( GetComponent<Rigidbody>() )
GetComponent<Rigidbody>().freezeRotation = true;
}
void LateUpdate()
{
if( target )
{
x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
distance = Mathf.Clamp(distance - Input.GetAxis( "Mouse ScrollWheel" ) * ScrollSpeed, distanceMin, distanceMax );
//Vector3 negDistance = new Vector3( 0.0f, 0.0f, -distance );
//Vector3 position = rotation * negDistance + target.position;
transform.localRotation = rotation;
//transform.position = position;
}
}
} | 26.457627 | 116 | 0.639974 | [
"MIT"
] | communityus-branch/thechase-demo-2013 | Assets/Scripts/Interactivity/InputOrbit.cs | 1,561 | C# |
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: APIKey.tt
// Build date: 2017-10-08
// C# generater version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Cloudresourcemanager v2beta1 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: The Google Cloud Resource Manager API provides methods for creating, reading, and updating project metadata.
// API Documentation Link https://cloud.google.com/resource-manager
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Cloudresourcemanager/v2beta1/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Cloudresourcemanager.v2beta1/
// Install Command: PM> Install-Package Google.Apis.Cloudresourcemanager.v2beta1
//
//------------------------------------------------------------------------------
using Google.Apis.Cloudresourcemanager.v2beta1;
using Google.Apis.Services;
using System;
namespace GoogleSamplecSharpSample.Cloudresourcemanagerv2beta1.Auth
{
/// <summary>
/// When calling APIs that do not access private user data, you can use simple API keys. These keys are used to authenticate your
/// application for accounting purposes. The Google API Console documentation also describes API keys.
/// https://support.google.com/cloud/answer/6158857
/// </summary>
public static class ApiKeyExample
{
/// <summary>
/// Get a valid CloudresourcemanagerService for a public API Key.
/// </summary>
/// <param name="apiKey">API key from Google Developer console</param>
/// <returns>CloudresourcemanagerService</returns>
public static CloudresourcemanagerService GetService(string apiKey)
{
try
{
if (string.IsNullOrEmpty(apiKey))
throw new ArgumentNullException("api Key");
return new CloudresourcemanagerService(new BaseClientService.Initializer()
{
ApiKey = apiKey,
ApplicationName = string.Format("{0} API key example", System.Diagnostics.Process.GetCurrentProcess().ProcessName),
});
}
catch (Exception ex)
{
throw new Exception("Failed to create new Cloudresourcemanager Service", ex);
}
}
}
}
| 45.432099 | 135 | 0.62663 | [
"Apache-2.0"
] | AhmerRaza/Google-Dotnet-Samples | Samples/Google Cloud Resource Manager API/v2beta1/APIKey.cs | 3,682 | C# |
/*
* Copyright (C) Sportradar AG. See LICENSE for full license governing this code
*/
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Sportradar.OddsFeed.SDK.Entities.REST.Enums;
using Sportradar.OddsFeed.SDK.Entities.REST.Internal.Caching.CI;
using Sportradar.OddsFeed.SDK.Messages;
namespace Sportradar.OddsFeed.SDK.Entities.REST.Internal.Caching.Events
{
/// <summary>
/// Defines a contract implemented by classes, which represent cached information about a lottery draw
/// </summary>
internal interface IDrawCI : ISportEventCI
{
/// <summary>
/// Asynchronously gets a <see cref="URN"/> representing id of the associated <see cref="ILotteryCI"/>
/// </summary>
/// <returns>The id of the associated lottery</returns>
Task<URN> GetLotteryIdAsync();
/// <summary>
/// Asynchronously gets <see cref="DrawStatus"/> associated with the current instance
/// </summary>
/// <returns>A <see cref="Task{T}"/> representing an async operation</returns>
Task<DrawStatus> GetStatusAsync();
/// <summary>
/// Asynchronously gets a bool value indicating if the results are in chronological order
/// </summary>
/// <returns>The value indicating if the results are in chronological order</returns>
Task<bool> AreResultsChronologicalAsync();
/// <summary>
/// Asynchronously gets <see cref="IEnumerable{T}"/> list of associated <see cref="DrawResultCI"/>
/// </summary>
/// <param name="cultures">A <see cref="IEnumerable{CultureInfo}"/> specifying the required languages</param>
/// <returns>A <see cref="Task{T}"/> representing an async operation</returns>
Task<IEnumerable<DrawResultCI>> GetResultsAsync(IEnumerable<CultureInfo> cultures);
/// <summary>
/// Gets the display identifier
/// </summary>
/// <value>The display identifier</value>
Task<int?> GetDisplayIdAsync();
}
} | 42 | 117 | 0.663751 | [
"Apache-2.0"
] | Furti87/UnifiedOddsSdkNet | src/Sportradar.OddsFeed.SDK.Entities.REST/Internal/Caching/Events/IDrawCI.cs | 2,060 | C# |
using System;
namespace Org.BouncyCastle.Asn1.Pkcs
{
public class CertBag
: Asn1Encodable
{
public static CertBag GetInstance(object obj)
{
if (obj is CertBag)
return (CertBag)obj;
if (obj == null)
return null;
return new CertBag(Asn1Sequence.GetInstance(obj));
}
private readonly DerObjectIdentifier certID;
private readonly Asn1Object certValue;
[Obsolete("Use 'GetInstance' instead")]
public CertBag(
Asn1Sequence seq)
{
if (seq.Count != 2)
throw new ArgumentException("Wrong number of elements in sequence", "seq");
this.certID = DerObjectIdentifier.GetInstance(seq[0]);
this.certValue = Asn1TaggedObject.GetInstance(seq[1]).GetObject();
}
public CertBag(
DerObjectIdentifier certID,
Asn1Object certValue)
{
this.certID = certID;
this.certValue = certValue;
}
public virtual DerObjectIdentifier CertID
{
get { return certID; }
}
public virtual Asn1Object CertValue
{
get { return certValue; }
}
public override Asn1Object ToAsn1Object()
{
return new DerSequence(certID, new DerTaggedObject(0, certValue));
}
}
}
| 25.127273 | 80 | 0.571635 | [
"MIT"
] | straight-coding/EmbedTools | crypto/src/asn1/pkcs/CertBag.cs | 1,382 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("LinqExam2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LinqExam2")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("c07a3e49-7f77-43de-8ece-078d06f24e9c")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.054054 | 57 | 0.743256 | [
"Apache-2.0"
] | kekyo-workshops/LinqExam2 | LinqExam2/Properties/AssemblyInfo.cs | 1,644 | C# |
using System;
using RazorCart.Core.ActionPipeline;
namespace MyCompany.RazorCart.Integration
{
public class MyPipeline : PipelineManager
{
/// <summary>
/// Register the Pipeline Action List to be executed once an item(s) requested to be added to the cart
/// </summary>
/// <returns>A <see cref="RazorCart.Core.ActionPipeline.PipelineAction[]"/></returns>
protected override PipelineAction[] ListCartPipelineActions()
{
return base.ListCartPipelineActions();
}
/// <summary>
/// Register the Pipeline Action List to be executed on cart totals calculation request
/// </summary>
/// <returns>A <see cref="RazorCart.Core.ActionPipeline.PipelineAction[]"/></returns>
protected override PipelineAction[] ListCalculatorPipelineActions()
{
return new PipelineAction[]
{
new CalculateSubTotal(),
new CalculateOrderDiscount(),
new CalculateCouponDiscount(),
new CalculateShipping(),
new CalculateHandling(),
new MyCalculateTax(),
new CalculateFinal()
};
}
/// <summary>
/// Register the Pipeline Action List to be executed on cart checkout/place order
/// </summary>
/// <returns>A <see cref="RazorCart.Core.ActionPipeline.PipelineAction[]"/></returns>
protected override PipelineAction[] ListCheckoutPipelineActions()
{
return base.ListCheckoutPipelineActions();
}
}
}
| 35.977778 | 110 | 0.600988 | [
"MIT"
] | SmithConsulting/MyCompany.RazorCart.Integration | Pipeline/MyPipeline.cs | 1,621 | C# |
using System;
using System.IO;
using System.Text;
using System.Net.Http;
using System.IO.Compression;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Swashbuckle.AspNetCore.SwaggerGen;
using IdentityServer4.MicroService.Enums;
using IdentityServer4.MicroService.Services;
using IdentityServer4.MicroService.CacheKeys;
using IdentityServer4.MicroService.Models.Apis.Common;
using IdentityServer4.MicroService.Models.Apis.CodeGenController;
using IdentityServer4.MicroService.Models.Apis.ApiResourceController;
using static IdentityServer4.MicroService.AppConstant;
using static IdentityServer4.MicroService.MicroserviceConfig;
namespace IdentityServer4.MicroService.Apis
{
/// <summary>
/// 代码生成
/// </summary>
[Route("CodeGen")]
[Produces("application/json")]
public class CodeGenController : BasicController
{
#region Services
readonly SwaggerCodeGenService swagerCodeGen;
readonly INodeServices nodeServices;
// azure Storage
readonly AzureStorageService storageService;
#endregion
#region 构造函数
public CodeGenController(
AzureStorageService _storageService,
IStringLocalizer<CodeGenController> localizer,
SwaggerCodeGenService _swagerCodeGen,
INodeServices _nodeServices,
RedisService _redis)
{
l = localizer;
swagerCodeGen = _swagerCodeGen;
nodeServices = _nodeServices;
storageService = _storageService;
redis = _redis;
}
#endregion
#region 代码生成 - 客户端列表
/// <summary>
/// 代码生成 - 客户端列表
/// </summary>
/// <remarks>支持生成的客户端集合</remarks>
/// <returns></returns>
/// <remarks>
/// <label>Client Scopes:</label><code>ids4.ms.codegen.clients</code>
/// </remarks>
[HttpGet("Clients")]
[SwaggerOperation("CodeGen/Clients")]
[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenClients)]
public ApiResult<List<SwaggerCodeGenItem>> Clients(bool fromCache = true)
{
var result = fromCache ? swagerCodeGen.ClientItemsCache : swagerCodeGen.ClientItems;
return new ApiResult<List<SwaggerCodeGenItem>>(result);
}
#endregion
#region 代码生成 - 服务端列表
/// <summary>
/// 代码生成 - 服务端列表
/// </summary>
/// <remarks>支持生成的服务端集合</remarks>
/// <returns></returns>
/// <remarks>
/// <label>Client Scopes:</label><code>ids4.ms.codegen.servers</code>
/// </remarks>
[HttpGet("Servers")]
[SwaggerOperation("CodeGen/Servers")]
[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenServers)]
public ApiResult<List<SwaggerCodeGenItem>> Servers(bool fromCache = true)
{
var result = fromCache ? swagerCodeGen.ServerItemsCache : swagerCodeGen.ServerItems;
return new ApiResult<List<SwaggerCodeGenItem>>(result);
}
#endregion
#region 代码生成 - 发布SDK
/// <summary>
/// 代码生成 - 发布SDK
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks>
/// <label>Client Scopes:</label><code>ids4.ms.codegen.releasesdk</code>
/// </remarks>
[HttpPost("ReleaseSDK")]
[SwaggerOperation("CodeGen/ReleaseSDK")]
[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenReleaseSDK)]
public async Task<ApiResult<bool>> ReleaseSDK([FromBody]GenerateClientRequest value)
{
if (!ModelState.IsValid)
{
return new ApiResult<bool>()
{
code = (int)BasicControllerEnums.UnprocessableEntity,
message = ModelErrors()
};
}
var platformPath = $"./Node/sdkgen/{Enum.GetName(typeof(PackagePlatform), value.platform)}/";
try
{
var swaggerDoc = string.Empty;
using (var hc = new HttpClient())
{
swaggerDoc = await hc.GetStringAsync(value.swaggerUrl);
}
if (string.IsNullOrWhiteSpace(swaggerDoc))
{
return new ApiResult<bool>(l, CodeGenControllerEnums.GenerateClient_GetSwaggerFialed);
}
var templateDirectory = platformPath + Enum.GetName(typeof(Language), value.language) + "_" + DateTime.Now.Ticks.ToString();
if (!Directory.Exists(templateDirectory))
{
Directory.CreateDirectory(templateDirectory);
}
#region 重置swagger.json >> info >> title节点
// 获取的文档中,info-title节点是网关上的微服务名称,
// 生成的class时,命名一般都是英文的
var options = await GetNpmOptions(value.language, value.apiId);
if (options != null && !string.IsNullOrWhiteSpace(options.sdkName))
{
try
{
var swaggerDocJson = JsonConvert.DeserializeObject<JObject>(swaggerDoc);
swaggerDocJson["info"]["title"] = options.sdkName;
swaggerDoc = swaggerDocJson.ToString();
}
catch
{
}
}
#endregion
var SdkCode = await nodeServices.InvokeAsync<string>(platformPath + value.language,
swaggerDoc, value.apiId);
switch (value.platform)
{
case PackagePlatform.npm:
var PublishResult = ReleasePackage_NPM(templateDirectory, value.language, SdkCode, value.apiId);
break;
case PackagePlatform.nuget:
break;
case PackagePlatform.spm:
break;
case PackagePlatform.gradle:
break;
default:
break;
}
return new ApiResult<bool>(true);
}
catch (Exception ex)
{
return new ApiResult<bool>(l,
BasicControllerEnums.ExpectationFailed,
ex.Message);
}
}
async Task<bool> ReleasePackage_NPM(string templateDirectory, Language lan, string SdkCode, string apiId)
{
#region 写SDK文件
var fileName = string.Empty;
switch (lan)
{
case Language.angular2:
fileName = templateDirectory + "/index.ts";
break;
case Language.jQuery:
fileName = templateDirectory + "/index.js";
break;
default:
break;
}
using (var sw = new StreamWriter(fileName, false, Encoding.UTF8))
{
sw.WriteLine(SdkCode);
}
#endregion
#region 更新包信息
var configFilePath = templateDirectory + "/package.json";
var options = await GetNpmOptions(lan, apiId);
var JsonDoc = new JObject();
if (!string.IsNullOrWhiteSpace(options.name))
{
JsonDoc["name"] = options.name;
}
if (!string.IsNullOrWhiteSpace(options.homepage))
{
JsonDoc["homepage"] = options.homepage;
}
if (!string.IsNullOrWhiteSpace(options.author))
{
JsonDoc["author"] = options.author;
}
if (options.keywords != null && options.keywords.Length > 0)
{
JsonDoc["keywords"] = JToken.FromObject(options.keywords);
}
if (!string.IsNullOrWhiteSpace(options.description))
{
JsonDoc["description"] = options.description;
}
if (string.IsNullOrWhiteSpace(options.version)) { options.version = "0.0.0"; }
if (!string.IsNullOrWhiteSpace(options.license))
{
JsonDoc["license"] = options.license;
}
#region version
var CurrentVersion = Version.Parse(options.version);
var newVersion = string.Empty;
if (CurrentVersion.Build + 1 < int.MaxValue)
{
newVersion = $"{CurrentVersion.Major}.{CurrentVersion.Minor}.{CurrentVersion.Build + 1}";
}
else if (CurrentVersion.Minor + 1 < int.MaxValue)
{
newVersion = $"{CurrentVersion.Major}.{CurrentVersion.Minor + 1}.{CurrentVersion.Build}";
}
else if (CurrentVersion.Major + 1 < int.MaxValue)
{
newVersion = $"{CurrentVersion.Major + 1}.{CurrentVersion.Minor}.{CurrentVersion.Build}";
}
JsonDoc["version"] = newVersion;
#endregion
using (var sw = new StreamWriter(configFilePath, false, Encoding.UTF8))
{
await sw.WriteLineAsync(JsonDoc.ToString());
}
#endregion
var npmrcFilePath = templateDirectory + "/.npmrc";
if (!string.IsNullOrWhiteSpace(options.token))
{
using (var sw = new StreamWriter(npmrcFilePath, false, Encoding.UTF8))
{
await sw.WriteLineAsync("//registry.npmjs.org/:_authToken=" + options.token);
}
}
var readmeFilePath = templateDirectory + "/README.md";
if (!string.IsNullOrWhiteSpace(options.README))
{
var releaseREAME = options.README.Replace("<%SdkCode%>", SdkCode);
using (var sw = new StreamWriter(readmeFilePath, false, Encoding.UTF8))
{
await sw.WriteLineAsync(releaseREAME);
}
}
#region 打包SDK文件为.zip
var releaseDirectory = templateDirectory + "_release/";
if (!Directory.Exists(releaseDirectory))
{
Directory.CreateDirectory(releaseDirectory);
}
var templateName = Directory.GetParent(templateDirectory).Name;
var languageName = Path.GetFileName(templateDirectory);
var packageFileName = $"{templateName}.{languageName}_{newVersion}.zip";
ZipFile.CreateFromDirectory(templateDirectory, releaseDirectory + packageFileName);
#endregion
#region 上传.zip,发消息到发包队列
var blobUrl = string.Empty;
using (var zipFileStream = new FileStream(releaseDirectory + packageFileName, FileMode.Open, FileAccess.Read))
{
blobUrl = await storageService.UploadBlobAsync(zipFileStream, "codegen-npm", packageFileName);
}
await storageService.AddMessageAsync("publish-package-npm", blobUrl);
#endregion
#region 清理本地文件
try
{
Directory.Delete(releaseDirectory, true);
Directory.Delete(templateDirectory, true);
}
catch { }
#endregion
options.version = newVersion;
await SetNpmOptions(apiId, lan, options);
return true;
}
#endregion
#region 代码生成 - NPM设置
/// <summary>
/// 代码生成 - NPM设置
/// </summary>
/// <param name="id">微服务ID</param>
/// <param name="language">语言</param>
/// <returns></returns>
/// <remarks>
/// <label>Client Scopes:</label><code>ids4.ms.codegen.npmoptions</code>
/// </remarks>
[HttpGet("{id}/NpmOptions/{language}")]
[SwaggerOperation("CodeGen/NpmOptions")]
[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenNpmOptions)]
public async Task<ApiResult<CodeGenNpmOptionsModel>> NpmOptions(string id, Language language)
{
var result = await GetNpmOptions(language, id);
var key = CodeGenControllerKeys.NpmOptions + id;
var cacheResult = await redis.GetAsync(key);
if (result != null)
{
return new ApiResult<CodeGenNpmOptionsModel>(result);
}
else
{
return new ApiResult<CodeGenNpmOptionsModel>(l, CodeGenControllerEnums.NpmOptions_GetOptionsFialed);
}
}
async Task<CodeGenNpmOptionsModel> GetNpmOptions(Language lan, string id)
{
var key = CodeGenControllerKeys.NpmOptions + Enum.GetName(typeof(Language), lan) + ":" + id;
var cacheResult = await redis.GetAsync(key);
if (!string.IsNullOrWhiteSpace(cacheResult))
{
try
{
var result = JsonConvert.DeserializeObject<CodeGenNpmOptionsModel>(cacheResult);
return result;
}
catch
{
return null;
}
}
return null;
}
#endregion
#region 代码生成 - 更新NPM设置
/// <summary>
/// 代码生成 - 更新NPM设置
/// </summary>
/// <param name="id">微服务ID</param>
/// <param name="language">语言</param>
/// <param name="value">package.json的内容字符串</param>
/// <returns></returns>
/// <remarks>
/// <label>Client Scopes:</label><code>ids4.ms.codegen.putnpmoptions</code>
/// 更新微服务的NPM发布设置
/// </remarks>
[HttpPut("{id}/NpmOptions/{language}")]
[SwaggerOperation("CodeGen/PutNpmOptions")]
[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenPutNpmOptions)]
public async Task<ApiResult<bool>> NpmOptions(string id, Language language, [FromBody]CodeGenNpmOptionsModel value)
{
if (!ModelState.IsValid)
{
return new ApiResult<bool>(l, BasicControllerEnums.UnprocessableEntity,
ModelErrors());
}
var result = await SetNpmOptions(id, language, value);
return new ApiResult<bool>(result);
}
async Task<bool> SetNpmOptions(string id, Language lan, CodeGenNpmOptionsModel value)
{
var key = CodeGenControllerKeys.NpmOptions + Enum.GetName(typeof(Language), lan) + ":" + id;
var cacheResult = JsonConvert.SerializeObject(value);
var result = await redis.SetAsync(key, cacheResult, null);
return result;
}
#endregion
#region 代码生成 - Github设置
/// <summary>
/// 代码生成 - Github设置
/// </summary>
/// <param name="id">微服务ID</param>
/// <returns></returns>
/// <remarks>
/// <label>Client Scopes:</label><code>ids4.ms.codegen.githuboptions</code>
/// </remarks>
[HttpGet("{id}/GithubOptions")]
[SwaggerOperation("CodeGen/GithubOptions")]
[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenGithubOptions)]
public async Task<ApiResult<ApiResourceGithubPublishRequest>> GithubOptions(string id)
{
var result = await GetGithubOptions(id);
var key = CodeGenControllerKeys.GithubOptions + id;
var cacheResult = await redis.GetAsync(key);
if (result != null)
{
return new ApiResult<ApiResourceGithubPublishRequest>(result);
}
else
{
return new ApiResult<ApiResourceGithubPublishRequest>(l, CodeGenControllerEnums.GithubOptions_GetOptionsFialed);
}
}
async Task<ApiResourceGithubPublishRequest> GetGithubOptions(string id)
{
var key = CodeGenControllerKeys.GithubOptions + id;
var cacheResult = await redis.GetAsync(key);
if (!string.IsNullOrWhiteSpace(cacheResult))
{
try
{
var result = JsonConvert.DeserializeObject<ApiResourceGithubPublishRequest>(cacheResult);
return result;
}
catch
{
return null;
}
}
return null;
}
#endregion
#region 代码生成 - 更新Github设置
/// <summary>
/// 代码生成 - 更新Github设置
/// </summary>
/// <param name="id">微服务ID</param>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks>
/// <label>Client Scopes:</label><code>ids4.ms.codegen.putgithuboptions</code>
/// 更新微服务的Github发布设置
/// </remarks>
[HttpPut("{id}/GithubOptions")]
[SwaggerOperation("CodeGen/PutGithubOptions")]
[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenPutGithubOptions)]
public async Task<ApiResult<bool>> GithubOptions(string id, [FromBody]ApiResourceGithubPublishRequest value)
{
if (!ModelState.IsValid)
{
return new ApiResult<bool>(l, BasicControllerEnums.UnprocessableEntity,
ModelErrors());
}
var result = await SetGithubOptions(id, value);
return new ApiResult<bool>(result);
}
async Task<bool> SetGithubOptions(string id, ApiResourceGithubPublishRequest value)
{
var key = CodeGenControllerKeys.GithubOptions + id;
var cacheResult = JsonConvert.SerializeObject(value);
var result = await redis.SetAsync(key, cacheResult, null);
return result;
}
#endregion
#region 代码生成 - 生成
/// <summary>
/// 代码生成 - 生成
/// </summary>
/// <remarks></remarks>
/// <returns></returns>
/// <remarks>
/// </remarks>
[HttpPost("Gen")]
[SwaggerOperation("CodeGen/Gen")]
[AllowAnonymous]
//[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenGen)]
public async Task<ApiResult<string>> Gen([FromBody]CodeGenGenRequest value)
{
if (!ModelState.IsValid)
{
return new ApiResult<string>(l, BasicControllerEnums.UnprocessableEntity,
ModelErrors());
}
try
{
var swaggerDoc = string.Empty;
using (var hc = new HttpClient())
{
swaggerDoc = await hc.GetStringAsync(value.swaggerUrl);
}
if (string.IsNullOrWhiteSpace(swaggerDoc))
{
return new ApiResult<string>(l, CodeGenControllerEnums.GenerateClient_GetSwaggerFialed);
}
var platformPath = $"./Node/";
var result = await nodeServices.InvokeAsync<string>(platformPath + value.genName,
swaggerDoc, new { value.swaggerUrl });
return new ApiResult<string>(result);
}
catch (Exception ex)
{
return new ApiResult<string>(l,
BasicControllerEnums.ExpectationFailed,
ex.Message);
}
}
#endregion
#region 代码生成 - 同步Github
/// <summary>
/// 代码生成 - 同步Github
/// </summary>
/// <param name="id">微服务ID</param>
/// <returns></returns>
/// <remarks>
/// <label>Client Scopes:</label><code>ids4.ms.codegen.putgithuboptions</code>
/// 更新微服务的Github发布设置
/// </remarks>
[HttpPut("{id}/SyncGithub")]
[SwaggerOperation("CodeGen/SyncGithub")]
[Authorize(AuthenticationSchemes = AppAuthenScheme, Policy = ClientScopes.CodeGenSyncGithub)]
public async Task<ApiResult<bool>> SyncGithub(string id)
{
if (!ModelState.IsValid)
{
return new ApiResult<bool>(l, BasicControllerEnums.UnprocessableEntity,
ModelErrors());
}
var githubConfiguration = await GetGithubOptions(id);
if (githubConfiguration != null && !string.IsNullOrWhiteSpace(githubConfiguration.token))
{
if (githubConfiguration.syncLabels)
{
await storageService.AddMessageAsync("apiresource-publish-github",
JsonConvert.SerializeObject(githubConfiguration));
}
if (githubConfiguration.syncDocs)
{
await storageService.AddMessageAsync("apiresource-publish-github-readthedocs",
JsonConvert.SerializeObject(githubConfiguration));
}
}
return new ApiResult<bool>(true);
}
#endregion
}
}
| 33.927786 | 140 | 0.548168 | [
"Apache-2.0"
] | wanglong/IdentityServer4.MicroService | IdentityServer4.MicroService/Apis/CodeGenController.cs | 22,188 | C# |
//
// DO NOT MODIFY. THIS IS AUTOMATICALLY GENERATED FILE.
//
#nullable enable
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
using System;
using System.Collections.Generic;
namespace CefNet.DevTools.Protocol.Page
{
/// <summary>Layout viewport position and dimensions.</summary>
public sealed class LayoutViewport
{
/// <summary>
/// Horizontal offset relative to the document (CSS pixels).
/// </summary>
public int PageX { get; set; }
/// <summary>
/// Vertical offset relative to the document (CSS pixels).
/// </summary>
public int PageY { get; set; }
/// <summary>
/// Width (CSS pixels), excludes scrollbar if present.
/// </summary>
public int ClientWidth { get; set; }
/// <summary>
/// Height (CSS pixels), excludes scrollbar if present.
/// </summary>
public int ClientHeight { get; set; }
}
}
| 29.914286 | 140 | 0.617956 | [
"MIT"
] | CefNet/CefNet.DevTools.Protocol | CefNet.DevTools.Protocol/Generated/Page/LayoutViewport.g.cs | 1,047 | C# |
// Copyright (c) Aspose 2002-2016. All Rights Reserved.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using GroupDocsSignatureVisualStudioPlugin.Core;
using EnvDTE80;
namespace GroupDocsSignatureVisualStudioPlugin.GUI
{
public partial class ComponentWizardPage : Form
{
Task progressTask;
private bool examplesNotAvailable = false;
private bool downloadTaskCompleted = false;
//AsyncDownloadList downloadList = new AsyncDownloadList();
AsyncDownload asyncActiveDownload = null;
private DTE2 _application = null;
public ComponentWizardPage()
{
InitializeComponent();
AsyncDownloadList.list.Clear();
GroupDocsComponents components = new GroupDocsComponents();
if (!GlobalData.isAutoOpened)
{
AbortButton.Text = "Close";
}
GlobalData.SelectedComponent = null;
ContinueButton_Click(new object(), new EventArgs());
}
public ComponentWizardPage(DTE2 application)
{
_application = application;
InitializeComponent();
AsyncDownloadList.list.Clear();
GroupDocsComponents components = new GroupDocsComponents();
if (!GlobalData.isAutoOpened)
{
AbortButton.Text = "Close";
}
GlobalData.SelectedComponent = null;
ContinueButton_Click(new object(), new EventArgs());
}
private void performPostFinish()
{
AbortButton.Enabled = true;
GroupDocsComponent component;
GroupDocsComponents.list.TryGetValue(Constants.GROUPDOCS_COMPONENT, out component);
checkAndUpdateRepo(component);
}
private bool performFinish()
{
ContinueButton.Enabled = false;
processComponents();
if (!GroupDocsComponentsManager.isIneternetConnected())
{
this.showMessage(Constants.INTERNET_CONNECTION_REQUIRED_MESSAGE_TITLE, Constants.INTERNET_CONNECTION_REQUIRED_MESSAGE, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
return false;
}
GlobalData.backgroundWorker = new BackgroundWorker();
GlobalData.backgroundWorker.WorkerReportsProgress = true;
GlobalData.backgroundWorker.WorkerSupportsCancellation = true;
GlobalData.backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
GlobalData.backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
GlobalData.backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
GlobalData.backgroundWorker.RunWorkerAsync();
return true;
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
UpdateProgress(1);
int total = 10;
int index = 0;
GroupDocsComponentsManager comManager = new GroupDocsComponentsManager(this);
foreach (GroupDocsComponent component in GroupDocsComponents.list.Values)
{
if (component.is_selected())
{
GlobalData.SelectedComponent = component.get_name();
if (GroupDocsComponentsManager.libraryAlreadyExists(component.get_downloadFileName()))
{
component.set_downloaded(true);
}
else
{
GroupDocsComponentsManager.addToDownloadList(component, component.get_downloadUrl(), component.get_downloadFileName());
}
}
decimal percentage = ((decimal)(index + 1) / (decimal)total) * 100;
UpdateProgress(Convert.ToInt32(percentage));
index++;
}
UpdateProgress(100);
UpdateText("All operations completed");
}
catch (Exception) { }
}
private void UpdateText(string textToUpdate)
{
if (GlobalData.backgroundWorker != null)
{
toolStripStatusMessage.BeginInvoke(new TaskDescriptionCallback(this.TaskDescriptionLabel),
new object[] { textToUpdate });
}
}
private void UpdateProgress(int progressValue)
{
if (GlobalData.backgroundWorker != null)
{
progressBar.BeginInvoke(new UpdateCurrentProgressBarCallback(this.UpdateCurrentProgressBar), new object[] { progressValue });
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.ProgressPercentage == 0)
progressBar.Value = 1;
else
progressBar.Value = e.ProgressPercentage;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
processDownloadList();
}
public delegate void TaskDescriptionCallback(string value);
private void TaskDescriptionLabel(string value)
{
toolStripStatusMessage.Text = value;
}
public delegate void UpdateCurrentProgressBarCallback(int value);
private void UpdateCurrentProgressBar(int value)
{
if (value < 0) value = 0;
if (value > 100) value = 100;
progressBar.Value = value;
}
private void processDownloadList()
{
if (AsyncDownloadList.list.Count > 0)
{
asyncActiveDownload = AsyncDownloadList.list[0];
AsyncDownloadList.list.Remove(asyncActiveDownload);
downloadFileFromWeb(asyncActiveDownload.Url, asyncActiveDownload.LocalPath);
toolStripStatusMessage.Text = "Downloading " + asyncActiveDownload.Component.Name + " API";
}
else
{
performPostFinish();
}
}
private void downloadFileFromWeb(string sourceURL, string destinationPath)
{
progressBar.Visible = true;
// do nuget download
//IServiceProvider serviceProvider=new System.IServiceProvider;
//var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
//IVsPackageInstallerServices installerServices = componentModel.GetService<IVsPackageInstallerServices>();
//var installedPackages = installerServices.GetInstalledPackages();
//Console.WriteLine(installedPackages.FirstOrDefault().Title);
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
Uri url = new Uri("https://www.nuget.org/api/v2/package/groupdocs-signature-dotnet/3.0.0");
webClient.DownloadFileAsync(url, destinationPath);
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
progressBar.Value = 100;
asyncActiveDownload.Component.Downloaded = true;
GroupDocsComponentsManager.storeVersion(asyncActiveDownload.Component);
UnZipDownloadedFile(asyncActiveDownload);
AbortButton.Enabled = true;
processDownloadList();
}
private void UnZipDownloadedFile(AsyncDownload download)
{
GroupDocsComponentsManager.unZipFile(download.LocalPath, Path.Combine(Path.GetDirectoryName(download.LocalPath), download.Component.Name));
}
public DialogResult showMessage(string title, string message, MessageBoxButtons buttons, MessageBoxIcon icon)
{
return MessageBox.Show(message, title, buttons, icon);
}
private bool validateForm()
{
clearError();
return true;
}
void processComponents()
{
GroupDocsComponent component = new GroupDocsComponent();
GroupDocsComponents.list.TryGetValue(Constants.GROUPDOCS_COMPONENT, out component);
component.Selected = true;
}
private void setErrorMessage(string message)
{
toolStripStatusMessage.Text = message;
ContinueButton.Enabled = false;
}
private void clearError()
{
ContinueButton.Enabled = true;
}
private void setTooltip(Control control, string message)
{
ToolTip buttonToolTip = new ToolTip();
buttonToolTip.ToolTipTitle = control.Text;
buttonToolTip.UseFading = true;
buttonToolTip.UseAnimation = true;
buttonToolTip.IsBalloon = true;
buttonToolTip.ToolTipIcon = ToolTipIcon.Info;
buttonToolTip.ShowAlways = true;
buttonToolTip.AutoPopDelay = 90000;
buttonToolTip.InitialDelay = 100;
buttonToolTip.ReshowDelay = 100;
buttonToolTip.SetToolTip(control, message);
}
#region events
private void linkLabelGroupDocs_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
linkLabelGroupDocs.LinkVisited = true;
System.Diagnostics.Process.Start("http://groupdocs.com/dot-net/total-library");
}
#endregion
private void logoButton_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://www.groupdocs.com");
}
private void textBoxProjectName_TextChanged(object sender, EventArgs e)
{
validateForm();
}
private void ContinueButton_Click(object sender, EventArgs e)
{
progressBar.Value = 1;
progressBar.Visible = true;
toolStripStatusMessage.Visible = true;
toolStripStatusMessage.Text = "Fetching API info: - Please wait while we configure you preferences";
GlobalData.isComponentFormAborted = false;
performFinish();
}
private void AbortButton_Click(object sender, EventArgs e)
{
if (GlobalData.isAutoOpened)
GlobalData.isComponentFormAborted = true;
Close();
}
#region Download Examples from GitHub
private void checkAndUpdateRepo(GroupDocsComponent component)
{
if (null == component)
return;
if (null == component.get_remoteExamplesRepository() || component.RemoteExamplesRepository == string.Empty)
{
showMessage("Examples not available", component.get_name() + " - " + Constants.EXAMPLES_NOT_AVAILABLE_MESSAGE, MessageBoxButtons.OK, MessageBoxIcon.Information);
examplesNotAvailable = true;
return;
}
else
{
examplesNotAvailable = false;
}
if (GroupDocsComponentsManager.isIneternetConnected())
{
CloneOrCheckOutRepo(component);
}
else
{
showMessage(Constants.INTERNET_CONNECTION_REQUIRED_MESSAGE_TITLE, component.get_name() + " - " + Constants.EXAMPLES_INTERNET_CONNECTION_REQUIRED_MESSAGE, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void CloneOrCheckOutRepo(GroupDocsComponent component)
{
UpdateProgress(0);
downloadTaskCompleted = false;
timer1.Start();
Task repoUpdateWorker = new Task(delegate { CloneOrCheckOutRepoWorker(component); });
repoUpdateWorker.Start();
progressTask = new Task(delegate { progressDisplayTask(); });
progressBar.Enabled = true;
progressTask.Start();
ContinueButton.Enabled = false;
toolStripStatusMessage.Text = "Please wait while the Examples are being downloaded...";
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateProgress((progressBar.Value < 90 ? progressBar.Value + 1 : 90));
if (downloadTaskCompleted)
{
timer1.Stop();
RepositoryUpdateCompleted();
}
}
private void progressDisplayTask()
{
try
{
this.Invoke(new MethodInvoker(delegate() { progressBar.Visible = true; }));
}
catch (Exception)
{
}
}
private void RepositoryUpdateCompleted()
{
UpdateProgress(100);
ContinueButton.Enabled = true;
toolStripStatusMessage.Text = "Examples downloaded successfully.";
downloadTaskCompleted = true;
progressBar.Value = 0;
progressBar.Visible = false;
UpdateProgress(0);
Close();
}
private string GetDestinationPath(string destinationRoot, string selectedProject)
{
if (!Directory.Exists(destinationRoot))
Directory.CreateDirectory(destinationRoot);
string path = destinationRoot + "\\" + Path.GetFileName(selectedProject);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
else
{
int index = 1;
while (Directory.Exists(path + index))
{
index++;
}
path = path + index;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
return path;
}
private void CloneOrCheckOutRepoWorker(GroupDocsComponent component)
{
GitHelper.CloneOrCheckOutRepo(component);
downloadTaskCompleted = true;
}
#endregion
private void label1_Click(object sender, EventArgs e)
{
}
}
}
| 33.879195 | 223 | 0.598455 | [
"MIT"
] | groupdocs/GroupDocs.Signature-for-.NET | Plugins/GroupDocsSignatureVSPlugin/GroupDocs.Signature.VisualStudioPlugin/GroupDocsVisualStudioPlugin/GUI/ComponentWizardPage.cs | 15,146 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlimCanvas.View.Controls.EventTypes
{
/// <summary>
/// to be added
/// </summary>
public delegate void DrawUpdateEventHandler(object sender, DrawUpdateEventArgs e);
/// <summary>
/// to be added
/// </summary>
public class DrawUpdateEventArgs
{
/// <summary>
/// to be added
/// </summary>
public TimeSpan Time { get; set; }
}
}
| 21.24 | 86 | 0.623352 | [
"MIT"
] | twytec/SlimCanvas | Shared/SharedPCL/View/Controls/EventTypes/DrawUpdateEvent.cs | 533 | C# |
using EPiServer.Reference.Commerce.Site.Features.Warehouse.Services;
using EPiServer.Reference.Commerce.Site.Features.Warehouse.ViewModels;
using System.Collections.Generic;
using System.Linq;
namespace EPiServer.Reference.Commerce.Site.Features.Warehouse.ViewModelFactories
{
public class WarehouseViewModelFactory
{
private readonly IWarehouseService _warehouseService;
public WarehouseViewModelFactory(IWarehouseService warehouseService)
{
_warehouseService = warehouseService;
}
public virtual IEnumerable<WarehouseInventoryViewModel> CreateAvailabilityViewModels(string skuCode)
{
return _warehouseService
.GetWarehouseAvailability(skuCode)
.Select(x => new WarehouseInventoryViewModel
{
WarehouseName = x.Warehouse.Name,
InStockQuantity = x.InStock,
WarehouseCode = x.Warehouse.Code,
SkuCode = skuCode
});
}
public virtual WarehouseViewModel CreateWarehouseViewModel(string warehouseCode)
{
var viewModel = new WarehouseViewModel
{
Warehouse = _warehouseService.GetWarehouse(warehouseCode)
};
return viewModel;
}
}
} | 33.8 | 108 | 0.642751 | [
"Apache-2.0"
] | Cauldrath/Quicksilver | Sources/EPiServer.Reference.Commerce.Site/Features/Warehouse/ViewModelFactories/WarehouseViewModelFactory.cs | 1,354 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using EmpowerBusiness.Controllers;
using EmpowerBusiness.Enums;
using EmpowerBusiness.Managers;
using EmpowerBusiness.Models.Appraisals;
using EmpowerBusiness.Models.Notes;
using EmpowerData.EntityModels;
using EmpowerWeb.Models.common;
using EmpowerWeb.utils;
using EmpowerWeb.utils.ExcelUtils;
using EmpowerWeb.utils.KendoHelpers;
using Kendo.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Newtonsoft.Json;
using Org.BouncyCastle.Ocsp;
namespace EmpowerWeb.Controllers.Api
{
[System.Web.Http.RoutePrefix("api/notes")]
public class NotesController : ApiController
{
private readonly IDataAccessBase _db;
private readonly int _currentUserId;
public NotesController(IDataAccessBase db)
{
_db = db;
_currentUserId = AuthHelpers.GetCurrentUserSysId();
}
// GET
/// <summary>
/// An API controller method that gets the CMS_Notes entries identified as BI demands.
/// </summary>
/// <param name="request">
/// Input parameters specified by Kendo's DataSourceRequest
/// </param>
/// <param name="includeAnswered">
/// Indicates whether the method should include answered BI demands in it's response
/// </param>
/// <returns>Returns a list of BI demands as BiDemandModel objects</returns>
[Route("bidemands")]
public HttpResponseMessage GetBiDemands(
[System.Web.Http.ModelBinding.ModelBinder(typeof(CustomDataSourceRequestModelBinder))]
DataSourceRequest request, bool includeAnswered = false)
{
var query = _db.DbNotes.GetBiDemands();
if (!includeAnswered)
{
query = query.Where(x => x.DemandResponseDate == null);
}
if (request.Filters != null)
{
// Handle custom filter behaviors
var receivedFromFilter = KendoHelpers.RemoveFilterDescriptor(request.Filters, "ReceivedFrom");
var adjusterFilter = KendoHelpers.RemoveFilterDescriptor(request.Filters, "Adjuster");
var claimantFilter = KendoHelpers.RemoveFilterDescriptor(request.Filters, "Claimant");
var medBillAlgdFilter = KendoHelpers.RemoveFilterDescriptor(request.Filters, "MedBillAlleged");
if (receivedFromFilter != null)
{
if (receivedFromFilter.Operator == FilterOperator.Contains)
{
query = query.Where(x =>
x.ReceivedFrom.Contains(receivedFromFilter.ConvertedValue.ToString()));
}
}
if (adjusterFilter != null)
{
if (adjusterFilter.Operator == FilterOperator.Contains)
{
query = query.Where(x =>
x.BIAdjusterId == null &&
(x.PDAdjusterFirstName + " " + x.PDAdjusterLastName)
.Contains(adjusterFilter.ConvertedValue.ToString()) ||
(x.BIAdjusterFirstName + " " + x.BIAdjusterLastName)
.Contains(adjusterFilter.ConvertedValue.ToString()));
}
}
if (claimantFilter != null)
{
if (claimantFilter.Operator == FilterOperator.Contains)
{
query = query.Where(x =>
(x.ClaimantFirstName + " " + x.ClaimantLastName)
.Contains(claimantFilter.ConvertedValue.ToString()));
}
}
if (medBillAlgdFilter != null)
{
if (medBillAlgdFilter.Operator == FilterOperator.IsEqualTo)
{
if (medBillAlgdFilter.ConvertedValue.ToString() == "Y")
{
query = query.Where(x => x.MedicalBillAmount != null);
}
else
{
query = query.Where(x => x.MedicalBillAmount == null);
}
}
}
}
DataSourceResult demandList = null;
// Handle adjuster sort case
if (request.Sorts != null && request.Sorts.Any(s => s.Member == "Adjuster"))
{
var sortDescriptor = request.Sorts.First(s => s.Member == "Adjuster");
var direction = sortDescriptor.SortDirection;
request.Sorts.Remove(sortDescriptor);
demandList = query.ToDataSourceResult(request);
if (demandList.Data is IEnumerable<BiDemandModel> data)
{
demandList.Data = direction == ListSortDirection.Ascending
? data.OrderBy(d => d.BIAdjusterId == null
? d.PDAdjusterLastName
: d.BIAdjusterLastName)
: data.OrderByDescending(d => d.BIAdjusterId == null
? d.PDAdjusterLastName
: d.BIAdjusterLastName);
}
}
return Request.CreateResponse(HttpStatusCode.OK, demandList ?? query.ToDataSourceResult(request));
}
/// <summary>
/// An API method for getting the total, answered and unanswered bi demand counts
/// </summary>
/// <returns>Returns an object containing the Total, Answered, and Unanswered counts</returns>
[Route("bidemands/counts")]
public HttpResponseMessage GetTotals()
{
var response = new
{
Total = _db.DbNotes.GetBiDemands().Count(),
Unanswered = _db.DbNotes.GetUnansweredCount(),
Answered = _db.DbNotes.GetAnsweredCount()
};
return Request.CreateResponse(HttpStatusCode.OK, response);
}
// POST
/// <summary>
/// An API controller method that updates a BI Demand entry with a response and adds a corresponding
/// note to the CMS_Notes table
/// </summary>
/// <param name="demand">An instance of the BI Demand Model</param>
/// <returns>Returns 200: "Success" if response was saved,
/// and a 409: "Invalid Demand Object" if not.</returns>
[Route("bidemands/respond")]
public HttpResponseMessage Post([FromBody] BiDemandModel demand)
{
if (demand.BISysID == 0)
{
return Request.CreateResponse(HttpStatusCode.Conflict, new {Error = "Invalid Demand Object"});
}
var demandObj = Mapper.Map<CMS_BI_Demand>(demand);
try
{
_db.DbNotes.SubmitDemandResponse(demandObj, _currentUserId);
_db.Save();
return Request.CreateResponse(HttpStatusCode.OK, "Success");
}
catch (Exception err)
{
return Request.CreateResponse(HttpStatusCode.Conflict, new {Error = err});
}
}
[Route("bidemands/export")]
[HttpGet]
public IHttpActionResult ExportToExcel([FromUri] PageRequestModel request, bool includeAnswered = false)
{
request.PageSize = request.PageSize ?? 20;
var data = _db.DbNotes.GetBiDemands();
if (!includeAnswered)
{
data = data.Where(x => x.DemandResponseDate == null);
}
return Ok(data);
}
protected override void Dispose(bool disposing)
{
_db.Dispose();
base.Dispose(disposing);
}
}
} | 37.477273 | 112 | 0.550273 | [
"Apache-2.0"
] | HaloImageEngine/EmpowerClaim-hotfix-1.25.1 | EmpowerWeb/Controllers/Api/NotesController.cs | 8,245 | C# |
#pragma checksum "E:\projetos\IdentityCourse\WebAppIdentity\WebAppIdentity\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7091c65830b0329e613be026ede8a57552863778"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views__ViewStart), @"mvc.1.0.view", @"/Views/_ViewStart.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "E:\projetos\IdentityCourse\WebAppIdentity\WebAppIdentity\Views\_ViewImports.cshtml"
using WebAppIdentity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "E:\projetos\IdentityCourse\WebAppIdentity\WebAppIdentity\Views\_ViewImports.cshtml"
using WebAppIdentity.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7091c65830b0329e613be026ede8a57552863778", @"/Views/_ViewStart.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"97dd174fbcd90e389b5418a91699d1162822bfaf", @"/Views/_ViewImports.cshtml")]
public class Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "E:\projetos\IdentityCourse\WebAppIdentity\WebAppIdentity\Views\_ViewStart.cshtml"
Layout = "_Layout";
#line default
#line hidden
#nullable disable
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 47.152542 | 183 | 0.773185 | [
"MIT"
] | karolinagb/CourseIdentity | WebAppIdentity/WebAppIdentity/obj/Debug/netcoreapp3.1/Razor/Views/_ViewStart.cshtml.g.cs | 2,782 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.