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
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // As informações gerais sobre um assembly são controladas por // conjunto de atributos. Altere estes valores de atributo para modificar as informações // associadas a um assembly. [assembly: AssemblyTitle("SistemaMediaAluno")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SistemaMediaAluno")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Definir ComVisible como false torna os tipos neste assembly invisíveis // para componentes COM. Caso precise acessar um tipo neste assembly de // COM, defina o atributo ComVisible como true nesse tipo. [assembly: ComVisible(false)] // O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM [assembly: Guid("a7863dec-a8ec-4559-9e74-36b854e4cc85")] // As informações da versão de um assembly consistem nos quatro valores a seguir: // // Versão Principal // Versão Secundária // Número da Versão // Revisão // // É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão // usando o "*" como mostrado abaixo: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.459459
95
0.754743
[ "MIT" ]
miguelhp373/Desenvolvimento_De_Sistemas_Modulo02
Lista de Exercicios 26-02/03 - SistemaMediaAluno/Properties/AssemblyInfo.cs
1,448
C#
/* * 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; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml; using Aliyun.Acs.Core.Auth; using Aliyun.Acs.Core.Regions.Location; [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] namespace Aliyun.Acs.Core.Regions { internal class InternalEndpointsParser : IEndpointsProvider { private const string BUNDLED_ENDPOINTS_RESOURCE_PATH = "endpoints.xml"; public Endpoint GetEndpoint(string region, string product) { var allProducts = GetProducts(); ISet<string> regionSet = new HashSet<string>(); var productDomains = new List<ProductDomain>(); foreach (var p in allProducts) { if (!string.Equals(product, p.Code, StringComparison.InvariantCultureIgnoreCase)) { continue; } foreach (var e in p.RegionalEndpoints) { if (!string.Equals(region, e.Key, StringComparison.InvariantCultureIgnoreCase)) { continue; } regionSet.Add(region); var productDomain = new ProductDomain(); productDomain.ProductName = product; productDomain.DomianName = e.Value; productDomains.Add(productDomain); } if (regionSet.Count == 0) { if (string.IsNullOrEmpty(p.GlobalEndpoint)) { return null; } regionSet.Add(region); var productDomain = new ProductDomain(); productDomain.ProductName = product; productDomain.DomianName = p.GlobalEndpoint; productDomains.Add(productDomain); } break; } return new Endpoint(region, regionSet, productDomains); } public Endpoint GetEndpoint(string region, string product, string serviceCode, string endpointType, Credential credential, LocationConfig locationConfig) { throw new NotSupportedException(); } private static List<Product> ParseProducts(Stream stream) { var doc = new XmlDocument(); doc.Load(stream); using (var productNodes = doc.GetElementsByTagName("product")) { var products = new List<Product>(); foreach (XmlNode node in productNodes) { var product = new Product(); product.Code = node.SelectSingleNode("code").InnerText; product.LocationServiceCode = node.SelectSingleNode("location_service_code").InnerText; product.DocumentId = node.SelectSingleNode("document_id").InnerText; product.RegionalEndpoints = new Dictionary<string, string>(); using (var regional_endpoints = node.SelectSingleNode("regional_endpoints").SelectNodes("regional_endpoint")) { foreach (XmlNode regionalNode in regional_endpoints) { product.RegionalEndpoints.Add(regionalNode.SelectSingleNode("region_id").InnerText, regionalNode.SelectSingleNode("endpoint").InnerText); } product.GlobalEndpoint = node.SelectSingleNode("global_endpoint").InnerText; product.RegionalEndpointPattern = node.SelectSingleNode("regional_endpoint_pattern").InnerText; products.Add(product); } } return products; } } public virtual List<Product> GetProducts() { var type = MethodBase.GetCurrentMethod().DeclaringType; var _namespace = type.Namespace; var _assembly = Assembly.GetExecutingAssembly(); var resourceName = _namespace + "." + BUNDLED_ENDPOINTS_RESOURCE_PATH; using (var stream = _assembly.GetManifestResourceStream(resourceName)) { return ParseProducts(stream); } } public class Product { public string Code { get; set; } public string LocationServiceCode { get; set; } public string DocumentId { get; set; } public Dictionary<string, string> RegionalEndpoints { get; set; } public string GlobalEndpoint { get; set; } public string RegionalEndpointPattern { get; set; } } } }
37.886667
119
0.577864
[ "Apache-2.0" ]
fossabot/aliyun-openapi-net-sdk
aliyun-net-sdk-core/Regions/InternalEndpointsParser.cs
5,683
C#
#region copyright // Copyright 2015 Habart Thierry // // 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. #endregion using SimpleIdentityServer.Core.Common.Models; using SimpleIdentityServer.Core.Common.Repositories; using SimpleIdentityServer.Core.Errors; using SimpleIdentityServer.OAuth.Logging; using System; using System.Linq; using System.Threading.Tasks; namespace SimpleIdentityServer.Core.Authenticate { public interface IAuthenticateClient { Task<AuthenticationResult> AuthenticateAsync(AuthenticateInstruction instruction, string issuerName, bool isAuthorizationCodeGrantType = false); } public class AuthenticateClient : IAuthenticateClient { private readonly IClientSecretBasicAuthentication _clientSecretBasicAuthentication; private readonly IClientSecretPostAuthentication _clientSecretPostAuthentication; private readonly IClientAssertionAuthentication _clientAssertionAuthentication; private readonly IClientTlsAuthentication _clientTlsAuthentication; private readonly IClientRepository _clientRepository; private readonly IOAuthEventSource _oauthEventSource; public AuthenticateClient( IClientSecretBasicAuthentication clientSecretBasicAuthentication, IClientSecretPostAuthentication clientSecretPostAuthentication, IClientAssertionAuthentication clientAssertionAuthentication, IClientTlsAuthentication clientTlsAuthentication, IClientRepository clientRepository, IOAuthEventSource oAuthEventSource) { _clientSecretBasicAuthentication = clientSecretBasicAuthentication; _clientSecretPostAuthentication = clientSecretPostAuthentication; _clientAssertionAuthentication = clientAssertionAuthentication; _clientTlsAuthentication = clientTlsAuthentication; _clientRepository = clientRepository; _oauthEventSource = oAuthEventSource; } public async Task<AuthenticationResult> AuthenticateAsync(AuthenticateInstruction instruction, string issuerName, bool isAuthorizationCodeGrantType = false) { if (instruction == null) { throw new ArgumentNullException(nameof(instruction)); } Client client = null; // First we try to fetch the client_id // The different client authentication mechanisms are described here : http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication var clientId = TryGettingClientId(instruction); if (!string.IsNullOrWhiteSpace(clientId)) { client = await _clientRepository.GetClientByIdAsync(clientId).ConfigureAwait(false); } if (client == null) { return new AuthenticationResult(null, ErrorDescriptions.TheClientDoesntExist); } if (isAuthorizationCodeGrantType && client.RequirePkce) { return new AuthenticationResult(client, string.Empty); } var tokenEndPointAuthMethod = client.TokenEndPointAuthMethod; var authenticationType = Enum.GetName(typeof(TokenEndPointAuthenticationMethods), tokenEndPointAuthMethod); _oauthEventSource.StartToAuthenticateTheClient(client.ClientId, authenticationType); var errorMessage = string.Empty; switch (tokenEndPointAuthMethod) { case TokenEndPointAuthenticationMethods.client_secret_basic: client = _clientSecretBasicAuthentication.AuthenticateClient(instruction, client); if (client == null) { errorMessage = ErrorDescriptions.TheClientCannotBeAuthenticatedWithSecretBasic; } break; case TokenEndPointAuthenticationMethods.client_secret_post: client = _clientSecretPostAuthentication.AuthenticateClient(instruction, client); if (client == null) { errorMessage = ErrorDescriptions.TheClientCannotBeAuthenticatedWithSecretPost; } break; case TokenEndPointAuthenticationMethods.client_secret_jwt: if (client.Secrets == null || !client.Secrets.Any(s => s.Type == ClientSecretTypes.SharedSecret)) { errorMessage = string.Format(ErrorDescriptions.TheClientDoesntContainASharedSecret, client.ClientId); break; } return await _clientAssertionAuthentication.AuthenticateClientWithClientSecretJwtAsync(instruction, client.Secrets.First(s => s.Type == ClientSecretTypes.SharedSecret).Value, issuerName).ConfigureAwait(false); case TokenEndPointAuthenticationMethods.private_key_jwt: return await _clientAssertionAuthentication.AuthenticateClientWithPrivateKeyJwtAsync(instruction, issuerName).ConfigureAwait(false); case TokenEndPointAuthenticationMethods.tls_client_auth: client = _clientTlsAuthentication.AuthenticateClient(instruction, client); if (client == null) { errorMessage = ErrorDescriptions.TheClientCannotBeAuthenticatedWithTls; } break; } if (client != null) { _oauthEventSource.FinishToAuthenticateTheClient(client.ClientId, authenticationType); } return new AuthenticationResult(client, errorMessage); } /// <summary> /// Try to get the client id from the HTTP body or HTTP header. /// </summary> /// <param name="instruction">Authentication instruction</param> /// <returns>Client id</returns> private string TryGettingClientId(AuthenticateInstruction instruction) { var clientId = _clientAssertionAuthentication.GetClientId(instruction); if (!string.IsNullOrWhiteSpace(clientId)) { return clientId; } clientId= _clientSecretBasicAuthentication.GetClientId(instruction); if (!string.IsNullOrWhiteSpace(clientId)) { return clientId; } return _clientSecretPostAuthentication.GetClientId(instruction); } } }
46.214286
229
0.666011
[ "Apache-2.0" ]
appkins/SimpleIdentityServer
SimpleIdentityServer/src/Apis/SimpleIdServer/SimpleIdentityServer.Core/Authenticate/AuthenticateClient.cs
7,119
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 Interface.SCM; using Application.Common; using Application.Presentation; using System.Globalization; using System.Collections; using System.Diagnostics; namespace IQCare.SCM { public partial class frmHolisticBudgetView : Form { DataSet dsCostAllocationList = new DataSet(); DataTable DTItemlist = new DataTable(); DataSet dsGetDefaultDate = new DataSet(); DataSet dsHolisticBudgetViewList = new DataSet(); private const int CONST_CODEID = 201; //CHECK WITH SANJAY WHERE TO PUT THIS VALUE? public frmHolisticBudgetView() { InitializeComponent(); } private void frmHolisticBudgetView_Load(object sender, EventArgs e) { try { this.Location = new System.Drawing.Point(1, 1); clsCssStyle theStyle = new clsCssStyle(); theStyle.setStyle(this); Init_Form(); //BindDropdown(); SetRights(); } catch (Exception err) { MsgBuilder theBuilder = new MsgBuilder(); theBuilder.DataElements["MessageText"] = err.Message.ToString(); IQCareWindowMsgBox.ShowWindowConfirm("#C1", theBuilder, this); } } private void SetRights() { if (!GblIQCare.HasFunctionRight(ApplicationAccess.BudgetConfiguration, FunctionAccess.Delete, GblIQCare.dtUserRight)) { dgwHolisticBudgetView.ReadOnly = true; } } private void Init_Form() { IBudgetConfigDetail objCostAllocationlist = (IBudgetConfigDetail)ObjectFactory.CreateInstance("BusinessProcess.SCM.BBudgetConfigDetail,BusinessProcess.SCM"); dsCostAllocationList = objCostAllocationlist.GetCostAllocation(CONST_CODEID); DataRow row = dsCostAllocationList.Tables[0].NewRow(); row["Name"] = "Total Budget"; row["Id"] = "0"; dsCostAllocationList.Tables[0].Rows.InsertAt(row, 0); BindDropdown(); dsGetDefaultDate = objCostAllocationlist.GetHolisticBudgetViewDefaultYear(); if ((dsGetDefaultDate.Tables[0].Rows[0]["ProgramYear"].ToString() != "") || (dsGetDefaultDate.Tables[0].Rows[0]["ProgramYear"] != DBNull.Value)) { ddlCalendarYear.SelectedValue = dsGetDefaultDate.Tables[0].Rows[0]["ProgramYear"].ToString(); } else ddlCalendarYear.SelectedValue = DateTime.Now.Year.ToString(); //SelectedComboVal(); } private void BindDropdown() { string XmlFile = GblIQCare.GetXMLPath() + "Currency.xml"; DataSet theDSCurrencyXML = new DataSet(); theDSCurrencyXML.ReadXml(XmlFile); string CurrencyCode = theDSCurrencyXML.Tables[0].Select("Id = '" + GblIQCare.AppCountryId + "'").SingleOrDefault().ItemArray[1].ToString().Split('(').LastOrDefault().Replace(")", ""); lblCurrency.Text = "Currency: " + CurrencyCode; BindFunctions objBindControls = new BindFunctions(); DataTable theDT = new DataTable(); theDT = objBindControls.GetYears(DateTime.Now.AddYears(1).Year, "Name", "Id"); ddlCalendarYear.Items.Clear(); objBindControls.Win_BindCombo(ddlCalendarYear, theDT, "Name", "Id"); ddlCostCategory.DataSource = null; ddlCostCategory.Items.Clear(); objBindControls.Win_BindCombo(ddlCostCategory, dsCostAllocationList.Tables[0], "Name", "Id"); } private void LoadGrid(DataTable theDT) { Hashtable colHash = new Hashtable(); int j = 0; dgwHolisticBudgetView.ReadOnly = true; if (ddlCostCategory.SelectedValue != null) { if (ddlCostCategory.SelectedIndex != 0) { if (theDT.Rows.Count == 0) { IQCareWindowMsgBox.ShowWindow("No Budget Information exists.", "", "", this); } } } if (theDT.Rows.Count > 0) { DataRow row = theDT.NewRow(); row["BudgetMonthID"] = "13"; row["BudgetMonthName"] = "Total"; for (Int32 i = 5; i <= theDT.Columns.Count - 1; i++) { decimal theSum= Convert.ToDecimal(0); foreach (DataRow theSumDT in theDT.Rows) { theSum = theSum + Convert.ToDecimal(theSumDT[i]); } row[i] = theSum; } theDT.Rows.InsertAt(row, theDT.Rows.Count); } dgwHolisticBudgetView.DataSource = null; dgwHolisticBudgetView.Columns.Clear(); dgwHolisticBudgetView.AutoGenerateColumns = true; dgwHolisticBudgetView.DataSource = theDT; dgwHolisticBudgetView.Columns[0].Visible = false; dgwHolisticBudgetView.Columns[1].Visible = false; dgwHolisticBudgetView.Columns[2].Visible = false; dgwHolisticBudgetView.Columns[3].Visible = false; foreach (DataGridViewTextBoxColumn dgc in dgwHolisticBudgetView.Columns) { dgc.HeaderText = CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(dgc.HeaderText.ToLower()); dgc.Width = 270; dgc.SortMode = DataGridViewColumnSortMode.NotSortable; if (dgc.HeaderText.ToUpper() == "MONTHLYTOTAL") { //dgc.HeaderText = "Monthly Total"; dgc.HeaderText = ddlCostCategory.Text; dgc.Width = 260; } else if (dgc.HeaderText.ToUpper() == "BUDGETMONTHNAME") { dgc.HeaderText = "Month"; dgc.Width = 150; } if (dgc.HeaderText.Split('-').Count() > 1) { j = j + 1; colHash.Add(dgc.HeaderText + " %", dgc.Index + j); } } dgwHolisticBudgetView.AutoGenerateColumns = false; //foreach (DictionaryEntry item in colHash) //{ // DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn(); // col1.HeaderText = item.Key.ToString(); // col1.Name = item.Key.ToString(); // dgwHolisticBudgetView.Columns.Insert(Convert.ToInt32(item.Value), col1); //} } private DataSet LoadGridData(int costCategoryVal, int calendarYearVal) { IBudgetConfigDetail objHolisticBudgetViewList = (IBudgetConfigDetail)ObjectFactory.CreateInstance("BusinessProcess.SCM.BBudgetConfigDetail,BusinessProcess.SCM"); dsHolisticBudgetViewList = objHolisticBudgetViewList.GetHolisticBudgetView(costCategoryVal, calendarYearVal); return dsHolisticBudgetViewList; } private void ddlCostCategory_SelectedIndexChanged(object sender, EventArgs e) { SelectedComboVal(); } private void ddlCalendarYear_SelectedIndexChanged(object sender, EventArgs e) { SelectedComboVal(); } private void SelectedComboVal() { try { //if (ddlCostCategory.SelectedIndex == 0) { return; } if (ddlCalendarYear.SelectedIndex == 0) { return; } BindFunctions objBindControls = new BindFunctions(); int costCategoryVal = 0; int calendarYearVal = 0; if (ddlCostCategory.SelectedValue != null) { if (ddlCostCategory.SelectedIndex >= 0) { costCategoryVal = Convert.ToInt32(ddlCostCategory.SelectedValue); } } if (ddlCalendarYear.SelectedValue != null) { if (ddlCalendarYear.SelectedIndex != 0) { calendarYearVal = Convert.ToInt32(ddlCalendarYear.SelectedValue); } } LoadGrid(LoadGridData(costCategoryVal, calendarYearVal).Tables[0]); dgwHolisticBudgetView.Focus(); } catch (Exception err) { MsgBuilder theBuilder = new MsgBuilder(); theBuilder.DataElements["MessageText"] = err.Message.ToString(); IQCareWindowMsgBox.ShowWindowConfirm("#C1", theBuilder, this); } } public Hashtable SelectedValue(int DonorID, int ProgramID, int ProgramYearId) { Hashtable selectedValHash = new Hashtable(); selectedValHash.Add("DonorID", DonorID); selectedValHash.Add("ProgramID", ProgramID); selectedValHash.Add("ProgramYearID", ProgramYearId); return selectedValHash; } private void dgwHolisticBudgetView_GotFocus(object sender, EventArgs e) { try { ///////////DTItemlist = (DataTable)dgwHolisticBudgetView.DataSource; //////////if (DTItemlist.Rows.Count > 0) //////////{ ////////// for (int j = 5; j < dgwHolisticBudgetView.Columns.Count; ++j) ////////// { ////////// double total = 0; ////////// for (int i = 0; i < dgwHolisticBudgetView.Rows.Count - 1; ++i) ////////// { ////////// total += Convert.ToDouble(dgwHolisticBudgetView.Rows[i].Cells[j].Value); ////////// } ////////// dgwHolisticBudgetView.Rows[12].Cells[j].Value = total.ToString("F"); ////////// } //////////} foreach (DataGridViewTextBoxColumn dgc in dgwHolisticBudgetView.Columns) { if (dgc.HeaderText.Split('%').Count() > 1) { for (int f = 0; f < dgwHolisticBudgetView.Rows.Count; ++f) { dgwHolisticBudgetView.Rows[f].Cells[dgc.Index].Value = (((Convert.ToDouble(dgwHolisticBudgetView.Rows[f].Cells[dgc.Index - 1].Value)) / (Convert.ToDouble(dgwHolisticBudgetView.Rows[f].Cells[5].Value))) * 100).ToString("F").Replace("NaN", "0.00"); } } } } catch (Exception err) { MsgBuilder theBuilder = new MsgBuilder(); theBuilder.DataElements["MessageText"] = err.Message.ToString(); IQCareWindowMsgBox.ShowWindowConfirm("#C1", theBuilder, this); } } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } } }
42.108209
274
0.544262
[ "MIT" ]
uon-coehm/IQCare
SourceBase/IQCare Management/IQCare.SCM/frmHolisticBudgetView.cs
11,287
C#
using System; using FluentAssertions.Specs.Primitives; using Xunit; using Xunit.Sdk; namespace FluentAssertions.Specs.Types { /// <content> /// The [Not]BeAssignableTo specs. /// </content> public partial class TypeAssertionSpecs { #region BeAssignableTo [Fact] public void When_its_own_type_it_succeeds() { // Arrange / Act / Assert typeof(DummyImplementingClass).Should().BeAssignableTo<DummyImplementingClass>(); } [Fact] public void When_its_base_type_it_succeeds() { // Arrange / Act / Assert typeof(DummyImplementingClass).Should().BeAssignableTo<DummyBaseClass>(); } [Fact] public void When_implemented_interface_type_it_succeeds() { // Arrange / Act / Assert typeof(DummyImplementingClass).Should().BeAssignableTo<IDisposable>(); } [Fact] public void When_an_unrelated_type_it_fails() { // Arrange Type someType = typeof(DummyImplementingClass); Action act = () => someType.Should().BeAssignableTo<DateTime>("we want to test the failure {0}", "message"); // Act / Assert act.Should().Throw<XunitException>() .WithMessage( "Expected someType *.DummyImplementingClass to be assignable to *.DateTime *failure message*" + ", but it is not."); } [Fact] public void When_its_own_type_instance_it_succeeds() { // Arrange / Act / Assert typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(DummyImplementingClass)); } [Fact] public void When_its_base_type_instance_it_succeeds() { // Arrange / Act / Assert typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(DummyBaseClass)); } [Fact] public void When_an_implemented_interface_type_instance_it_succeeds() { // Arrange / Act / Assert typeof(DummyImplementingClass).Should().BeAssignableTo(typeof(IDisposable)); } [Fact] public void When_an_unrelated_type_instance_it_fails() { // Arrange Type someType = typeof(DummyImplementingClass); // Act Action act = () => someType.Should().BeAssignableTo(typeof(DateTime), "we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("*.DummyImplementingClass to be assignable to *.DateTime *failure message*"); } [Fact] public void When_constructed_of_open_generic_it_succeeds() { // Arrange / Act / Assert typeof(IDummyInterface<IDummyInterface>).Should().BeAssignableTo(typeof(IDummyInterface<>)); } [Fact] public void When_implementation_of_open_generic_interface_it_succeeds() { // Arrange / Act / Assert typeof(ClassWithGenericBaseType).Should().BeAssignableTo(typeof(IDummyInterface<>)); } [Fact] public void When_derived_of_open_generic_class_it_succeeds() { // Arrange / Act / Assert typeof(ClassWithGenericBaseType).Should().BeAssignableTo(typeof(DummyBaseType<>)); } [Fact] public void When_unrelated_to_open_generic_interface_it_fails() { // Arrange Type someType = typeof(IDummyInterface); // Act Action act = () => someType.Should().BeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected someType *.IDummyInterface to be assignable to *.IDummyInterface`1[T] *failure message*" + ", but it is not."); } [Fact] public void When_unrelated_to_open_generic_type_it_fails() { // Arrange Type someType = typeof(ClassWithAttribute); Action act = () => someType.Should().BeAssignableTo(typeof(DummyBaseType<>), "we want to test the failure {0}", "message"); // Act / Assert act.Should().Throw<XunitException>() .WithMessage("*.ClassWithAttribute to be assignable to *.DummyBaseType* *failure message*"); } [Fact] public void When_asserting_an_open_generic_class_is_assignable_to_itself_it_succeeds() { // Arrange / Act / Assert typeof(DummyBaseType<>).Should().BeAssignableTo(typeof(DummyBaseType<>)); } [Fact] public void When_asserting_a_type_to_be_assignable_to_null_it_should_throw() { // Arrange var type = typeof(DummyBaseType<>); // Act Action act = () => type.Should().BeAssignableTo(null); // Assert act.Should().ThrowExactly<ArgumentNullException>() .WithParameterName("type"); } #endregion #region NotBeAssignableTo [Fact] public void When_its_own_type_and_asserting_not_assignable_it_fails() { // Arrange var type = typeof(DummyImplementingClass); // Act Action act = () => type.Should().NotBeAssignableTo<DummyImplementingClass>("we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected type *.DummyImplementingClass to not be assignable to *.DummyImplementingClass *failure message*"); } [Fact] public void When_its_base_type_and_asserting_not_assignable_it_fails() { // Arrange var type = typeof(DummyImplementingClass); // Act Action act = () => type.Should().NotBeAssignableTo<DummyBaseClass>("we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected type *.DummyImplementingClass to not be assignable to *.DummyBaseClass *failure message*" + ", but it is."); } [Fact] public void When_implemented_interface_type_and_asserting_not_assignable_it_fails() { // Arrange var type = typeof(DummyImplementingClass); // Act Action act = () => type.Should().NotBeAssignableTo<IDisposable>("we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected type *.DummyImplementingClass to not be assignable to *.IDisposable *failure message*, but it is."); } [Fact] public void When_an_unrelated_type_and_asserting_not_assignable_it_succeeds() { // Arrange / Act / Assert typeof(DummyImplementingClass).Should().NotBeAssignableTo<DateTime>(); } [Fact] public void When_its_own_type_instance_and_asserting_not_assignable_it_fails() { // Arrange var type = typeof(DummyImplementingClass); // Act Action act = () => type.Should().NotBeAssignableTo(typeof(DummyImplementingClass), "we want to test the failure {0}", "message"); // Act / Assert act.Should().Throw<XunitException>() .WithMessage( "Expected type *.DummyImplementingClass to not be assignable to *.DummyImplementingClass *failure message*" + ", but it is."); } [Fact] public void When_its_base_type_instance_and_asserting_not_assignable_it_fails() { // Arrange var type = typeof(DummyImplementingClass); // Act Action act = () => type.Should().NotBeAssignableTo(typeof(DummyBaseClass), "we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected type *.DummyImplementingClass to not be assignable to *.DummyBaseClass *failure message*" + ", but it is."); } [Fact] public void When_an_implemented_interface_type_instance_and_asserting_not_assignable_it_fails() { // Arrange var type = typeof(DummyImplementingClass); // Act Action act = () => type.Should().NotBeAssignableTo(typeof(IDisposable), "we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected type *.DummyImplementingClass to not be assignable to *.IDisposable *failure message*, but it is."); } [Fact] public void When_an_unrelated_type_instance_and_asserting_not_assignable_it_succeeds() { // Arrange / Act / Assert typeof(DummyImplementingClass).Should().NotBeAssignableTo(typeof(DateTime)); } [Fact] public void When_unrelated_to_open_generic_interface_and_asserting_not_assignable_it_succeeds() { // Arrange / Act / Assert typeof(ClassWithAttribute).Should().NotBeAssignableTo(typeof(IDummyInterface<>)); } [Fact] public void When_unrelated_to_open_generic_class_and_asserting_not_assignable_it_succeeds() { // Arrange / Act / Assert typeof(ClassWithAttribute).Should().NotBeAssignableTo(typeof(DummyBaseType<>)); } [Fact] public void When_implementation_of_open_generic_interface_and_asserting_not_assignable_it_fails() { // Arrange Type type = typeof(ClassWithGenericBaseType); // Act Action act = () => type.Should().NotBeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected type *.ClassWithGenericBaseType to not be assignable to *.IDummyInterface`1[T] *failure message*" + ", but it is."); } [Fact] public void When_derived_from_open_generic_class_and_asserting_not_assignable_it_fails() { // Arrange Type type = typeof(ClassWithGenericBaseType); // Act Action act = () => type.Should().NotBeAssignableTo(typeof(IDummyInterface<>), "we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage( "Expected type *.ClassWithGenericBaseType to not be assignable to *.IDummyInterface`1[T] *failure message*" + ", but it is."); } [Fact] public void When_asserting_a_type_not_to_be_assignable_to_null_it_should_throw() { // Arrange var type = typeof(DummyBaseType<>); // Act Action act = () => type.Should().NotBeAssignableTo(null); // Assert act.Should().ThrowExactly<ArgumentNullException>() .WithParameterName("type"); } #endregion } }
34.725146
130
0.571236
[ "Apache-2.0" ]
ABergBN/fluentassertions
Tests/FluentAssertions.Specs/Types/TypeAssertionSpecs.BeAssignableTo.cs
11,878
C#
using System; using NHapi.Base.Model; using NHapi.Base; using NHapi.Base.Model.Primitive; namespace NHapi.Model.V28.Datatype { ///<summary> ///Represents the HL7 NM (Numeric) datatype. A NM contains a single String value. ///</summary> [Serializable] public class NM : AbstractPrimitive { ///<summary> ///Constructs an uninitialized NM. ///<param name="message">The Message to which this Type belongs</param> ///</summary> public NM(IMessage message) : base(message){ } ///<summary> ///Constructs an uninitialized NM. ///<param name="message">The Message to which this Type belongs</param> ///<param name="description">The description of this type</param> ///</summary> public NM(IMessage message, string description) : base(message,description){ } ///<summary> /// @return "2.8" ///</summary> public string getVersion() { return "2.8"; } } }
24.857143
82
0.695402
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V28/Datatype/NM.cs
870
C#
using System; using System.Collections.Generic; using UnityEngine; using Object = System.Object; namespace UniMediator.Internal { /// <summary> /// Lazily allocates a List only when more than 1 item is added. Beware this /// is a Value Type and will behave in unexpected ways if you use it as you /// would a reference type, like a regular List /// </summary> /// <typeparam name="T">The type the elements in this List</typeparam> internal struct LazySingleItemList<T> { private List<T> _list; private T _item0; private int _count; public int Count => _count; public void Add(T item) { if (_count == 0 && _list == null) { _item0 = item; } else if (_count == 1 && _list == null) { _list = new List<T>(4) { _item0, item }; } else { _list.Add(item); } _count++; } public T this[int index] { get { if (index == 0 && _list == null) return _item0; return _list[index]; } } /// <summary> /// Removes an item from the List by removing the last item and using it to /// replace the item to be removed. Prevents array elements having to shift to /// the left, but does not maintain ordering /// </summary> /// <param name="item">The item to be removed</param> public void FastRemove(T item) { if (_count == 0) return; if (_list == null) { _item0 = default(T); } else { T last = GetAndRemoveLast(); if (!EqualityComparer<T>.Default.Equals(last, item)) { _list[_list.IndexOf(item)] = last; } } _count--; } private T GetAndRemoveLast() { int lastIdx = _list.Count - 1; T last = _list[lastIdx]; _list.RemoveAt(lastIdx); return last; } } }
27.487805
86
0.4685
[ "MIT" ]
tharinga/UniMediator
Runtime/Internal/LazySingleItemList.cs
2,254
C#
using System; namespace Feedz.Client.Resources { public class PackageVersionResponse : IResource { public Guid Id { get; set; } public string PackageId { get; set; } public string Version { get; set; } public int DownloadCount { get; set; } public bool Listed { get; set; } public bool Pinned { get; set; } public long PackageSize { get; set; } public DateTimeOffset LastUpdated { get; set; } public string Tags { get; set; } } }
30.294118
55
0.601942
[ "Apache-2.0" ]
feedz-io/Client
src/Client/Resources/PackageVersionResponse.cs
517
C#
/* * 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; namespace Contrib.Regex { /// <summary> /// C# Regex based implementation of <see cref="IRegexCapabilities"/>. /// </summary> /// <remarks>http://www.java2s.com/Open-Source/Java-Document/Net/lucene-connector/org/apache/lucene/search/regex/JavaUtilRegexCapabilities.java.htm</remarks> public class CSharpRegexCapabilities : IRegexCapabilities, IEquatable<CSharpRegexCapabilities> { private System.Text.RegularExpressions.Regex _rPattern; /// <summary> /// Called by the constructor of <see cref="RegexTermEnum"/> allowing implementations to cache /// a compiled version of the regular expression pattern. /// </summary> /// <param name="pattern">regular expression pattern</param> public void Compile(string pattern) { _rPattern = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.Compiled); } /// <summary> /// True on match. /// </summary> /// <param name="s">text to match</param> /// <returns>true on match</returns> public bool Match(string s) { return _rPattern.IsMatch(s); } /// <summary> /// A wise prefix implementation can reduce the term enumeration (and thus performance) /// of RegexQuery dramatically. /// </summary> /// <returns>static non-regex prefix of the pattern last passed to <see cref="IRegexCapabilities.Compile"/>. /// May return null</returns> public string Prefix() { return null; } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> /// <param name="other">An object to compare with this object</param> public bool Equals(CSharpRegexCapabilities other) { if (other == null) return false; if (this == other) return true; if (_rPattern != null ? !_rPattern.Equals(other._rPattern) : other._rPattern != null) return false; return true; } public override bool Equals(object obj) { if (obj as CSharpRegexCapabilities == null) return false; return Equals((CSharpRegexCapabilities) obj); } public override int GetHashCode() { return (_rPattern != null ? _rPattern.GetHashCode() : 0); } } }
34.76087
159
0.690432
[ "Apache-2.0" ]
Anomalous-Software/Lucene.NET
src/contrib/Regex/CSharpRegexCapabilities.cs
3,200
C#
namespace NerdCats.Owin { using System.Collections.Generic; using Microsoft.Owin; /// <summary> /// Generic interface to define a http forwarded header wrapper /// </summary> public interface IForwardedHeaders { /// <summary> /// Forwarded port value defined X-Forwarded-Port header. Ignored in RFC-7239 implementation here /// </summary> int? ForwardedPort { get; } /// <summary> /// List of forwarder sets found in the header description /// </summary> List<ForwarderSet> Forwarders { get; set; } /// <summary> /// Apply changes to the current http request according to the forwarders found in the header /// </summary> /// <param name="request">Owin request context</param> /// <returns>Updated set of headers after applying the changes</returns> IHeaderDictionary ApplyForwardedHeaders(IOwinRequest request); } }
37
105
0.634096
[ "MIT" ]
thehoneymad/OwinForwardedHeaderMiddleware
NerdCats.Owin.ForwardedHeaders/NerdCats.Owin.ForwardedHeaders/IForwardedHeaders.cs
964
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d12.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public partial struct D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { [NativeTypeName("D3D12_GPU_VIRTUAL_ADDRESS")] public ulong Dest; [NativeTypeName("UINT32")] public uint Value; } }
31.352941
145
0.722326
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/d3d12/D3D12_WRITEBUFFERIMMEDIATE_PARAMETER.cs
535
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticbeanstalk-2010-12-01.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.ElasticBeanstalk.Model { /// <summary> /// The specified account has reached its limit of Amazon S3 buckets. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class TooManyBucketsException : AmazonElasticBeanstalkException { /// <summary> /// Constructs a new TooManyBucketsException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public TooManyBucketsException(string message) : base(message) {} /// <summary> /// Construct instance of TooManyBucketsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TooManyBucketsException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of TooManyBucketsException /// </summary> /// <param name="innerException"></param> public TooManyBucketsException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of TooManyBucketsException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TooManyBucketsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of TooManyBucketsException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TooManyBucketsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the TooManyBucketsException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected TooManyBucketsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
47.282258
178
0.68088
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/ElasticBeanstalk/Generated/Model/TooManyBucketsException.cs
5,863
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using Mods; using ExtraOptions; public static class Options { private static OptionsUI optionsUI; public static string Playmat; public static string BackgroundImage; public static string CheckVersionUrl; public static float MusicVolume; public static float SfxVolume; public static float AnimationSpeed; public static float ManeuverSpeed; public static string Avatar; public static string NickName; public static string Title; public static string Edition; public static bool DontShowAiInfo; public static string AiType; public static string DiceStats; public static bool FullScreen; public static bool ShowFps; public static int Quality; public static string Resolution; public static readonly string DefaultAvatar = "UpgradesList.FirstEdition.VeteranInstincts"; static Options() { ReadOptions(); } public static void ReadOptions() { Playmat = PlayerPrefs.GetString("PlaymatName", "Endor"); BackgroundImage = PlayerPrefs.GetString("BackgroundImage", "_RANDOM"); CheckVersionUrl = PlayerPrefs.GetString("CheckVersionUrl", "http://sandrem.freeasphost.net/data/currentversion.txt"); MusicVolume = PlayerPrefs.GetFloat("Music Volume", 0.25f); SfxVolume = PlayerPrefs.GetFloat("SFX Volume", 0.25f); AnimationSpeed = PlayerPrefs.GetFloat("Animation Speed", 0.25f); ManeuverSpeed = PlayerPrefs.GetFloat("Maneuver Speed", 0.25f); Avatar = PlayerPrefs.GetString("Avatar", Options.DefaultAvatar); NickName = PlayerPrefs.GetString("NickName", "Unknown Pilot"); Title = PlayerPrefs.GetString("Title", "Test Pilot"); DontShowAiInfo = PlayerPrefs.GetInt("DontShowAiInfo", 0) == 1; AiType = PlayerPrefs.GetString("AiType", "AI: Aggressor"); Edition = PlayerPrefs.GetString("Edition", "SecondEdition"); FullScreen = PlayerPrefs.GetInt("FullScreen", 1) == 1; ShowFps = PlayerPrefs.GetInt("ShowFps", 0) == 1; Resolution = PlayerPrefs.GetString("Resolution", Screen.currentResolution.ToString()); Quality = PlayerPrefs.GetInt("Quality", 4); DiceStats = PlayerPrefs.GetString("DiceStats", "AT-0|AC-0|AS-0|AE-0|AB-0|DT-0|DS-0|DE-0|DB-0&AT-0|AC-0|AS-0|AE-0|AB-0|DT-0|DS-0|DE-0|DB-0"); DiceStatsTracker.ReadFromString(DiceStats); MainMenu.SetEdition(Edition); ReadMods(); } private static void ReadMods() { foreach (var modHolder in ModsManager.Mods) { modHolder.Value.IsOn = PlayerPrefs.GetInt("mods/" + modHolder.Key.ToString(), 0) == 1; } } public static void InitializePanel() { optionsUI = GameObject.Find("UI/Panels/OptionsPanel").GetComponentInChildren<OptionsUI>(); SetPlaymatOption(); SetValueControllers(); } private static void SetPlaymatOption() { foreach (Transform playmatImage in optionsUI.transform.Find("PlaymatsSelection/ImageList")) { if (playmatImage.name == Playmat) { optionsUI.PlaymatSelector.transform.position = playmatImage.transform.position; break; } } } private static void SetValueControllers() { foreach (OptionsValueController valueController in GameObject.Find("UI/Panels/OptionsPanel").GetComponentsInChildren<OptionsValueController>()) { valueController.Start(); } } public static void ChangeParameterValue(string parameter, float value) { PlayerPrefs.SetFloat(parameter, value); PlayerPrefs.Save(); switch (parameter) { case "Music Volume": MusicVolume = value; SetMusicVolume(value); break; case "SFX Volume": SfxVolume = value; break; case "Animation Speed": AnimationSpeed = value; break; case "Maneuver Speed": ManeuverSpeed = value; break; default: break; } } public static void ChangeParameterValue(string parameter, string value) { PlayerPrefs.SetString(parameter, value); PlayerPrefs.Save(); } public static void ChangeParameterValue(string parameter, bool value) { PlayerPrefs.SetInt(parameter, (value) ? 1 : 0); PlayerPrefs.Save(); } public static void ChangeParameterValue(string parameter, int value) { PlayerPrefs.SetInt(parameter, value); PlayerPrefs.Save(); } public static void UpdateVolume() { SetMusicVolume(PlayerPrefs.GetFloat("Music Volume", 0.25f)); } private static void SetMusicVolume(float value) { GameObject.Find("Music").GetComponent<AudioSource>().volume = value * 0.2f; } public static void SetCheckVersionUrl(string newUrl) { PlayerPrefs.SetString("CheckVersionUrl", newUrl); CheckVersionUrl = newUrl; } }
32.018405
151
0.640353
[ "MIT" ]
DavinFelth23/FlyCasual
Assets/Scripts/MainMenu/Model/Options.cs
5,221
C#
// /* // Copyright (c) 2017-12 // // moljac // Test.cs // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // */ #if XUNIT using Xunit; // NUnit aliases using Test = Xunit.FactAttribute; using OneTimeSetUp = HolisticWare.Core.Testing.UnitTests.UnitTestsCompatibilityAliasAttribute; // XUnit aliases using TestClass = HolisticWare.Core.Testing.UnitTests.UnitTestsCompatibilityAliasAttribute; #elif NUNIT using NUnit.Framework; // MSTest aliases using TestInitialize = NUnit.Framework.SetUpAttribute; using TestProperty = NUnit.Framework.PropertyAttribute; using TestClass = HolisticWare.Core.Testing.UnitTests.UnitTestsCompatibilityAliasAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; // XUnit aliases using Fact = NUnit.Framework.TestAttribute; #elif MSTEST using Microsoft.VisualStudio.TestTools.UnitTesting; // NUnit aliases using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using OneTimeSetUp = Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute; // XUnit aliases using Fact = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; #endif #if BENCHMARKDOTNET using BenchmarkDotNet.Running; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Attributes.Jobs; #else using Benchmark = HolisticWare.Core.Testing.BenchmarkTests.Benchmark; using ShortRunJob = HolisticWare.Core.Testing.BenchmarkTests.ShortRunJob; #endif using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using System.Collections.ObjectModel; using Core.Math.Statistics.Descriptive.Sequential; namespace UnitTests.Core.Math.Statistics.Descriptive.Sequential.Sync { public partial class Tests20180119Dataset02 { } }
37.692308
95
0.762585
[ "MIT" ]
HolisticWare/HolisticWare.Core.Math.Statistics.Descriptive.Sequential
tests/Tests.CommonShared/01-DarkVaderTests/Tests20180119Dataset02/Tests09MeasuresDispersion.StandardDeviation.cs
2,942
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace WebApplication.Entities { public class Persons { [Key] public int IdPerson { get; set; } public string FirstName { get; set; } public string Surname { get; set; } public string Position { get; set; } } }
21
45
0.656642
[ "MIT" ]
gitekamerica/MAGc
WebApplication/Entities/Persons.cs
401
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 ReactiveUI; using Xamarin.Forms; namespace ReactiveUI.XamForms { /// <summary> /// This is an <see cref="ViewCell"/> that is also an <see cref="IViewFor{T}"/>. /// </summary> /// <typeparam name="TViewModel">The type of the view model.</typeparam> /// <seealso cref="Xamarin.Forms.ViewCell" /> /// <seealso cref="ReactiveUI.IViewFor{TViewModel}" /> public class ReactiveViewCell<TViewModel> : ViewCell, IViewFor<TViewModel> where TViewModel : class { /// <summary> /// The view model bindable property. /// </summary> public static readonly BindableProperty ViewModelProperty = BindableProperty.Create( nameof(ViewModel), typeof(TViewModel), typeof(ReactiveViewCell<TViewModel>), default(TViewModel), BindingMode.OneWay, propertyChanged: OnViewModelChanged); /// <inheritdoc/> public TViewModel ViewModel { get => (TViewModel)GetValue(ViewModelProperty); set => SetValue(ViewModelProperty, value); } /// <inheritdoc/> object IViewFor.ViewModel { get => ViewModel; set => ViewModel = (TViewModel)value; } /// <inheritdoc/> protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); ViewModel = BindingContext as TViewModel; } private static void OnViewModelChanged(BindableObject bindableObject, object oldValue, object newValue) { bindableObject.BindingContext = newValue; } } }
32.842105
111
0.616453
[ "MIT" ]
Nilox/ReactiveUI
src/ReactiveUI.XamForms/ReactiveViewCell.cs
1,874
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the storagegateway-2013-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.StorageGateway.Model { /// <summary> /// /// </summary> public partial class CreateCachediSCSIVolumeResult : AmazonWebServiceResponse { private string _targetARN; private string _volumeARN; /// <summary> /// Gets and sets the property TargetARN. /// </summary> public string TargetARN { get { return this._targetARN; } set { this._targetARN = value; } } // Check to see if TargetARN property is set internal bool IsSetTargetARN() { return this._targetARN != null; } /// <summary> /// Gets and sets the property VolumeARN. /// </summary> public string VolumeARN { get { return this._volumeARN; } set { this._volumeARN = value; } } // Check to see if VolumeARN property is set internal bool IsSetVolumeARN() { return this._volumeARN != null; } } }
27.826087
112
0.63125
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet35/Amazon.StorageGateway/Model/CreateCachediSCSIVolumeResult.cs
1,920
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Raven.Client; using Raven.Database.Config; using Raven.Server; namespace Mileage.Tests.RavenDBConcurrency { public class Data { public string Id { get; set; } public string Name { get; set; } } class Program { static void Main(string[] args) { var ravenDbServer = new RavenDbServer(new RavenConfiguration { RunInMemory = true }); ravenDbServer.Initialize(); WorkWithDocumentStore(ravenDbServer.DocumentStore).Wait(); } private static async Task WorkWithDocumentStore(IDocumentStore documentStore) { using (var session = documentStore.OpenAsyncSession()) { await session.StoreAsync(new Data { Id = "Data/1", Name = "asdf" }); await session.SaveChangesAsync(); } using (var session = documentStore.OpenAsyncSession()) { await session.StoreAsync(new Data { Id = "Data/1", Name = "jklö" }); await session.SaveChangesAsync(); } using (var session = documentStore.OpenAsyncSession()) { var data = await session.LoadAsync<Data>("Data/1"); } } } }
26.508475
85
0.516624
[ "MIT" ]
haefele/Mileage
src/05 Tests/Mileage.Tests.RavenDBConcurrency/Program.cs
1,567
C#
// SPDX-License-Identifier: BSD-3-Clause // // Copyright 2020 Raritan Inc. All rights reserved. // // This file was generated by IdlC from PeripheralDeviceManager.idl. using System; using System.Linq; using LightJson; using Com.Raritan.Idl; using Com.Raritan.JsonRpc; using Com.Raritan.Util; #pragma warning disable 0108, 0219, 0414, 1591 namespace Com.Raritan.JsonRpc.peripheral.DeviceManager_2_0_1 { public class PackageAddedEvent_ValObjCodec : Com.Raritan.JsonRpc.peripheral.DeviceManager_2_0_1.PackageEvent_ValObjCodec { public static new void Register() { ValueObjectCodec.RegisterCodec(Com.Raritan.Idl.peripheral.DeviceManager_2_0_1.PackageAddedEvent.typeInfo, new PackageAddedEvent_ValObjCodec()); } public override void EncodeValObj(LightJson.JsonObject json, ValueObject vo) { base.EncodeValObj(json, vo); var inst = (Com.Raritan.Idl.peripheral.DeviceManager_2_0_1.PackageAddedEvent)vo; } public override ValueObject DecodeValObj(ValueObject vo, LightJson.JsonObject json, Agent agent) { Com.Raritan.Idl.peripheral.DeviceManager_2_0_1.PackageAddedEvent inst; if (vo == null) { inst = new Com.Raritan.Idl.peripheral.DeviceManager_2_0_1.PackageAddedEvent(); } else { inst = (Com.Raritan.Idl.peripheral.DeviceManager_2_0_1.PackageAddedEvent)vo; } base.DecodeValObj(vo, json, agent); return inst; } } }
34.463415
149
0.753008
[ "BSD-3-Clause" ]
gregoa/raritan-pdu-json-rpc-sdk
pdu-dotnet-api/_idlc_gen/dotnet/Com/Raritan/JsonRpc/peripheral/DeviceManager_2_0_1/PackageAddedEvent_ValObjCodec.cs
1,413
C#
/* // <copyright> // dotNetRDF is free and open source software licensed under the MIT License // ------------------------------------------------------------------------- // // Copyright (c) 2009-2020 dotNetRDF Project (http://dotnetrdf.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> */ using System; using VDS.RDF.Query.Construct; namespace VDS.RDF.Query.Patterns { /// <summary> /// Pattern which matches the Blank Node with the given Internal ID regardless of the Graph the nodes come from. /// </summary> public class FixedBlankNodePattern : PatternItem { private String _id; /// <summary> /// Creates a new Fixed Blank Node Pattern. /// </summary> /// <param name="id">ID.</param> public FixedBlankNodePattern(String id) { if (id.StartsWith("_:")) { _id = id.Substring(2); } else { _id = id; } } /// <summary> /// Gets the Blank Node ID. /// </summary> public String InternalID { get { return _id; } } /// <summary> /// Checks whether the pattern accepts the given Node. /// </summary> /// <param name="context">SPARQL Evaluation Context.</param> /// <param name="obj">Node to test.</param> /// <returns></returns> protected internal override bool Accepts(SparqlEvaluationContext context, INode obj) { if (obj.NodeType == NodeType.Blank) { return ((IBlankNode)obj).InternalID.Equals(_id); } else { return false; } } /// <summary> /// Returns a Blank Node with a fixed ID scoped to whichever graph is provided. /// </summary> /// <param name="context">Construct Context.</param> protected internal override INode Construct(ConstructContext context) { if (context.Graph != null) { IBlankNode b = context.Graph.GetBlankNode(_id); if (b != null) { return b; } else { return context.Graph.CreateBlankNode(_id); } } else { return new BlankNode(context.Graph, _id); } } /// <summary> /// Gets the String representation of the Pattern Item. /// </summary> /// <returns></returns> public override string ToString() { return "<_:" + _id + ">"; } } }
32.525424
116
0.549766
[ "MIT" ]
blackwork/dotnetrdf
Libraries/dotNetRDF/Query/Patterns/FixedBlankNodePattern.cs
3,838
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ExpenseMgr.API { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
24.192308
62
0.63593
[ "MIT" ]
simonbassey/ExpenseManagerAPI
src/ExpenseMgr.API/Program.cs
631
C#
using System; using System.Text; namespace Castaway.Assets { [Loads("txt")] public class TextAssetType : IAssetType { public T To<T>(Asset a) { if (typeof(T) == typeof(string)) return (T) (dynamic) Encoding.UTF8.GetString(a.GetBytes()); throw new InvalidOperationException($"Cannot convert TextAssetType to {typeof(T).FullName}"); } } }
26.0625
105
0.594724
[ "MIT" ]
LiamCoal/castaway
Castaway.Assets/TextAssetType.cs
417
C#
using System; using System.Collections.Generic; using System.Text; namespace Polly.Contrib.BlankTemplate // Choose a namespace indicating the theme of your contrib. { /// <summary> /// Rename this class and build your contribution. /// </summary> public class MyContrib { } }
21.642857
98
0.689769
[ "BSD-3-Clause" ]
Polly-Contrib/Polly.Contrib.BlankTemplate
src/Polly.Contrib.BlankTemplate/MyContrib.cs
305
C#
using System; using System.Diagnostics; namespace org.apache.utils { internal class ZooKeeperLogger { internal static readonly ZooKeeperLogger Instance = new ZooKeeperLogger(); internal ILogConsumer CustomLogConsumer; internal TraceLevel LogLevel = TraceLevel.Warning; private readonly LogWriter logWriter = new LogWriter(); internal bool LogToFile { get { return logWriter.LogToFile; } set { logWriter.LogToFile = value; } } internal bool LogToTrace { get { return logWriter.LogToTrace; } set { logWriter.LogToTrace = value; } } internal string LogFileName { get { return logWriter.FileName; } } internal void Log(TraceLevel sev, string className, string message, Exception exception = null) { if (sev > LogLevel) { return; } logWriter.Log(sev, className, message, exception); var logConsumer = CustomLogConsumer; if (logConsumer == null) return; try { logConsumer.Log(sev, className, message, exception); } catch (Exception e) { Trace.TraceError( $@"Exception while passing a log message to log consumer. TraceLogger type:{logConsumer.GetType().FullName}, name:{className}, severity:{sev}, message:{message}, message exception:{exception}, log consumer exception:{e}"); } } } }
31.745098
136
0.562075
[ "Apache-2.0" ]
jabellard/zookeeper
src/csharp/src/ZooKeeperNetEx/utils/log/ZooKeeperLogger.cs
1,619
C#
using System; using System.Globalization; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers; using Xunit; using ReDocApp = ReDoc; namespace Swashbuckle.AspNetCore.IntegrationTests { public class SwaggerGenIntegrationTests { [Theory] [InlineData(typeof(Basic.Startup), "/swagger/v1/swagger.json")] [InlineData(typeof(CliExample.Startup), "/api-docs/v1/swagger.json")] //[InlineData(typeof(ConfigFromFile.Startup), "/swagger/v1/swagger.json")] [InlineData(typeof(CustomUIConfig.Startup), "/swagger/v1/swagger.json")] [InlineData(typeof(CustomUIIndex.Startup), "/swagger/v1/swagger.json")] [InlineData(typeof(GenericControllers.Startup), "/swagger/v1/swagger.json")] [InlineData(typeof(MultipleVersions.Startup), "/swagger/1.0/swagger.json")] [InlineData(typeof(MultipleVersions.Startup), "/swagger/2.0/swagger.json")] //[InlineData(typeof(NetCore21.Startup), "/swagger/v1/swagger.json")] [InlineData(typeof(OAuth2Integration.Startup), "/resource-server/swagger/v1/swagger.json")] [InlineData(typeof(ReDocApp.Startup), "/api-docs/v1/swagger.json")] [InlineData(typeof(TestFirst.Startup), "/api-docs/v1-generated/openapi.json")] public async Task SwaggerEndpoint_ReturnsValidSwaggerJson( Type startupType, string swaggerRequestUri) { var testSite = new TestSite(startupType); var client = testSite.BuildClient(); var swaggerResponse = await client.GetAsync(swaggerRequestUri); swaggerResponse.EnsureSuccessStatusCode(); await AssertResponseDoesNotContainByteOrderMark(swaggerResponse); await AssertValidSwaggerAsync(swaggerResponse); } [Theory] [InlineData("en-US")] [InlineData("sv-SE")] public async Task SwaggerEndpoint_ReturnsCorrectPriceExample_ForDifferentCultures(string culture) { var testSite = new TestSite(typeof(Basic.Startup)); var client = testSite.BuildClient(); var swaggerResponse = await client.GetAsync($"/swagger/v1/swagger.json?culture={culture}"); swaggerResponse.EnsureSuccessStatusCode(); var contentStream = await swaggerResponse.Content.ReadAsStreamAsync(); var currentCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; try { var openApiDocument = new OpenApiStreamReader().Read(contentStream, out OpenApiDiagnostic diagnostic); var example = openApiDocument.Components.Schemas["Product"].Example as OpenApiObject; var price = (example["price"] as OpenApiDouble); Assert.NotNull(price); Assert.Equal(14.37, price.Value); } finally { CultureInfo.CurrentCulture = currentCulture; } } [Fact] public async Task SwaggerEndpoint_ReturnsNotFound_IfUnknownSwaggerDocument() { var testSite = new TestSite(typeof(Basic.Startup)); var client = testSite.BuildClient(); var swaggerResponse = await client.GetAsync("/swagger/v2/swagger.json"); Assert.Equal(System.Net.HttpStatusCode.NotFound, swaggerResponse.StatusCode); } [Theory] [InlineData("tempuri.org", null, null, null, "http://tempuri.org")] [InlineData("tempuri.org:8080", null, null, null, "http://tempuri.org:8080")] [InlineData("tempuri.org", "https", "443", null, "https://tempuri.org")] [InlineData("tempuri.org", null, "8080", null, "http://tempuri.org:8080")] [InlineData("tempuri.org", null, null, "/foo", "http://tempuri.org/foo")] public async Task SwaggerEndpoint_InfersServerMetadataFromReverseProxyHeaders_IfPresent( string xForwardedHost, string xForwardedProto, string xForwardedPort, string xForwardedPrefix, string expectedServerUrl) { var testSite = new TestSite(typeof(Basic.Startup)); var client = testSite.BuildClient(); if (xForwardedHost != null) client.DefaultRequestHeaders.Add("X-Forwarded-Host", xForwardedHost); if (xForwardedProto != null) client.DefaultRequestHeaders.Add("X-Forwarded-Proto", xForwardedProto); if (xForwardedPort != null) client.DefaultRequestHeaders.Add("X-Forwarded-Port", xForwardedPort); if (xForwardedPrefix != null) client.DefaultRequestHeaders.Add("X-Forwarded-Prefix", xForwardedPrefix); var swaggerResponse = await client.GetAsync("/swagger/v1/swagger.json"); var contentStream = await swaggerResponse.Content.ReadAsStreamAsync(); var openApiDocument = new OpenApiStreamReader().Read(contentStream, out _); Assert.NotNull(openApiDocument.Servers); Assert.NotEmpty(openApiDocument.Servers); Assert.Equal(expectedServerUrl, openApiDocument.Servers[0].Url); } private async Task AssertResponseDoesNotContainByteOrderMark(HttpResponseMessage swaggerResponse) { var responseAsByteArray = await swaggerResponse.Content.ReadAsByteArrayAsync(); var bomByteArray = Encoding.UTF8.GetPreamble(); var byteIndex = 0; var doesContainBom = true; while (byteIndex < bomByteArray.Length && doesContainBom) { if (bomByteArray[byteIndex] != responseAsByteArray[byteIndex]) { doesContainBom = false; } byteIndex += 1; } Assert.False(doesContainBom); } private async Task AssertValidSwaggerAsync(HttpResponseMessage swaggerResponse) { var contentStream = await swaggerResponse.Content.ReadAsStreamAsync(); var openApiDocument = new OpenApiStreamReader().Read(contentStream, out OpenApiDiagnostic diagnostic); Assert.Equal(Enumerable.Empty<OpenApiError>(), diagnostic.Errors); } } }
42.450331
118
0.64571
[ "MIT" ]
aelij/Swashbuckle.AspNetCore
test/Swashbuckle.AspNetCore.IntegrationTests/SwaggerGenIntegrationTests.cs
6,412
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace UILab { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.206897
71
0.628947
[ "MIT" ]
CodingWithDavid/NewANImprovedSearchGrid
UILab/Program.cs
760
C#
using System; using System.IO; using System.Threading.Tasks; using Dissonance.Engine.Graphics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; namespace Dissonance.Engine.IO { public class PngReader : IAssetReader<Texture> { public string[] Extensions { get; } = { ".png" }; public async ValueTask<Texture> ReadFromStream(Stream stream, string assetPath, MainThreadCreationContext switchToMainThread) { var (width, height, pixels) = LoadImageData<Rgba32>(stream); await switchToMainThread; // Switches context to the main thread for texture uploading. var texture = new Texture(width, height); texture.SetPixels(pixels); return texture; } // Has to be split because async methods can't work with ref structures like Span<T>. private static unsafe (int width, int height, TPixel[] pixels) LoadImageData<TPixel>(Stream stream) where TPixel : unmanaged, IPixel<TPixel> { var decoder = new PngDecoder(); var image = Image.Load<TPixel>(stream, decoder); if (!image.TryGetSinglePixelSpan(out var span)) { throw new InvalidOperationException($"Internal error in {nameof(PngReader)}."); } var data = span.ToArray(); return (image.Width, image.Height, data); } } }
29.159091
142
0.736555
[ "MIT" ]
ExterminatorX99/DissonanceEngine
Src/IO/Readers/Textures/PngReader.cs
1,283
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.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Formats.Asn1; using System.Security.Cryptography.Apple; using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Security.Cryptography.X509Certificates { internal sealed partial class AppleCertificatePal : ICertificatePal { public DSA? GetDSAPrivateKey() { if (_identityHandle == null) return null; Debug.Assert(!_identityHandle.IsInvalid); SafeSecKeyRefHandle publicKey = Interop.AppleCrypto.X509GetPublicKey(_certHandle); SafeSecKeyRefHandle privateKey = Interop.AppleCrypto.X509GetPrivateKeyFromIdentity(_identityHandle); if (publicKey.IsInvalid) { // SecCertificateCopyKey returns null for DSA, so fall back to manually building it. publicKey = Interop.AppleCrypto.ImportEphemeralKey(_certData.SubjectPublicKeyInfo, false); } return new DSAImplementation.DSASecurityTransforms(publicKey, privateKey); } public ICertificatePal CopyWithPrivateKey(DSA privateKey) { var typedKey = privateKey as DSAImplementation.DSASecurityTransforms; if (typedKey != null) { return CopyWithPrivateKey(typedKey.GetKeys().PrivateKey); } DSAParameters dsaParameters = privateKey.ExportParameters(true); using (PinAndClear.Track(dsaParameters.X!)) using (typedKey = new DSAImplementation.DSASecurityTransforms()) { typedKey.ImportParameters(dsaParameters); return CopyWithPrivateKey(typedKey.GetKeys().PrivateKey); } } public ICertificatePal CopyWithPrivateKey(ECDsa privateKey) { var typedKey = privateKey as ECDsaImplementation.ECDsaSecurityTransforms; byte[] ecPrivateKey; if (typedKey != null) { ECParameters ecParameters = default; if (typedKey.TryExportDataKeyParameters(includePrivateParameters: true, ref ecParameters)) { using (PinAndClear.Track(ecParameters.D!)) { AsnWriter writer = EccKeyFormatHelper.WriteECPrivateKey(ecParameters); ecPrivateKey = writer.Encode(); writer.Reset(); } } else { return CopyWithPrivateKey(typedKey.GetKeys().PrivateKey); } } else { ecPrivateKey = privateKey.ExportECPrivateKey(); } using (PinAndClear.Track(ecPrivateKey)) using (SafeSecKeyRefHandle privateSecKey = Interop.AppleCrypto.ImportEphemeralKey(ecPrivateKey, true)) { return CopyWithPrivateKey(privateSecKey); } } public ICertificatePal CopyWithPrivateKey(ECDiffieHellman privateKey) { var typedKey = privateKey as ECDiffieHellmanImplementation.ECDiffieHellmanSecurityTransforms; byte[] ecPrivateKey; if (typedKey != null) { ECParameters ecParameters = default; if (typedKey.TryExportDataKeyParameters(includePrivateParameters: true, ref ecParameters)) { using (PinAndClear.Track(ecParameters.D!)) { AsnWriter writer = EccKeyFormatHelper.WriteECPrivateKey(ecParameters); ecPrivateKey = writer.Encode(); writer.Reset(); } } else { return CopyWithPrivateKey(typedKey.GetKeys().PrivateKey); } } else { ecPrivateKey = privateKey.ExportECPrivateKey(); } using (PinAndClear.Track(ecPrivateKey)) using (SafeSecKeyRefHandle privateSecKey = Interop.AppleCrypto.ImportEphemeralKey(ecPrivateKey, true)) { return CopyWithPrivateKey(privateSecKey); } } public ICertificatePal CopyWithPrivateKey(RSA privateKey) { var typedKey = privateKey as RSAImplementation.RSASecurityTransforms; if (typedKey != null) { return CopyWithPrivateKey(typedKey.GetKeys().PrivateKey); } byte[] rsaPrivateKey = privateKey.ExportRSAPrivateKey(); using (PinAndClear.Track(rsaPrivateKey)) using (SafeSecKeyRefHandle privateSecKey = Interop.AppleCrypto.ImportEphemeralKey(rsaPrivateKey, true)) { return CopyWithPrivateKey(privateSecKey); } } private ICertificatePal CopyWithPrivateKey(SafeSecKeyRefHandle? privateKey) { if (privateKey == null) { // Both Windows and Linux/OpenSSL are unaware if they bound a public or private key. // Here, we do know. So throw if we can't do what they asked. throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); } SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(privateKey); // If we're using a key already in a keychain don't add the certificate to that keychain here, // do it in the temporary add/remove in the shim. SafeKeychainHandle cloneKeychain = SafeTemporaryKeychainHandle.InvalidHandle; if (keychain.IsInvalid) { keychain = Interop.AppleCrypto.CreateTemporaryKeychain(); cloneKeychain = keychain; } // Because SecIdentityRef only has private constructors we need to have the cert and the key // in the same keychain. That almost certainly means we're going to need to add this cert to a // keychain, and when a cert that isn't part of a keychain gets added to a keychain then the // interior pointer of "what keychain did I come from?" used by SecKeychainItemCopyKeychain gets // set. That makes this function have side effects, which is not desired. // // It also makes reference tracking on temporary keychains broken, since the cert can // DangerousRelease a handle it didn't DangerousAddRef on. And so CopyWithPrivateKey makes // a temporary keychain, then deletes it before anyone has a chance to (e.g.) export the // new identity as a PKCS#12 blob. // // Solution: Clone the cert, like we do in Windows. SafeSecCertificateHandle tempHandle; { byte[] export = RawData; const bool exportable = false; SafeSecIdentityHandle identityHandle; tempHandle = Interop.AppleCrypto.X509ImportCertificate( export, X509ContentType.Cert, SafePasswordHandle.InvalidHandle, cloneKeychain, exportable, out identityHandle); Debug.Assert(identityHandle.IsInvalid, "identityHandle should be IsInvalid"); identityHandle.Dispose(); Debug.Assert(!tempHandle.IsInvalid, "tempHandle should not be IsInvalid"); } using (keychain) using (tempHandle) { SafeSecIdentityHandle identityHandle = Interop.AppleCrypto.X509CopyWithPrivateKey( tempHandle, privateKey, keychain); AppleCertificatePal newPal = new AppleCertificatePal(identityHandle); return newPal; } } } }
39.349282
115
0.588278
[ "MIT" ]
AUTOMATE-2001/runtime
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.Keys.macOS.cs
8,224
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using PizzaWorld.Storing; namespace PizzaWorld.Storing.Migrations { [DbContext(typeof(PizzaWorldContext))] partial class PizzaWorldContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.1"); modelBuilder.Entity("PizzaWorld.Domain.Abstracts.APizzaModel", b => { b.Property<long>("EntityId") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("Crust") .HasColumnType("nvarchar(max)"); b.Property<long?>("OrderEntityId") .HasColumnType("bigint"); b.Property<string>("Size") .HasColumnType("nvarchar(max)"); b.HasKey("EntityId"); b.HasIndex("OrderEntityId"); b.ToTable("APizzaModel"); }); modelBuilder.Entity("PizzaWorld.Domain.Models.Order", b => { b.Property<long>("EntityId") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<double>("Price") .HasColumnType("float"); b.Property<long?>("StoreEntityId") .HasColumnType("bigint"); b.Property<long?>("StoreEntityId1") .HasColumnType("bigint"); b.Property<long?>("UserEntityId") .HasColumnType("bigint"); b.HasKey("EntityId"); b.HasIndex("StoreEntityId"); b.HasIndex("StoreEntityId1"); b.HasIndex("UserEntityId"); b.ToTable("Order"); }); modelBuilder.Entity("PizzaWorld.Domain.Models.Store", b => { b.Property<long>("EntityId") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("EntityId"); b.ToTable("Stores"); b.HasData( new { EntityId = 2L, Name = "Dominoes" }, new { EntityId = 3L, Name = "Pizza Hut" }); }); modelBuilder.Entity("PizzaWorld.Domain.Models.User", b => { b.Property<long>("EntityId") .ValueGeneratedOnAdd() .HasColumnType("bigint") .UseIdentityColumn(); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<long?>("SelectedStoreEntityId") .HasColumnType("bigint"); b.HasKey("EntityId"); b.HasIndex("SelectedStoreEntityId"); b.ToTable("Users"); b.HasData( new { EntityId = 1L, Name = "Michael" }, new { EntityId = 2L, Name = "Shulk" }); }); modelBuilder.Entity("PizzaWorld.Domain.Abstracts.APizzaModel", b => { b.HasOne("PizzaWorld.Domain.Models.Order", null) .WithMany("Pizzas") .HasForeignKey("OrderEntityId"); }); modelBuilder.Entity("PizzaWorld.Domain.Models.Order", b => { b.HasOne("PizzaWorld.Domain.Models.Store", null) .WithMany("CompletedOrders") .HasForeignKey("StoreEntityId"); b.HasOne("PizzaWorld.Domain.Models.Store", null) .WithMany("Orders") .HasForeignKey("StoreEntityId1"); b.HasOne("PizzaWorld.Domain.Models.User", null) .WithMany("Orders") .HasForeignKey("UserEntityId"); }); modelBuilder.Entity("PizzaWorld.Domain.Models.User", b => { b.HasOne("PizzaWorld.Domain.Models.Store", "SelectedStore") .WithMany() .HasForeignKey("SelectedStoreEntityId"); b.Navigation("SelectedStore"); }); modelBuilder.Entity("PizzaWorld.Domain.Models.Order", b => { b.Navigation("Pizzas"); }); modelBuilder.Entity("PizzaWorld.Domain.Models.Store", b => { b.Navigation("CompletedOrders"); b.Navigation("Orders"); }); modelBuilder.Entity("PizzaWorld.Domain.Models.User", b => { b.Navigation("Orders"); }); #pragma warning restore 612, 618 } } }
33.302703
79
0.42834
[ "MIT" ]
mlaba49/project-p0
PizzaWorld.Storing/Migrations/PizzaWorldContextModelSnapshot.cs
6,163
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Taknet.Textc.Core.Processors { public class HttpCommandProcessor : ICommandProcessor { private readonly string _uriTemplate; private readonly string _method; private readonly IDictionary<string, string> _headers; public HttpCommandProcessor(string uriTemplate, string method, string bodyTemplate = null, IDictionary<string, string> headers = null, IOutputProcessor outputProcessor = null, params Syntax[] syntaxes) { if (syntaxes.Length == 0) throw new ArgumentException("Argument is empty collection", nameof(syntaxes)); _uriTemplate = uriTemplate ?? throw new ArgumentNullException(nameof(uriTemplate)); _method = method ?? throw new ArgumentNullException(nameof(method)); _headers = headers; OutputProcessor = outputProcessor; Syntaxes = syntaxes; } public Syntax[] Syntaxes { get; } public Task ProcessAsync(Expression expression, CancellationToken cancellationToken) { throw new NotImplementedException(); } public IOutputProcessor OutputProcessor { get; } } }
35.916667
122
0.676721
[ "Apache-2.0" ]
PiotrFerenc/textc-csharp
src/Taknet.Textc.Core/Processors/HttpCommandProcessor.cs
1,295
C#
#region Copyright //======================================================================================= // Microsoft Azure Customer Advisory Team // // This sample is supplemental to the technical guidance published on my personal // blog at http://blogs.msdn.com/b/paolos/. // // Author: Paolo Salvatori //======================================================================================= // Copyright (c) Microsoft Corporation. All rights reserved. // // LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE // FILES 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. //======================================================================================= #endregion #region Using Directives using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing.Design; using System.Runtime.CompilerServices; #endregion namespace Microsoft.Azure.ServiceBusExplorer.Helpers { [TypeConverter(typeof(CustomObjectConverter))] public class CustomObject : INotifyPropertyChanged { #region Private Fields private List<CustomProperty> propertyList = new List<CustomProperty>(); private readonly Dictionary<string, object> valueDictionary = new Dictionary<string, object>(); #endregion #region Public Events public event PropertyChangedEventHandler PropertyChanged; #endregion #region Public Properties [Browsable(false)] public List<CustomProperty> Properties { get { return propertyList; } set { propertyList = value; NotifyPropertyChanged(); } } public object this[string name] { get { object val; valueDictionary.TryGetValue(name, out val); return val; } set { valueDictionary[name] = value; NotifyPropertyChanged(); } } #endregion #region Private Classes private class CustomObjectConverter : ExpandableObjectConverter { public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { var standardProperties = base.GetProperties(context, value, attributes); var obj = value as CustomObject; var customProps = obj == null ? null : obj.Properties; var props = new PropertyDescriptor[standardProperties.Count + (customProps == null ? 0 : customProps.Count)]; standardProperties.CopyTo(props, 0); if (customProps != null) { var index = standardProperties.Count; foreach (var property in customProps) { props[index++] = new CustomPropertyDescriptor(property); } } return new PropertyDescriptorCollection(props); } } private class CustomPropertyDescriptor : PropertyDescriptor { private readonly CustomProperty property; public CustomPropertyDescriptor(CustomProperty property) : base(property.Name, null) { this.property = property; } public override string Category { get { return "Parameters"; } } public override string Description { get { return property.Description; } } public override string Name { get { return property.Name; } } public override bool ShouldSerializeValue(object component) { return ((CustomObject)component)[property.Name] != null; } public override void ResetValue(object component) { ((CustomObject)component)[property.Name] = null; } public override bool IsBrowsable { get { return property.IsBrowsable; } } public override bool IsReadOnly { get { return property.IsReadOnly; } } public override bool DesignTimeOnly { get { return property.DesignTimeOnly; } } public override Type PropertyType { get { return property.Type; } } public override bool CanResetValue(object component) { return true; } public override Type ComponentType { get { return typeof(CustomObject); } } public override void SetValue(object component, object value) { ((CustomObject)component)[property.Name] = value; } public override object GetValue(object component) { return ((CustomObject)component)[property.Name] ?? property.DefaultValue; } public override object GetEditor(Type editorBaseType) { return property.Editor ?? base.GetEditor(editorBaseType); } } #endregion #region Private Methods // This method is called by the Set accessor of each property. // The CallerMemberName attribute that is applied to the optional propertyName // parameter causes the property name of the caller to be substituted as an argument. private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } public class CustomProperty { #region Private Fields private Type type; #endregion #region Public Constructor public CustomProperty() { IsBrowsable = true; IsReadOnly = false; DesignTimeOnly = false; } #endregion #region Public Properties public string Name { get; set; } public string Description { get; set; } public object DefaultValue { get; set; } public bool IsBrowsable { get; set; } public bool IsReadOnly { get; set; } public bool DesignTimeOnly { get; set; } public UITypeEditor Editor { get; set; } public Type Type { get { return type; } set { type = value; if (type != typeof(string) && type.IsPrimitive) { DefaultValue = Activator.CreateInstance(value); } } } #endregion } }
38.338798
140
0.576112
[ "Apache-2.0" ]
Estormann/ServiceBusExplorer
src/ServiceBusExplorer/Helpers/CustomObject.cs
7,018
C#
/* * Copyright 2001-2010 Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using Quartz.Impl.Matchers; using Quartz.Logging; using Quartz.Spi; using Quartz.Util; using Quartz.Xml.JobSchedulingData20; namespace Quartz.Xml { /// <summary> /// Parses an XML file that declares Jobs and their schedules (Triggers). /// </summary> /// <remarks> /// <para> /// The xml document must conform to the format defined in "job_scheduling_data_2_0.xsd" /// </para> /// /// <para> /// After creating an instance of this class, you should call one of the <see cref="ProcessFile()" /> /// functions, after which you may call the ScheduledJobs() /// function to get a handle to the defined Jobs and Triggers, which can then be /// scheduled with the <see cref="IScheduler" />. Alternatively, you could call /// the <see cref="ProcessFileAndScheduleJobs(Quartz.IScheduler)" /> function to do all of this /// in one step. /// </para> /// /// <para> /// The same instance can be used again and again, with the list of defined Jobs /// being cleared each time you call a <see cref="ProcessFile()" /> method, /// however a single instance is not thread-safe. /// </para> /// </remarks> /// <author><a href="mailto:bonhamcm@thirdeyeconsulting.com">Chris Bonham</a></author> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> /// <author>Christian Krumm (.NET Bugfix)</author> public class XMLSchedulingDataProcessor { private readonly ILog log; public const string PropertyQuartzSystemIdDir = "quartz.system.id.dir"; public const string QuartzXmlFileName = "quartz_jobs.xml"; public const string QuartzSchema = "http://quartznet.sourceforge.net/xml/job_scheduling_data_2_0.xsd"; public const string QuartzXsdResourceName = "Quartz.Xml.job_scheduling_data_2_0.xsd"; // pre-processing commands private readonly IList<string> jobGroupsToDelete = new List<string>(); private readonly IList<string> triggerGroupsToDelete = new List<string>(); private readonly IList<JobKey> jobsToDelete = new List<JobKey>(); private readonly IList<TriggerKey> triggersToDelete = new List<TriggerKey>(); // scheduling commands private readonly List<IJobDetail> loadedJobs = new List<IJobDetail>(); private readonly List<ITrigger> loadedTriggers = new List<ITrigger>(); // directives private readonly IList<Exception> validationExceptions = new List<Exception>(); protected readonly ITypeLoadHelper typeLoadHelper; private readonly IList<string> jobGroupsToNeverDelete = new List<string>(); private readonly IList<string> triggerGroupsToNeverDelete = new List<string>(); /// <summary> /// Constructor for XMLSchedulingDataProcessor. /// </summary> public XMLSchedulingDataProcessor(ITypeLoadHelper typeLoadHelper) { OverWriteExistingData = true; IgnoreDuplicates = false; log = LogProvider.GetLogger(GetType()); this.typeLoadHelper = typeLoadHelper; } /// <summary> /// Whether the existing scheduling data (with same identifiers) will be /// overwritten. /// </summary> /// <remarks> /// If false, and <see cref="IgnoreDuplicates" /> is not false, and jobs or /// triggers with the same names already exist as those in the file, an /// error will occur. /// </remarks> /// <seealso cref="IgnoreDuplicates" /> public bool OverWriteExistingData { get; set; } /// <summary> /// If true (and <see cref="OverWriteExistingData" /> is false) then any /// job/triggers encountered in this file that have names that already exist /// in the scheduler will be ignored, and no error will be produced. /// </summary> /// <seealso cref="OverWriteExistingData"/> public bool IgnoreDuplicates { get; set; } /// <summary> /// If true (and <see cref="OverWriteExistingData" /> is true) then any /// job/triggers encountered in this file that already exist is scheduler /// will be updated with start time relative to old trigger. Effectively /// new trigger's last fire time will be updated to old trigger's last fire time /// and trigger's next fire time will updated to be next from this last fire time. /// </summary> public bool ScheduleTriggerRelativeToReplacedTrigger { get; set; } /// <summary> /// Gets the log. /// </summary> /// <value>The log.</value> protected ILog Log { get { return log; } } protected IList<IJobDetail> LoadedJobs { get { return loadedJobs.AsReadOnly(); } } protected IList<ITrigger> LoadedTriggers { get { return loadedTriggers.AsReadOnly(); } } /// <summary> /// Process the xml file in the default location (a file named /// "quartz_jobs.xml" in the current working directory). /// </summary> public virtual Task ProcessFile() { return ProcessFile(QuartzXmlFileName); } /// <summary> /// Process the xml file named <see param="fileName" />. /// </summary> /// <param name="fileName">meta data file name.</param> public virtual Task ProcessFile(string fileName) { return ProcessFile(fileName, fileName); } /// <summary> /// Process the xmlfile named <see param="fileName" /> with the given system /// ID. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="systemId">The system id.</param> public virtual async Task ProcessFile(string fileName, string systemId) { // resolve file name first fileName = FileUtil.ResolveFile(fileName); Log.InfoFormat("Parsing XML file: {0} with systemId: {1}", fileName, systemId); using (var stream = File.Open(fileName, FileMode.Open)) using (StreamReader sr = new StreamReader(stream)) { ProcessInternal(await sr.ReadToEndAsync().ConfigureAwait(false)); } } /// <summary> /// Process the xmlfile named <see param="fileName" /> with the given system /// ID. /// </summary> /// <param name="stream">The stream.</param> /// <param name="systemId">The system id.</param> public virtual async Task ProcessStream(Stream stream, string systemId) { Log.InfoFormat("Parsing XML from stream with systemId: {0}", systemId); using (StreamReader sr = new StreamReader(stream)) { ProcessInternal(await sr.ReadToEndAsync().ConfigureAwait(false)); } } protected virtual void PrepForProcessing() { ClearValidationExceptions(); OverWriteExistingData = true; IgnoreDuplicates = false; jobGroupsToDelete.Clear(); jobsToDelete.Clear(); triggerGroupsToDelete.Clear(); triggersToDelete.Clear(); loadedJobs.Clear(); loadedTriggers.Clear(); } protected virtual void ProcessInternal(string xml) { PrepForProcessing(); #if XML_SCHEMA ValidateXml(xml); #endif // XML_SCHEMA MaybeThrowValidationException(); // deserialize as object model XmlSerializer xs = new XmlSerializer(typeof (QuartzXmlConfiguration20)); QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20) xs.Deserialize(new StringReader(xml)); if (data == null) { throw new SchedulerConfigException("Job definition data from XML was null after deserialization"); } // // Extract pre-processing commands // if (data.preprocessingcommands != null) { foreach (preprocessingcommandsType command in data.preprocessingcommands) { if (command.deletejobsingroup != null) { foreach (string s in command.deletejobsingroup) { string deleteJobGroup = s.NullSafeTrim(); if (!string.IsNullOrEmpty(deleteJobGroup)) { jobGroupsToDelete.Add(deleteJobGroup); } } } if (command.deletetriggersingroup != null) { foreach (string s in command.deletetriggersingroup) { string deleteTriggerGroup = s.NullSafeTrim(); if (!string.IsNullOrEmpty(deleteTriggerGroup)) { triggerGroupsToDelete.Add(deleteTriggerGroup); } } } if (command.deletejob != null) { foreach (preprocessingcommandsTypeDeletejob s in command.deletejob) { string name = s.name.TrimEmptyToNull(); string group = s.group.TrimEmptyToNull(); if (name == null) { throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified."); } jobsToDelete.Add(new JobKey(name, group)); } } if (command.deletetrigger != null) { foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger) { string name = s.name.TrimEmptyToNull(); string group = s.group.TrimEmptyToNull(); if (name == null) { throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified."); } triggersToDelete.Add(new TriggerKey(name, group)); } } } } if (log.IsDebugEnabled()) { log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands."); log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands."); log.Debug("Found " + jobsToDelete.Count + " delete job commands."); log.Debug("Found " + triggersToDelete.Count + " delete trigger commands."); } // // Extract directives // if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool overWrite = data.processingdirectives[0].overwriteexistingdata; log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite); OverWriteExistingData = overWrite; } else { log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + OverWriteExistingData); } if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates; log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates); IgnoreDuplicates = ignoreduplicates; } else { log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + IgnoreDuplicates); } if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool scheduleRelative = data.processingdirectives[0].scheduletriggerrelativetoreplacedtrigger; log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' specified as: " + scheduleRelative); ScheduleTriggerRelativeToReplacedTrigger = scheduleRelative; } else { log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' not specified, defaulting to " + ScheduleTriggerRelativeToReplacedTrigger); } // // Extract Job definitions... // List<jobdetailType> jobNodes = new List<jobdetailType>(); if (data.schedule != null) { foreach (var schedule in data.schedule) { if (schedule != null) { if (schedule.job != null) { jobNodes.AddRange(schedule.job); } } } } log.Debug("Found " + jobNodes.Count + " job definitions."); foreach (jobdetailType jobDetailType in jobNodes) { string jobName = jobDetailType.name.TrimEmptyToNull(); string jobGroup = jobDetailType.group.TrimEmptyToNull(); string jobDescription = jobDetailType.description.TrimEmptyToNull(); string jobTypeName = jobDetailType.jobtype.TrimEmptyToNull(); bool jobDurability = jobDetailType.durable; bool jobRecoveryRequested = jobDetailType.recover; Type jobType = typeLoadHelper.LoadType(jobTypeName); IJobDetail jobDetail = JobBuilder.Create(jobType) .WithIdentity(jobName, jobGroup) .WithDescription(jobDescription) .StoreDurably(jobDurability) .RequestRecovery(jobRecoveryRequested) .Build(); if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null) { foreach (entryType entry in jobDetailType.jobdatamap.entry) { string key = entry.key.TrimEmptyToNull(); string value = entry.value.TrimEmptyToNull(); jobDetail.JobDataMap.Add(key, value); } } if (log.IsDebugEnabled()) { log.Debug("Parsed job definition: " + jobDetail); } AddJobToSchedule(jobDetail); } // // Extract Trigger definitions... // List<triggerType> triggerEntries = new List<triggerType>(); if (data.schedule != null) { foreach (var schedule in data.schedule) { if (schedule != null && schedule.trigger != null) { triggerEntries.AddRange(schedule.trigger); } } } log.Debug("Found " + triggerEntries.Count + " trigger definitions."); foreach (triggerType triggerNode in triggerEntries) { string triggerName = triggerNode.Item.name.TrimEmptyToNull(); string triggerGroup = triggerNode.Item.group.TrimEmptyToNull(); string triggerDescription = triggerNode.Item.description.TrimEmptyToNull(); string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull(); string triggerJobName = triggerNode.Item.jobname.TrimEmptyToNull(); string triggerJobGroup = triggerNode.Item.jobgroup.TrimEmptyToNull(); int triggerPriority = TriggerConstants.DefaultPriority; if (!triggerNode.Item.priority.IsNullOrWhiteSpace()) { triggerPriority = Convert.ToInt32(triggerNode.Item.priority); } DateTimeOffset triggerStartTime = SystemTime.UtcNow(); if (triggerNode.Item.Item != null) { if (triggerNode.Item.Item is DateTime) { triggerStartTime = new DateTimeOffset((DateTime) triggerNode.Item.Item); } else { triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item)); } } DateTime? triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?) null; IScheduleBuilder sched; if (triggerNode.Item is simpleTriggerType) { simpleTriggerType simpleTrigger = (simpleTriggerType) triggerNode.Item; string repeatCountString = simpleTrigger.repeatcount.TrimEmptyToNull(); string repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull(); int repeatCount = ParseSimpleTriggerRepeatCount(repeatCountString); TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString)); sched = SimpleScheduleBuilder.Create() .WithInterval(repeatInterval) .WithRepeatCount(repeatCount); if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((SimpleScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction)); } } else if (triggerNode.Item is cronTriggerType) { cronTriggerType cronTrigger = (cronTriggerType) triggerNode.Item; string cronExpression = cronTrigger.cronexpression.TrimEmptyToNull(); string timezoneString = cronTrigger.timezone.TrimEmptyToNull(); TimeZoneInfo tz = timezoneString != null ? TimeZoneUtil.FindTimeZoneById(timezoneString) : null; sched = CronScheduleBuilder.CronSchedule(cronExpression) .InTimeZone(tz); if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((CronScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction)); } } else if (triggerNode.Item is calendarIntervalTriggerType) { calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType) triggerNode.Item; string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull(); IntervalUnit intervalUnit = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull()); int repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString); sched = CalendarIntervalScheduleBuilder.Create() .WithInterval(repeatInterval, intervalUnit); if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((CalendarIntervalScheduleBuilder) sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction)); } } else { throw new SchedulerConfigException("Unknown trigger type in XML configuration"); } IMutableTrigger trigger = (IMutableTrigger) TriggerBuilder.Create() .WithIdentity(triggerName, triggerGroup) .WithDescription(triggerDescription) .ForJob(triggerJobName, triggerJobGroup) .StartAt(triggerStartTime) .EndAt(triggerEndTime) .WithPriority(triggerPriority) .ModifiedByCalendar(triggerCalendarRef) .WithSchedule(sched) .Build(); if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null) { foreach (entryType entry in triggerNode.Item.jobdatamap.entry) { string key = entry.key.TrimEmptyToNull(); string value = entry.value.TrimEmptyToNull(); trigger.JobDataMap.Add(key, value); } } if (log.IsDebugEnabled()) { log.Debug("Parsed trigger definition: " + trigger); } AddTriggerToSchedule(trigger); } } protected virtual void AddJobToSchedule(IJobDetail job) { loadedJobs.Add(job); } protected virtual void AddTriggerToSchedule(IMutableTrigger trigger) { loadedTriggers.Add(trigger); } protected virtual int ParseSimpleTriggerRepeatCount(string repeatcount) { int value = Convert.ToInt32(repeatcount, CultureInfo.InvariantCulture); return value; } protected virtual int ReadMisfireInstructionFromString(string misfireinstruction) { Constants c = new Constants(typeof (MisfireInstruction), typeof (MisfireInstruction.CronTrigger), typeof (MisfireInstruction.SimpleTrigger)); return c.AsNumber(misfireinstruction); } protected virtual IntervalUnit ParseDateIntervalTriggerIntervalUnit(string intervalUnit) { if (string.IsNullOrEmpty(intervalUnit)) { return IntervalUnit.Day; } IntervalUnit retValue; if (!TryParseEnum(intervalUnit, out retValue)) { throw new SchedulerConfigException("Unknown interval unit for DateIntervalTrigger: " + intervalUnit); } return retValue; } protected virtual bool TryParseEnum<T>(string str, out T value) where T : struct { var names = Enum.GetNames(typeof (T)); value = (T) Enum.GetValues(typeof (T)).GetValue(0); foreach (var name in names) { if (name == str) { value = (T) Enum.Parse(typeof (T), name); return true; } } return false; } #if XML_SCHEMA private void ValidateXml(string xml) { try { XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; Stream stream = GetType().Assembly.GetManifestResourceStream(QuartzXsdResourceName); XmlSchema schema = XmlSchema.Read(stream, XmlValidationCallBack); settings.Schemas.Add(schema); settings.ValidationEventHandler += XmlValidationCallBack; // stream to validate using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings)) { while (reader.Read()) { } } } catch (Exception ex) { log.WarnException("Unable to validate XML with schema: " + ex.Message, ex); } } private void XmlValidationCallBack(object sender, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Error) { validationExceptions.Add(e.Exception); } else { Log.Warn(e.Message); } } #endif // XML_SCHEMA /// <summary> /// Process the xml file in the default location, and schedule all of the jobs defined within it. /// </summary> /// <remarks>Note that we will set overWriteExistingJobs after the default xml is parsed.</remarks> /// <param name="sched"></param> /// <param name="overWriteExistingJobs"></param> public async Task ProcessFileAndScheduleJobs(IScheduler sched, bool overWriteExistingJobs) { await ProcessFile(QuartzXmlFileName, QuartzXmlFileName).ConfigureAwait(false); // The overWriteExistingJobs flag was set by processFile() -> prepForProcessing(), then by xml parsing, and then now // we need to reset it again here by this method parameter to override it. OverWriteExistingData = overWriteExistingJobs; await ExecutePreProcessCommands(sched).ConfigureAwait(false); await ScheduleJobs(sched).ConfigureAwait(false); } /// <summary> /// Process the xml file in the default location, and schedule all of the /// jobs defined within it. /// </summary> public virtual void ProcessFileAndScheduleJobs(IScheduler sched) { ProcessFileAndScheduleJobs(QuartzXmlFileName, sched); } /// <summary> /// Process the xml file in the given location, and schedule all of the /// jobs defined within it. /// </summary> /// <param name="fileName">meta data file name.</param> /// <param name="sched">The scheduler.</param> public virtual Task ProcessFileAndScheduleJobs(string fileName, IScheduler sched) { return ProcessFileAndScheduleJobs(fileName, fileName, sched); } /// <summary> /// Process the xml file in the given location, and schedule all of the /// jobs defined within it. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="systemId">The system id.</param> /// <param name="sched">The sched.</param> public virtual async Task ProcessFileAndScheduleJobs(string fileName, string systemId, IScheduler sched) { await ProcessFile(fileName, systemId).ConfigureAwait(false); await ExecutePreProcessCommands(sched).ConfigureAwait(false); await ScheduleJobs(sched).ConfigureAwait(false); } /// <summary> /// Process the xml file in the given location, and schedule all of the /// jobs defined within it. /// </summary> /// <param name="stream">stream to read XML data from.</param> /// <param name="sched">The sched.</param> public virtual async Task ProcessStreamAndScheduleJobs(Stream stream, IScheduler sched) { using (var sr = new StreamReader(stream)) { ProcessInternal(await sr.ReadToEndAsync().ConfigureAwait(false)); } await ExecutePreProcessCommands(sched).ConfigureAwait(false); await ScheduleJobs(sched).ConfigureAwait(false); } /// <summary> /// Schedules the given sets of jobs and triggers. /// </summary> /// <param name="sched">The sched.</param> public virtual async Task ScheduleJobs(IScheduler sched) { List<IJobDetail> jobs = new List<IJobDetail>(LoadedJobs); List<ITrigger> triggers = new List<ITrigger>(LoadedTriggers); log.Info("Adding " + jobs.Count + " jobs, " + triggers.Count + " triggers."); IDictionary<JobKey, List<IMutableTrigger>> triggersByFQJobName = BuildTriggersByFQJobNameMap(triggers); // add each job, and it's associated triggers while (jobs.Count > 0) { // remove jobs as we handle them... IJobDetail detail = jobs[0]; jobs.Remove(detail); IJobDetail dupeJ = null; try { // The existing job could have been deleted, and Quartz API doesn't allow us to query this without // loading the job class, so use try/catch to handle it. dupeJ = await sched.GetJobDetail(detail.Key).ConfigureAwait(false); } catch (JobPersistenceException e) { if (e.InnerException is TypeLoadException && OverWriteExistingData) { // We are going to replace jobDetail anyway, so just delete it first. log.Info("Removing job: " + detail.Key); await sched.DeleteJob(detail.Key).ConfigureAwait(false); } else { throw; } } if (dupeJ != null) { if (!OverWriteExistingData && IgnoreDuplicates) { log.Info("Not overwriting existing job: " + dupeJ.Key); continue; // just ignore the entry } if (!OverWriteExistingData && !IgnoreDuplicates) { throw new ObjectAlreadyExistsException(detail); } } if (dupeJ != null) { log.Info("Replacing job: " + detail.Key); } else { log.Info("Adding job: " + detail.Key); } List<IMutableTrigger> triggersOfJob; triggersByFQJobName.TryGetValue(detail.Key, out triggersOfJob); if (!detail.Durable && (triggersOfJob == null || triggersOfJob.Count == 0)) { if (dupeJ == null) { throw new SchedulerException( "A new job defined without any triggers must be durable: " + detail.Key); } if ((dupeJ.Durable && (await sched.GetTriggersOfJob(detail.Key).ConfigureAwait(false)).Count == 0)) { throw new SchedulerException( "Can't change existing durable job without triggers to non-durable: " + detail.Key); } } if (dupeJ != null || detail.Durable) { if (triggersOfJob != null && triggersOfJob.Count > 0) { await sched.AddJob(detail, true, true).ConfigureAwait(false); // add the job regardless is durable or not b/c we have trigger to add } else { await sched.AddJob(detail, true, false).ConfigureAwait(false); // add the job only if a replacement or durable, else exception will throw! } } else { bool addJobWithFirstSchedule = true; // Add triggers related to the job... while (triggersOfJob.Count > 0) { IMutableTrigger trigger = triggersOfJob[0]; // remove triggers as we handle them... triggersOfJob.Remove(trigger); ITrigger dupeT = await sched.GetTrigger(trigger.Key).ConfigureAwait(false); if (dupeT != null) { if (OverWriteExistingData) { if (log.IsDebugEnabled()) { log.DebugFormat("Rescheduling job: {0} with updated trigger: {1}", trigger.JobKey, trigger.Key); } } else if (IgnoreDuplicates) { log.Info("Not overwriting existing trigger: " + dupeT.Key); continue; // just ignore the trigger (and possibly job) } else { throw new ObjectAlreadyExistsException(trigger); } if (!dupeT.JobKey.Equals(trigger.JobKey)) { log.WarnFormat("Possibly duplicately named ({0}) triggers in jobs xml file! ", trigger.Key); } await DoRescheduleJob(sched, trigger, dupeT).ConfigureAwait(false); } else { if (log.IsDebugEnabled()) { log.DebugFormat("Scheduling job: {0} with trigger: {1}", trigger.JobKey, trigger.Key); } try { if (addJobWithFirstSchedule) { await sched.ScheduleJob(detail, trigger).ConfigureAwait(false); // add the job if it's not in yet... addJobWithFirstSchedule = false; } else { await sched.ScheduleJob(trigger).ConfigureAwait(false); } } catch (ObjectAlreadyExistsException) { if (log.IsDebugEnabled()) { log.DebugFormat("Adding trigger: {0} for job: {1} failed because the trigger already existed. " + "This is likely due to a race condition between multiple instances " + "in the cluster. Will try to reschedule instead.", trigger.Key, detail.Key); } // Let's try one more time as reschedule. var oldTrigger = await sched.GetTrigger(trigger.Key).ConfigureAwait(false); await DoRescheduleJob(sched, trigger, oldTrigger).ConfigureAwait(false); } } } } } // add triggers that weren't associated with a new job... (those we already handled were removed above) foreach (IMutableTrigger trigger in triggers) { ITrigger dupeT = await sched.GetTrigger(trigger.Key).ConfigureAwait(false); if (dupeT != null) { if (OverWriteExistingData) { if (log.IsDebugEnabled()) { log.DebugFormat("Rescheduling job: " + trigger.JobKey + " with updated trigger: " + trigger.Key); } } else if (IgnoreDuplicates) { log.Info("Not overwriting existing trigger: " + dupeT.Key); continue; // just ignore the trigger } else { throw new ObjectAlreadyExistsException(trigger); } if (!dupeT.JobKey.Equals(trigger.JobKey)) { log.WarnFormat("Possibly duplicately named ({0}) triggers in jobs xml file! ", trigger.Key); } await DoRescheduleJob(sched, trigger, dupeT).ConfigureAwait(false); } else { if (log.IsDebugEnabled()) { log.DebugFormat("Scheduling job: {0} with trigger: {1}", trigger.JobKey, trigger.Key); } try { await sched.ScheduleJob(trigger).ConfigureAwait(false); } catch (ObjectAlreadyExistsException) { if (log.IsDebugEnabled()) { log.Debug( "Adding trigger: " + trigger.Key + " for job: " + trigger.JobKey + " failed because the trigger already existed. " + "This is likely due to a race condition between multiple instances " + "in the cluster. Will try to reschedule instead."); } // Let's rescheduleJob one more time. var oldTrigger = await sched.GetTrigger(trigger.Key).ConfigureAwait(false); await DoRescheduleJob(sched, trigger, oldTrigger).ConfigureAwait(false); } } } } private Task DoRescheduleJob(IScheduler sched, IMutableTrigger trigger, ITrigger oldTrigger) { // if this is a trigger with default start time we can consider relative scheduling if (oldTrigger != null && trigger.StartTimeUtc - SystemTime.UtcNow() < TimeSpan.FromSeconds(5) && ScheduleTriggerRelativeToReplacedTrigger) { Log.DebugFormat("Using relative scheduling for trigger with key {0}", trigger.Key); var oldTriggerPreviousFireTime = oldTrigger.GetPreviousFireTimeUtc(); trigger.StartTimeUtc = oldTrigger.StartTimeUtc; ((IOperableTrigger)trigger).SetPreviousFireTimeUtc(oldTriggerPreviousFireTime); ((IOperableTrigger)trigger).SetNextFireTimeUtc(trigger.GetFireTimeAfter(oldTriggerPreviousFireTime)); } return sched.RescheduleJob(trigger.Key, trigger); } protected virtual IDictionary<JobKey, List<IMutableTrigger>> BuildTriggersByFQJobNameMap(List<ITrigger> triggers) { IDictionary<JobKey, List<IMutableTrigger>> triggersByFQJobName = new Dictionary<JobKey, List<IMutableTrigger>>(); foreach (IMutableTrigger trigger in triggers) { List<IMutableTrigger> triggersOfJob; if (!triggersByFQJobName.TryGetValue(trigger.JobKey, out triggersOfJob)) { triggersOfJob = new List<IMutableTrigger>(); triggersByFQJobName[trigger.JobKey] = triggersOfJob; } triggersOfJob.Add(trigger); } return triggersByFQJobName; } protected async Task ExecutePreProcessCommands(IScheduler scheduler) { foreach (string group in jobGroupsToDelete) { if (group.Equals("*")) { log.Info("Deleting all jobs in ALL groups."); foreach (string groupName in await scheduler.GetJobGroupNames().ConfigureAwait(false)) { if (!jobGroupsToNeverDelete.Contains(groupName)) { foreach (JobKey key in await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName)).ConfigureAwait(false)) { await scheduler.DeleteJob(key).ConfigureAwait(false); } } } } else { if (!jobGroupsToNeverDelete.Contains(group)) { log.InfoFormat("Deleting all jobs in group: {0}", group); foreach (JobKey key in await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(@group)).ConfigureAwait(false)) { await scheduler.DeleteJob(key).ConfigureAwait(false); } } } } foreach (string group in triggerGroupsToDelete) { if (group.Equals("*")) { log.Info("Deleting all triggers in ALL groups."); foreach (string groupName in await scheduler.GetTriggerGroupNames().ConfigureAwait(false)) { if (!triggerGroupsToNeverDelete.Contains(groupName)) { foreach (TriggerKey key in await scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(groupName)).ConfigureAwait(false)) { await scheduler.UnscheduleJob(key).ConfigureAwait(false); } } } } else { if (!triggerGroupsToNeverDelete.Contains(group)) { log.InfoFormat("Deleting all triggers in group: {0}", group); foreach (TriggerKey key in await scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals(@group)).ConfigureAwait(false)) { await scheduler.UnscheduleJob(key).ConfigureAwait(false); } } } } foreach (JobKey key in jobsToDelete) { if (!jobGroupsToNeverDelete.Contains(key.Group)) { log.InfoFormat("Deleting job: {0}", key); await scheduler.DeleteJob(key).ConfigureAwait(false); } } foreach (TriggerKey key in triggersToDelete) { if (!triggerGroupsToNeverDelete.Contains(key.Group)) { log.InfoFormat("Deleting trigger: {0}", key); await scheduler.UnscheduleJob(key).ConfigureAwait(false); } } } /// <summary> /// Adds a detected validation exception. /// </summary> /// <param name="e">The exception.</param> protected virtual void AddValidationException(XmlException e) { validationExceptions.Add(e); } /// <summary> /// Resets the number of detected validation exceptions. /// </summary> protected virtual void ClearValidationExceptions() { validationExceptions.Clear(); } /// <summary> /// Throws a ValidationException if the number of validationExceptions /// detected is greater than zero. /// </summary> /// <exception cref="ValidationException"> /// DTD validation exception. /// </exception> protected virtual void MaybeThrowValidationException() { if (validationExceptions.Count > 0) { throw new ValidationException(validationExceptions); } } public void AddJobGroupToNeverDelete(string jobGroupName) { jobGroupsToNeverDelete.Add(jobGroupName); } public void AddTriggerGroupToNeverDelete(string triggerGroupName) { triggerGroupsToNeverDelete.Add(triggerGroupName); } /// <summary> /// Helper class to map constant names to their values. /// </summary> internal class Constants { private readonly Type[] types; public Constants(params Type[] reflectedTypes) { types = reflectedTypes; } public int AsNumber(string field) { foreach (Type type in types) { FieldInfo fi = type.GetField(field); if (fi != null) { return Convert.ToInt32(fi.GetValue(null), CultureInfo.InvariantCulture); } } // not found throw new Exception($"Unknown field '{field}'"); } } } }
42.535747
175
0.518935
[ "Apache-2.0" ]
jvilalta/quartznet
src/Quartz/Xml/XMLSchedulingDataProcessor.cs
47,002
C#
using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Tenu.Core.Models; using Tenu.FrontEnd.PropertyConverters; namespace Tenu.FrontEnd { public class PropertyConverterService { private readonly IServiceProvider _services; public PropertyConverterService(IServiceProvider services) { _services = services; } public T Convert<T>(Content.ContentProperty property) { var converters = _services.GetServices<IPropertyConverter<T>>(); var converter = converters.FirstOrDefault(x => x.PropertyTypeAlias == property.PropertyTypeAlias); if (converter == null) throw new MissingConverterException(property.PropertyTypeAlias, typeof(T)); return converter.Convert(property.RawValue); } public object ConvertDefault(Content.ContentProperty property) { var converters = _services.GetServices<IDefaultPropertyConverter>(); var converter = converters.FirstOrDefault(x => x.PropertyTypeAlias == property.PropertyTypeAlias); if (converter == null) throw new MissingDefaultConverterException(property.PropertyTypeAlias); return converter.ConvertDefault(property.RawValue); } } public class MissingConverterException : Exception { public MissingConverterException(string propertyTypeAlias, Type wantedType) : base($"No converter from {propertyTypeAlias} to {wantedType}") { } } public class MissingDefaultConverterException : Exception { public MissingDefaultConverterException(string propertyTypeAlias) : base($"No default converter from {propertyTypeAlias}") { } } }
33.259259
148
0.679844
[ "MIT" ]
leddt/tenu
Tenu.FrontEnd/PropertyConverterService.cs
1,798
C#
namespace FoxOffice.Controllers { using System; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using FoxOffice.ReadModel; using FoxOffice.ReadModel.DataAccess; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class QueriesController_specs { [TestMethod] public void sut_inherits_ControllerBase() { typeof(QueriesController).Should().BeDerivedFrom<ControllerBase>(); } [TestMethod] public void sut_is_decorated_with_ApiController_attribute() { typeof(QueriesController).Should() .BeDecoratedWith<ApiControllerAttribute>(); } [TestMethod, AutoData] public async Task GetAllTheaters_returns_OkObjectResult( Theater[] theaters, InMemoryTheaterRepository readerStub, [NoAutoProperties] QueriesController sut) { theaters.ForEach(t => readerStub.Data[t.Id] = t); var facade = new TheaterReadModelFacade(readerStub); IActionResult actual = await sut.GetAllTheaters(facade); actual.Should().BeOfType<OkObjectResult>(); } [TestMethod, AutoData] public async Task GetAllTheaters_returns_transfer_objects_as_content( Theater[] theaters, InMemoryTheaterRepository readerStub, [NoAutoProperties] QueriesController sut) { theaters.ForEach(t => readerStub.Data[t.Id] = t); var facade = new TheaterReadModelFacade(readerStub); var actual = (OkObjectResult)await sut.GetAllTheaters(facade); actual.Value.Should().BeEquivalentTo(await facade.GetAllTheaters()); } [TestMethod, AutoData] public async Task given_theater_found_then_FindTheater_returns_OkObjectResult( Theater theater, InMemoryTheaterRepository readerStub, [NoAutoProperties] QueriesController sut) { readerStub.Data[theater.Id] = theater; var facade = new TheaterReadModelFacade(readerStub); IActionResult actual = await sut.FindTheater(theater.Id, facade); actual.Should().BeOfType<OkObjectResult>(); } [TestMethod, AutoData] public async Task given_theater_found_then_FindTheater_returns_transfer_object_as_content( Theater theater, InMemoryTheaterRepository readerStub, [NoAutoProperties] QueriesController sut) { readerStub.Data[theater.Id] = theater; var facade = new TheaterReadModelFacade(readerStub); IActionResult result = await sut.FindTheater(theater.Id, facade); object actual = result.As<OkObjectResult>().Value; actual.Should().BeOfType<TheaterDto>(); actual.Should().BeEquivalentTo(new { theater.Id, theater.Name, theater.SeatRowCount, theater.SeatColumnCount, }); } [TestMethod, AutoData] public async Task given_theater_not_found_then_FindTheater_returns_NotFoundResult( Guid theaterId, InMemoryTheaterRepository readerStub, [NoAutoProperties] QueriesController sut) { var facade = new TheaterReadModelFacade(readerStub); IActionResult actual = await sut.FindTheater(theaterId, facade); actual.Should().BeOfType<NotFoundResult>(); } [TestMethod, AutoData] public async Task GetAllMovies_returns_OkObjectResult( Movie[] movies, InMemoryMovieRepository readerStub, [NoAutoProperties] QueriesController sut) { movies.ForEach(t => readerStub.Data[t.Id] = t); var facade = new MovieReadModelFacade(readerStub); IActionResult actual = await sut.GetAllMovies(facade); actual.Should().BeOfType<OkObjectResult>(); } [TestMethod, AutoData] public async Task GetAllMovies_returns_transfer_objects_as_content( Movie[] movies, InMemoryMovieRepository readerStub, [NoAutoProperties] QueriesController sut) { movies.ForEach(t => readerStub.Data[t.Id] = t); var facade = new MovieReadModelFacade(readerStub); var actual = (OkObjectResult)await sut.GetAllMovies(facade); actual.Value.Should().BeEquivalentTo(await facade.GetAllMovies()); } [TestMethod, AutoData] public async Task given_movie_found_then_FindMovie_returns_OkObjectResult( Movie movie, InMemoryMovieRepository readerStub, [NoAutoProperties] QueriesController sut) { readerStub.Data[movie.Id] = movie; var facade = new MovieReadModelFacade(readerStub); IActionResult actual = await sut.FindMovie(movie.Id, facade); actual.Should().BeOfType<OkObjectResult>(); } [TestMethod, AutoData] public async Task given_movie_found_then_FindMovie_returns_transfer_object_as_content( Movie movie, InMemoryMovieRepository readerStub, [NoAutoProperties] QueriesController sut) { readerStub.Data[movie.Id] = movie; var facade = new MovieReadModelFacade(readerStub); IActionResult result = await sut.FindMovie(movie.Id, facade); object actual = result.As<OkObjectResult>().Value; actual.Should().BeOfType<MovieDto>(); actual.Should().BeEquivalentTo(new { movie.Id, movie.Title, movie.CreatedAt, }); } [TestMethod, AutoData] public async Task given_movie_not_found_then_FindMovie_returns_NotFoundResult( Guid movieId, InMemoryMovieRepository readerStub, [NoAutoProperties] QueriesController sut) { var facade = new MovieReadModelFacade(readerStub); IActionResult actual = await sut.FindMovie(movieId, facade); actual.Should().BeOfType<NotFoundResult>(); } [TestMethod, AutoData] public async Task given_screening_found_then_FindScreening_returns_OkObjectResult( Movie movie, InMemoryMovieRepository readerStub, [NoAutoProperties] QueriesController sut) { readerStub.Data[movie.Id] = movie; var facade = new MovieReadModelFacade(readerStub); Screening screening = movie.Screenings.Shuffle().First(); IActionResult actual = await sut.FindScreening(movie.Id, screening.Id, facade); actual.Should().BeOfType<OkObjectResult>(); } [TestMethod, AutoData] public async Task given_screening_found_then_FindScreening_returns_transfer_object_as_content( Movie movie, InMemoryMovieRepository readerStub, [NoAutoProperties] QueriesController sut) { // Arrange readerStub.Data[movie.Id] = movie; var facade = new MovieReadModelFacade(readerStub); Screening screening = movie.Screenings.Shuffle().First(); // Act dynamic result = await sut.FindScreening(movie.Id, screening.Id, facade); // Assert object actual = result.Value; actual.Should().BeOfType<ScreeningDto>(); actual.Should().BeEquivalentTo( expectation: screening, config: c => c.ExcludingMissingMembers()); } [TestMethod, AutoData] public async Task given_movie_not_found_then_FindScreening_returns_NotFoundResult( Guid movieId, Guid screeningId, IMovieReader readerStub, [NoAutoProperties] QueriesController sut) { var facade = new MovieReadModelFacade(readerStub); IActionResult actual = await sut.FindScreening(movieId, screeningId, facade); actual.Should().BeOfType<NotFoundResult>(); } [TestMethod, AutoData] public async Task given_screening_not_found_then_FindScreening_returns_NotFoundResult( Movie movie, Guid screeningId, InMemoryMovieRepository readerStub, [NoAutoProperties] QueriesController sut) { readerStub.Data[movie.Id] = movie; var facade = new MovieReadModelFacade(readerStub); IActionResult actual = await sut.FindScreening(movie.Id, screeningId, facade); actual.Should().BeOfType<NotFoundResult>(); } } }
36.03629
102
0.620902
[ "MIT" ]
Reacture/FoxOffice
source/FoxOffice.Tests/Controllers/QueriesController_specs.cs
8,939
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; namespace Quasardb.Tests.Cluster { [TestClass] public class PerformanceTrace { private readonly QdbCluster _cluster = QdbTestCluster.Instance; [TestMethod] public void DisabledByDefault() { var traces = _cluster.GetPerformanceTraces(); Assert.AreEqual(0, traces.Length); } [TestMethod] public void ReturnNoLabelsWhenEnabled() { _cluster.EnablePerformanceTraces(); try { var traces = _cluster.GetPerformanceTraces(); Assert.AreEqual(0, traces.Length); } finally { _cluster.DisablePerformanceTraces(); } } [TestMethod] public void ReturnWriteEntryLabels() { var key = _cluster.Integer("quarante-deux"); _cluster.EnablePerformanceTraces(); key.Put(42); try { var traces = _cluster.GetPerformanceTraces(); Assert.AreEqual(1, traces.Length); var trace = traces[0]; Assert.AreEqual("integer.put", traces[0].name); var labels = trace.measures.Select(m => m.label).ToArray(); CollectionAssert.AreEqual(new string[]{ "received", "deserialization_starts", "deserialization_ends", "entering_chord", "dispatch", "deserialization_starts", "deserialization_ends", "processing_starts", "entry_trimming_starts", "entry_trimming_ends", "content_writing_starts", "content_writing_ends", "entry_writing_starts", "entry_writing_ends", "processing_ends" }, labels); traces = _cluster.GetPerformanceTraces(); Assert.AreEqual(0, traces.Length); } finally { _cluster.DisablePerformanceTraces(); key.Remove(); } } [TestMethod] public void ReturnReadEntryLabels() { var key = _cluster.Integer("quarante-deux"); key.Put(42); try { _cluster.EnablePerformanceTraces(); key.Get(); var traces = _cluster.GetPerformanceTraces(); Assert.AreEqual(1, traces.Length); var trace = traces[0]; Assert.AreEqual("common.get", trace.name); var labels = trace.measures.Select(m => m.label).ToArray(); CollectionAssert.AreEqual(new string[]{ "received", "deserialization_starts", "deserialization_ends", "entering_chord", "dispatch", "deserialization_starts", "deserialization_ends", "processing_starts", "content_reading_starts", "content_reading_ends", "processing_ends" }, labels); traces = _cluster.GetPerformanceTraces(); Assert.AreEqual(0, traces.Length); } finally { _cluster.DisablePerformanceTraces(); key.Remove(); } } } }
31.411765
75
0.471375
[ "BSD-3-Clause" ]
bureau14/qdb-api-dotnet
Quasardb.Tests/Cluster/PerformanceTrace.cs
3,740
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("React-ory.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("React-ory.Tests")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [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("ab371179-3de1-4825-9d11-343c2136b51c")] // 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")]
38.405405
84
0.746657
[ "MIT" ]
stephenbreen/React-ory
React-ory/React-ory.Tests/Properties/AssemblyInfo.cs
1,424
C#
using Enkata.Core.Interfaces; using Enkata.Core.ProjectAggregate; using Enkata.Core.ProjectAggregate.Events; using Enkata.Core.ProjectAggregate.Handlers; using Moq; using Xunit; namespace Enkata.UnitTests.Core.Handlers; public class ItemCompletedEmailNotificationHandlerHandle { private ItemCompletedEmailNotificationHandler _handler; private Mock<IEmailSender> _emailSenderMock; public ItemCompletedEmailNotificationHandlerHandle() { _emailSenderMock = new Mock<IEmailSender>(); _handler = new ItemCompletedEmailNotificationHandler(_emailSenderMock.Object); } [Fact] public async Task ThrowsExceptionGivenNullEventArgument() { #nullable disable Exception ex = await Assert.ThrowsAsync<ArgumentNullException>(() => _handler.Handle(null, CancellationToken.None)); #nullable enable } [Fact] public async Task SendsEmailGivenEventInstance() { await _handler.Handle(new ToDoItemCompletedEvent(new ToDoItem()), CancellationToken.None); _emailSenderMock.Verify(sender => sender.SendEmailAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once); } }
31.72973
154
0.762351
[ "MIT" ]
muliswilliam/SampleAuth
tests/Enkata.UnitTests/Core/Handlers/ItemCompletedEmailNotificationHandlerHandle.cs
1,176
C#
namespace FreediverApp.Utils { class AuthenticationHelper { public static string RECOVERY_SERVICE_EMAIL = "recoveryservice.freediverteam@gmx.net"; public static string RECOVERY_SERVICE_PASSWORD = "JJ$8fUo(8n3%2Gb/7fc"; public static string RECOVERY_SERVICE_MAILSERVER = "mail.gmx.net"; } }
37.111111
100
0.712575
[ "MIT" ]
ArrOwHe4D/FreediverApp
Utils/AuthenticationHelper.cs
336
C#
namespace ZENBEAR.Services.Data { using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; using ZENBEAR.Data.Common.Repositories; using ZENBEAR.Data.Models; using ZENBEAR.Data.Models.Enums; using ZENBEAR.Web.ViewModels; using ZENBEAR.Web.ViewModels.Tickets; public class TicketsService : ITicketsService { private readonly IDeletableEntityRepository<Ticket> ticketsRepo; private readonly IProjectsService projectsService; private readonly IUsersService usersService; private readonly IIssuesService issuesService; public TicketsService( IDeletableEntityRepository<Ticket> ticketsRepo, IProjectsService projectsService, IUsersService usersService, IIssuesService issuesService) { this.ticketsRepo = ticketsRepo; this.projectsService = projectsService; this.usersService = usersService; this.issuesService = issuesService; } public IEnumerable<MyTicketsViewModel> GetAllTickets(int itemsPerPage, int page) { var skip = (page - 1) * itemsPerPage; var allTickets = this.ticketsRepo .All() .OrderByDescending(x => x.CreatedOn) .OrderBy(x => x.ProjectId) .Skip(skip) .Take(itemsPerPage) .Select(x => new MyTicketsViewModel { Id = x.Id, IssueType = x.Issue.Name, Summary = x.Summary, Reporter = x.ReporterId, Assignee = x.AssigneeId, CreateOn = x.CreatedOn.ToString("dd/MM/yyyy"), Status = x.Status.ToString(), }) .ToList(); foreach (var ticket in allTickets) { ticket.Assignee = this.AssignNameToAssignee(ticket.Assignee); ticket.Reporter = this.usersService.GetEmployeeFullName(ticket.Reporter); } return allTickets; } public IEnumerable<OpenTicketsViewModel> GetOpenTickets(string project, int itemsPerPage, int page) { var skip = (page - 1) * itemsPerPage; var openTickets = this.ticketsRepo .All() .Where(x => x.Status == Status.Open) .Where(x => x.Project.Name == project) .OrderByDescending(x => x.CreatedOn) .Skip(skip) .Take(itemsPerPage) .Select(x => new OpenTicketsViewModel { Id = x.Id, IssueType = x.Issue.Name, Summary = x.Summary, Reporter = x.ReporterId, Assignee = x.AssigneeId, CreateOn = x.CreatedOn.ToString("dd/MM/yyyy"), }) .ToList(); foreach (var ticket in openTickets) { ticket.Assignee = this.AssignNameToAssignee(ticket.Assignee); ticket.Reporter = this.usersService.GetEmployeeFullName(ticket.Reporter); } return openTickets; } public IEnumerable<MyTicketsViewModel> GetUserTickets(string userId, int itemsPerPage, int page) { var skip = (page - 1) * itemsPerPage; var userTickets = this.ticketsRepo.AllAsNoTracking() .Where(x => x.ReporterId == userId) .OrderBy(x => x.Status) .ThenByDescending(x => x.CreatedOn) .Skip(skip) .Take(itemsPerPage) .Select(x => new MyTicketsViewModel { Id = x.Id, IssueType = x.Issue.Name, Summary = x.Summary, Reporter = userId, Assignee = x.AssigneeId, CreateOn = x.CreatedOn.ToString("dd/MM/yyyy"), Status = x.Status.ToString(), Rate = x.Rate.Value, }) .ToList(); foreach (var ticket in userTickets) { ticket.Assignee = this.AssignNameToAssignee(ticket.Assignee); } return userTickets; } public IEnumerable<ClosedTicketsViewModel> GetClosedTickets(string project, int itemsPerPage, int page) { var skip = (page - 1) * itemsPerPage; var closedTickets = this.ticketsRepo .All() .Where(x => x.Status == Status.Closed) .Where(x => x.Project.Name == project) .OrderByDescending(x => x.CreatedOn) .Skip(skip) .Take(itemsPerPage) .Select(x => new ClosedTicketsViewModel { Id = x.Id, IssueType = x.Issue.Name, Summary = x.Summary, Reporter = x.ReporterId, Assignee = x.AssigneeId, CreateOn = x.CreatedOn.ToString("dd/MM/yyyy"), Rate = x.Rate.Value, }) .ToList(); foreach (var ticket in closedTickets) { ticket.Assignee = this.AssignNameToAssignee(ticket.Assignee); ticket.Reporter = this.usersService.GetEmployeeFullName(ticket.Reporter); } return closedTickets; } public async Task AssigneeUserToTicketAsync(int ticketId, string userId) { var ticket = this.ticketsRepo.All().FirstOrDefault(x => x.Id == ticketId); if (userId != "Unassigned") { ticket.AssigneeId = userId; } else { ticket.AssigneeId = null; } await this.ticketsRepo.SaveChangesAsync(); } public Ticket GetTicketById(int id) { return this.ticketsRepo.AllAsNoTracking().FirstOrDefault(x => x.Id == id); } public SearchedTicketViewModel GetSearchedTicket(int id, string projectName) { var ticket = this.ticketsRepo.AllAsNoTracking() .Where(x => x.Id == id) .Where(x => x.Project.Name == projectName) .Select(x => new SearchedTicketViewModel { Id = x.Id, IssueType = x.Issue.Name, Summary = x.Summary, Reporter = x.ReporterId, Assignee = x.AssigneeId, CreateOn = x.CreatedOn.ToString("dd/MM/yyyy"), Rate = x.Rate.Value, Status = x.Status.ToString(), }) .FirstOrDefault(); if (ticket == null) { return null; } ticket.Assignee = this.AssignNameToAssignee(ticket.Assignee); ticket.Reporter = this.usersService.GetEmployeeFullName(ticket.Reporter); return ticket; } public TicketsDetailsViewModel GetTicketDetailById(int id) { var ticket = this.ticketsRepo .AllAsNoTracking() .Where(x => x.Id == id) .Select(x => new TicketsDetailsViewModel { Id = x.Id, IssueType = x.Issue.Name, Summary = x.Summary, Description = x.Description, CreateOn = x.CreatedOn.ToShortDateString(), Assignee = x.AssigneeId, ReporterId = x.ReporterId, Priority = x.Priority.ToString(), Status = x.Status.ToString(), Comments = x.Comments.OrderByDescending(x => x.CreatedOn) .Select(x => new CommentDetailsViewModel { Content = x.Content, CreatedOn = x.CreatedOn, AddByUser = x.AddedByUser.FirstName + " " + x.AddedByUser.LastName, }).ToList(), Attachments = x.Attachments, PhoneNumber = x.PhoneNumber, }) .FirstOrDefault(); ticket.Assignee = this.AssignNameToAssignee(ticket.Assignee); ticket.Reporter = this.usersService.GetReporterById(ticket.ReporterId); return ticket; } public IEnumerable<SelectListItem> GetAllProjectEmployees(string departmentName) { var dbEmployees = this.usersService.GetDepartmentEmployees(departmentName); var employees = new List<SelectListItem>(); foreach (var employee in dbEmployees) { var temp = new SelectListItem { Text = employee.FirstName + " " + employee.LastName, Value = employee.Id, }; employees.Add(temp); } var unAssignee = new SelectListItem { Text = "Unassigned", }; employees.Add(unAssignee); return employees; } public int GetUserTicketsCount(string userId) { return this.ticketsRepo.AllAsNoTrackingWithDeleted().Where(x => x.ReporterId == userId).Count(); } public int GetOpenTicketsCount() { return this.ticketsRepo.AllAsNoTrackingWithDeleted().Where(x => x.Status == Status.Open).Count(); } public int GetClosedTicketsCount() { return this.ticketsRepo.AllAsNoTrackingWithDeleted().Where(x => x.Status == Status.Closed).Count(); } public async Task CreateAsync(CreateTicketinputModel input, string userId, string filesPath) { int index = int.Parse(input.Issue); var project = this.projectsService.GetProjectByName(input.Project); var pi = this.projectsService.GetProjectsItems(); var issueIndex = pi[input.Project].ElementAt(index); var issue = this.issuesService.GetIssueByName(issueIndex); var ticket = new Ticket { ProjectId = project.Id, IssueId = issue.Id, Summary = input.Summary, Description = input.Description, Priority = input.Priority, ReporterId = userId, Status = Status.Open, PhoneNumber = input.PhoneNumber, }; if (input.Attachments != null) { Directory.CreateDirectory($"{filesPath}/tickets/"); foreach (var attach in input.Attachments) { var extension = Path.GetExtension(attach.FileName).TrimStart('.'); var dbFile = new Attachment { AddedByUserId = userId, Extension = extension, }; ticket.Attachments.Add(dbFile); var physicalPath = $"{filesPath}/tickets/{dbFile.Id}.{extension}"; using Stream fileStream = new FileStream(physicalPath, FileMode.Create); await attach.CopyToAsync(fileStream); } } await this.ticketsRepo.AddAsync(ticket); await this.ticketsRepo.SaveChangesAsync(); } public async Task ResolveTicketAsync(int ticketId) { var ticket = this.ticketsRepo.All().FirstOrDefault(x => x.Id == ticketId); ticket.Status = Status.Closed; await this.ticketsRepo.SaveChangesAsync(); } public int GetCount() { return this.ticketsRepo.AllAsNoTracking().Count(); } private string AssignNameToAssignee(string assign) { if (assign != null) { assign = this.usersService.GetEmployeeFullName(assign); } else { assign = "Unassigned"; } return assign; } } }
35.144044
111
0.501537
[ "Unlicense" ]
gready000/ZENBEAR-Digital
Services/ZENBEAR.Services.Data/TicketsService.cs
12,689
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace Plasticine { public class MeshBuilder { // // Link between a position in space and the triangles that use this position // See 'Build()' method // private class PositionLinks { public Dictionary<int, int> triangleToVertex = new Dictionary<int, int> (); } // // A Triangle // private class Triangle { public int[] pIndex = new int[3]; // indices in m_positions } // Positions (can be shared) private List<Vector3> m_positions = new List<Vector3> (); private Dictionary<int, int> m_uidToIndex = new Dictionary<int, int> (); // Important for vertex sharing between triangles // UVs private List<Vector2> m_uvs = new List<Vector2> (); // Triangles private List<Triangle> m_triangles = new List<Triangle> (); // // // public void Cap(PointList points) { // Add positions for(int i=0; i<points.Count; i++) { AddPosition (points, i); } // Add triangles for (int i = 0; i < points.Count - 2; i++) { AddTriangle (points.Uid (0), points.Uid (i + 1), points.Uid (i + 2)); } } // // Add a position from a PointList // Warning : here we assume uvs and positions share the same index ... NOT SURE AT ALL ! // private void AddPosition(PointList points, int i) { int uid = points.Uid (i); if (!m_uidToIndex.ContainsKey (uid)) { Vector3 point = points [i]; int index = m_positions.Count; m_positions.Add ( point ); m_uvs.Add ( points.UVMapper.GetUV(point) ); m_uidToIndex [uid] = index; } } private void AddTriangle(int uid0, int uid1, int uid2) { Triangle t = new Triangle (); t.pIndex [0] = m_uidToIndex [uid0]; t.pIndex [1] = m_uidToIndex [uid1]; t.pIndex [2] = m_uidToIndex [uid2]; m_triangles.Add (t); } // // // public void Cap(List<PointList> list) { foreach (PointList points in list) { Cap (points); } } // // Compute one normal per triangle // private List<Vector3> ComputeFlatNormals() { List<Vector3> flatNormals = new List<Vector3> (); for (int triIndex = 0; triIndex < m_triangles.Count; triIndex++) { Triangle tri = m_triangles [triIndex]; Vector3 v0 = m_positions [tri.pIndex [0]]; Vector3 v1 = m_positions [tri.pIndex [1]]; Vector3 v2 = m_positions [tri.pIndex [2]]; flatNormals.Add( Vector3.Cross (v1-v0, v2-v0).normalized ); } return flatNormals; } // // Create one PositionLink per Position // private List<PositionLinks> ComputePositionLinks () { List<PositionLinks> links = new List<PositionLinks>(); for (int posIndex = 0; posIndex < m_positions.Count; posIndex++) { links.Add(new PositionLinks()); } for (int triIndex = 0; triIndex < m_triangles.Count; triIndex++) { Triangle tri = m_triangles [triIndex]; links [tri.pIndex [0]].triangleToVertex.Add(triIndex, -1); links [tri.pIndex [1]].triangleToVertex.Add(triIndex, -1); links [tri.pIndex [2]].triangleToVertex.Add(triIndex, -1); } return links; } // // Create Unity Mesh, smooh normals using smoothAngles // public Mesh Build( float smoothAngle = 45f ) { // Compute normal for each triangle List<Vector3> flatNormals = ComputeFlatNormals (); // Compute PositionLink, one per position, init with -1 List<PositionLinks> links = ComputePositionLinks(); // Data for Mesh creation List<Vector3> vertices = new List<Vector3> (); List<Vector2> uvs = new List<Vector2> (); List<int> triangles = new List<int> (); for (int triIndex = 0; triIndex < m_triangles.Count; triIndex++) { Triangle tri = m_triangles[triIndex]; for (int i = 0; i < 3; i++) { int posIndex = tri.pIndex [i]; int vtxIndex = links [posIndex].triangleToVertex [triIndex]; if (vtxIndex != -1) { // Vertex already known triangles.Add (vtxIndex); } else { // Create new Vertex vtxIndex = vertices.Count; vertices.Add (m_positions[posIndex]); uvs.Add (m_uvs [posIndex]); // Use new vertex triangles.Add (vtxIndex); // Make all triangles whose angle is under limitAngle also use new vertex int keysCount = links [posIndex].triangleToVertex.Keys.Count; int[] keys = new int[keysCount]; links [posIndex].triangleToVertex.Keys.CopyTo (keys, 0); for (int j = 0; j < keysCount; j++) { if(Vector3.Angle( flatNormals[triIndex], flatNormals[keys[j]] ) < smoothAngle) { links [posIndex].triangleToVertex [keys[j]] = vtxIndex; } } } } } // Create Mesh Mesh mesh = new Mesh (); mesh.SetVertices(vertices); mesh.SetUVs (0, uvs); mesh.SetTriangles(triangles, 0); mesh.RecalculateNormals(); mesh.RecalculateBounds (); #if UNITY_EDITOR if(uvs.Count>0) { Unwrapping.GenerateSecondaryUVSet (mesh); } #endif return mesh; } // // // public void Add(MeshBuilder pmesh) { // TODO : Reindex every position to avoid issues with uids int indexOffset = m_positions.Count; // Add positions and uvs for(int i = 0; i<pmesh.m_positions.Count; i++) { m_positions.Add ( pmesh.m_positions [i] ); m_uvs.Add (pmesh.m_uvs [i]); } // Add uids : does it matter ? Dictionary<int, int>.KeyCollection uids = pmesh.m_uidToIndex.Keys; foreach (int uid in uids) { m_uidToIndex [uid] = pmesh.m_uidToIndex[uid] + indexOffset; } // Add triangles for (int i = 0; i < pmesh.m_triangles.Count; i++) { Triangle tOther = pmesh.m_triangles [i]; Triangle tNew = new Triangle (); tNew.pIndex[0] = tOther.pIndex[0] + indexOffset; tNew.pIndex[1] = tOther.pIndex[1] + indexOffset; tNew.pIndex[2] = tOther.pIndex[2] + indexOffset; m_triangles.Add (tNew); } } } }
34.298643
130
0.491425
[ "MIT" ]
dondi3go/Plasticine
Core/MeshBuilder.cs
7,582
C#
using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.SharePoint.Client; using Provisioning.Common.Authentication; using Provisioning.Common.Configuration; using Provisioning.Common.Configuration.Application; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Provisioning.Common.Utilities; using Provisioning.Common.Data.SiteRequests; using System.Diagnostics; using Provisioning.Common.Mail; using Provisioning.Common.Data.Templates; using static Provisioning.Common.MdlzComponents.TeamsProvisioning; using Newtonsoft.Json; namespace Provisioning.Common.Data.SiteRequests.Impl { /// <summary> /// Implmentation class for the Site Request Repository that leverages SharePoint as the datasource. /// </summary> internal class SPSiteRequestManager : AbstractModule, ISiteRequestManager, ISharePointClientService { #region Private Instance Members private static readonly IConfigurationFactory _cf = ConfigurationFactory.GetInstance(); private static readonly IAppSettingsManager _manager = _cf.GetAppSetingsManager(); const string LOGGING_SOURCE = "SPSiteRequestManagerImpl"; const string FIELD_XML_FORMAT = @"<Field Type=""{0}"" Name=""{1}"" StaticName=""{1}"" DisplayName=""{2}"" ID=""{3}"" {4}/>"; const string CAML_NEWREQUEST_BY_URL = "<Query><Where><And><Eq><FieldRef Name=SP_Url'/><Value Type='Text'>{0}</Value></Eq><Eq><FieldRef Name='Status'/><Value Type='Text'>New</Value></Eq></And></Where></Query>"; const string CAML_NEWREQUESTS = "<View><Query><Where><Eq><FieldRef Name='SP_ProvisioningStatus'/><Value Type='Text'>New</Value></Eq></Where></Query><RowLimit>100</RowLimit></View>"; const string CAML_GETREQUEST_BY_URL = "<View><Query><Where><Eq><FieldRef Name='SP_Url'/><Value Type='Text'>{0}</Value></Eq></Where></Query><RowLimit>100</RowLimit></View>"; //const string CAML_APPROVEDREQUESTS = "<View><Query><Where><In> <FieldRef Name='ID'/> <Values> <Value Type='Number'>7463</Value> </Values> </In></Where></Query><RowLimit>100</RowLimit></View>"; const string CAML_APPROVEDREQUESTS = "<View><Query><Where><Eq><FieldRef Name='SP_ProvisioningStatus'/><Value Type='Text'>Approved</Value></Eq></Where></Query><RowLimit>100</RowLimit></View>"; const string CAML_GETREQUESTSBYOWNER = "<View><Query><Where><Or><Eq><FieldRef Name='SP_Owner' LookupId='True'/><Value Type='Int'>{0}</Value></Eq><Eq><FieldRef Name='SP_RequestedBy' LookupId='True'/><Value Type='Int'>{0}</Value></Eq></Or></Where></Query></View>"; const string CAML_INCOMPLETEREQUESTS = "<View><Query><Where><And><And><Neq><FieldRef Name='SP_ProvisioningStatus'/><Value Type='Text'>Complete</Value></Neq><Neq><FieldRef Name='SP_ProvisioningStatus'/><Value Type='Text'>Approved</Value></Neq></And><Neq><FieldRef Name='SP_ProvisioningStatus'/><Value Type='Text'>New</Value></Neq></And></Where></Query><RowLimit>100</RowLimit></View>"; const string CAML_APPROVALANDREJECTEDSITESFORNOTIFICATION = "<View> <Query> <Where> <And> <Or> <IsNull> <FieldRef Name='SP_NotificationStatus' /> </IsNull> <Neq> <FieldRef Name='SP_NotificationStatus'/> <Value Type='Text'>Rejected Mail Sent</Value> </Neq> </Or> <In> <FieldRef Name='SP_ProvisioningStatus'/> <Values> <Value Type='Text'>New</Value> <Value Type='Text'>Rejected</Value> </Values> </In> </And> </Where> </Query> <RowLimit>100</RowLimit> </View>"; #endregion #region Constructor public SPSiteRequestManager() { } #endregion #region Private Methods /// <summary> /// Member to return SiteRequest from the SharePoint SiteRequest Repository /// </summary> /// <param name="camlQuery">Query Query to Execute</param> /// <returns></returns> private ICollection<SiteInformation> GetSiteRequestsByCaml(string camlQuery) { List<SiteInformation> _siteRequests = new List<SiteInformation>(); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _camlQuery = new CamlQuery(); _camlQuery.ViewXml = camlQuery; Log.Info("SPSiteRequestManager.GetSiteRequestsByCaml", "Querying SharePoint Request Repository {0}, Caml Query {1}", SiteRequestList.LISTURL, _camlQuery.ViewXml); //var _web = ctx.Web; //ctx.Load(_web); //if (!_web.ListExists(SiteRequestList.TITLE)) //{ // var _message = String.Format("The List {0} does not exist in Site {1}", // SiteRequestList.TITLE, // _web.Url); // Log.Fatal("SPSiteRequestManager.GetSiteRequestsByCaml", _message); // throw new DataStoreException(_message); //} var _list = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE); var _listItemCollection = _list.GetItems(_camlQuery); ctx.Load(_listItemCollection, eachItem => eachItem.Include( item => item, item => item[SiteRequestFields.TITLE], item => item[SiteRequestFields.DESCRIPTION_NAME], item => item[SiteRequestFields.TEMPLATE_NAME], item => item[SiteRequestFields.POLICY_NAME], item => item[SiteRequestFields.URL_NAME], item => item[SiteRequestFields.OWNER_NAME], item => item[SiteRequestFields.ADD_ADMINS_NAME], item => item[SiteRequestFields.LCID_NAME], item => item[SiteRequestFields.EXTERNALSHARING_NAME], item => item[SiteRequestFields.PROVISIONING_STATUS_NAME], item => item[SiteRequestFields.ONPREM_REQUEST_NAME], item => item[SiteRequestFields.LCID_NAME], item => item[SiteRequestFields.TIMEZONE_NAME], item => item[SiteRequestFields.BC_NAME], item => item[SiteRequestFields.PROPS_NAME], item => item[SiteRequestFields.STATUSMESSAGE_NAME], item => item[SiteRequestFields.ListItemID_NAME], item => item[SiteRequestFields.NOTIFICATIONSTATUS_NAME], item => item[SiteRequestFields.TEMPLATE_NAME], item => item[SiteRequestFields.ListItemCREATED_NAME], item => item[SiteRequestFields.ISCONFIDENTIAL_NAME])); var lc_Templates = ctx.Web.Lists.GetByTitle("Templates").GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(lc_Templates, eachItem => eachItem.Include( // item => item, item => item[TemplateFields.TTILE_NAME], item => item[TemplateFields.TEMPLATE_NAME] // item => item[TemplateFields.DESCRIPTION_NAME], // item => item[TemplateFields.TEMPLATEIMAGE_NAME], //item => item[TemplateFields.HOSTPATH_NAME], //item => item[TemplateFields.TENANTURL_NAME], //item => item[TemplateFields.ONPREM_NAME], //item => item[TemplateFields.STORAGEMAX_NAME], //item => item[TemplateFields.STORAGEWARN_NAME], //item => item[TemplateFields.USERCODEMAX_NAME], //item => item[TemplateFields.USERCODEWARN_NAME], // item => item[TemplateFields.ENABLED_NAME], //item => item[TemplateFields.ROOTWEBONLY_NAME], //item => item[TemplateFields.SUBWEBONLY_NAME], //item => item[TemplateFields.USETEMPLATESITEPOLICY_NAME], //item => item[TemplateFields.AutoApprove], //item => item[TemplateFields.PROVISIONINGTEMPLATE_NAME], //item => item[TemplateFields.MdlzSiteCategory] )); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "SPSiteRequestManager.GetSiteRequestsByCaml", _timespan.Elapsed); var provTemplates = lc_Templates.Select(x => new { BaseTemplate = x.BaseGet(TemplateFields.TEMPLATE_NAME), TemplateTitle = x.BaseGet(TemplateFields.TTILE_NAME) }); Dictionary<int, User> list = new Dictionary<int, User>(); foreach (var item in _listItemCollection) { var _fieldUser = ((FieldUserValue)(item[SiteRequestFields.OWNER_NAME])); var _user = ctx.Web.GetUserById(_fieldUser.LookupId); ctx.Load(_user, u => u.LoginName, u => u.Email, u => u.Id); list[_fieldUser.LookupId] = _user; var addAdmins = (item[SiteRequestFields.ADD_ADMINS_NAME] as FieldUserValue[]); if (addAdmins != null) { foreach (var c in addAdmins) { var _u = ctx.Web.GetUserById(c.LookupId); ctx.Load(_u, u => u.LoginName, u => u.Email, u => u.Id); list[c.LookupId] = _u; } } } ctx.ExecuteQuery(); Func<ListItem, SiteUser> getUserObj = (item) => { SiteUser _owner = new SiteUser(); var _fieldUser = ((FieldUserValue)(item[SiteRequestFields.OWNER_NAME])); var u = list[_fieldUser.LookupId]; return new SiteUser { Name = u.LoginName, Email = u.Email }; }; Func<ListItem, List<SiteUser>> getUserArray = (item) => { List<SiteUser> users = new List<SiteUser>(); var _fieldUser = item[SiteRequestFields.ADD_ADMINS_NAME] as FieldUserValue[]; if (_fieldUser != null && _fieldUser.Length > 0) users = _fieldUser.Select(x => { var u = list[x.LookupId]; return new SiteUser { Name = u.LoginName, Email = u.Email }; }).ToList(); return users; }; foreach (ListItem _item in _listItemCollection) { var _site = new SiteInformation() { Title = _item.BaseGet(SiteRequestFields.TITLE), Description = _item.BaseGet(SiteRequestFields.DESCRIPTION_NAME), Template = _item.BaseGet(SiteRequestFields.TEMPLATE_NAME), SitePolicy = _item.BaseGet(SiteRequestFields.POLICY_NAME), Url = _item.BaseGet(SiteRequestFields.URL_NAME), //SiteOwner = _item.BaseGetUser(SiteRequestFields.OWNER_NAME), //AdditionalAdministrators = _item.BaseGetUsers(SiteRequestFields.ADD_ADMINS_NAME), SiteOwner = getUserObj(_item), AdditionalAdministrators = getUserArray(_item), //EnableExternalSharing = _item.BaseGet<bool>(SiteRequestFields.EXTERNALSHARING_NAME), RequestStatus = _item.BaseGet(SiteRequestFields.PROVISIONING_STATUS_NAME), Lcid = _item.BaseGetUint(SiteRequestFields.LCID_NAME), TimeZoneId = _item.BaseGetInt(SiteRequestFields.TIMEZONE_NAME), SharePointOnPremises = _item.BaseGet<bool>(SiteRequestFields.ONPREM_REQUEST_NAME), BusinessCase = _item.BaseGet(SiteRequestFields.BC_NAME), SiteMetadataJson = _item.BaseGet(SiteRequestFields.PROPS_NAME), RequestStatusMessage = _item.BaseGet(SiteRequestFields.STATUSMESSAGE_NAME), IsConfidential = _item.BaseGet<bool>(SiteRequestFields.ISCONFIDENTIAL_NAME), Id = _item.BaseGet(SiteRequestFields.ListItemID_NAME), NotificationStatus = _item.BaseGet(SiteRequestFields.NOTIFICATIONSTATUS_NAME), SubmitDate = _item.BaseGet<DateTime>(SiteRequestFields.ListItemCREATED_NAME), }; _site.BaseTemplate = provTemplates.FirstOrDefault(x => x.TemplateTitle == _site.Template)?.BaseTemplate; _siteRequests.Add(_site); } }); return _siteRequests; } private SiteInformation GetSiteRequestByCaml(string camlQuery, string filter) { SiteInformation _siteRequest = null; UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); CamlQuery _camlQuery = new CamlQuery(); _camlQuery.ViewXml = string.Format(camlQuery, filter); Log.Info("SPSiteRequestManager.GetSiteRequestsByCaml", "Querying SharePoint Request Repository: {0}, Caml Query: {1} Filter: {2}", SiteRequestList.LISTURL, _camlQuery.ViewXml, filter); var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(SiteRequestList.TITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", SiteRequestList.TITLE, _web.Url); Log.Fatal("SPSiteRequestManager.GetSiteRequestsByCaml", _message); throw new DataStoreException(_message); } var _list = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE); var _listItemCollection = _list.GetItems(_camlQuery); ctx.Load(_listItemCollection, eachItem => eachItem.Include( item => item, item => item[SiteRequestFields.TITLE], item => item[SiteRequestFields.DESCRIPTION_NAME], item => item[SiteRequestFields.TEMPLATE_NAME], item => item[SiteRequestFields.POLICY_NAME], item => item[SiteRequestFields.URL_NAME], item => item[SiteRequestFields.OWNER_NAME], item => item[SiteRequestFields.PROVISIONING_STATUS_NAME], item => item[SiteRequestFields.ADD_ADMINS_NAME], item => item[SiteRequestFields.LCID_NAME], item => item[SiteRequestFields.EXTERNALSHARING_NAME], item => item[SiteRequestFields.PROVISIONING_STATUS_NAME], item => item[SiteRequestFields.ONPREM_REQUEST_NAME], item => item[SiteRequestFields.LCID_NAME], item => item[SiteRequestFields.TIMEZONE_NAME], item => item[SiteRequestFields.BC_NAME], item => item[SiteRequestFields.PROPS_NAME], item => item[SiteRequestFields.STATUSMESSAGE_NAME])); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "SPSiteRequestManager.GetSiteRequestsByCaml", _timespan.Elapsed); if (_listItemCollection.Count > 0) { ListItem _item = _listItemCollection.First(); _siteRequest = new SiteInformation() { Title = _item.BaseGet(SiteRequestFields.TITLE), Description = _item.BaseGet(SiteRequestFields.DESCRIPTION_NAME), Template = _item.BaseGet(SiteRequestFields.TEMPLATE_NAME), SitePolicy = _item.BaseGet(SiteRequestFields.POLICY_NAME), Url = _item.BaseGet(SiteRequestFields.URL_NAME), SiteOwner = _item.BaseGetUser(SiteRequestFields.OWNER_NAME), AdditionalAdministrators = _item.BaseGetUsers(SiteRequestFields.ADD_ADMINS_NAME), //EnableExternalSharing = _item.BaseGet<bool>(SiteRequestFields.EXTERNALSHARING_NAME), RequestStatus = _item.BaseGet(SiteRequestFields.PROVISIONING_STATUS_NAME), Lcid = _item.BaseGetUint(SiteRequestFields.LCID_NAME), TimeZoneId = _item.BaseGetInt(SiteRequestFields.TIMEZONE_NAME), SharePointOnPremises = _item.BaseGet<bool>(SiteRequestFields.ONPREM_REQUEST_NAME), BusinessCase = _item.BaseGet(SiteRequestFields.BC_NAME), SiteMetadataJson = _item.BaseGet(SiteRequestFields.PROPS_NAME), RequestStatusMessage = _item.BaseGet(SiteRequestFields.STATUSMESSAGE_NAME) }; } }); return _siteRequest; } #endregion #region ISharePointClientService Members /// <summary> /// Class used for working with the ClientContext /// </summary> /// <param name="action"></param> public virtual void UsingContext(Action<ClientContext> action) { UsingContext(action, Timeout.Infinite); } /// <summary> /// Class used for working with the ClientContext /// </summary> /// <param name="action"></param> /// <param name="csomTimeOut"></param> public virtual void UsingContext(Action<ClientContext> action, int csomTimeout) { using (ClientContext _ctx = Authentication.GetAuthenticatedContext()) { _ctx.RequestTimeout = csomTimeout; action(_ctx); } } #endregion #region Properties /// <summary> /// Returns the implementation for AppOnlyAuthentication /// </summary> public IAuthentication Authentication { get { return new AppOnlyAuthenticationSite(); } } #endregion #region ISiteRequestManager Members public ICollection<SiteInformation> GetOwnerRequests(string email) { Log.Info("SPSiteRequestManager.GetOwnerRequests", "Entering GetOwnerRequests by email {0}", email); ICollection<SiteInformation> _returnResults = new List<SiteInformation>(); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); try { var _user = ctx.Web.EnsureUser(email); ctx.Load(_user); ctx.ExecuteQuery(); if (_user != null) { var _userID = _user.Id; var camlString = string.Format(CAML_GETREQUESTSBYOWNER, _userID); _returnResults = this.GetSiteRequestsByCaml(camlString); _timespan.Stop(); Log.TraceApi("SharePoint", "SPSiteRequestManager.GetOwnerRequests", _timespan.Elapsed); } else { Log.Warning("SPSiteRequestManager.GetOwnerRequests", "GetOwnerRequests email {0} not found", email); } } catch (Exception _ex) { //TODO LOG } }); return _returnResults; } public void CreateNewSiteRequest(SiteInformation siteRequest) { Log.Info("SPSiteRequestManager.CreateNewSiteRequest", "Entering CreateNewSiteRequest requested url {0}", siteRequest.Url); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(SiteRequestList.TITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", SiteRequestList.TITLE, _web.Url); Log.Fatal("SPSiteRequestManager.CreateNewSiteRequest", _message); throw new DataStoreException(_message); } List list = _web.Lists.GetByTitle(SiteRequestList.TITLE); ListItemCreationInformation _listItemCreation = new ListItemCreationInformation(); ListItem _record = list.AddItem(_listItemCreation); _record[SiteRequestFields.TITLE] = siteRequest.Title; _record[SiteRequestFields.DESCRIPTION_NAME] = siteRequest.Description; _record[SiteRequestFields.TEMPLATE_NAME] = siteRequest.Template; _record[SiteRequestFields.URL_NAME] = siteRequest.Url; _record[SiteRequestFields.LCID_NAME] = siteRequest.Lcid; _record[SiteRequestFields.TIMEZONE_NAME] = siteRequest.TimeZoneId; _record[SiteRequestFields.POLICY_NAME] = siteRequest.SitePolicy; _record[SiteRequestFields.EXTERNALSHARING_NAME] = siteRequest.EnableExternalSharing; _record[SiteRequestFields.ONPREM_REQUEST_NAME] = siteRequest.SharePointOnPremises; _record[SiteRequestFields.BC_NAME] = siteRequest.BusinessCase; _record[SiteRequestFields.PROPS_NAME] = siteRequest.SiteMetadataJson; _record[SiteRequestFields.ISCONFIDENTIAL_NAME] = siteRequest.IsConfidential; if (!string.IsNullOrEmpty(siteRequest.RequestedBy)) { _record[SiteRequestFields.REQUESTEDBY_NAME] = FieldUserValue.FromUser(siteRequest.RequestedBy); } //If Settings are set to autoapprove then automatically approve the requests if (_manager.GetAppSettings().AutoApprove && siteRequest.AutoApprove) { _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.Approved.ToString(); _record[SiteRequestFields.APPROVEDDATE_NAME] = DateTime.Now; } else { _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.New.ToString(); } FieldUserValue _siteOwner = FieldUserValue.FromUser(siteRequest.SiteOwner.Name); _record[SiteRequestFields.OWNER_NAME] = _siteOwner; //Additional Admins if (siteRequest.AdditionalAdministrators != null) { if (siteRequest.AdditionalAdministrators.Count > 0) { FieldUserValue[] _additionalAdmins = new FieldUserValue[siteRequest.AdditionalAdministrators.Count]; int _index = 0; foreach (SiteUser _user in siteRequest.AdditionalAdministrators) { FieldUserValue _adminFieldUser = FieldUserValue.FromUser(_user.Name); _additionalAdmins[_index] = _adminFieldUser; _index++; } _record[SiteRequestFields.ADD_ADMINS_NAME] = _additionalAdmins; } } _record.Update(); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "SPSiteRequestManager.CreateNewSiteRequest", _timespan.Elapsed); Log.Info("SPSiteRequestManager.CreateNewSiteRequest", PCResources.SiteRequestNew_Successful, siteRequest.Url); } ); } public SiteInformation GetSiteRequestByUrl(string url) { Log.Info("SPSiteRequestManager.GetSiteRequestByUrl", "Entering GetSiteRequestByUrl url {0}", url); return this.GetSiteRequestByCaml(CAML_GETREQUEST_BY_URL, url); } public ICollection<SiteInformation> GetNewRequests() { Log.Info("SPSiteRequestManager.GetNewRequests", "Entering GetNewRequests"); return this.GetSiteRequestsByCaml(CAML_NEWREQUESTS); } public ICollection<SiteInformation> GetApprovedRequests() { Log.Info("SPSiteRequestManager.GetNewRequests", "Entering GetApprovedRequests"); return this.GetSiteRequestsByCaml(CAML_APPROVEDREQUESTS); } public ICollection<SiteInformation> GetIncompleteRequests() { Log.Info("SPSiteRequestManager.GetIncompleteRequests", "Entering GetIncompleteRequests"); return this.GetSiteRequestsByCaml(CAML_INCOMPLETEREQUESTS); } public ICollection<SiteInformation> GetApprovalAndRejectedSitesForNotification() { Log.Info("SPSiteRequestManager.GetIncompleteRequests", "Entering GetIncompleteRequests"); return this.GetSiteRequestsByCaml(CAML_APPROVALANDREJECTEDSITESFORNOTIFICATION); } public bool DoesSiteRequestExist(string url) { Log.Info("SPSiteRequestManager.DoesSiteRequestExist", "Entering DoesSiteRequestExist url {0}", url); var _result = this.GetSiteRequestByUrl(url); if (_result != null) { return true; } return false; } public void UpdateRequestStatus(string url, SiteRequestStatus status) { Log.Info("SPSiteRequestManager.UpdateRequestStatus", "Entering UpdateRequestStatus url {0} status {1}", url, status.ToString()); this.UpdateRequestStatus(url, status, string.Empty); } public void UpdateRequestStatus(string url, SiteRequestStatus status, string statusMessage) { Log.Info("SPSiteRequestManager.UpdateRequestStatus", "Entering UpdateRequestStatus url {0} status {1} status message", url, status.ToString(), statusMessage); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(SiteRequestList.TITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", SiteRequestList.TITLE, _web.Url); Log.Fatal("SPSiteRequestManager.UpdateRequestStatus", _message); throw new DataStoreException(_message); } var _list = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE); var _query = new CamlQuery(); _query.ViewXml = string.Format(CAML_GETREQUEST_BY_URL, url); ListItemCollection _itemCollection = _list.GetItems(_query); ctx.Load(_itemCollection); ctx.ExecuteQuery(); if (_itemCollection.Count != 0) { ListItem _item = _itemCollection.FirstOrDefault(); _item[SiteRequestFields.PROVISIONING_STATUS_NAME] = status.ToString(); _item[SiteRequestFields.STATUSMESSAGE_NAME] = statusMessage; _item.Update(); ctx.ExecuteQuery(); } _timespan.Stop(); Log.Info("SPSiteRequestManager.UpdateRequestStatus", PCResources.SiteRequestUpdate_Successful, url, status.ToString()); Log.TraceApi("SharePoint", "SPSiteRequestManager.UpdateRequestStatus", _timespan.Elapsed); }); } public void UpdateRequestUrl(string url, string newUrl) { Log.Info("SPSiteRequestManager.UpdateRequestUrl", "Entering UpdateRequestUrl url {0} status {1} status message", url, newUrl); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(SiteRequestList.TITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", SiteRequestList.TITLE, _web.Url); Log.Fatal("SPSiteRequestManager.UpdateRequestUrl", _message); throw new DataStoreException(_message); } var _list = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE); var _query = new CamlQuery(); _query.ViewXml = string.Format(CAML_GETREQUEST_BY_URL, url); ListItemCollection _itemCollection = _list.GetItems(_query); ctx.Load(_itemCollection); ctx.ExecuteQuery(); if (_itemCollection.Count != 0) { ListItem _item = _itemCollection.FirstOrDefault(); _item[SiteRequestFields.URL_NAME] = newUrl; _item.Update(); ctx.ExecuteQuery(); } _timespan.Stop(); Log.Info("SPSiteRequestManager.UpdateRequestUrl", PCResources.SiteRequestUpdate_Successful, url, newUrl); Log.TraceApi("SharePoint", "SPSiteRequestManager.UpdateRequestUrl", _timespan.Elapsed); }); } public void UpdateNotificationStatus(string url, string notifStatusMessage) { Log.Info("SPSiteRequestManager.UpdateRequestStatus", "Entering UpdateRequestStatus url {0} status {1} status message", url, notifStatusMessage); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(SiteRequestList.TITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", SiteRequestList.TITLE, _web.Url); Log.Fatal("SPSiteRequestManager.UpdateRequestStatus", _message); throw new DataStoreException(_message); } var _list = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE); var _query = new CamlQuery(); _query.ViewXml = string.Format(CAML_GETREQUEST_BY_URL, url); ListItemCollection _itemCollection = _list.GetItems(_query); ctx.Load(_itemCollection); ctx.ExecuteQuery(); if (_itemCollection.Count != 0) { ListItem _item = _itemCollection.FirstOrDefault(); _item[SiteRequestFields.NOTIFICATIONSTATUS_NAME] = notifStatusMessage; _item.Update(); ctx.ExecuteQuery(); } _timespan.Stop(); Log.Info("SPSiteRequestManager.UpdateNotificationStatus", PCResources.SiteRequestUpdate_Successful, url, notifStatusMessage.ToString()); Log.TraceApi("SharePoint", "SPSiteRequestManager.UpdateNotificationStatus", _timespan.Elapsed); }); } public IEnumerable<SiteUser> GetRequestApprovers() { IEnumerable<SiteUser> ret = null; UsingContext(ctx => { string strSiteRequestApproversGroupName = "Site Request Approvers"; try { var approverGroup = ctx.Web.SiteGroups.GetByName(strSiteRequestApproversGroupName); ctx.Load(approverGroup, x => x.Users.Include(y => y.Title, y => y.Email)); ctx.ExecuteQuery(); ret = approverGroup?.Users.Select(x => new SiteUser { Email = x.Email, Name = x.Title }); } catch (Exception ex) { bool isGroupNotFoundException = false; if (ex is ServerException) { if (((ServerException)ex).ServerErrorCode == -2146232832 && ((ServerException)ex).ServerErrorTypeName.Equals("Microsoft.SharePoint.SPException", StringComparison.InvariantCultureIgnoreCase)) { isGroupNotFoundException = true; } } if (isGroupNotFoundException) Log.Fatal("SPSiteRequestManager.GetRequestApprovers", $"{strSiteRequestApproversGroupName} group not found hence approval mails for new site requests will not be sent to approvers."); else Log.Fatal("SPSiteRequestManager.GetRequestApprovers", ex.ToString()); } }); return ret ?? new List<SiteUser>(); } public void UpdateRequestMetadataForTeamsAndMarkAsCompleted(SiteInformation request, CreatedTeam team) { Log.Info("SPSiteRequestManager.UpdateRequestMetadataForTeams", "Entering UpdateRequestMetadataForTeams url {0}", team.SharePointSiteUrl); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _web = ctx.Web; ctx.Load(_web); var _item = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE).GetItemById(request.Id); ctx.Load(_item); ctx.ExecuteQuery(); if (_item != null) { var spProps = !string.IsNullOrEmpty(request.SiteMetadataJson) ? JsonConvert.DeserializeObject<Dictionary<string, string>>(request.SiteMetadataJson) : new Dictionary<string, string>() ; spProps["_site_props_team_url"] = team.TeamUrl; spProps["_site_props_group_id"] = team.GroupID; spProps["_site_props_mail_nickname"] = team.Mail; _item[SiteRequestFields.PROPS_NAME] = JsonConvert.SerializeObject(spProps); _item[SiteRequestFields.URL_NAME] = team.SharePointSiteUrl; _item[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.Complete.ToString(); _item.Update(); ctx.ExecuteQuery(); } _timespan.Stop(); Log.Info("SPSiteRequestManager.UpdateRequestMetadataForTeams", PCResources.SiteRequestUpdate_Successful, team.SharePointSiteUrl, "Microsoft Team Created"); Log.TraceApi("SharePoint", "SPSiteRequestManager.UpdateRequestMetadataForTeams", _timespan.Elapsed); }); } #endregion } }
50.437768
467
0.574229
[ "MIT" ]
nikhildere/PnP
Solutions/Provisioning.UX.App/Provisioning.Common/Data/SiteRequests/Impl/SPSiteRequestManager.cs
35,258
C#
using System; namespace Metaheuristics { public class DiscreteSS2OptFirst4QAP : DiscreteSS { public QAPInstance Instance { get; protected set; } protected int generatedSolutions; public DiscreteSS2OptFirst4QAP(QAPInstance instance, int poolSize, int refSetSize, double explorationFactor) : base(poolSize, refSetSize, explorationFactor) { Instance = instance; generatedSolutions = 0; } protected override double Fitness(int[] solution) { return QAPUtils.Fitness(Instance, solution); } protected override int[] RandomSolution() { int[] solution; if (generatedSolutions < 2) { solution = QAPUtils.GRCSolution(Instance, 1.0); } else { solution = QAPUtils.RandomSolution(Instance); } generatedSolutions++; return solution; } protected override void Repair(int[] solution) { QAPUtils.Repair(Instance, solution); } protected override void Improve (int[] solution) { QAPUtils.LocalSearch2OptFirst(Instance, solution); } protected override double Distance(int[] a, int[] b) { return QAPUtils.Distance(Instance, a, b); } } }
21.4
74
0.674596
[ "MIT" ]
yasserglez/metaheuristics
Common/QAP/DiscreteSS2OptFirst4QAP.cs
1,177
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 dynamodb-2012-08-10.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.Runtime; using Amazon.DynamoDBv2.Model; namespace Amazon.DynamoDBv2 { /// <summary> /// Interface for accessing DynamoDB /// /// Amazon DynamoDB /// <para> /// Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable /// performance with seamless scalability. DynamoDB lets you offload the administrative /// burdens of operating and scaling a distributed database, so that you don't have to /// worry about hardware provisioning, setup and configuration, replication, software /// patching, or cluster scaling. /// </para> /// /// <para> /// With DynamoDB, you can create database tables that can store and retrieve any amount /// of data, and serve any level of request traffic. You can scale up or scale down your /// tables' throughput capacity without downtime or performance degradation, and use the /// Amazon Web Services Management Console to monitor resource utilization and performance /// metrics. /// </para> /// /// <para> /// DynamoDB automatically spreads the data and traffic for your tables over a sufficient /// number of servers to handle your throughput and storage requirements, while maintaining /// consistent and fast performance. All of your data is stored on solid state disks (SSDs) /// and automatically replicated across multiple Availability Zones in an Amazon Web Services /// Region, providing built-in high availability and data durability. /// </para> /// </summary> public partial interface IAmazonDynamoDB : IAmazonService, IDisposable { #if AWS_ASYNC_ENUMERABLES_API /// <summary> /// Paginators for the service /// </summary> IDynamoDBv2PaginatorFactory Paginators { get; } #endif #region BatchExecuteStatement /// <summary> /// This operation allows you to perform batch reads or writes on data stored in DynamoDB, /// using PartiQL. /// /// <note> /// <para> /// The entire batch must consist of either read statements or write statements, you cannot /// mix both in one batch. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchExecuteStatement service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchExecuteStatement service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchExecuteStatement">REST API Reference for BatchExecuteStatement Operation</seealso> Task<BatchExecuteStatementResponse> BatchExecuteStatementAsync(BatchExecuteStatementRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region BatchGetItem /// <summary> /// The <code>BatchGetItem</code> operation returns the attributes of one or more items /// from one or more tables. You identify requested items by primary key. /// /// /// <para> /// A single operation can retrieve up to 16 MB of data, which can contain as many as /// 100 items. <code>BatchGetItem</code> returns a partial result if the response size /// limit is exceeded, the table's provisioned throughput is exceeded, or an internal /// processing failure occurs. If a partial result is returned, the operation returns /// a value for <code>UnprocessedKeys</code>. You can use this value to retry the operation /// starting with the next item to get. /// </para> /// <important> /// <para> /// If you request more than 100 items, <code>BatchGetItem</code> returns a <code>ValidationException</code> /// with the message "Too many items requested for the BatchGetItem call." /// </para> /// </important> /// <para> /// For example, if you ask to retrieve 100 items, but each individual item is 300 KB /// in size, the system returns 52 items (so as not to exceed the 16 MB limit). It also /// returns an appropriate <code>UnprocessedKeys</code> value so you can get the next /// page of results. If desired, your application can include its own logic to assemble /// the pages of results into one dataset. /// </para> /// /// <para> /// If <i>none</i> of the items can be processed due to insufficient provisioned throughput /// on all of the tables in the request, then <code>BatchGetItem</code> returns a <code>ProvisionedThroughputExceededException</code>. /// If <i>at least one</i> of the items is successfully processed, then <code>BatchGetItem</code> /// completes successfully, while returning the keys of the unread items in <code>UnprocessedKeys</code>. /// </para> /// <important> /// <para> /// If DynamoDB returns any unprocessed items, you should retry the batch operation on /// those items. However, <i>we strongly recommend that you use an exponential backoff /// algorithm</i>. If you retry the batch operation immediately, the underlying read or /// write requests can still fail due to throttling on the individual tables. If you delay /// the batch operation using exponential backoff, the individual requests in the batch /// are much more likely to succeed. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#BatchOperations">Batch /// Operations and Error Handling</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </important> /// <para> /// By default, <code>BatchGetItem</code> performs eventually consistent reads on every /// table in the request. If you want strongly consistent reads instead, you can set <code>ConsistentRead</code> /// to <code>true</code> for any or all tables. /// </para> /// /// <para> /// In order to minimize response latency, <code>BatchGetItem</code> retrieves items in /// parallel. /// </para> /// /// <para> /// When designing your application, keep in mind that DynamoDB does not return items /// in any particular order. To help parse the response by item, include the primary key /// values for the items in your request in the <code>ProjectionExpression</code> parameter. /// </para> /// /// <para> /// If a requested item does not exist, it is not returned in the result. Requests for /// nonexistent items consume the minimum read capacity units according to the type of /// read. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html#CapacityUnitCalculations">Working /// with Tables</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="requestItems">A map of one or more table names and, for each table, a map that describes one or more items to retrieve from that table. Each table name can be used only once per <code>BatchGetItem</code> request. Each element in the map of items to retrieve consists of the following: <ul> <li> <code>ConsistentRead</code> - If <code>true</code>, a strongly consistent read is used; if <code>false</code> (the default), an eventually consistent read is used. </li> <li> <code>ExpressionAttributeNames</code> - One or more substitution tokens for attribute names in the <code>ProjectionExpression</code> parameter. The following are some use cases for using <code>ExpressionAttributeNames</code>: <ul> <li> To access an attribute whose name conflicts with a DynamoDB reserved word. </li> <li> To create a placeholder for repeating occurrences of an attribute name in an expression. </li> <li> To prevent special characters in an attribute name from being misinterpreted in an expression. </li> </ul> Use the <b>#</b> character in an expression to dereference an attribute name. For example, consider the following attribute name: <ul> <li> <code>Percentile</code> </li> </ul> The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html">Reserved Words</a> in the <i>Amazon DynamoDB Developer Guide</i>). To work around this, you could specify the following for <code>ExpressionAttributeNames</code>: <ul> <li> <code>{"#P":"Percentile"}</code> </li> </ul> You could then use this substitution in an expression, as in this example: <ul> <li> <code>#P = :val</code> </li> </ul> <note> Tokens that begin with the <b>:</b> character are <i>expression attribute values</i>, which are placeholders for the actual value at runtime. </note> For more information about expression attribute names, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Accessing Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. </li> <li> <code>Keys</code> - An array of primary key attribute values that define specific items in the table. For each primary key, you must provide <i>all</i> of the key attributes. For example, with a simple primary key, you only need to provide the partition key value. For a composite key, you must provide <i>both</i> the partition key value and the sort key value. </li> <li> <code>ProjectionExpression</code> - A string that identifies one or more attributes to retrieve from the table. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes are returned. If any of the requested attributes are not found, they do not appear in the result. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Accessing Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. </li> <li> <code>AttributesToGet</code> - This is a legacy parameter. Use <code>ProjectionExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html">AttributesToGet</a> in the <i>Amazon DynamoDB Developer Guide</i>. </li> </ul></param> /// <param name="returnConsumedCapacity">A property of BatchGetItemRequest used to execute the BatchGetItem service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchGetItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchGetItem">REST API Reference for BatchGetItem Operation</seealso> Task<BatchGetItemResponse> BatchGetItemAsync(Dictionary<string, KeysAndAttributes> requestItems, ReturnConsumedCapacity returnConsumedCapacity, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>BatchGetItem</code> operation returns the attributes of one or more items /// from one or more tables. You identify requested items by primary key. /// /// /// <para> /// A single operation can retrieve up to 16 MB of data, which can contain as many as /// 100 items. <code>BatchGetItem</code> returns a partial result if the response size /// limit is exceeded, the table's provisioned throughput is exceeded, or an internal /// processing failure occurs. If a partial result is returned, the operation returns /// a value for <code>UnprocessedKeys</code>. You can use this value to retry the operation /// starting with the next item to get. /// </para> /// <important> /// <para> /// If you request more than 100 items, <code>BatchGetItem</code> returns a <code>ValidationException</code> /// with the message "Too many items requested for the BatchGetItem call." /// </para> /// </important> /// <para> /// For example, if you ask to retrieve 100 items, but each individual item is 300 KB /// in size, the system returns 52 items (so as not to exceed the 16 MB limit). It also /// returns an appropriate <code>UnprocessedKeys</code> value so you can get the next /// page of results. If desired, your application can include its own logic to assemble /// the pages of results into one dataset. /// </para> /// /// <para> /// If <i>none</i> of the items can be processed due to insufficient provisioned throughput /// on all of the tables in the request, then <code>BatchGetItem</code> returns a <code>ProvisionedThroughputExceededException</code>. /// If <i>at least one</i> of the items is successfully processed, then <code>BatchGetItem</code> /// completes successfully, while returning the keys of the unread items in <code>UnprocessedKeys</code>. /// </para> /// <important> /// <para> /// If DynamoDB returns any unprocessed items, you should retry the batch operation on /// those items. However, <i>we strongly recommend that you use an exponential backoff /// algorithm</i>. If you retry the batch operation immediately, the underlying read or /// write requests can still fail due to throttling on the individual tables. If you delay /// the batch operation using exponential backoff, the individual requests in the batch /// are much more likely to succeed. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#BatchOperations">Batch /// Operations and Error Handling</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </important> /// <para> /// By default, <code>BatchGetItem</code> performs eventually consistent reads on every /// table in the request. If you want strongly consistent reads instead, you can set <code>ConsistentRead</code> /// to <code>true</code> for any or all tables. /// </para> /// /// <para> /// In order to minimize response latency, <code>BatchGetItem</code> retrieves items in /// parallel. /// </para> /// /// <para> /// When designing your application, keep in mind that DynamoDB does not return items /// in any particular order. To help parse the response by item, include the primary key /// values for the items in your request in the <code>ProjectionExpression</code> parameter. /// </para> /// /// <para> /// If a requested item does not exist, it is not returned in the result. Requests for /// nonexistent items consume the minimum read capacity units according to the type of /// read. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html#CapacityUnitCalculations">Working /// with Tables</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="requestItems">A map of one or more table names and, for each table, a map that describes one or more items to retrieve from that table. Each table name can be used only once per <code>BatchGetItem</code> request. Each element in the map of items to retrieve consists of the following: <ul> <li> <code>ConsistentRead</code> - If <code>true</code>, a strongly consistent read is used; if <code>false</code> (the default), an eventually consistent read is used. </li> <li> <code>ExpressionAttributeNames</code> - One or more substitution tokens for attribute names in the <code>ProjectionExpression</code> parameter. The following are some use cases for using <code>ExpressionAttributeNames</code>: <ul> <li> To access an attribute whose name conflicts with a DynamoDB reserved word. </li> <li> To create a placeholder for repeating occurrences of an attribute name in an expression. </li> <li> To prevent special characters in an attribute name from being misinterpreted in an expression. </li> </ul> Use the <b>#</b> character in an expression to dereference an attribute name. For example, consider the following attribute name: <ul> <li> <code>Percentile</code> </li> </ul> The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html">Reserved Words</a> in the <i>Amazon DynamoDB Developer Guide</i>). To work around this, you could specify the following for <code>ExpressionAttributeNames</code>: <ul> <li> <code>{"#P":"Percentile"}</code> </li> </ul> You could then use this substitution in an expression, as in this example: <ul> <li> <code>#P = :val</code> </li> </ul> <note> Tokens that begin with the <b>:</b> character are <i>expression attribute values</i>, which are placeholders for the actual value at runtime. </note> For more information about expression attribute names, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Accessing Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. </li> <li> <code>Keys</code> - An array of primary key attribute values that define specific items in the table. For each primary key, you must provide <i>all</i> of the key attributes. For example, with a simple primary key, you only need to provide the partition key value. For a composite key, you must provide <i>both</i> the partition key value and the sort key value. </li> <li> <code>ProjectionExpression</code> - A string that identifies one or more attributes to retrieve from the table. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes are returned. If any of the requested attributes are not found, they do not appear in the result. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Accessing Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. </li> <li> <code>AttributesToGet</code> - This is a legacy parameter. Use <code>ProjectionExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html">AttributesToGet</a> in the <i>Amazon DynamoDB Developer Guide</i>. </li> </ul></param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchGetItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchGetItem">REST API Reference for BatchGetItem Operation</seealso> Task<BatchGetItemResponse> BatchGetItemAsync(Dictionary<string, KeysAndAttributes> requestItems, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>BatchGetItem</code> operation returns the attributes of one or more items /// from one or more tables. You identify requested items by primary key. /// /// /// <para> /// A single operation can retrieve up to 16 MB of data, which can contain as many as /// 100 items. <code>BatchGetItem</code> returns a partial result if the response size /// limit is exceeded, the table's provisioned throughput is exceeded, or an internal /// processing failure occurs. If a partial result is returned, the operation returns /// a value for <code>UnprocessedKeys</code>. You can use this value to retry the operation /// starting with the next item to get. /// </para> /// <important> /// <para> /// If you request more than 100 items, <code>BatchGetItem</code> returns a <code>ValidationException</code> /// with the message "Too many items requested for the BatchGetItem call." /// </para> /// </important> /// <para> /// For example, if you ask to retrieve 100 items, but each individual item is 300 KB /// in size, the system returns 52 items (so as not to exceed the 16 MB limit). It also /// returns an appropriate <code>UnprocessedKeys</code> value so you can get the next /// page of results. If desired, your application can include its own logic to assemble /// the pages of results into one dataset. /// </para> /// /// <para> /// If <i>none</i> of the items can be processed due to insufficient provisioned throughput /// on all of the tables in the request, then <code>BatchGetItem</code> returns a <code>ProvisionedThroughputExceededException</code>. /// If <i>at least one</i> of the items is successfully processed, then <code>BatchGetItem</code> /// completes successfully, while returning the keys of the unread items in <code>UnprocessedKeys</code>. /// </para> /// <important> /// <para> /// If DynamoDB returns any unprocessed items, you should retry the batch operation on /// those items. However, <i>we strongly recommend that you use an exponential backoff /// algorithm</i>. If you retry the batch operation immediately, the underlying read or /// write requests can still fail due to throttling on the individual tables. If you delay /// the batch operation using exponential backoff, the individual requests in the batch /// are much more likely to succeed. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#BatchOperations">Batch /// Operations and Error Handling</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </important> /// <para> /// By default, <code>BatchGetItem</code> performs eventually consistent reads on every /// table in the request. If you want strongly consistent reads instead, you can set <code>ConsistentRead</code> /// to <code>true</code> for any or all tables. /// </para> /// /// <para> /// In order to minimize response latency, <code>BatchGetItem</code> retrieves items in /// parallel. /// </para> /// /// <para> /// When designing your application, keep in mind that DynamoDB does not return items /// in any particular order. To help parse the response by item, include the primary key /// values for the items in your request in the <code>ProjectionExpression</code> parameter. /// </para> /// /// <para> /// If a requested item does not exist, it is not returned in the result. Requests for /// nonexistent items consume the minimum read capacity units according to the type of /// read. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html#CapacityUnitCalculations">Working /// with Tables</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchGetItem service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchGetItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchGetItem">REST API Reference for BatchGetItem Operation</seealso> Task<BatchGetItemResponse> BatchGetItemAsync(BatchGetItemRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region BatchWriteItem /// <summary> /// The <code>BatchWriteItem</code> operation puts or deletes multiple items in one or /// more tables. A single call to <code>BatchWriteItem</code> can write up to 16 MB of /// data, which can comprise as many as 25 put or delete requests. Individual items to /// be written can be as large as 400 KB. /// /// <note> /// <para> /// <code>BatchWriteItem</code> cannot update items. To update items, use the <code>UpdateItem</code> /// action. /// </para> /// </note> /// <para> /// The individual <code>PutItem</code> and <code>DeleteItem</code> operations specified /// in <code>BatchWriteItem</code> are atomic; however <code>BatchWriteItem</code> as /// a whole is not. If any requested operations fail because the table's provisioned throughput /// is exceeded or an internal processing failure occurs, the failed operations are returned /// in the <code>UnprocessedItems</code> response parameter. You can investigate and optionally /// resend the requests. Typically, you would call <code>BatchWriteItem</code> in a loop. /// Each iteration would check for unprocessed items and submit a new <code>BatchWriteItem</code> /// request with those unprocessed items until all items have been processed. /// </para> /// /// <para> /// If <i>none</i> of the items can be processed due to insufficient provisioned throughput /// on all of the tables in the request, then <code>BatchWriteItem</code> returns a <code>ProvisionedThroughputExceededException</code>. /// </para> /// <important> /// <para> /// If DynamoDB returns any unprocessed items, you should retry the batch operation on /// those items. However, <i>we strongly recommend that you use an exponential backoff /// algorithm</i>. If you retry the batch operation immediately, the underlying read or /// write requests can still fail due to throttling on the individual tables. If you delay /// the batch operation using exponential backoff, the individual requests in the batch /// are much more likely to succeed. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#Programming.Errors.BatchOperations">Batch /// Operations and Error Handling</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </important> /// <para> /// With <code>BatchWriteItem</code>, you can efficiently write or delete large amounts /// of data, such as from Amazon EMR, or copy data from another database into DynamoDB. /// In order to improve performance with these large-scale operations, <code>BatchWriteItem</code> /// does not behave in the same way as individual <code>PutItem</code> and <code>DeleteItem</code> /// calls would. For example, you cannot specify conditions on individual put and delete /// requests, and <code>BatchWriteItem</code> does not return deleted items in the response. /// </para> /// /// <para> /// If you use a programming language that supports concurrency, you can use threads to /// write items in parallel. Your application must include the necessary logic to manage /// the threads. With languages that don't support threading, you must update or delete /// the specified items one at a time. In both situations, <code>BatchWriteItem</code> /// performs the specified put and delete operations in parallel, giving you the power /// of the thread pool approach without having to introduce complexity into your application. /// </para> /// /// <para> /// Parallel processing reduces latency, but each specified put and delete request consumes /// the same number of write capacity units whether it is processed in parallel or not. /// Delete operations on nonexistent items consume one write capacity unit. /// </para> /// /// <para> /// If one or more of the following is true, DynamoDB rejects the entire batch write operation: /// </para> /// <ul> <li> /// <para> /// One or more tables specified in the <code>BatchWriteItem</code> request does not exist. /// </para> /// </li> <li> /// <para> /// Primary key attributes specified on an item in the request do not match those in the /// corresponding table's primary key schema. /// </para> /// </li> <li> /// <para> /// You try to perform multiple operations on the same item in the same <code>BatchWriteItem</code> /// request. For example, you cannot put and delete the same item in the same <code>BatchWriteItem</code> /// request. /// </para> /// </li> <li> /// <para> /// Your request contains at least two items with identical hash and range keys (which /// essentially is two put operations). /// </para> /// </li> <li> /// <para> /// There are more than 25 requests in the batch. /// </para> /// </li> <li> /// <para> /// Any individual item in a batch exceeds 400 KB. /// </para> /// </li> <li> /// <para> /// The total request size exceeds 16 MB. /// </para> /// </li> </ul> /// </summary> /// <param name="requestItems">A map of one or more table names and, for each table, a list of operations to be performed (<code>DeleteRequest</code> or <code>PutRequest</code>). Each element in the map consists of the following: <ul> <li> <code>DeleteRequest</code> - Perform a <code>DeleteItem</code> operation on the specified item. The item to be deleted is identified by a <code>Key</code> subelement: <ul> <li> <code>Key</code> - A map of primary key attribute values that uniquely identify the item. Each entry in this map consists of an attribute name and an attribute value. For each primary key, you must provide <i>all</i> of the key attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for <i>both</i> the partition key and the sort key. </li> </ul> </li> <li> <code>PutRequest</code> - Perform a <code>PutItem</code> operation on the specified item. The item to be put is identified by an <code>Item</code> subelement: <ul> <li> <code>Item</code> - A map of attributes and their values. Each entry in this map consists of an attribute name and an attribute value. Attribute values must not be null; string and binary type attributes must have lengths greater than zero; and set type attributes must not be empty. Requests that contain empty values are rejected with a <code>ValidationException</code> exception. If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition. </li> </ul> </li> </ul></param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchWriteItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchWriteItem">REST API Reference for BatchWriteItem Operation</seealso> Task<BatchWriteItemResponse> BatchWriteItemAsync(Dictionary<string, List<WriteRequest>> requestItems, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>BatchWriteItem</code> operation puts or deletes multiple items in one or /// more tables. A single call to <code>BatchWriteItem</code> can write up to 16 MB of /// data, which can comprise as many as 25 put or delete requests. Individual items to /// be written can be as large as 400 KB. /// /// <note> /// <para> /// <code>BatchWriteItem</code> cannot update items. To update items, use the <code>UpdateItem</code> /// action. /// </para> /// </note> /// <para> /// The individual <code>PutItem</code> and <code>DeleteItem</code> operations specified /// in <code>BatchWriteItem</code> are atomic; however <code>BatchWriteItem</code> as /// a whole is not. If any requested operations fail because the table's provisioned throughput /// is exceeded or an internal processing failure occurs, the failed operations are returned /// in the <code>UnprocessedItems</code> response parameter. You can investigate and optionally /// resend the requests. Typically, you would call <code>BatchWriteItem</code> in a loop. /// Each iteration would check for unprocessed items and submit a new <code>BatchWriteItem</code> /// request with those unprocessed items until all items have been processed. /// </para> /// /// <para> /// If <i>none</i> of the items can be processed due to insufficient provisioned throughput /// on all of the tables in the request, then <code>BatchWriteItem</code> returns a <code>ProvisionedThroughputExceededException</code>. /// </para> /// <important> /// <para> /// If DynamoDB returns any unprocessed items, you should retry the batch operation on /// those items. However, <i>we strongly recommend that you use an exponential backoff /// algorithm</i>. If you retry the batch operation immediately, the underlying read or /// write requests can still fail due to throttling on the individual tables. If you delay /// the batch operation using exponential backoff, the individual requests in the batch /// are much more likely to succeed. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#Programming.Errors.BatchOperations">Batch /// Operations and Error Handling</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </important> /// <para> /// With <code>BatchWriteItem</code>, you can efficiently write or delete large amounts /// of data, such as from Amazon EMR, or copy data from another database into DynamoDB. /// In order to improve performance with these large-scale operations, <code>BatchWriteItem</code> /// does not behave in the same way as individual <code>PutItem</code> and <code>DeleteItem</code> /// calls would. For example, you cannot specify conditions on individual put and delete /// requests, and <code>BatchWriteItem</code> does not return deleted items in the response. /// </para> /// /// <para> /// If you use a programming language that supports concurrency, you can use threads to /// write items in parallel. Your application must include the necessary logic to manage /// the threads. With languages that don't support threading, you must update or delete /// the specified items one at a time. In both situations, <code>BatchWriteItem</code> /// performs the specified put and delete operations in parallel, giving you the power /// of the thread pool approach without having to introduce complexity into your application. /// </para> /// /// <para> /// Parallel processing reduces latency, but each specified put and delete request consumes /// the same number of write capacity units whether it is processed in parallel or not. /// Delete operations on nonexistent items consume one write capacity unit. /// </para> /// /// <para> /// If one or more of the following is true, DynamoDB rejects the entire batch write operation: /// </para> /// <ul> <li> /// <para> /// One or more tables specified in the <code>BatchWriteItem</code> request does not exist. /// </para> /// </li> <li> /// <para> /// Primary key attributes specified on an item in the request do not match those in the /// corresponding table's primary key schema. /// </para> /// </li> <li> /// <para> /// You try to perform multiple operations on the same item in the same <code>BatchWriteItem</code> /// request. For example, you cannot put and delete the same item in the same <code>BatchWriteItem</code> /// request. /// </para> /// </li> <li> /// <para> /// Your request contains at least two items with identical hash and range keys (which /// essentially is two put operations). /// </para> /// </li> <li> /// <para> /// There are more than 25 requests in the batch. /// </para> /// </li> <li> /// <para> /// Any individual item in a batch exceeds 400 KB. /// </para> /// </li> <li> /// <para> /// The total request size exceeds 16 MB. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchWriteItem service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the BatchWriteItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchWriteItem">REST API Reference for BatchWriteItem Operation</seealso> Task<BatchWriteItemResponse> BatchWriteItemAsync(BatchWriteItemRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateBackup /// <summary> /// Creates a backup for an existing table. /// /// /// <para> /// Each time you create an on-demand backup, the entire table data is backed up. There /// is no limit to the number of on-demand backups that can be taken. /// </para> /// /// <para> /// When you create an on-demand backup, a time marker of the request is cataloged, and /// the backup is created asynchronously, by applying all changes until the time of the /// request to the last full table snapshot. Backup requests are processed instantaneously /// and become available for restore within minutes. /// </para> /// /// <para> /// You can call <code>CreateBackup</code> at a maximum rate of 50 times per second. /// </para> /// /// <para> /// All backups in DynamoDB work without consuming any provisioned throughput on the table. /// </para> /// /// <para> /// If you submit a backup request on 2018-12-14 at 14:25:00, the backup is guaranteed /// to contain all data committed to the table up to 14:24:00, and data committed after /// 14:26:00 will not be. The backup might contain data modifications made between 14:24:00 /// and 14:26:00. On-demand backup does not support causal consistency. /// </para> /// /// <para> /// Along with data, the following are also included on the backups: /// </para> /// <ul> <li> /// <para> /// Global secondary indexes (GSIs) /// </para> /// </li> <li> /// <para> /// Local secondary indexes (LSIs) /// </para> /// </li> <li> /// <para> /// Streams /// </para> /// </li> <li> /// <para> /// Provisioned read and write capacity /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateBackup service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateBackup service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.BackupInUseException"> /// There is another ongoing conflicting backup control plane operation on the table. /// The backup is either being created, deleted or restored to a table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ContinuousBackupsUnavailableException"> /// Backups have not yet been enabled for this table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableInUseException"> /// A target table with the specified name is either being created or deleted. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableNotFoundException"> /// A source table with the name <code>TableName</code> does not currently exist within /// the subscriber's account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/CreateBackup">REST API Reference for CreateBackup Operation</seealso> Task<CreateBackupResponse> CreateBackupAsync(CreateBackupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateGlobalTable /// <summary> /// Creates a global table from an existing table. A global table creates a replication /// relationship between two or more DynamoDB tables with the same table name in the provided /// Regions. /// /// <note> /// <para> /// This operation only applies to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html">Version /// 2017.11.29</a> of global tables. /// </para> /// </note> /// <para> /// If you want to add a new replica table to a global table, each of the following conditions /// must be true: /// </para> /// <ul> <li> /// <para> /// The table must have the same primary key as all of the other replicas. /// </para> /// </li> <li> /// <para> /// The table must have the same name as all of the other replicas. /// </para> /// </li> <li> /// <para> /// The table must have DynamoDB Streams enabled, with the stream containing both the /// new and the old images of the item. /// </para> /// </li> <li> /// <para> /// None of the replica tables in the global table can contain any data. /// </para> /// </li> </ul> /// <para> /// If global secondary indexes are specified, then the following conditions must also /// be met: /// </para> /// <ul> <li> /// <para> /// The global secondary indexes must have the same name. /// </para> /// </li> <li> /// <para> /// The global secondary indexes must have the same hash key and sort key (if present). /// /// </para> /// </li> </ul> /// <para> /// If local secondary indexes are specified, then the following conditions must also /// be met: /// </para> /// <ul> <li> /// <para> /// The local secondary indexes must have the same name. /// </para> /// </li> <li> /// <para> /// The local secondary indexes must have the same hash key and sort key (if present). /// /// </para> /// </li> </ul> <important> /// <para> /// Write capacity settings should be set consistently across your replica tables and /// secondary indexes. DynamoDB strongly recommends enabling auto scaling to manage the /// write capacity settings for all of your global tables replicas and indexes. /// </para> /// /// <para> /// If you prefer to manage write capacity settings manually, you should provision equal /// replicated write capacity units to your replica tables. You should also provision /// equal replicated write capacity units to matching secondary indexes across your global /// table. /// </para> /// </important> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateGlobalTable service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateGlobalTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.GlobalTableAlreadyExistsException"> /// The specified global table already exists. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableNotFoundException"> /// A source table with the name <code>TableName</code> does not currently exist within /// the subscriber's account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/CreateGlobalTable">REST API Reference for CreateGlobalTable Operation</seealso> Task<CreateGlobalTableResponse> CreateGlobalTableAsync(CreateGlobalTableRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateTable /// <summary> /// The <code>CreateTable</code> operation adds a new table to your account. In an Amazon /// Web Services account, table names must be unique within each Region. That is, you /// can have two tables with same name if you create the tables in different Regions. /// /// /// <para> /// <code>CreateTable</code> is an asynchronous operation. Upon receiving a <code>CreateTable</code> /// request, DynamoDB immediately returns a response with a <code>TableStatus</code> of /// <code>CREATING</code>. After the table is created, DynamoDB sets the <code>TableStatus</code> /// to <code>ACTIVE</code>. You can perform read and write operations only on an <code>ACTIVE</code> /// table. /// </para> /// /// <para> /// You can optionally define secondary indexes on the new table, as part of the <code>CreateTable</code> /// operation. If you want to create multiple tables with secondary indexes on them, you /// must create the tables sequentially. Only one table with secondary indexes can be /// in the <code>CREATING</code> state at any given time. /// </para> /// /// <para> /// You can use the <code>DescribeTable</code> action to check the table status. /// </para> /// </summary> /// <param name="tableName">The name of the table to create.</param> /// <param name="keySchema">Specifies the attributes that make up the primary key for a table or an index. The attributes in <code>KeySchema</code> must also be defined in the <code>AttributeDefinitions</code> array. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html">Data Model</a> in the <i>Amazon DynamoDB Developer Guide</i>. Each <code>KeySchemaElement</code> in the array is composed of: <ul> <li> <code>AttributeName</code> - The name of this key attribute. </li> <li> <code>KeyType</code> - The role that the key attribute will assume: <ul> <li> <code>HASH</code> - partition key </li> <li> <code>RANGE</code> - sort key </li> </ul> </li> </ul> <note> The partition key of an item is also known as its <i>hash attribute</i>. The term "hash attribute" derives from the DynamoDB usage of an internal hash function to evenly distribute data items across partitions, based on their partition key values. The sort key of an item is also known as its <i>range attribute</i>. The term "range attribute" derives from the way DynamoDB stores items with the same partition key physically close together, in sorted order by the sort key value. </note> For a simple primary key (partition key), you must provide exactly one element with a <code>KeyType</code> of <code>HASH</code>. For a composite primary key (partition key and sort key), you must provide exactly two elements, in this order: The first element must have a <code>KeyType</code> of <code>HASH</code>, and the second element must have a <code>KeyType</code> of <code>RANGE</code>. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html#WorkingWithTables.primary.key">Working with Tables</a> in the <i>Amazon DynamoDB Developer Guide</i>.</param> /// <param name="attributeDefinitions">An array of attributes that describe the key schema for the table and indexes.</param> /// <param name="provisionedThroughput">Represents the provisioned throughput settings for a specified table or index. The settings can be modified using the <code>UpdateTable</code> operation. If you set BillingMode as <code>PROVISIONED</code>, you must specify this property. If you set BillingMode as <code>PAY_PER_REQUEST</code>, you cannot specify this property. For current minimum and maximum provisioned throughput values, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html">Service, Account, and Table Quotas</a> in the <i>Amazon DynamoDB Developer Guide</i>.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/CreateTable">REST API Reference for CreateTable Operation</seealso> Task<CreateTableResponse> CreateTableAsync(string tableName, List<KeySchemaElement> keySchema, List<AttributeDefinition> attributeDefinitions, ProvisionedThroughput provisionedThroughput, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>CreateTable</code> operation adds a new table to your account. In an Amazon /// Web Services account, table names must be unique within each Region. That is, you /// can have two tables with same name if you create the tables in different Regions. /// /// /// <para> /// <code>CreateTable</code> is an asynchronous operation. Upon receiving a <code>CreateTable</code> /// request, DynamoDB immediately returns a response with a <code>TableStatus</code> of /// <code>CREATING</code>. After the table is created, DynamoDB sets the <code>TableStatus</code> /// to <code>ACTIVE</code>. You can perform read and write operations only on an <code>ACTIVE</code> /// table. /// </para> /// /// <para> /// You can optionally define secondary indexes on the new table, as part of the <code>CreateTable</code> /// operation. If you want to create multiple tables with secondary indexes on them, you /// must create the tables sequentially. Only one table with secondary indexes can be /// in the <code>CREATING</code> state at any given time. /// </para> /// /// <para> /// You can use the <code>DescribeTable</code> action to check the table status. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateTable service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the CreateTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/CreateTable">REST API Reference for CreateTable Operation</seealso> Task<CreateTableResponse> CreateTableAsync(CreateTableRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteBackup /// <summary> /// Deletes an existing backup of a table. /// /// /// <para> /// You can call <code>DeleteBackup</code> at a maximum rate of 10 times per second. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteBackup service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteBackup service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.BackupInUseException"> /// There is another ongoing conflicting backup control plane operation on the table. /// The backup is either being created, deleted or restored to a table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.BackupNotFoundException"> /// Backup not found for the given BackupARN. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteBackup">REST API Reference for DeleteBackup Operation</seealso> Task<DeleteBackupResponse> DeleteBackupAsync(DeleteBackupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteItem /// <summary> /// Deletes a single item in a table by primary key. You can perform a conditional delete /// operation that deletes the item if it exists, or if it has an expected attribute value. /// /// /// <para> /// In addition to deleting an item, you can also return the item's attribute values in /// the same operation, using the <code>ReturnValues</code> parameter. /// </para> /// /// <para> /// Unless you specify conditions, the <code>DeleteItem</code> is an idempotent operation; /// running it multiple times on the same item or attribute does <i>not</i> result in /// an error response. /// </para> /// /// <para> /// Conditional deletes are useful for deleting items only if specific conditions are /// met. If those conditions are met, DynamoDB performs the delete. Otherwise, the item /// is not deleted. /// </para> /// </summary> /// <param name="tableName">The name of the table from which to delete the item.</param> /// <param name="key">A map of attribute names to <code>AttributeValue</code> objects, representing the primary key of the item to delete. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteItem">REST API Reference for DeleteItem Operation</seealso> Task<DeleteItemResponse> DeleteItemAsync(string tableName, Dictionary<string, AttributeValue> key, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a single item in a table by primary key. You can perform a conditional delete /// operation that deletes the item if it exists, or if it has an expected attribute value. /// /// /// <para> /// In addition to deleting an item, you can also return the item's attribute values in /// the same operation, using the <code>ReturnValues</code> parameter. /// </para> /// /// <para> /// Unless you specify conditions, the <code>DeleteItem</code> is an idempotent operation; /// running it multiple times on the same item or attribute does <i>not</i> result in /// an error response. /// </para> /// /// <para> /// Conditional deletes are useful for deleting items only if specific conditions are /// met. If those conditions are met, DynamoDB performs the delete. Otherwise, the item /// is not deleted. /// </para> /// </summary> /// <param name="tableName">The name of the table from which to delete the item.</param> /// <param name="key">A map of attribute names to <code>AttributeValue</code> objects, representing the primary key of the item to delete. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.</param> /// <param name="returnValues">Use <code>ReturnValues</code> if you want to get the item attributes as they appeared before they were deleted. For <code>DeleteItem</code>, the valid values are: <ul> <li> <code>NONE</code> - If <code>ReturnValues</code> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <code>ReturnValues</code>.) </li> <li> <code>ALL_OLD</code> - The content of the old item is returned. </li> </ul> <note> The <code>ReturnValues</code> parameter is used by several DynamoDB operations; however, <code>DeleteItem</code> does not recognize any values other than <code>NONE</code> or <code>ALL_OLD</code>. </note></param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteItem">REST API Reference for DeleteItem Operation</seealso> Task<DeleteItemResponse> DeleteItemAsync(string tableName, Dictionary<string, AttributeValue> key, ReturnValue returnValues, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a single item in a table by primary key. You can perform a conditional delete /// operation that deletes the item if it exists, or if it has an expected attribute value. /// /// /// <para> /// In addition to deleting an item, you can also return the item's attribute values in /// the same operation, using the <code>ReturnValues</code> parameter. /// </para> /// /// <para> /// Unless you specify conditions, the <code>DeleteItem</code> is an idempotent operation; /// running it multiple times on the same item or attribute does <i>not</i> result in /// an error response. /// </para> /// /// <para> /// Conditional deletes are useful for deleting items only if specific conditions are /// met. If those conditions are met, DynamoDB performs the delete. Otherwise, the item /// is not deleted. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteItem service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteItem">REST API Reference for DeleteItem Operation</seealso> Task<DeleteItemResponse> DeleteItemAsync(DeleteItemRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteTable /// <summary> /// The <code>DeleteTable</code> operation deletes a table and all of its items. After /// a <code>DeleteTable</code> request, the specified table is in the <code>DELETING</code> /// state until DynamoDB completes the deletion. If the table is in the <code>ACTIVE</code> /// state, you can delete it. If a table is in <code>CREATING</code> or <code>UPDATING</code> /// states, then DynamoDB returns a <code>ResourceInUseException</code>. If the specified /// table does not exist, DynamoDB returns a <code>ResourceNotFoundException</code>. If /// table is already in the <code>DELETING</code> state, no error is returned. /// /// <note> /// <para> /// DynamoDB might continue to accept data read and write operations, such as <code>GetItem</code> /// and <code>PutItem</code>, on a table in the <code>DELETING</code> state until the /// table deletion is complete. /// </para> /// </note> /// <para> /// When you delete a table, any indexes on that table are also deleted. /// </para> /// /// <para> /// If you have DynamoDB Streams enabled on the table, then the corresponding stream on /// that table goes into the <code>DISABLED</code> state, and the stream is automatically /// deleted after 24 hours. /// </para> /// /// <para> /// Use the <code>DescribeTable</code> action to check the status of the table. /// </para> /// </summary> /// <param name="tableName">The name of the table to delete.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteTable">REST API Reference for DeleteTable Operation</seealso> Task<DeleteTableResponse> DeleteTableAsync(string tableName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>DeleteTable</code> operation deletes a table and all of its items. After /// a <code>DeleteTable</code> request, the specified table is in the <code>DELETING</code> /// state until DynamoDB completes the deletion. If the table is in the <code>ACTIVE</code> /// state, you can delete it. If a table is in <code>CREATING</code> or <code>UPDATING</code> /// states, then DynamoDB returns a <code>ResourceInUseException</code>. If the specified /// table does not exist, DynamoDB returns a <code>ResourceNotFoundException</code>. If /// table is already in the <code>DELETING</code> state, no error is returned. /// /// <note> /// <para> /// DynamoDB might continue to accept data read and write operations, such as <code>GetItem</code> /// and <code>PutItem</code>, on a table in the <code>DELETING</code> state until the /// table deletion is complete. /// </para> /// </note> /// <para> /// When you delete a table, any indexes on that table are also deleted. /// </para> /// /// <para> /// If you have DynamoDB Streams enabled on the table, then the corresponding stream on /// that table goes into the <code>DISABLED</code> state, and the stream is automatically /// deleted after 24 hours. /// </para> /// /// <para> /// Use the <code>DescribeTable</code> action to check the status of the table. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteTable service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteTable">REST API Reference for DeleteTable Operation</seealso> Task<DeleteTableResponse> DeleteTableAsync(DeleteTableRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeBackup /// <summary> /// Describes an existing backup of a table. /// /// /// <para> /// You can call <code>DescribeBackup</code> at a maximum rate of 10 times per second. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeBackup service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeBackup service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.BackupNotFoundException"> /// Backup not found for the given BackupARN. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeBackup">REST API Reference for DescribeBackup Operation</seealso> Task<DescribeBackupResponse> DescribeBackupAsync(DescribeBackupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeContinuousBackups /// <summary> /// Checks the status of continuous backups and point in time recovery on the specified /// table. Continuous backups are <code>ENABLED</code> on all tables at table creation. /// If point in time recovery is enabled, <code>PointInTimeRecoveryStatus</code> will /// be set to ENABLED. /// /// /// <para> /// After continuous backups and point in time recovery are enabled, you can restore /// to any point in time within <code>EarliestRestorableDateTime</code> and <code>LatestRestorableDateTime</code>. /// /// </para> /// /// <para> /// <code>LatestRestorableDateTime</code> is typically 5 minutes before the current time. /// You can restore your table to any point in time during the last 35 days. /// </para> /// /// <para> /// You can call <code>DescribeContinuousBackups</code> at a maximum rate of 10 times /// per second. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeContinuousBackups service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeContinuousBackups service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableNotFoundException"> /// A source table with the name <code>TableName</code> does not currently exist within /// the subscriber's account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeContinuousBackups">REST API Reference for DescribeContinuousBackups Operation</seealso> Task<DescribeContinuousBackupsResponse> DescribeContinuousBackupsAsync(DescribeContinuousBackupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeContributorInsights /// <summary> /// Returns information about contributor insights, for a given table or global secondary /// index. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeContributorInsights service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeContributorInsights service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeContributorInsights">REST API Reference for DescribeContributorInsights Operation</seealso> Task<DescribeContributorInsightsResponse> DescribeContributorInsightsAsync(DescribeContributorInsightsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeEndpoints /// <summary> /// Returns the regional endpoint information. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEndpoints service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeEndpoints service method, as returned by DynamoDB.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeEndpoints">REST API Reference for DescribeEndpoints Operation</seealso> Task<DescribeEndpointsResponse> DescribeEndpointsAsync(DescribeEndpointsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeExport /// <summary> /// Describes an existing table export. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeExport service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeExport service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ExportNotFoundException"> /// The specified export was not found. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeExport">REST API Reference for DescribeExport Operation</seealso> Task<DescribeExportResponse> DescribeExportAsync(DescribeExportRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeGlobalTable /// <summary> /// Returns information about the specified global table. /// /// <note> /// <para> /// This operation only applies to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html">Version /// 2017.11.29</a> of global tables. If you are using global tables <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html">Version /// 2019.11.21</a> you can use <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeTable.html">DescribeTable</a> /// instead. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeGlobalTable service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeGlobalTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.GlobalTableNotFoundException"> /// The specified global table does not exist. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeGlobalTable">REST API Reference for DescribeGlobalTable Operation</seealso> Task<DescribeGlobalTableResponse> DescribeGlobalTableAsync(DescribeGlobalTableRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeGlobalTableSettings /// <summary> /// Describes Region-specific settings for a global table. /// /// <note> /// <para> /// This operation only applies to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html">Version /// 2017.11.29</a> of global tables. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeGlobalTableSettings service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeGlobalTableSettings service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.GlobalTableNotFoundException"> /// The specified global table does not exist. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeGlobalTableSettings">REST API Reference for DescribeGlobalTableSettings Operation</seealso> Task<DescribeGlobalTableSettingsResponse> DescribeGlobalTableSettingsAsync(DescribeGlobalTableSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeKinesisStreamingDestination /// <summary> /// Returns information about the status of Kinesis streaming. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeKinesisStreamingDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeKinesisStreamingDestination service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeKinesisStreamingDestination">REST API Reference for DescribeKinesisStreamingDestination Operation</seealso> Task<DescribeKinesisStreamingDestinationResponse> DescribeKinesisStreamingDestinationAsync(DescribeKinesisStreamingDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeLimits /// <summary> /// Returns the current provisioned-capacity quotas for your Amazon Web Services account /// in a Region, both for the Region as a whole and for any one DynamoDB table that you /// create there. /// /// /// <para> /// When you establish an Amazon Web Services account, the account has initial quotas /// on the maximum read capacity units and write capacity units that you can provision /// across all of your DynamoDB tables in a given Region. Also, there are per-table quotas /// that apply when you create a table there. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html">Service, /// Account, and Table Quotas</a> page in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// Although you can increase these quotas by filing a case at <a href="https://console.aws.amazon.com/support/home#/">Amazon /// Web Services Support Center</a>, obtaining the increase is not instantaneous. The /// <code>DescribeLimits</code> action lets you write code to compare the capacity you /// are currently using to those quotas imposed by your account so that you have enough /// time to apply for an increase before you hit a quota. /// </para> /// /// <para> /// For example, you could use one of the Amazon Web Services SDKs to do the following: /// </para> /// <ol> <li> /// <para> /// Call <code>DescribeLimits</code> for a particular Region to obtain your current account /// quotas on provisioned capacity there. /// </para> /// </li> <li> /// <para> /// Create a variable to hold the aggregate read capacity units provisioned for all your /// tables in that Region, and one to hold the aggregate write capacity units. Zero them /// both. /// </para> /// </li> <li> /// <para> /// Call <code>ListTables</code> to obtain a list of all your DynamoDB tables. /// </para> /// </li> <li> /// <para> /// For each table name listed by <code>ListTables</code>, do the following: /// </para> /// <ul> <li> /// <para> /// Call <code>DescribeTable</code> with the table name. /// </para> /// </li> <li> /// <para> /// Use the data returned by <code>DescribeTable</code> to add the read capacity units /// and write capacity units provisioned for the table itself to your variables. /// </para> /// </li> <li> /// <para> /// If the table has one or more global secondary indexes (GSIs), loop over these GSIs /// and add their provisioned capacity values to your variables as well. /// </para> /// </li> </ul> </li> <li> /// <para> /// Report the account quotas for that Region returned by <code>DescribeLimits</code>, /// along with the total current provisioned capacity levels you have calculated. /// </para> /// </li> </ol> /// <para> /// This will let you see whether you are getting close to your account-level quotas. /// </para> /// /// <para> /// The per-table quotas apply only when you are creating a new table. They restrict the /// sum of the provisioned capacity of the new table itself and all its global secondary /// indexes. /// </para> /// /// <para> /// For existing tables and their GSIs, DynamoDB doesn't let you increase provisioned /// capacity extremely rapidly, but the only quota that applies is that the aggregate /// provisioned capacity over all your tables and GSIs cannot exceed either of the per-account /// quotas. /// </para> /// <note> /// <para> /// <code>DescribeLimits</code> should only be called periodically. You can expect throttling /// errors if you call it more than once in a minute. /// </para> /// </note> /// <para> /// The <code>DescribeLimits</code> Request element has no content. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeLimits service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeLimits service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeLimits">REST API Reference for DescribeLimits Operation</seealso> Task<DescribeLimitsResponse> DescribeLimitsAsync(DescribeLimitsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeTable /// <summary> /// Returns information about the table, including the current status of the table, when /// it was created, the primary key schema, and any indexes on the table. /// /// <note> /// <para> /// If you issue a <code>DescribeTable</code> request immediately after a <code>CreateTable</code> /// request, DynamoDB might return a <code>ResourceNotFoundException</code>. This is because /// <code>DescribeTable</code> uses an eventually consistent query, and the metadata for /// your table might not be available at that moment. Wait for a few seconds, and then /// try the <code>DescribeTable</code> request again. /// </para> /// </note> /// </summary> /// <param name="tableName">The name of the table to describe.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTable">REST API Reference for DescribeTable Operation</seealso> Task<DescribeTableResponse> DescribeTableAsync(string tableName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns information about the table, including the current status of the table, when /// it was created, the primary key schema, and any indexes on the table. /// /// <note> /// <para> /// If you issue a <code>DescribeTable</code> request immediately after a <code>CreateTable</code> /// request, DynamoDB might return a <code>ResourceNotFoundException</code>. This is because /// <code>DescribeTable</code> uses an eventually consistent query, and the metadata for /// your table might not be available at that moment. Wait for a few seconds, and then /// try the <code>DescribeTable</code> request again. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTable service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTable">REST API Reference for DescribeTable Operation</seealso> Task<DescribeTableResponse> DescribeTableAsync(DescribeTableRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeTableReplicaAutoScaling /// <summary> /// Describes auto scaling settings across replicas of the global table at once. /// /// <note> /// <para> /// This operation only applies to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html">Version /// 2019.11.21</a> of global tables. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTableReplicaAutoScaling service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeTableReplicaAutoScaling service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTableReplicaAutoScaling">REST API Reference for DescribeTableReplicaAutoScaling Operation</seealso> Task<DescribeTableReplicaAutoScalingResponse> DescribeTableReplicaAutoScalingAsync(DescribeTableReplicaAutoScalingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeTimeToLive /// <summary> /// Gives a description of the Time to Live (TTL) status on the specified table. /// </summary> /// <param name="tableName">The name of the table to be described.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeTimeToLive service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTimeToLive">REST API Reference for DescribeTimeToLive Operation</seealso> Task<DescribeTimeToLiveResponse> DescribeTimeToLiveAsync(string tableName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gives a description of the Time to Live (TTL) status on the specified table. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeTimeToLive service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeTimeToLive service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTimeToLive">REST API Reference for DescribeTimeToLive Operation</seealso> Task<DescribeTimeToLiveResponse> DescribeTimeToLiveAsync(DescribeTimeToLiveRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DisableKinesisStreamingDestination /// <summary> /// Stops replication from the DynamoDB table to the Kinesis data stream. This is done /// without deleting either of the resources. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisableKinesisStreamingDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DisableKinesisStreamingDestination service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DisableKinesisStreamingDestination">REST API Reference for DisableKinesisStreamingDestination Operation</seealso> Task<DisableKinesisStreamingDestinationResponse> DisableKinesisStreamingDestinationAsync(DisableKinesisStreamingDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region EnableKinesisStreamingDestination /// <summary> /// Starts table data replication to the specified Kinesis data stream at a timestamp /// chosen during the enable workflow. If this operation doesn't return results immediately, /// use DescribeKinesisStreamingDestination to check if streaming to the Kinesis data /// stream is ACTIVE. /// </summary> /// <param name="request">Container for the necessary parameters to execute the EnableKinesisStreamingDestination service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the EnableKinesisStreamingDestination service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/EnableKinesisStreamingDestination">REST API Reference for EnableKinesisStreamingDestination Operation</seealso> Task<EnableKinesisStreamingDestinationResponse> EnableKinesisStreamingDestinationAsync(EnableKinesisStreamingDestinationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ExecuteStatement /// <summary> /// This operation allows you to perform reads and singleton writes on data stored in /// DynamoDB, using PartiQL. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ExecuteStatement service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ExecuteStatement service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.DuplicateItemException"> /// There was an attempt to insert an item with the same primary key as an item that /// already exists in the DynamoDB table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ExecuteStatement">REST API Reference for ExecuteStatement Operation</seealso> Task<ExecuteStatementResponse> ExecuteStatementAsync(ExecuteStatementRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ExecuteTransaction /// <summary> /// This operation allows you to perform transactional reads or writes on data stored /// in DynamoDB, using PartiQL. /// /// <note> /// <para> /// The entire transaction must consist of either read statements or write statements, /// you cannot mix both in one transaction. The EXISTS function is an exception and can /// be used to check the condition of specific attributes of the item in a similar manner /// to <code>ConditionCheck</code> in the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis.html#transaction-apis-txwriteitems">TransactWriteItems</a> /// API. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ExecuteTransaction service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ExecuteTransaction service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.IdempotentParameterMismatchException"> /// DynamoDB rejected the request because you retried a request with a different payload /// but with an idempotent token that was already used. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionCanceledException"> /// The entire transaction request was canceled. /// /// /// <para> /// DynamoDB cancels a <code>TransactWriteItems</code> request under the following circumstances: /// </para> /// <ul> <li> /// <para> /// A condition in one of the condition expressions is not met. /// </para> /// </li> <li> /// <para> /// A table in the <code>TransactWriteItems</code> request is in a different account or /// region. /// </para> /// </li> <li> /// <para> /// More than one action in the <code>TransactWriteItems</code> operation targets the /// same item. /// </para> /// </li> <li> /// <para> /// There is insufficient provisioned capacity for the transaction to be completed. /// </para> /// </li> <li> /// <para> /// An item size becomes too large (larger than 400 KB), or a local secondary index (LSI) /// becomes too large, or a similar validation error occurs because of changes made by /// the transaction. /// </para> /// </li> <li> /// <para> /// There is a user error, such as an invalid data format. /// </para> /// </li> </ul> /// <para> /// DynamoDB cancels a <code>TransactGetItems</code> request under the following circumstances: /// </para> /// <ul> <li> /// <para> /// There is an ongoing <code>TransactGetItems</code> operation that conflicts with a /// concurrent <code>PutItem</code>, <code>UpdateItem</code>, <code>DeleteItem</code> /// or <code>TransactWriteItems</code> request. In this case the <code>TransactGetItems</code> /// operation fails with a <code>TransactionCanceledException</code>. /// </para> /// </li> <li> /// <para> /// A table in the <code>TransactGetItems</code> request is in a different account or /// region. /// </para> /// </li> <li> /// <para> /// There is insufficient provisioned capacity for the transaction to be completed. /// </para> /// </li> <li> /// <para> /// There is a user error, such as an invalid data format. /// </para> /// </li> </ul> <note> /// <para> /// If using Java, DynamoDB lists the cancellation reasons on the <code>CancellationReasons</code> /// property. This property is not set for other languages. Transaction cancellation reasons /// are ordered in the order of requested items, if an item has no error it will have /// <code>NONE</code> code and <code>Null</code> message. /// </para> /// </note> /// <para> /// Cancellation reason codes and possible error messages: /// </para> /// <ul> <li> /// <para> /// No Errors: /// </para> /// <ul> <li> /// <para> /// Code: <code>NONE</code> /// </para> /// </li> <li> /// <para> /// Message: <code>null</code> /// </para> /// </li> </ul> </li> <li> /// <para> /// Conditional Check Failed: /// </para> /// <ul> <li> /// <para> /// Code: <code>ConditionalCheckFailed</code> /// </para> /// </li> <li> /// <para> /// Message: The conditional request failed. /// </para> /// </li> </ul> </li> <li> /// <para> /// Item Collection Size Limit Exceeded: /// </para> /// <ul> <li> /// <para> /// Code: <code>ItemCollectionSizeLimitExceeded</code> /// </para> /// </li> <li> /// <para> /// Message: Collection size exceeded. /// </para> /// </li> </ul> </li> <li> /// <para> /// Transaction Conflict: /// </para> /// <ul> <li> /// <para> /// Code: <code>TransactionConflict</code> /// </para> /// </li> <li> /// <para> /// Message: Transaction is ongoing for the item. /// </para> /// </li> </ul> </li> <li> /// <para> /// Provisioned Throughput Exceeded: /// </para> /// <ul> <li> /// <para> /// Code: <code>ProvisionedThroughputExceeded</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// The level of configured provisioned throughput for the table was exceeded. Consider /// increasing your provisioning level with the UpdateTable API. /// </para> /// <note> /// <para> /// This Message is received when provisioned throughput is exceeded is on a provisioned /// DynamoDB table. /// </para> /// </note> </li> <li> /// <para> /// The level of configured provisioned throughput for one or more global secondary indexes /// of the table was exceeded. Consider increasing your provisioning level for the under-provisioned /// global secondary indexes with the UpdateTable API. /// </para> /// <note> /// <para> /// This message is returned when provisioned throughput is exceeded is on a provisioned /// GSI. /// </para> /// </note> </li> </ul> </li> </ul> </li> <li> /// <para> /// Throttling Error: /// </para> /// <ul> <li> /// <para> /// Code: <code>ThrottlingError</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// Throughput exceeds the current capacity of your table or index. DynamoDB is automatically /// scaling your table or index so please try again shortly. If exceptions persist, check /// if you have a hot key: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html. /// </para> /// <note> /// <para> /// This message is returned when writes get throttled on an On-Demand table as DynamoDB /// is automatically scaling the table. /// </para> /// </note> </li> <li> /// <para> /// Throughput exceeds the current capacity for one or more global secondary indexes. /// DynamoDB is automatically scaling your index so please try again shortly. /// </para> /// <note> /// <para> /// This message is returned when when writes get throttled on an On-Demand GSI as DynamoDB /// is automatically scaling the GSI. /// </para> /// </note> </li> </ul> </li> </ul> </li> <li> /// <para> /// Validation Error: /// </para> /// <ul> <li> /// <para> /// Code: <code>ValidationError</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// One or more parameter values were invalid. /// </para> /// </li> <li> /// <para> /// The update expression attempted to update the secondary index key beyond allowed size /// limits. /// </para> /// </li> <li> /// <para> /// The update expression attempted to update the secondary index key to unsupported type. /// </para> /// </li> <li> /// <para> /// An operand in the update expression has an incorrect data type. /// </para> /// </li> <li> /// <para> /// Item size to update has exceeded the maximum allowed size. /// </para> /// </li> <li> /// <para> /// Number overflow. Attempting to store a number with magnitude larger than supported /// range. /// </para> /// </li> <li> /// <para> /// Type mismatch for attribute to update. /// </para> /// </li> <li> /// <para> /// Nesting Levels have exceeded supported limits. /// </para> /// </li> <li> /// <para> /// The document path provided in the update expression is invalid for update. /// </para> /// </li> <li> /// <para> /// The provided expression refers to an attribute that does not exist in the item. /// </para> /// </li> </ul> </li> </ul> </li> </ul> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionInProgressException"> /// The transaction with the given request token is already in progress. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ExecuteTransaction">REST API Reference for ExecuteTransaction Operation</seealso> Task<ExecuteTransactionResponse> ExecuteTransactionAsync(ExecuteTransactionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ExportTableToPointInTime /// <summary> /// Exports table data to an S3 bucket. The table must have point in time recovery enabled, /// and you can export data from any time within the point in time recovery window. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ExportTableToPointInTime service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ExportTableToPointInTime service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ExportConflictException"> /// There was a conflict when writing to the specified S3 bucket. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InvalidExportTimeException"> /// The specified <code>ExportTime</code> is outside of the point in time recovery window. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.PointInTimeRecoveryUnavailableException"> /// Point in time recovery has not yet been enabled for this source table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableNotFoundException"> /// A source table with the name <code>TableName</code> does not currently exist within /// the subscriber's account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ExportTableToPointInTime">REST API Reference for ExportTableToPointInTime Operation</seealso> Task<ExportTableToPointInTimeResponse> ExportTableToPointInTimeAsync(ExportTableToPointInTimeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetItem /// <summary> /// The <code>GetItem</code> operation returns a set of attributes for the item with the /// given primary key. If there is no matching item, <code>GetItem</code> does not return /// any data and there will be no <code>Item</code> element in the response. /// /// /// <para> /// <code>GetItem</code> provides an eventually consistent read by default. If your application /// requires a strongly consistent read, set <code>ConsistentRead</code> to <code>true</code>. /// Although a strongly consistent read might take more time than an eventually consistent /// read, it always returns the last updated value. /// </para> /// </summary> /// <param name="tableName">The name of the table containing the requested item.</param> /// <param name="key">A map of attribute names to <code>AttributeValue</code> objects, representing the primary key of the item to retrieve. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/GetItem">REST API Reference for GetItem Operation</seealso> Task<GetItemResponse> GetItemAsync(string tableName, Dictionary<string, AttributeValue> key, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>GetItem</code> operation returns a set of attributes for the item with the /// given primary key. If there is no matching item, <code>GetItem</code> does not return /// any data and there will be no <code>Item</code> element in the response. /// /// /// <para> /// <code>GetItem</code> provides an eventually consistent read by default. If your application /// requires a strongly consistent read, set <code>ConsistentRead</code> to <code>true</code>. /// Although a strongly consistent read might take more time than an eventually consistent /// read, it always returns the last updated value. /// </para> /// </summary> /// <param name="tableName">The name of the table containing the requested item.</param> /// <param name="key">A map of attribute names to <code>AttributeValue</code> objects, representing the primary key of the item to retrieve. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.</param> /// <param name="consistentRead">Determines the read consistency model: If set to <code>true</code>, then the operation uses strongly consistent reads; otherwise, the operation uses eventually consistent reads.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/GetItem">REST API Reference for GetItem Operation</seealso> Task<GetItemResponse> GetItemAsync(string tableName, Dictionary<string, AttributeValue> key, bool consistentRead, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>GetItem</code> operation returns a set of attributes for the item with the /// given primary key. If there is no matching item, <code>GetItem</code> does not return /// any data and there will be no <code>Item</code> element in the response. /// /// /// <para> /// <code>GetItem</code> provides an eventually consistent read by default. If your application /// requires a strongly consistent read, set <code>ConsistentRead</code> to <code>true</code>. /// Although a strongly consistent read might take more time than an eventually consistent /// read, it always returns the last updated value. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetItem service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/GetItem">REST API Reference for GetItem Operation</seealso> Task<GetItemResponse> GetItemAsync(GetItemRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListBackups /// <summary> /// List backups associated with an Amazon Web Services account. To list backups for a /// given table, specify <code>TableName</code>. <code>ListBackups</code> returns a paginated /// list of results with at most 1 MB worth of items in a page. You can also specify a /// maximum number of entries to be returned in a page. /// /// /// <para> /// In the request, start time is inclusive, but end time is exclusive. Note that these /// boundaries are for the time at which the original backup was requested. /// </para> /// /// <para> /// You can call <code>ListBackups</code> a maximum of five times per second. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListBackups service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListBackups service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListBackups">REST API Reference for ListBackups Operation</seealso> Task<ListBackupsResponse> ListBackupsAsync(ListBackupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListContributorInsights /// <summary> /// Returns a list of ContributorInsightsSummary for a table and all its global secondary /// indexes. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListContributorInsights service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListContributorInsights service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListContributorInsights">REST API Reference for ListContributorInsights Operation</seealso> Task<ListContributorInsightsResponse> ListContributorInsightsAsync(ListContributorInsightsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListExports /// <summary> /// Lists completed exports within the past 90 days. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListExports service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListExports service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListExports">REST API Reference for ListExports Operation</seealso> Task<ListExportsResponse> ListExportsAsync(ListExportsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListGlobalTables /// <summary> /// Lists all global tables that have a replica in the specified Region. /// /// <note> /// <para> /// This operation only applies to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html">Version /// 2017.11.29</a> of global tables. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListGlobalTables service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListGlobalTables service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListGlobalTables">REST API Reference for ListGlobalTables Operation</seealso> Task<ListGlobalTablesResponse> ListGlobalTablesAsync(ListGlobalTablesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListTables /// <summary> /// Returns an array of table names associated with the current account and endpoint. /// The output from <code>ListTables</code> is paginated, with each page returning a maximum /// of 100 table names. /// </summary> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTables service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTables">REST API Reference for ListTables Operation</seealso> Task<ListTablesResponse> ListTablesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns an array of table names associated with the current account and endpoint. /// The output from <code>ListTables</code> is paginated, with each page returning a maximum /// of 100 table names. /// </summary> /// <param name="exclusiveStartTableName">The first table name that this operation will evaluate. Use the value that was returned for <code>LastEvaluatedTableName</code> in a previous operation, so that you can obtain the next page of results.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTables service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTables">REST API Reference for ListTables Operation</seealso> Task<ListTablesResponse> ListTablesAsync(string exclusiveStartTableName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns an array of table names associated with the current account and endpoint. /// The output from <code>ListTables</code> is paginated, with each page returning a maximum /// of 100 table names. /// </summary> /// <param name="exclusiveStartTableName">The first table name that this operation will evaluate. Use the value that was returned for <code>LastEvaluatedTableName</code> in a previous operation, so that you can obtain the next page of results.</param> /// <param name="limit">A maximum number of table names to return. If this parameter is not specified, the limit is 100.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTables service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTables">REST API Reference for ListTables Operation</seealso> Task<ListTablesResponse> ListTablesAsync(string exclusiveStartTableName, int limit, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns an array of table names associated with the current account and endpoint. /// The output from <code>ListTables</code> is paginated, with each page returning a maximum /// of 100 table names. /// </summary> /// <param name="limit">A maximum number of table names to return. If this parameter is not specified, the limit is 100.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTables service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTables">REST API Reference for ListTables Operation</seealso> Task<ListTablesResponse> ListTablesAsync(int limit, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns an array of table names associated with the current account and endpoint. /// The output from <code>ListTables</code> is paginated, with each page returning a maximum /// of 100 table names. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTables service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTables service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTables">REST API Reference for ListTables Operation</seealso> Task<ListTablesResponse> ListTablesAsync(ListTablesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListTagsOfResource /// <summary> /// List all tags on an Amazon DynamoDB resource. You can call ListTagsOfResource up to /// 10 times per second, per account. /// /// /// <para> /// For an overview on tagging DynamoDB resources, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html">Tagging /// for DynamoDB</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListTagsOfResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListTagsOfResource service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTagsOfResource">REST API Reference for ListTagsOfResource Operation</seealso> Task<ListTagsOfResourceResponse> ListTagsOfResourceAsync(ListTagsOfResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutItem /// <summary> /// Creates a new item, or replaces an old item with a new item. If an item that has the /// same primary key as the new item already exists in the specified table, the new item /// completely replaces the existing item. You can perform a conditional put operation /// (add a new item if one with the specified primary key doesn't exist), or replace an /// existing item if it has certain attribute values. You can return the item's attribute /// values in the same operation, using the <code>ReturnValues</code> parameter. /// /// <important> /// <para> /// This topic provides general information about the <code>PutItem</code> API. /// </para> /// /// <para> /// For information on how to call the <code>PutItem</code> API using the Amazon Web Services /// SDK in specific languages, see the following: /// </para> /// <ul> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem"> PutItem /// in the Command Line Interface</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for .NET</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for C++</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForGoV1/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Go</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForJava/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Java</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for JavaScript</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for PHP V3</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem"> PutItem /// in the SDK for Python (Boto)</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForRubyV2/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Ruby V2</a> /// </para> /// </li> </ul> </important> /// <para> /// When you add an item, the primary key attributes are the only required attributes. /// Attribute values cannot be null. /// </para> /// /// <para> /// Empty String and Binary attribute values are allowed. Attribute values of type String /// and Binary must have a length greater than zero if the attribute is used as a key /// attribute for a table or index. Set type attributes cannot be empty. /// </para> /// /// <para> /// Invalid Requests with empty values will be rejected with a <code>ValidationException</code> /// exception. /// </para> /// <note> /// <para> /// To prevent a new item from replacing an existing item, use a conditional expression /// that contains the <code>attribute_not_exists</code> function with the name of the /// attribute being used as the partition key for the table. Since every record must contain /// that attribute, the <code>attribute_not_exists</code> function will only succeed if /// no matching item exists. /// </para> /// </note> /// <para> /// For more information about <code>PutItem</code>, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working /// with Items</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="tableName">The name of the table to contain the item.</param> /// <param name="item">A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item. You must provide all of the attributes for the primary key. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide both values for both the partition key and the sort key. If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition. Empty String and Binary attribute values are allowed. Attribute values of type String and Binary must have a length greater than zero if the attribute is used as a key attribute for a table or index. For more information about primary keys, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.PrimaryKey">Primary Key</a> in the <i>Amazon DynamoDB Developer Guide</i>. Each element in the <code>Item</code> map is an <code>AttributeValue</code> object.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/PutItem">REST API Reference for PutItem Operation</seealso> Task<PutItemResponse> PutItemAsync(string tableName, Dictionary<string, AttributeValue> item, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a new item, or replaces an old item with a new item. If an item that has the /// same primary key as the new item already exists in the specified table, the new item /// completely replaces the existing item. You can perform a conditional put operation /// (add a new item if one with the specified primary key doesn't exist), or replace an /// existing item if it has certain attribute values. You can return the item's attribute /// values in the same operation, using the <code>ReturnValues</code> parameter. /// /// <important> /// <para> /// This topic provides general information about the <code>PutItem</code> API. /// </para> /// /// <para> /// For information on how to call the <code>PutItem</code> API using the Amazon Web Services /// SDK in specific languages, see the following: /// </para> /// <ul> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem"> PutItem /// in the Command Line Interface</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for .NET</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for C++</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForGoV1/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Go</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForJava/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Java</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for JavaScript</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for PHP V3</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem"> PutItem /// in the SDK for Python (Boto)</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForRubyV2/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Ruby V2</a> /// </para> /// </li> </ul> </important> /// <para> /// When you add an item, the primary key attributes are the only required attributes. /// Attribute values cannot be null. /// </para> /// /// <para> /// Empty String and Binary attribute values are allowed. Attribute values of type String /// and Binary must have a length greater than zero if the attribute is used as a key /// attribute for a table or index. Set type attributes cannot be empty. /// </para> /// /// <para> /// Invalid Requests with empty values will be rejected with a <code>ValidationException</code> /// exception. /// </para> /// <note> /// <para> /// To prevent a new item from replacing an existing item, use a conditional expression /// that contains the <code>attribute_not_exists</code> function with the name of the /// attribute being used as the partition key for the table. Since every record must contain /// that attribute, the <code>attribute_not_exists</code> function will only succeed if /// no matching item exists. /// </para> /// </note> /// <para> /// For more information about <code>PutItem</code>, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working /// with Items</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="tableName">The name of the table to contain the item.</param> /// <param name="item">A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item. You must provide all of the attributes for the primary key. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide both values for both the partition key and the sort key. If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition. Empty String and Binary attribute values are allowed. Attribute values of type String and Binary must have a length greater than zero if the attribute is used as a key attribute for a table or index. For more information about primary keys, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.PrimaryKey">Primary Key</a> in the <i>Amazon DynamoDB Developer Guide</i>. Each element in the <code>Item</code> map is an <code>AttributeValue</code> object.</param> /// <param name="returnValues">Use <code>ReturnValues</code> if you want to get the item attributes as they appeared before they were updated with the <code>PutItem</code> request. For <code>PutItem</code>, the valid values are: <ul> <li> <code>NONE</code> - If <code>ReturnValues</code> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <code>ReturnValues</code>.) </li> <li> <code>ALL_OLD</code> - If <code>PutItem</code> overwrote an attribute name-value pair, then the content of the old item is returned. </li> </ul> The values returned are strongly consistent. <note> The <code>ReturnValues</code> parameter is used by several DynamoDB operations; however, <code>PutItem</code> does not recognize any values other than <code>NONE</code> or <code>ALL_OLD</code>. </note></param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/PutItem">REST API Reference for PutItem Operation</seealso> Task<PutItemResponse> PutItemAsync(string tableName, Dictionary<string, AttributeValue> item, ReturnValue returnValues, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a new item, or replaces an old item with a new item. If an item that has the /// same primary key as the new item already exists in the specified table, the new item /// completely replaces the existing item. You can perform a conditional put operation /// (add a new item if one with the specified primary key doesn't exist), or replace an /// existing item if it has certain attribute values. You can return the item's attribute /// values in the same operation, using the <code>ReturnValues</code> parameter. /// /// <important> /// <para> /// This topic provides general information about the <code>PutItem</code> API. /// </para> /// /// <para> /// For information on how to call the <code>PutItem</code> API using the Amazon Web Services /// SDK in specific languages, see the following: /// </para> /// <ul> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem"> PutItem /// in the Command Line Interface</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for .NET</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for C++</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForGoV1/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Go</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForJava/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Java</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for JavaScript</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for PHP V3</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem"> PutItem /// in the SDK for Python (Boto)</a> /// </para> /// </li> <li> /// <para> /// <a href="http://docs.aws.amazon.com/goto/SdkForRubyV2/dynamodb-2012-08-10/PutItem"> /// PutItem in the SDK for Ruby V2</a> /// </para> /// </li> </ul> </important> /// <para> /// When you add an item, the primary key attributes are the only required attributes. /// Attribute values cannot be null. /// </para> /// /// <para> /// Empty String and Binary attribute values are allowed. Attribute values of type String /// and Binary must have a length greater than zero if the attribute is used as a key /// attribute for a table or index. Set type attributes cannot be empty. /// </para> /// /// <para> /// Invalid Requests with empty values will be rejected with a <code>ValidationException</code> /// exception. /// </para> /// <note> /// <para> /// To prevent a new item from replacing an existing item, use a conditional expression /// that contains the <code>attribute_not_exists</code> function with the name of the /// attribute being used as the partition key for the table. Since every record must contain /// that attribute, the <code>attribute_not_exists</code> function will only succeed if /// no matching item exists. /// </para> /// </note> /// <para> /// For more information about <code>PutItem</code>, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working /// with Items</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PutItem service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the PutItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/PutItem">REST API Reference for PutItem Operation</seealso> Task<PutItemResponse> PutItemAsync(PutItemRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Query /// <summary> /// You must provide the name of the partition key attribute and a single value for that /// attribute. <code>Query</code> returns all items with that partition key value. Optionally, /// you can provide a sort key attribute and use a comparison operator to refine the search /// results. /// /// /// <para> /// Use the <code>KeyConditionExpression</code> parameter to provide a specific value /// for the partition key. The <code>Query</code> operation will return all of the items /// from the table or index with that partition key value. You can optionally narrow the /// scope of the <code>Query</code> operation by specifying a sort key value and a comparison /// operator in <code>KeyConditionExpression</code>. To further refine the <code>Query</code> /// results, you can optionally provide a <code>FilterExpression</code>. A <code>FilterExpression</code> /// determines which items within the results should be returned to you. All of the other /// results are discarded. /// </para> /// /// <para> /// A <code>Query</code> operation always returns a result set. If no matching items /// are found, the result set will be empty. Queries that do not return results consume /// the minimum number of read capacity units for that type of read operation. /// </para> /// <note> /// <para> /// DynamoDB calculates the number of read capacity units consumed based on item size, /// not on the amount of data that is returned to an application. The number of capacity /// units consumed will be the same whether you request all of the attributes (the default /// behavior) or just some of them (using a projection expression). The number will also /// be the same whether or not you use a <code>FilterExpression</code>. /// </para> /// </note> /// <para> /// <code>Query</code> results are always sorted by the sort key value. If the data type /// of the sort key is Number, the results are returned in numeric order; otherwise, the /// results are returned in order of UTF-8 bytes. By default, the sort order is ascending. /// To reverse the order, set the <code>ScanIndexForward</code> parameter to false. /// </para> /// /// <para> /// A single <code>Query</code> operation will read up to the maximum number of items /// set (if using the <code>Limit</code> parameter) or a maximum of 1 MB of data and then /// apply any filtering to the results using <code>FilterExpression</code>. If <code>LastEvaluatedKey</code> /// is present in the response, you will need to paginate the result set. For more information, /// see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html#Query.Pagination">Paginating /// the Results</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>FilterExpression</code> is applied after a <code>Query</code> finishes, but /// before the results are returned. A <code>FilterExpression</code> cannot contain partition /// key or sort key attributes. You need to specify those attributes in the <code>KeyConditionExpression</code>. /// /// </para> /// <note> /// <para> /// A <code>Query</code> operation can return an empty result set and a <code>LastEvaluatedKey</code> /// if all the items read for the page of results are filtered out. /// </para> /// </note> /// <para> /// You can query a table, a local secondary index, or a global secondary index. For a /// query on a table or on a local secondary index, you can set the <code>ConsistentRead</code> /// parameter to <code>true</code> and obtain a strongly consistent result. Global secondary /// indexes support eventually consistent reads only, so do not specify <code>ConsistentRead</code> /// when querying a global secondary index. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the Query service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the Query service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Query">REST API Reference for Query Operation</seealso> Task<QueryResponse> QueryAsync(QueryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RestoreTableFromBackup /// <summary> /// Creates a new table from an existing backup. Any number of users can execute up to /// 4 concurrent restores (any type of restore) in a given account. /// /// /// <para> /// You can call <code>RestoreTableFromBackup</code> at a maximum rate of 10 times per /// second. /// </para> /// /// <para> /// You must manually set up the following on the restored table: /// </para> /// <ul> <li> /// <para> /// Auto scaling policies /// </para> /// </li> <li> /// <para> /// IAM policies /// </para> /// </li> <li> /// <para> /// Amazon CloudWatch metrics and alarms /// </para> /// </li> <li> /// <para> /// Tags /// </para> /// </li> <li> /// <para> /// Stream settings /// </para> /// </li> <li> /// <para> /// Time to Live (TTL) settings /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the RestoreTableFromBackup service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the RestoreTableFromBackup service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.BackupInUseException"> /// There is another ongoing conflicting backup control plane operation on the table. /// The backup is either being created, deleted or restored to a table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.BackupNotFoundException"> /// Backup not found for the given BackupARN. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableAlreadyExistsException"> /// A target table with the specified name already exists. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableInUseException"> /// A target table with the specified name is either being created or deleted. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/RestoreTableFromBackup">REST API Reference for RestoreTableFromBackup Operation</seealso> Task<RestoreTableFromBackupResponse> RestoreTableFromBackupAsync(RestoreTableFromBackupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RestoreTableToPointInTime /// <summary> /// Restores the specified table to the specified point in time within <code>EarliestRestorableDateTime</code> /// and <code>LatestRestorableDateTime</code>. You can restore your table to any point /// in time during the last 35 days. Any number of users can execute up to 4 concurrent /// restores (any type of restore) in a given account. /// /// /// <para> /// When you restore using point in time recovery, DynamoDB restores your table data /// to the state based on the selected date and time (day:hour:minute:second) to a new /// table. /// </para> /// /// <para> /// Along with data, the following are also included on the new restored table using /// point in time recovery: /// </para> /// <ul> <li> /// <para> /// Global secondary indexes (GSIs) /// </para> /// </li> <li> /// <para> /// Local secondary indexes (LSIs) /// </para> /// </li> <li> /// <para> /// Provisioned read and write capacity /// </para> /// </li> <li> /// <para> /// Encryption settings /// </para> /// <important> /// <para> /// All these settings come from the current settings of the source table at the time /// of restore. /// </para> /// </important> </li> </ul> /// <para> /// You must manually set up the following on the restored table: /// </para> /// <ul> <li> /// <para> /// Auto scaling policies /// </para> /// </li> <li> /// <para> /// IAM policies /// </para> /// </li> <li> /// <para> /// Amazon CloudWatch metrics and alarms /// </para> /// </li> <li> /// <para> /// Tags /// </para> /// </li> <li> /// <para> /// Stream settings /// </para> /// </li> <li> /// <para> /// Time to Live (TTL) settings /// </para> /// </li> <li> /// <para> /// Point in time recovery settings /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the RestoreTableToPointInTime service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the RestoreTableToPointInTime service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InvalidRestoreTimeException"> /// An invalid restore time was specified. RestoreDateTime must be between EarliestRestorableDateTime /// and LatestRestorableDateTime. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.PointInTimeRecoveryUnavailableException"> /// Point in time recovery has not yet been enabled for this source table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableAlreadyExistsException"> /// A target table with the specified name already exists. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableInUseException"> /// A target table with the specified name is either being created or deleted. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableNotFoundException"> /// A source table with the name <code>TableName</code> does not currently exist within /// the subscriber's account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/RestoreTableToPointInTime">REST API Reference for RestoreTableToPointInTime Operation</seealso> Task<RestoreTableToPointInTimeResponse> RestoreTableToPointInTimeAsync(RestoreTableToPointInTimeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Scan /// <summary> /// The <code>Scan</code> operation returns one or more items and item attributes by accessing /// every item in a table or a secondary index. To have DynamoDB return fewer items, you /// can provide a <code>FilterExpression</code> operation. /// /// /// <para> /// If the total number of scanned items exceeds the maximum dataset size limit of 1 MB, /// the scan stops and results are returned to the user as a <code>LastEvaluatedKey</code> /// value to continue the scan in a subsequent operation. The results also include the /// number of items exceeding the limit. A scan can result in no table data meeting the /// filter criteria. /// </para> /// /// <para> /// A single <code>Scan</code> operation reads up to the maximum number of items set (if /// using the <code>Limit</code> parameter) or a maximum of 1 MB of data and then apply /// any filtering to the results using <code>FilterExpression</code>. If <code>LastEvaluatedKey</code> /// is present in the response, you need to paginate the result set. For more information, /// see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.Pagination">Paginating /// the Results</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>Scan</code> operations proceed sequentially; however, for faster performance /// on a large table or secondary index, applications can request a parallel <code>Scan</code> /// operation by providing the <code>Segment</code> and <code>TotalSegments</code> parameters. /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan">Parallel /// Scan</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>Scan</code> uses eventually consistent reads when accessing the data in a table; /// therefore, the result set might not include the changes to data in the table immediately /// before the operation began. If you need a consistent copy of the data, as of the time /// that the <code>Scan</code> begins, you can set the <code>ConsistentRead</code> parameter /// to <code>true</code>. /// </para> /// </summary> /// <param name="tableName">The name of the table containing the requested items; or, if you provide <code>IndexName</code>, the name of the table to which that index belongs.</param> /// <param name="attributesToGet">This is a legacy parameter. Use <code>ProjectionExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html">AttributesToGet</a> in the <i>Amazon DynamoDB Developer Guide</i>.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the Scan service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Scan">REST API Reference for Scan Operation</seealso> Task<ScanResponse> ScanAsync(string tableName, List<string> attributesToGet, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>Scan</code> operation returns one or more items and item attributes by accessing /// every item in a table or a secondary index. To have DynamoDB return fewer items, you /// can provide a <code>FilterExpression</code> operation. /// /// /// <para> /// If the total number of scanned items exceeds the maximum dataset size limit of 1 MB, /// the scan stops and results are returned to the user as a <code>LastEvaluatedKey</code> /// value to continue the scan in a subsequent operation. The results also include the /// number of items exceeding the limit. A scan can result in no table data meeting the /// filter criteria. /// </para> /// /// <para> /// A single <code>Scan</code> operation reads up to the maximum number of items set (if /// using the <code>Limit</code> parameter) or a maximum of 1 MB of data and then apply /// any filtering to the results using <code>FilterExpression</code>. If <code>LastEvaluatedKey</code> /// is present in the response, you need to paginate the result set. For more information, /// see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.Pagination">Paginating /// the Results</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>Scan</code> operations proceed sequentially; however, for faster performance /// on a large table or secondary index, applications can request a parallel <code>Scan</code> /// operation by providing the <code>Segment</code> and <code>TotalSegments</code> parameters. /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan">Parallel /// Scan</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>Scan</code> uses eventually consistent reads when accessing the data in a table; /// therefore, the result set might not include the changes to data in the table immediately /// before the operation began. If you need a consistent copy of the data, as of the time /// that the <code>Scan</code> begins, you can set the <code>ConsistentRead</code> parameter /// to <code>true</code>. /// </para> /// </summary> /// <param name="tableName">The name of the table containing the requested items; or, if you provide <code>IndexName</code>, the name of the table to which that index belongs.</param> /// <param name="scanFilter">This is a legacy parameter. Use <code>FilterExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ScanFilter.html">ScanFilter</a> in the <i>Amazon DynamoDB Developer Guide</i>.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the Scan service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Scan">REST API Reference for Scan Operation</seealso> Task<ScanResponse> ScanAsync(string tableName, Dictionary<string, Condition> scanFilter, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>Scan</code> operation returns one or more items and item attributes by accessing /// every item in a table or a secondary index. To have DynamoDB return fewer items, you /// can provide a <code>FilterExpression</code> operation. /// /// /// <para> /// If the total number of scanned items exceeds the maximum dataset size limit of 1 MB, /// the scan stops and results are returned to the user as a <code>LastEvaluatedKey</code> /// value to continue the scan in a subsequent operation. The results also include the /// number of items exceeding the limit. A scan can result in no table data meeting the /// filter criteria. /// </para> /// /// <para> /// A single <code>Scan</code> operation reads up to the maximum number of items set (if /// using the <code>Limit</code> parameter) or a maximum of 1 MB of data and then apply /// any filtering to the results using <code>FilterExpression</code>. If <code>LastEvaluatedKey</code> /// is present in the response, you need to paginate the result set. For more information, /// see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.Pagination">Paginating /// the Results</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>Scan</code> operations proceed sequentially; however, for faster performance /// on a large table or secondary index, applications can request a parallel <code>Scan</code> /// operation by providing the <code>Segment</code> and <code>TotalSegments</code> parameters. /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan">Parallel /// Scan</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>Scan</code> uses eventually consistent reads when accessing the data in a table; /// therefore, the result set might not include the changes to data in the table immediately /// before the operation began. If you need a consistent copy of the data, as of the time /// that the <code>Scan</code> begins, you can set the <code>ConsistentRead</code> parameter /// to <code>true</code>. /// </para> /// </summary> /// <param name="tableName">The name of the table containing the requested items; or, if you provide <code>IndexName</code>, the name of the table to which that index belongs.</param> /// <param name="attributesToGet">This is a legacy parameter. Use <code>ProjectionExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html">AttributesToGet</a> in the <i>Amazon DynamoDB Developer Guide</i>.</param> /// <param name="scanFilter">This is a legacy parameter. Use <code>FilterExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ScanFilter.html">ScanFilter</a> in the <i>Amazon DynamoDB Developer Guide</i>.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the Scan service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Scan">REST API Reference for Scan Operation</seealso> Task<ScanResponse> ScanAsync(string tableName, List<string> attributesToGet, Dictionary<string, Condition> scanFilter, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The <code>Scan</code> operation returns one or more items and item attributes by accessing /// every item in a table or a secondary index. To have DynamoDB return fewer items, you /// can provide a <code>FilterExpression</code> operation. /// /// /// <para> /// If the total number of scanned items exceeds the maximum dataset size limit of 1 MB, /// the scan stops and results are returned to the user as a <code>LastEvaluatedKey</code> /// value to continue the scan in a subsequent operation. The results also include the /// number of items exceeding the limit. A scan can result in no table data meeting the /// filter criteria. /// </para> /// /// <para> /// A single <code>Scan</code> operation reads up to the maximum number of items set (if /// using the <code>Limit</code> parameter) or a maximum of 1 MB of data and then apply /// any filtering to the results using <code>FilterExpression</code>. If <code>LastEvaluatedKey</code> /// is present in the response, you need to paginate the result set. For more information, /// see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.Pagination">Paginating /// the Results</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>Scan</code> operations proceed sequentially; however, for faster performance /// on a large table or secondary index, applications can request a parallel <code>Scan</code> /// operation by providing the <code>Segment</code> and <code>TotalSegments</code> parameters. /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.ParallelScan">Parallel /// Scan</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// /// <para> /// <code>Scan</code> uses eventually consistent reads when accessing the data in a table; /// therefore, the result set might not include the changes to data in the table immediately /// before the operation began. If you need a consistent copy of the data, as of the time /// that the <code>Scan</code> begins, you can set the <code>ConsistentRead</code> parameter /// to <code>true</code>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the Scan service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the Scan service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Scan">REST API Reference for Scan Operation</seealso> Task<ScanResponse> ScanAsync(ScanRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region TagResource /// <summary> /// Associate a set of tags with an Amazon DynamoDB resource. You can then activate these /// user-defined tags so that they appear on the Billing and Cost Management console for /// cost allocation tracking. You can call TagResource up to five times per second, per /// account. /// /// /// <para> /// For an overview on tagging DynamoDB resources, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html">Tagging /// for DynamoDB</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TagResource service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TagResource">REST API Reference for TagResource Operation</seealso> Task<TagResourceResponse> TagResourceAsync(TagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region TransactGetItems /// <summary> /// <code>TransactGetItems</code> is a synchronous operation that atomically retrieves /// multiple items from one or more tables (but not from indexes) in a single account /// and Region. A <code>TransactGetItems</code> call can contain up to 25 <code>TransactGetItem</code> /// objects, each of which contains a <code>Get</code> structure that specifies an item /// to retrieve from a table in the account and Region. A call to <code>TransactGetItems</code> /// cannot retrieve items from tables in more than one Amazon Web Services account or /// Region. The aggregate size of the items in the transaction cannot exceed 4 MB. /// /// /// <para> /// DynamoDB rejects the entire <code>TransactGetItems</code> request if any of the following /// is true: /// </para> /// <ul> <li> /// <para> /// A conflicting operation is in the process of updating an item to be read. /// </para> /// </li> <li> /// <para> /// There is insufficient provisioned capacity for the transaction to be completed. /// </para> /// </li> <li> /// <para> /// There is a user error, such as an invalid data format. /// </para> /// </li> <li> /// <para> /// The aggregate size of the items in the transaction cannot exceed 4 MB. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the TransactGetItems service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TransactGetItems service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionCanceledException"> /// The entire transaction request was canceled. /// /// /// <para> /// DynamoDB cancels a <code>TransactWriteItems</code> request under the following circumstances: /// </para> /// <ul> <li> /// <para> /// A condition in one of the condition expressions is not met. /// </para> /// </li> <li> /// <para> /// A table in the <code>TransactWriteItems</code> request is in a different account or /// region. /// </para> /// </li> <li> /// <para> /// More than one action in the <code>TransactWriteItems</code> operation targets the /// same item. /// </para> /// </li> <li> /// <para> /// There is insufficient provisioned capacity for the transaction to be completed. /// </para> /// </li> <li> /// <para> /// An item size becomes too large (larger than 400 KB), or a local secondary index (LSI) /// becomes too large, or a similar validation error occurs because of changes made by /// the transaction. /// </para> /// </li> <li> /// <para> /// There is a user error, such as an invalid data format. /// </para> /// </li> </ul> /// <para> /// DynamoDB cancels a <code>TransactGetItems</code> request under the following circumstances: /// </para> /// <ul> <li> /// <para> /// There is an ongoing <code>TransactGetItems</code> operation that conflicts with a /// concurrent <code>PutItem</code>, <code>UpdateItem</code>, <code>DeleteItem</code> /// or <code>TransactWriteItems</code> request. In this case the <code>TransactGetItems</code> /// operation fails with a <code>TransactionCanceledException</code>. /// </para> /// </li> <li> /// <para> /// A table in the <code>TransactGetItems</code> request is in a different account or /// region. /// </para> /// </li> <li> /// <para> /// There is insufficient provisioned capacity for the transaction to be completed. /// </para> /// </li> <li> /// <para> /// There is a user error, such as an invalid data format. /// </para> /// </li> </ul> <note> /// <para> /// If using Java, DynamoDB lists the cancellation reasons on the <code>CancellationReasons</code> /// property. This property is not set for other languages. Transaction cancellation reasons /// are ordered in the order of requested items, if an item has no error it will have /// <code>NONE</code> code and <code>Null</code> message. /// </para> /// </note> /// <para> /// Cancellation reason codes and possible error messages: /// </para> /// <ul> <li> /// <para> /// No Errors: /// </para> /// <ul> <li> /// <para> /// Code: <code>NONE</code> /// </para> /// </li> <li> /// <para> /// Message: <code>null</code> /// </para> /// </li> </ul> </li> <li> /// <para> /// Conditional Check Failed: /// </para> /// <ul> <li> /// <para> /// Code: <code>ConditionalCheckFailed</code> /// </para> /// </li> <li> /// <para> /// Message: The conditional request failed. /// </para> /// </li> </ul> </li> <li> /// <para> /// Item Collection Size Limit Exceeded: /// </para> /// <ul> <li> /// <para> /// Code: <code>ItemCollectionSizeLimitExceeded</code> /// </para> /// </li> <li> /// <para> /// Message: Collection size exceeded. /// </para> /// </li> </ul> </li> <li> /// <para> /// Transaction Conflict: /// </para> /// <ul> <li> /// <para> /// Code: <code>TransactionConflict</code> /// </para> /// </li> <li> /// <para> /// Message: Transaction is ongoing for the item. /// </para> /// </li> </ul> </li> <li> /// <para> /// Provisioned Throughput Exceeded: /// </para> /// <ul> <li> /// <para> /// Code: <code>ProvisionedThroughputExceeded</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// The level of configured provisioned throughput for the table was exceeded. Consider /// increasing your provisioning level with the UpdateTable API. /// </para> /// <note> /// <para> /// This Message is received when provisioned throughput is exceeded is on a provisioned /// DynamoDB table. /// </para> /// </note> </li> <li> /// <para> /// The level of configured provisioned throughput for one or more global secondary indexes /// of the table was exceeded. Consider increasing your provisioning level for the under-provisioned /// global secondary indexes with the UpdateTable API. /// </para> /// <note> /// <para> /// This message is returned when provisioned throughput is exceeded is on a provisioned /// GSI. /// </para> /// </note> </li> </ul> </li> </ul> </li> <li> /// <para> /// Throttling Error: /// </para> /// <ul> <li> /// <para> /// Code: <code>ThrottlingError</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// Throughput exceeds the current capacity of your table or index. DynamoDB is automatically /// scaling your table or index so please try again shortly. If exceptions persist, check /// if you have a hot key: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html. /// </para> /// <note> /// <para> /// This message is returned when writes get throttled on an On-Demand table as DynamoDB /// is automatically scaling the table. /// </para> /// </note> </li> <li> /// <para> /// Throughput exceeds the current capacity for one or more global secondary indexes. /// DynamoDB is automatically scaling your index so please try again shortly. /// </para> /// <note> /// <para> /// This message is returned when when writes get throttled on an On-Demand GSI as DynamoDB /// is automatically scaling the GSI. /// </para> /// </note> </li> </ul> </li> </ul> </li> <li> /// <para> /// Validation Error: /// </para> /// <ul> <li> /// <para> /// Code: <code>ValidationError</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// One or more parameter values were invalid. /// </para> /// </li> <li> /// <para> /// The update expression attempted to update the secondary index key beyond allowed size /// limits. /// </para> /// </li> <li> /// <para> /// The update expression attempted to update the secondary index key to unsupported type. /// </para> /// </li> <li> /// <para> /// An operand in the update expression has an incorrect data type. /// </para> /// </li> <li> /// <para> /// Item size to update has exceeded the maximum allowed size. /// </para> /// </li> <li> /// <para> /// Number overflow. Attempting to store a number with magnitude larger than supported /// range. /// </para> /// </li> <li> /// <para> /// Type mismatch for attribute to update. /// </para> /// </li> <li> /// <para> /// Nesting Levels have exceeded supported limits. /// </para> /// </li> <li> /// <para> /// The document path provided in the update expression is invalid for update. /// </para> /// </li> <li> /// <para> /// The provided expression refers to an attribute that does not exist in the item. /// </para> /// </li> </ul> </li> </ul> </li> </ul> /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TransactGetItems">REST API Reference for TransactGetItems Operation</seealso> Task<TransactGetItemsResponse> TransactGetItemsAsync(TransactGetItemsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region TransactWriteItems /// <summary> /// <code>TransactWriteItems</code> is a synchronous write operation that groups up to /// 25 action requests. These actions can target items in different tables, but not in /// different Amazon Web Services accounts or Regions, and no two actions can target the /// same item. For example, you cannot both <code>ConditionCheck</code> and <code>Update</code> /// the same item. The aggregate size of the items in the transaction cannot exceed 4 /// MB. /// /// /// <para> /// The actions are completed atomically so that either all of them succeed, or all of /// them fail. They are defined by the following objects: /// </para> /// <ul> <li> /// <para> /// <code>Put</code>  —   Initiates a <code>PutItem</code> operation to write a new item. /// This structure specifies the primary key of the item to be written, the name of the /// table to write it in, an optional condition expression that must be satisfied for /// the write to succeed, a list of the item's attributes, and a field indicating whether /// to retrieve the item's attributes if the condition is not met. /// </para> /// </li> <li> /// <para> /// <code>Update</code>  —   Initiates an <code>UpdateItem</code> operation to update /// an existing item. This structure specifies the primary key of the item to be updated, /// the name of the table where it resides, an optional condition expression that must /// be satisfied for the update to succeed, an expression that defines one or more attributes /// to be updated, and a field indicating whether to retrieve the item's attributes if /// the condition is not met. /// </para> /// </li> <li> /// <para> /// <code>Delete</code>  —   Initiates a <code>DeleteItem</code> operation to delete /// an existing item. This structure specifies the primary key of the item to be deleted, /// the name of the table where it resides, an optional condition expression that must /// be satisfied for the deletion to succeed, and a field indicating whether to retrieve /// the item's attributes if the condition is not met. /// </para> /// </li> <li> /// <para> /// <code>ConditionCheck</code>  —   Applies a condition to an item that is not being /// modified by the transaction. This structure specifies the primary key of the item /// to be checked, the name of the table where it resides, a condition expression that /// must be satisfied for the transaction to succeed, and a field indicating whether to /// retrieve the item's attributes if the condition is not met. /// </para> /// </li> </ul> /// <para> /// DynamoDB rejects the entire <code>TransactWriteItems</code> request if any of the /// following is true: /// </para> /// <ul> <li> /// <para> /// A condition in one of the condition expressions is not met. /// </para> /// </li> <li> /// <para> /// An ongoing operation is in the process of updating the same item. /// </para> /// </li> <li> /// <para> /// There is insufficient provisioned capacity for the transaction to be completed. /// </para> /// </li> <li> /// <para> /// An item size becomes too large (bigger than 400 KB), a local secondary index (LSI) /// becomes too large, or a similar validation error occurs because of changes made by /// the transaction. /// </para> /// </li> <li> /// <para> /// The aggregate size of the items in the transaction exceeds 4 MB. /// </para> /// </li> <li> /// <para> /// There is a user error, such as an invalid data format. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the TransactWriteItems service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the TransactWriteItems service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.IdempotentParameterMismatchException"> /// DynamoDB rejected the request because you retried a request with a different payload /// but with an idempotent token that was already used. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionCanceledException"> /// The entire transaction request was canceled. /// /// /// <para> /// DynamoDB cancels a <code>TransactWriteItems</code> request under the following circumstances: /// </para> /// <ul> <li> /// <para> /// A condition in one of the condition expressions is not met. /// </para> /// </li> <li> /// <para> /// A table in the <code>TransactWriteItems</code> request is in a different account or /// region. /// </para> /// </li> <li> /// <para> /// More than one action in the <code>TransactWriteItems</code> operation targets the /// same item. /// </para> /// </li> <li> /// <para> /// There is insufficient provisioned capacity for the transaction to be completed. /// </para> /// </li> <li> /// <para> /// An item size becomes too large (larger than 400 KB), or a local secondary index (LSI) /// becomes too large, or a similar validation error occurs because of changes made by /// the transaction. /// </para> /// </li> <li> /// <para> /// There is a user error, such as an invalid data format. /// </para> /// </li> </ul> /// <para> /// DynamoDB cancels a <code>TransactGetItems</code> request under the following circumstances: /// </para> /// <ul> <li> /// <para> /// There is an ongoing <code>TransactGetItems</code> operation that conflicts with a /// concurrent <code>PutItem</code>, <code>UpdateItem</code>, <code>DeleteItem</code> /// or <code>TransactWriteItems</code> request. In this case the <code>TransactGetItems</code> /// operation fails with a <code>TransactionCanceledException</code>. /// </para> /// </li> <li> /// <para> /// A table in the <code>TransactGetItems</code> request is in a different account or /// region. /// </para> /// </li> <li> /// <para> /// There is insufficient provisioned capacity for the transaction to be completed. /// </para> /// </li> <li> /// <para> /// There is a user error, such as an invalid data format. /// </para> /// </li> </ul> <note> /// <para> /// If using Java, DynamoDB lists the cancellation reasons on the <code>CancellationReasons</code> /// property. This property is not set for other languages. Transaction cancellation reasons /// are ordered in the order of requested items, if an item has no error it will have /// <code>NONE</code> code and <code>Null</code> message. /// </para> /// </note> /// <para> /// Cancellation reason codes and possible error messages: /// </para> /// <ul> <li> /// <para> /// No Errors: /// </para> /// <ul> <li> /// <para> /// Code: <code>NONE</code> /// </para> /// </li> <li> /// <para> /// Message: <code>null</code> /// </para> /// </li> </ul> </li> <li> /// <para> /// Conditional Check Failed: /// </para> /// <ul> <li> /// <para> /// Code: <code>ConditionalCheckFailed</code> /// </para> /// </li> <li> /// <para> /// Message: The conditional request failed. /// </para> /// </li> </ul> </li> <li> /// <para> /// Item Collection Size Limit Exceeded: /// </para> /// <ul> <li> /// <para> /// Code: <code>ItemCollectionSizeLimitExceeded</code> /// </para> /// </li> <li> /// <para> /// Message: Collection size exceeded. /// </para> /// </li> </ul> </li> <li> /// <para> /// Transaction Conflict: /// </para> /// <ul> <li> /// <para> /// Code: <code>TransactionConflict</code> /// </para> /// </li> <li> /// <para> /// Message: Transaction is ongoing for the item. /// </para> /// </li> </ul> </li> <li> /// <para> /// Provisioned Throughput Exceeded: /// </para> /// <ul> <li> /// <para> /// Code: <code>ProvisionedThroughputExceeded</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// The level of configured provisioned throughput for the table was exceeded. Consider /// increasing your provisioning level with the UpdateTable API. /// </para> /// <note> /// <para> /// This Message is received when provisioned throughput is exceeded is on a provisioned /// DynamoDB table. /// </para> /// </note> </li> <li> /// <para> /// The level of configured provisioned throughput for one or more global secondary indexes /// of the table was exceeded. Consider increasing your provisioning level for the under-provisioned /// global secondary indexes with the UpdateTable API. /// </para> /// <note> /// <para> /// This message is returned when provisioned throughput is exceeded is on a provisioned /// GSI. /// </para> /// </note> </li> </ul> </li> </ul> </li> <li> /// <para> /// Throttling Error: /// </para> /// <ul> <li> /// <para> /// Code: <code>ThrottlingError</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// Throughput exceeds the current capacity of your table or index. DynamoDB is automatically /// scaling your table or index so please try again shortly. If exceptions persist, check /// if you have a hot key: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html. /// </para> /// <note> /// <para> /// This message is returned when writes get throttled on an On-Demand table as DynamoDB /// is automatically scaling the table. /// </para> /// </note> </li> <li> /// <para> /// Throughput exceeds the current capacity for one or more global secondary indexes. /// DynamoDB is automatically scaling your index so please try again shortly. /// </para> /// <note> /// <para> /// This message is returned when when writes get throttled on an On-Demand GSI as DynamoDB /// is automatically scaling the GSI. /// </para> /// </note> </li> </ul> </li> </ul> </li> <li> /// <para> /// Validation Error: /// </para> /// <ul> <li> /// <para> /// Code: <code>ValidationError</code> /// </para> /// </li> <li> /// <para> /// Messages: /// </para> /// <ul> <li> /// <para> /// One or more parameter values were invalid. /// </para> /// </li> <li> /// <para> /// The update expression attempted to update the secondary index key beyond allowed size /// limits. /// </para> /// </li> <li> /// <para> /// The update expression attempted to update the secondary index key to unsupported type. /// </para> /// </li> <li> /// <para> /// An operand in the update expression has an incorrect data type. /// </para> /// </li> <li> /// <para> /// Item size to update has exceeded the maximum allowed size. /// </para> /// </li> <li> /// <para> /// Number overflow. Attempting to store a number with magnitude larger than supported /// range. /// </para> /// </li> <li> /// <para> /// Type mismatch for attribute to update. /// </para> /// </li> <li> /// <para> /// Nesting Levels have exceeded supported limits. /// </para> /// </li> <li> /// <para> /// The document path provided in the update expression is invalid for update. /// </para> /// </li> <li> /// <para> /// The provided expression refers to an attribute that does not exist in the item. /// </para> /// </li> </ul> </li> </ul> </li> </ul> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionInProgressException"> /// The transaction with the given request token is already in progress. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TransactWriteItems">REST API Reference for TransactWriteItems Operation</seealso> Task<TransactWriteItemsResponse> TransactWriteItemsAsync(TransactWriteItemsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UntagResource /// <summary> /// Removes the association of tags from an Amazon DynamoDB resource. You can call <code>UntagResource</code> /// up to five times per second, per account. /// /// /// <para> /// For an overview on tagging DynamoDB resources, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html">Tagging /// for DynamoDB</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UntagResource service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UntagResource">REST API Reference for UntagResource Operation</seealso> Task<UntagResourceResponse> UntagResourceAsync(UntagResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateContinuousBackups /// <summary> /// <code>UpdateContinuousBackups</code> enables or disables point in time recovery for /// the specified table. A successful <code>UpdateContinuousBackups</code> call returns /// the current <code>ContinuousBackupsDescription</code>. Continuous backups are <code>ENABLED</code> /// on all tables at table creation. If point in time recovery is enabled, <code>PointInTimeRecoveryStatus</code> /// will be set to ENABLED. /// /// /// <para> /// Once continuous backups and point in time recovery are enabled, you can restore to /// any point in time within <code>EarliestRestorableDateTime</code> and <code>LatestRestorableDateTime</code>. /// /// </para> /// /// <para> /// <code>LatestRestorableDateTime</code> is typically 5 minutes before the current time. /// You can restore your table to any point in time during the last 35 days. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateContinuousBackups service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateContinuousBackups service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ContinuousBackupsUnavailableException"> /// Backups have not yet been enabled for this table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableNotFoundException"> /// A source table with the name <code>TableName</code> does not currently exist within /// the subscriber's account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateContinuousBackups">REST API Reference for UpdateContinuousBackups Operation</seealso> Task<UpdateContinuousBackupsResponse> UpdateContinuousBackupsAsync(UpdateContinuousBackupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateContributorInsights /// <summary> /// Updates the status for contributor insights for a specific table or index. CloudWatch /// Contributor Insights for DynamoDB graphs display the partition key and (if applicable) /// sort key of frequently accessed items and frequently throttled items in plaintext. /// If you require the use of AWS Key Management Service (KMS) to encrypt this table’s /// partition key and sort key data with an AWS managed key or customer managed key, you /// should not enable CloudWatch Contributor Insights for DynamoDB for this table. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateContributorInsights service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateContributorInsights service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateContributorInsights">REST API Reference for UpdateContributorInsights Operation</seealso> Task<UpdateContributorInsightsResponse> UpdateContributorInsightsAsync(UpdateContributorInsightsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateGlobalTable /// <summary> /// Adds or removes replicas in the specified global table. The global table must already /// exist to be able to use this operation. Any replica to be added must be empty, have /// the same name as the global table, have the same key schema, have DynamoDB Streams /// enabled, and have the same provisioned and maximum write capacity units. /// /// <note> /// <para> /// Although you can use <code>UpdateGlobalTable</code> to add replicas and remove replicas /// in a single request, for simplicity we recommend that you issue separate requests /// for adding or removing replicas. /// </para> /// </note> /// <para> /// If global secondary indexes are specified, then the following conditions must also /// be met: /// </para> /// <ul> <li> /// <para> /// The global secondary indexes must have the same name. /// </para> /// </li> <li> /// <para> /// The global secondary indexes must have the same hash key and sort key (if present). /// /// </para> /// </li> <li> /// <para> /// The global secondary indexes must have the same provisioned and maximum write capacity /// units. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateGlobalTable service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateGlobalTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.GlobalTableNotFoundException"> /// The specified global table does not exist. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ReplicaAlreadyExistsException"> /// The specified replica is already part of the global table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ReplicaNotFoundException"> /// The specified replica is no longer part of the global table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TableNotFoundException"> /// A source table with the name <code>TableName</code> does not currently exist within /// the subscriber's account. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateGlobalTable">REST API Reference for UpdateGlobalTable Operation</seealso> Task<UpdateGlobalTableResponse> UpdateGlobalTableAsync(UpdateGlobalTableRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateGlobalTableSettings /// <summary> /// Updates settings for a global table. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateGlobalTableSettings service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateGlobalTableSettings service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.GlobalTableNotFoundException"> /// The specified global table does not exist. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.IndexNotFoundException"> /// The operation tried to access a nonexistent index. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ReplicaNotFoundException"> /// The specified replica is no longer part of the global table. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateGlobalTableSettings">REST API Reference for UpdateGlobalTableSettings Operation</seealso> Task<UpdateGlobalTableSettingsResponse> UpdateGlobalTableSettingsAsync(UpdateGlobalTableSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateItem /// <summary> /// Edits an existing item's attributes, or adds a new item to the table if it does not /// already exist. You can put, delete, or add attribute values. You can also perform /// a conditional update on an existing item (insert a new attribute name-value pair if /// it doesn't exist, or replace an existing name-value pair if it has certain expected /// attribute values). /// /// /// <para> /// You can also return the item's attribute values in the same <code>UpdateItem</code> /// operation using the <code>ReturnValues</code> parameter. /// </para> /// </summary> /// <param name="tableName">The name of the table containing the item to update.</param> /// <param name="key">The primary key of the item to be updated. Each element consists of an attribute name and a value for that attribute. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.</param> /// <param name="attributeUpdates">This is a legacy parameter. Use <code>UpdateExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributeUpdates.html">AttributeUpdates</a> in the <i>Amazon DynamoDB Developer Guide</i>.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItem">REST API Reference for UpdateItem Operation</seealso> Task<UpdateItemResponse> UpdateItemAsync(string tableName, Dictionary<string, AttributeValue> key, Dictionary<string, AttributeValueUpdate> attributeUpdates, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Edits an existing item's attributes, or adds a new item to the table if it does not /// already exist. You can put, delete, or add attribute values. You can also perform /// a conditional update on an existing item (insert a new attribute name-value pair if /// it doesn't exist, or replace an existing name-value pair if it has certain expected /// attribute values). /// /// /// <para> /// You can also return the item's attribute values in the same <code>UpdateItem</code> /// operation using the <code>ReturnValues</code> parameter. /// </para> /// </summary> /// <param name="tableName">The name of the table containing the item to update.</param> /// <param name="key">The primary key of the item to be updated. Each element consists of an attribute name and a value for that attribute. For the primary key, you must provide all of the attributes. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide values for both the partition key and the sort key.</param> /// <param name="attributeUpdates">This is a legacy parameter. Use <code>UpdateExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributeUpdates.html">AttributeUpdates</a> in the <i>Amazon DynamoDB Developer Guide</i>.</param> /// <param name="returnValues">Use <code>ReturnValues</code> if you want to get the item attributes as they appear before or after they are updated. For <code>UpdateItem</code>, the valid values are: <ul> <li> <code>NONE</code> - If <code>ReturnValues</code> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <code>ReturnValues</code>.) </li> <li> <code>ALL_OLD</code> - Returns all of the attributes of the item, as they appeared before the UpdateItem operation. </li> <li> <code>UPDATED_OLD</code> - Returns only the updated attributes, as they appeared before the UpdateItem operation. </li> <li> <code>ALL_NEW</code> - Returns all of the attributes of the item, as they appear after the UpdateItem operation. </li> <li> <code>UPDATED_NEW</code> - Returns only the updated attributes, as they appear after the UpdateItem operation. </li> </ul> There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed. The values returned are strongly consistent.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItem">REST API Reference for UpdateItem Operation</seealso> Task<UpdateItemResponse> UpdateItemAsync(string tableName, Dictionary<string, AttributeValue> key, Dictionary<string, AttributeValueUpdate> attributeUpdates, ReturnValue returnValues, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Edits an existing item's attributes, or adds a new item to the table if it does not /// already exist. You can put, delete, or add attribute values. You can also perform /// a conditional update on an existing item (insert a new attribute name-value pair if /// it doesn't exist, or replace an existing name-value pair if it has certain expected /// attribute values). /// /// /// <para> /// You can also return the item's attribute values in the same <code>UpdateItem</code> /// operation using the <code>ReturnValues</code> parameter. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateItem service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateItem service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException"> /// A condition specified in the operation could not be evaluated. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException"> /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException"> /// Your request rate is too high. The Amazon Web Services SDKs for DynamoDB automatically /// retry requests that receive this exception. Your request is eventually successful, /// unless your retry queue is too large to finish. Reduce the frequency of requests and /// use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.RequestLimitExceededException"> /// Throughput exceeds the current throughput quota for your account. Please contact <a /// href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a /// quota increase. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.TransactionConflictException"> /// Operation was rejected because there is an ongoing transaction for the item. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItem">REST API Reference for UpdateItem Operation</seealso> Task<UpdateItemResponse> UpdateItemAsync(UpdateItemRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateTable /// <summary> /// Modifies the provisioned throughput settings, global secondary indexes, or DynamoDB /// Streams settings for a given table. /// /// /// <para> /// You can only perform one of the following operations at once: /// </para> /// <ul> <li> /// <para> /// Modify the provisioned throughput settings of the table. /// </para> /// </li> <li> /// <para> /// Enable or disable DynamoDB Streams on the table. /// </para> /// </li> <li> /// <para> /// Remove a global secondary index from the table. /// </para> /// </li> <li> /// <para> /// Create a new global secondary index on the table. After the index begins backfilling, /// you can use <code>UpdateTable</code> to perform other operations. /// </para> /// </li> </ul> /// <para> /// <code>UpdateTable</code> is an asynchronous operation; while it is executing, the /// table status changes from <code>ACTIVE</code> to <code>UPDATING</code>. While it is /// <code>UPDATING</code>, you cannot issue another <code>UpdateTable</code> request. /// When the table returns to the <code>ACTIVE</code> state, the <code>UpdateTable</code> /// operation is complete. /// </para> /// </summary> /// <param name="tableName">The name of the table to be updated.</param> /// <param name="provisionedThroughput">The new provisioned throughput settings for the specified table or index.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTable">REST API Reference for UpdateTable Operation</seealso> Task<UpdateTableResponse> UpdateTableAsync(string tableName, ProvisionedThroughput provisionedThroughput, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Modifies the provisioned throughput settings, global secondary indexes, or DynamoDB /// Streams settings for a given table. /// /// /// <para> /// You can only perform one of the following operations at once: /// </para> /// <ul> <li> /// <para> /// Modify the provisioned throughput settings of the table. /// </para> /// </li> <li> /// <para> /// Enable or disable DynamoDB Streams on the table. /// </para> /// </li> <li> /// <para> /// Remove a global secondary index from the table. /// </para> /// </li> <li> /// <para> /// Create a new global secondary index on the table. After the index begins backfilling, /// you can use <code>UpdateTable</code> to perform other operations. /// </para> /// </li> </ul> /// <para> /// <code>UpdateTable</code> is an asynchronous operation; while it is executing, the /// table status changes from <code>ACTIVE</code> to <code>UPDATING</code>. While it is /// <code>UPDATING</code>, you cannot issue another <code>UpdateTable</code> request. /// When the table returns to the <code>ACTIVE</code> state, the <code>UpdateTable</code> /// operation is complete. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateTable service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateTable service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTable">REST API Reference for UpdateTable Operation</seealso> Task<UpdateTableResponse> UpdateTableAsync(UpdateTableRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateTableReplicaAutoScaling /// <summary> /// Updates auto scaling settings on your global tables at once. /// /// <note> /// <para> /// This operation only applies to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html">Version /// 2019.11.21</a> of global tables. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateTableReplicaAutoScaling service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateTableReplicaAutoScaling service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTableReplicaAutoScaling">REST API Reference for UpdateTableReplicaAutoScaling Operation</seealso> Task<UpdateTableReplicaAutoScalingResponse> UpdateTableReplicaAutoScalingAsync(UpdateTableReplicaAutoScalingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateTimeToLive /// <summary> /// The <code>UpdateTimeToLive</code> method enables or disables Time to Live (TTL) for /// the specified table. A successful <code>UpdateTimeToLive</code> call returns the current /// <code>TimeToLiveSpecification</code>. It can take up to one hour for the change to /// fully process. Any additional <code>UpdateTimeToLive</code> calls for the same table /// during this one hour duration result in a <code>ValidationException</code>. /// /// /// <para> /// TTL compares the current time in epoch time format to the time stored in the TTL attribute /// of an item. If the epoch time value stored in the attribute is less than the current /// time, the item is marked as expired and subsequently deleted. /// </para> /// <note> /// <para> /// The epoch time format is the number of seconds elapsed since 12:00:00 AM January /// 1, 1970 UTC. /// </para> /// </note> /// <para> /// DynamoDB deletes expired items on a best-effort basis to ensure availability of throughput /// for other data operations. /// </para> /// <important> /// <para> /// DynamoDB typically deletes expired items within two days of expiration. The exact /// duration within which an item gets deleted after expiration is specific to the nature /// of the workload. Items that have expired and not been deleted will still show up in /// reads, queries, and scans. /// </para> /// </important> /// <para> /// As items are deleted, they are removed from any local secondary index and global secondary /// index immediately in the same eventually consistent way as a standard delete operation. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html">Time /// To Live</a> in the Amazon DynamoDB Developer Guide. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateTimeToLive service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the UpdateTimeToLive service method, as returned by DynamoDB.</returns> /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException"> /// An error occurred on the server side. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.LimitExceededException"> /// There is no limit to the number of daily on-demand backups that can be taken. /// /// /// <para> /// Up to 50 simultaneous table operations are allowed per account. These operations include /// <code>CreateTable</code>, <code>UpdateTable</code>, <code>DeleteTable</code>,<code>UpdateTimeToLive</code>, /// <code>RestoreTableFromBackup</code>, and <code>RestoreTableToPointInTime</code>. /// </para> /// /// <para> /// The only exception is when you are creating a table with one or more secondary indexes. /// You can have up to 25 such requests running at a time; however, if the table or index /// specifications are complex, DynamoDB might temporarily reduce the number of concurrent /// operations. /// </para> /// /// <para> /// There is a soft account quota of 256 tables. /// </para> /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceInUseException"> /// The operation conflicts with the resource's availability. For example, you attempted /// to recreate an existing table, or tried to delete a table currently in the <code>CREATING</code> /// state. /// </exception> /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException"> /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be <code>ACTIVE</code>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTimeToLive">REST API Reference for UpdateTimeToLive Operation</seealso> Task<UpdateTimeToLiveResponse> UpdateTimeToLiveAsync(UpdateTimeToLiveRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
58.599281
3,568
0.635551
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/DynamoDBv2/Generated/_netstandard/IAmazonDynamoDB.cs
309,598
C#
using System; namespace Algorithms { public class GcdClass { public GcdClass() { } /// <summary> /// 最大公約数を返す /// </summary> /// <param name="a">整数1</param> /// <param name="b">整数2</param> /// <returns>最大公約数</returns> public static int Gcd(int a, int b) { if (a < b) // 引数を入替えて自分を呼び出す return Gcd(b, a); while (b != 0) { var remainder = a % b; a = b; b = remainder; } return a; } } }
20.419355
43
0.371248
[ "MIT" ]
riko-yyy/Algorithms
Algorithms/GcdClass.cs
697
C#
using Newtonsoft.Json; namespace PddOpenSdk.Models.Request.DdkTools { public partial class DetailDdkOauthGoodsRequestModel : PddRequestModel { /// <summary> /// 自定义参数,为链接打上自定义标签;自定义参数最长限制64个字节;格式为: {"uid":"11111","sid":"22222"} ,其中 uid 用户唯一标识,可自行加密后传入,每个用户仅且对应一个标识,必填; sid 上下文信息标识,例如sessionId等,非必填。该json字符串中也可以加入其他自定义的key。(如果使用GET请求,请使用URLEncode处理参数) /// </summary> [JsonProperty("custom_parameters")] public string CustomParameters { get; set; } /// <summary> /// 商品主图类型:1-场景图,2-白底图,默认为0 /// </summary> [JsonProperty("goods_img_type")] public int? GoodsImgType { get; set; } /// <summary> /// 商品goodsSign,支持通过goodsSign查询商品。goodsSign是加密后的goodsId, goodsId已下线,请使用goodsSign来替代。使用说明:https://jinbao.pinduoduo.com/qa-system?questionId=252 /// </summary> [JsonProperty("goods_sign")] public string GoodsSign { get; set; } /// <summary> /// 推广位id /// </summary> [JsonProperty("pid")] public string Pid { get; set; } /// <summary> /// 搜索id,建议填写,提高收益。来自pdd.ddk.goods.recommend.get、pdd.ddk.goods.search、pdd.ddk.top.goods.list.query等接口 /// </summary> [JsonProperty("search_id")] public string SearchId { get; set; } /// <summary> /// 招商多多客ID /// </summary> [JsonProperty("zs_duo_id")] public long? ZsDuoId { get; set; } } }
36.675
202
0.603272
[ "Apache-2.0" ]
niltor/open-pdd-net-sdk
PddOpenSdk/PddOpenSdk/Models/Request/DdkTools/DetailDdkOauthGoodsRequestModel.cs
1,861
C#
namespace _05._BarrackWars_Return_of_the_Dependencies.Models.Units { public class Archer : Unit { private const int DefaultHealth = 25; private const int DefaultDamage = 7; public Archer() : base(DefaultHealth, DefaultDamage) { } } }
23
67
0.615385
[ "MIT" ]
thelad43/CSharp-OOP-Advanced-SoftUni
08. Reflection and Attributes - Exercise/05. BarrackWars - Return of the Dependencies/Models/Units/Archer.cs
301
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SharpDX; using Fusion; using Fusion.Mathematics; using Fusion.Graphics; namespace Fusion.Graphics { public struct VertexColorTextureTBN { [Vertex("POSITION")] public Vector3 Position; [Vertex("TANGENT")] public Half4 Tangent ; [Vertex("BINORMAL")] public Half4 Binormal; [Vertex("NORMAL")] public Half4 Normal ; [Vertex("COLOR")] public Color Color ; [Vertex("TEXCOORD")] public Vector2 TexCoord; static public VertexInputElement[] Elements { get { return VertexInputElement.FromStructure( typeof(VertexColorTextureTBN) ); } } public static VertexColorTextureTBN Convert ( MeshVertex meshVertex ) { VertexColorTextureTBN v; v.Position = meshVertex.Position; v.Tangent = MathUtil.ToHalf4( meshVertex.Tangent, 0 ); v.Binormal = MathUtil.ToHalf4( meshVertex.Binormal, 0 ); v.Normal = MathUtil.ToHalf4( meshVertex.Normal, 0 ); v.Color = meshVertex.Color0; v.TexCoord = meshVertex.TexCoord0; return v; } } }
26.731707
77
0.729015
[ "MIT" ]
demiurghg/FusionFramework
Fusion/Graphics/Scene/VertexColorTextureTBN.cs
1,098
C#
using System; using System.Threading.Tasks; using Server.Core.Common.Repositories.Lists; namespace Server.Core.Common.Workflow.CheckUserListExists { /// <summary> /// Проверка на существование пользовательского списка. /// </summary> public class CheckUserListExistsStep:StepBase<CheckUserListExistsParams> { /// <summary> /// Реализация исполнения шага. /// </summary> /// <param name="state">Параметры шага.</param> /// <returns>Результат действия.</returns> public override async Task<StepResult> Execute(CheckUserListExistsParams state) { Guid listId; if (!Guid.TryParse(state.ListId, out listId)) { return ToFinish<UserListNotFoundStep>(); } var exists = await StartEnumServer.Instance.GetRepository<IListRepository>() .ActiveListExists(listId, state.User.PortalUserID); if (!exists) { return ToFinish<UserListNotFoundStep>(); } return Success(); } } }
29.157895
88
0.600181
[ "MIT" ]
alexs0ff/spisker
Server.Core/Server.Core.Common/Workflow/CheckUserListExists/CheckUserListExistsStep.cs
1,210
C#
using System; using System.Configuration; using System.Configuration.Provider; using System.Linq; using System.Web.Configuration; using System.Web.Security; using Microsoft.VisualStudio.TestTools.UnitTesting; using BirdBrain; using Raven.Client.Linq; using Role = BirdBrain.Role; namespace BirdBrainTest { [TestClass] public class RoleProviderTest { private EmbeddedBirdBrainRoleProvider provider; private EmbeddedBirdBrainMembershipProvider membershipProvider; [TestInitialize] public void Setup() { membershipProvider = new EmbeddedBirdBrainMembershipProvider(); provider = new EmbeddedBirdBrainRoleProvider(); var section = (MembershipSection)ConfigurationManager.GetSection("system.web/membership"); var config = section.Providers["BirdBrainMembership"].Parameters; membershipProvider.Initialize("MyApp", config); provider.Initialize("MyApp", config); membershipProvider.DocumentStore = provider.DocumentStore; } [TestCleanup] public void Cleanup() { membershipProvider.Dispose(); provider.Dispose(); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Role name can not be empty")] public void CreateRoleShouldThrowArgumentExceptionWhenRoleNameIsEmpty() { provider.CreateRole(""); } [TestMethod] [ExpectedException(typeof(ArgumentNullException), "Role name can not be null")] public void CreateRoleShouldThrowArgumentNullExceptionWhenRoleNameIsNull() { provider.CreateRole(null); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Role name can not have a comma in it")] public void CreateRoleShouldThrowArgumentNullExceptionWhenRoleNameHasComma() { provider.CreateRole("hi,there"); } [TestMethod] [ExpectedException(typeof (ProviderException), "Roles cannot be duplicate.")] public void CreateRoleShouldThrowProviderExceptionWhenRoleNameIsDuplicate() { provider.CreateRole("role 1"); provider.CreateRole("role 1"); } [TestMethod] public void CreateRoleShouldCreateUserWhenRoleNameIsValid() { provider.CreateRole("test role"); var session = provider.DocumentStore.OpenSession(); var roles = from role in session.Query<Role>() where role.Name == "test role" select role; Assert.AreEqual(1, roles.Count()); } [TestMethod] public void GetAllRolesShouldReturnEmptyRoleNamesWhenThereAreNoRoles() { string[] roleNames = provider.GetAllRoles(); Assert.AreEqual(0, roleNames.Count()); } [TestMethod] public void GetAllRolesShouldReturnListOfRoleNames() { provider.CreateRole("role 1"); provider.CreateRole("role 2"); string[] roleNames = provider.GetAllRoles(); Assert.AreEqual(2, roleNames.Count()); Assert.AreEqual("role 1", roleNames[0]); Assert.AreEqual("role 2", roleNames[1]); } [TestMethod] [ExpectedException(typeof(ArgumentNullException), "Role name can not be null")] public void RoleExistsShouldThrowArgumentNullExceptionWhenRoleNameIsNull() { provider.RoleExists(null); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Role name can not be empty")] public void RoleExistsShouldThrowArgumentExceptionWhenRoleNameIsEmpty() { provider.RoleExists(""); } [TestMethod] public void RoleExistsShouldReturnTrueWhenRoleNameExists() { provider.CreateRole("my new new role"); Assert.IsTrue(provider.RoleExists("my new new role")); } [TestMethod] public void RoleExistsShouldReturnFalseWhenRoleNameDoesNotExist() { provider.CreateRole("my role"); Assert.IsFalse(provider.RoleExists("my role1")); } [TestMethod] [ExpectedException(typeof(ArgumentNullException), "Username can not be null")] public void AddUsersToRolesShouldThrowArgumentNullExceptionWhenAnyOfUserNamesIsNull() { var userNames = new string[] {"user 1", "user 2", null}; var roleNames = new string[] {"role 1", "role 2"}; provider.AddUsersToRoles(userNames, roleNames); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Username can not be empty")] public void AddUsersToRolesShouldThrowArgumentExceptionWhenAnyOfUserNamesIsEmpty() { var userNames = new string[] { "user 1", "user 2", "" }; var roleNames = new string[] { "role 1", "role 2" }; provider.AddUsersToRoles(userNames, roleNames); } [TestMethod] [ExpectedException(typeof(ArgumentNullException), "Role name can not be null")] public void AddUsersToRolesShouldThrowArgumentNullExceptionWhenAnyOfRoleNamesIsNull() { var userNames = new string[] { "user 1", "user 2", "user 3" }; var roleNames = new string[] { "role 1", null }; provider.AddUsersToRoles(userNames, roleNames); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Role name can not be empty")] public void AddUsersToRolesShouldThrowArgumentExceptionWhenAnyOfRoleNamesIsEmpty() { var userNames = new string[] { "user 1", "user 2", "user 3" }; var roleNames = new string[] { "role 1", "" }; provider.AddUsersToRoles(userNames, roleNames); } [TestMethod] public void AddUsersToRolesShouldAssociateTheRolesToTheUsers() { MembershipCreateStatus status; membershipProvider.CreateUser("test", "password", "derp@herp.com", "Is this a test?", "yes", true, null, out status); provider.CreateRole("role 1"); provider.AddUsersToRoles(new string[] {"test"}, new string[] {"role 1"}); using (var session = provider.DocumentStore.OpenSession()) { var users = from user in session.Query<User>() where user.Username == "test" select user; var _array = users.ToArray(); Assert.AreEqual("role 1", _array.First().Roles[0]); } } [TestMethod] public void ShouldKnowUserIsInRole() { MembershipCreateStatus status; membershipProvider.CreateUser("test", "password", "derp@herp.com", "Is this a test?", "yes", true, null, out status); provider.CreateRole("role 1"); provider.AddUsersToRoles(new string[] { "test" }, new string[] { "role 1" }); Assert.IsTrue(provider.IsUserInRole("test", "role 1")); } [TestMethod] public void ShouldKnowHowToGetRolesForAUser() { MembershipCreateStatus status; membershipProvider.CreateUser("test", "password", "derp@herp.com", "Is this a test?", "yes", true, null, out status); var roles = new string[] {"role 1", "role 2"}; provider.CreateRole(roles[0]); provider.CreateRole(roles[1]); provider.AddUsersToRoles(new string[] { "test" }, roles); var userRoles = provider.GetRolesForUser("test"); foreach (string role in roles) { Assert.IsTrue(userRoles.Contains(role), string.Format("User roles [{0}] should contain the role [{1}].", string.Join(", ", userRoles), role)); } } [TestMethod] public void ShouldKnowHowToGetUsersInRole() { MembershipCreateStatus status; membershipProvider.CreateUser("test", "password", "derp@herp.com", "Is this a test?", "yes", true, null, out status); membershipProvider.CreateUser("real", "anotherpassword", "err@herp.com", "What Is that?", "Derp", true, null, out status); const string role = "role 1"; provider.CreateRole(role); var expectedUsers = new string[] {"test", "real"}; provider.AddUsersToRoles(expectedUsers, new string[] {role}); var usersInARole = provider.GetUsersInRole(role); foreach (var user in expectedUsers) { Assert.IsTrue(usersInARole.Contains(user), string.Format("Role [{0}] should contain the users [{1}].", role, string.Join(", ", expectedUsers))); } } [TestMethod] [ExpectedException(typeof(ProviderException), "Expected <ProviderException> when role does not exist.")] public void ShouldKnowThatUsersCannotBeFoundForNonexistantRoles() { MembershipCreateStatus status; membershipProvider.CreateUser("test", "password", "derp@herp.com", "Is this a test?", "yes", true, null, out status); provider.FindUsersInRole("nonexistant role", "test"); } [TestMethod] public void ShouldKnowThatUserCanBeFoundForRole() { MembershipCreateStatus status; membershipProvider.CreateUser("test", "password", "derp@herp.com", "Is this a test?", "yes", true, null, out status); provider.CreateRole("role"); provider.AddUsersToRoles(new string[] {"test"}, new string[] { "role" }); Assert.AreEqual("test", provider.FindUsersInRole("role", "test").First()); } [TestMethod] public void ShouldKnowThatNonexistantUserCannotBeFoundForRole() { provider.CreateRole("role"); Assert.AreEqual(0, provider.FindUsersInRole("role", "test").Length); } [TestMethod] public void ShouldKnowHowToRemoveUsersFromRoles() { MembershipCreateStatus status; membershipProvider.CreateUser("test", "password", "derp@herp.com", "Is this a test?", "yes", true, null, out status); membershipProvider.CreateUser("real", "anotherpassword", "err@herp.com", "What Is that?", "Derp", true, null, out status); const string role = "role 1"; provider.CreateRole(role); var expectedUsers = new string[] { "test", "real" }; provider.AddUsersToRoles(expectedUsers, new string[] { role }); provider.RemoveUsersFromRoles(expectedUsers, new string[] { role }); Assert.AreEqual(0, provider.GetUsersInRole(role).Length); } [TestMethod] [ExpectedException(typeof (ProviderException), "Expected <ProviderException> when user does not exist.")] public void ShouldThrowProviderExceptionWhenRoleNameOrUserNameIsNotExistant() { provider.CreateRole("role"); provider.RemoveUsersFromRoles(new string[] {"a name"}, new string[] {"role"}); } [TestMethod] public void ShouldKnowHowToDeleteRoleWithUsers() { MembershipCreateStatus status; membershipProvider.CreateUser("test", "password", "derp@herp.com", "Is this a test?", "yes", true, null, out status); membershipProvider.CreateUser("real", "anotherpassword", "err@herp.com", "What Is that?", "Derp", true, null, out status); const string role = "role 1"; provider.CreateRole(role); var expectedUsers = new string[] { "test", "real" }; provider.AddUsersToRoles(expectedUsers, new string[] { role }); Assert.IsTrue(provider.DeleteRole(role, false)); } } }
41.859649
160
0.609975
[ "BSD-3-Clause" ]
ThoughtWorksZA/birdbrain
BirdBrainTest/RoleProviderTest.cs
11,932
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. namespace Stride.Input { /// <summary> /// An event to describe a change in game controller direction state /// </summary> public class GameControllerDirectionEvent : InputEvent { /// <summary> /// The index of the direction controller /// </summary> public int Index; /// <summary> /// The new direction /// </summary> public Direction Direction; /// <summary> /// The gamepad that sent this event /// </summary> public IGameControllerDevice GameController => (IGameControllerDevice)Device; public override string ToString() { return $"{nameof(Index)}: {Index} ({GameController.DirectionInfos[Index].Name}), {nameof(Direction)}: {Direction} ({GetDirectionFriendlyName()}), {nameof(GameController)}: {GameController.Name}"; } private string GetDirectionFriendlyName() { if (Direction.IsNeutral) return "Neutral"; switch (Direction.GetTicks(8)) { case 0: return "Up"; case 1: return "RightUp"; case 2: return "Right"; case 3: return "RightDown"; case 4: return "Down"; case 5: return "LeftDown"; case 6: return "Left"; case 7: return "LeftUp"; default: return "Out of range"; } } } }
33.155172
207
0.513261
[ "MIT" ]
Alan-love/xenko
sources/engine/Stride.Input/GameControllerDirectionEvent.cs
1,923
C#
 /* c Siemens AG, 2017-2018 Author: Dr. Martin Bischoff (martin.bischoff@siemens.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. */ using System; using System.Collections.Generic; using System.Linq; namespace RosSharp.RosBridgeClient { public static class MessageTypes { public static readonly Dictionary<string, Type> Dictionary = new Dictionary<string, Type> { { "geometry_msgs/Twist", typeof(GeometryTwist) }, { "std_msgs/String", typeof(StandardString) }, { "geometry_msgs/Accel", typeof(GeometryAccel) }, { "sensor_msgs/JointState", typeof(SensorJointStates) }, { "geometry_msgs/Vector3", typeof(GeometryVector3) }, { "sensor_msgs/Joy", typeof(SensorJoy) }, { "nav_msgs/Odometry", typeof(NavigationOdometry) }, { "std_msgs/Header", typeof(StandardHeader) }, { "geometry_msgs/PoseWithCovariance",typeof(GeometryPoseWithCovariance) }, { "geometry_msgs/TwistWithCovariance", typeof(GeometryTwistWithCovariance) }, { "geometry_msgs/Pose", typeof(GeometryPose) }, { "geometry_msgs/PoseStamped", typeof(GeometryPoseStamped) }, { "geometry_msgs/Point", typeof(GeometryPoint) }, { "geometry_msgs/Quaternion",typeof(GeometryQuaternion) }, { "move_base_msgs/MoveBaseGoal",typeof(MoveBaseGoal) }, { "move_base_msgs/MoveBaseActionGoal",typeof(MoveBaseActionGoal) }, { "sensor_msgs/PointCloud2",typeof(SensorPointCloud2) }, { "sensor_msgs/PointField", typeof(SensorPointField) }, { "sensor_msgs/Image", typeof(SensorImage) }, { "sensor_msgs/CompressedImage", typeof(SensorCompressedImage) }, { "std_msgs/Time", typeof(StandardTime) }, { "nav_msgs/MapMetaData", typeof(NavigationMapMetaData) }, { "nav_msgs/OccupancyGrid", typeof(NavigationOccupancyGrid)}, { "nav_msgs/Path", typeof(PathPlan)}, { "geometry_msgs/Transform", typeof(GeometryTransform)}, { "geometry_msgs/TransformStamped", typeof(GeometryTransformStamped)}, { "tf2_msgs/TFMessage", typeof(TF2TFMessage)}, { "visualization_msgs/Marker", typeof (Marker)}, { "visualization_msgs/MarkerArray", typeof (MarkerArray) }, { "darknet_ros_msgs/BoundingBoxes",typeof(BoundingBoxes)}, //add { "darknet_ros_msgs/BoundingBox",typeof(BoundingBox) }, //add {"std_msgs/Int32",typeof(int32) }, //add { "std_msgs/ColorRGBA", typeof (ColorRGBA) } }; public static string RosMessageType(Type messageType) { return Dictionary.FirstOrDefault(x => x.Value == messageType).Key; } public static Type MessageType(string rosMessageType) { Type messageType; Dictionary.TryGetValue(rosMessageType, out messageType); return messageType; } } }
42.634146
97
0.65532
[ "Apache-2.0" ]
EmergentSystemLabStudent/HSR-ros-sharp
RosBridgeClient/Shared/MessageTypes.cs
3,498
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Cognito.Inputs { public sealed class UserPoolVerificationMessageTemplateGetArgs : Pulumi.ResourceArgs { /// <summary> /// Default email option. Must be either `CONFIRM_WITH_CODE` or `CONFIRM_WITH_LINK`. Defaults to `CONFIRM_WITH_CODE`. /// </summary> [Input("defaultEmailOption")] public Input<string>? DefaultEmailOption { get; set; } /// <summary> /// Email message template. Must contain the `{####}` placeholder. Conflicts with `email_verification_message` argument. /// </summary> [Input("emailMessage")] public Input<string>? EmailMessage { get; set; } /// <summary> /// Email message template for sending a confirmation link to the user, it must contain the `{##Click Here##}` placeholder. /// </summary> [Input("emailMessageByLink")] public Input<string>? EmailMessageByLink { get; set; } /// <summary> /// Subject line for the email message template. Conflicts with `email_verification_subject` argument. /// </summary> [Input("emailSubject")] public Input<string>? EmailSubject { get; set; } /// <summary> /// Subject line for the email message template for sending a confirmation link to the user. /// </summary> [Input("emailSubjectByLink")] public Input<string>? EmailSubjectByLink { get; set; } /// <summary> /// SMS message template. Must contain the `{####}` placeholder. Conflicts with `sms_verification_message` argument. /// </summary> [Input("smsMessage")] public Input<string>? SmsMessage { get; set; } public UserPoolVerificationMessageTemplateGetArgs() { } } }
37.553571
131
0.638612
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Cognito/Inputs/UserPoolVerificationMessageTemplateGetArgs.cs
2,103
C#
// 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; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.Xml; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Thrift.Collections; namespace Thrift.Tests.Collections { // ReSharper disable once InconsistentNaming [TestClass] public class TCollectionsTests { //TODO: Add tests for IEnumerable with objects and primitive values inside [TestMethod] public void TCollection_List_Equals_Primitive_Test() { var collection1 = new List<int> {1,2,3}; var collection2 = new List<int> {1,2,3}; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_List_Equals_Primitive_Different_Test() { var collection1 = new List<int> { 1, 2, 3 }; var collection2 = new List<int> { 1, 2 }; Assert.IsFalse(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); collection2.Add(4); Assert.IsFalse(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_List_Equals_Objects_Test() { var collection1 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; var collection2 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_List_List_Equals_Objects_Test() { var collection1 = new List<List<ExampleClass>> { new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } } }; var collection2 = new List<List<ExampleClass>> { new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } } }; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); // SequenceEqual() calls Equals() of the inner list instead of SequenceEqual() } [TestMethod] public void TCollection_List_Equals_OneAndTheSameObject_Test() { var collection1 = new List<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; var collection2 = collection1; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_Set_Equals_Primitive_Test() { var collection1 = new HashSet<int> {1,2,3}; var collection2 = new HashSet<int> {1,2,3}; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_Set_Equals_Primitive_Different_Test() { var collection1 = new HashSet<int> { 1, 2, 3 }; var collection2 = new HashSet<int> { 1, 2 }; Assert.IsFalse(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); collection2.Add(4); Assert.IsFalse(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_Set_Equals_Objects_Test() { var collection1 = new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; var collection2 = new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_Set_Set_Equals_Objects_Test() { var collection1 = new HashSet<HashSet<ExampleClass>> { new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } } }; var collection2 = new HashSet<HashSet<ExampleClass>> { new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } } }; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); // SequenceEqual() calls Equals() of the inner list instead of SequenceEqual() } [TestMethod] public void TCollection_Set_Equals_OneAndTheSameObject_Test() { var collection1 = new HashSet<ExampleClass> { new ExampleClass { X = 1 }, new ExampleClass { X = 2 } }; var collection2 = collection1; // references to one and the same collection Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_Map_Equals_Primitive_Test() { var collection1 = new Dictionary<int, int> { [1] = 1, [2] = 2, [3] = 3 }; var collection2 = new Dictionary<int, int> { [1] = 1, [2] = 2, [3] = 3 }; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_Map_Equals_Primitive_Different_Test() { var collection1 = new Dictionary<int, int> { [1] = 1, [2] = 2, [3] = 3 }; var collection2 = new Dictionary<int, int> { [1] = 1, [2] = 2 }; Assert.IsFalse(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); collection2[3] = 3; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); collection2[3] = 4; Assert.IsFalse(TCollections.Equals(collection1, collection2)); } [TestMethod] public void TCollection_Map_Equals_Objects_Test() { var collection1 = new Dictionary<int, ExampleClass> { [1] = new ExampleClass { X = 1 }, [-1] = new ExampleClass { X = 2 } }; var collection2 = new Dictionary<int, ExampleClass> { [1] = new ExampleClass { X = 1 }, [-1] = new ExampleClass { X = 2 } }; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } [TestMethod] public void TCollection_Map_Map_Equals_Objects_Test() { var collection1 = new Dictionary<int, Dictionary<int, ExampleClass>> { [0] = new Dictionary<int, ExampleClass> { [1] = new ExampleClass { X = 1 }, [-1] = new ExampleClass { X = 2 } } }; var collection2 = new Dictionary<int, Dictionary<int, ExampleClass>> { [0] = new Dictionary<int, ExampleClass> { [1] = new ExampleClass { X = 1 }, [-1] = new ExampleClass { X = 2 } } }; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsFalse(collection1.SequenceEqual(collection2)); // SequenceEqual() calls Equals() of the inner list instead of SequenceEqual() } [TestMethod] public void TCollection_Map_Equals_OneAndTheSameObject_Test() { var collection1 = new Dictionary<int, ExampleClass> { [1] = new ExampleClass { X = 1 }, [-1] = new ExampleClass { X = 2 } }; var collection2 = collection1; Assert.IsTrue(TCollections.Equals(collection1, collection2)); Assert.IsTrue(collection1.SequenceEqual(collection2)); } private class ExampleClass { public int X { get; set; } // all Thrift-generated classes override Equals(), we do just the same public override bool Equals(object? that) { if (that is not ExampleClass other) return false; if (ReferenceEquals(this, other)) return true; return this.X == other.X; } // overriding Equals() requires GetHashCode() as well public override int GetHashCode() { int hashcode = 157; unchecked { hashcode = (hashcode * 397) + X.GetHashCode(); } return hashcode; } } } }
41.73444
154
0.602605
[ "Apache-2.0" ]
BearerPipelineTest/thrift
lib/netstd/Tests/Thrift.Tests/Collections/TCollectionsTests.cs
10,058
C#
namespace SharedTrip { using Microsoft.EntityFrameworkCore; using SharedTrip.Models; public class ApplicationDbContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<Trip> Trips { get; set; } public DbSet<UserTrip> UsersTrips { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer(DatabaseConfiguration.ConnectionString); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<UserTrip>(entity => { entity.HasKey(k => new { k.UserId, k.TripId }); }); } } }
26.21875
85
0.617402
[ "MIT" ]
ilkerBuguner/CSharp-Web
Pratical Exam - 16.02.2020/SharedTrip/Data/ApplicationDbContext.cs
841
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Dynamic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Z.Dapper.Plus; namespace Z.Test { public partial class Bulk_BulkAction_BulkInsert_SingleMixedSelector { [TestMethod] public void Z_Test_0035() { Helper.CleanDatabase(); var single1 = new SingleMany {ColumnInt = 1}; var single2 = new SingleMany {ColumnInt = 8}; var single3 = new SingleMany {ColumnInt = 64}; var many1 = new List<SingleMany> {new SingleMany {ColumnInt = 512}, new SingleMany {ColumnInt = 1024}, new SingleMany {ColumnInt = 2048}}; var many2 = new List<SingleMany> {new SingleMany {ColumnInt = 4096}, new SingleMany {ColumnInt = 8192}, new SingleMany {ColumnInt = 16384}}; var many3 = new List<SingleMany> {new SingleMany {ColumnInt = 32768}, new SingleMany {ColumnInt = 65536}, new SingleMany {ColumnInt = 131072}}; Helper.LinkSingleMany(single1, single2, single3, many1, many2, many3); Helper.InsertFromMetas("".Split(';').ToList(), single1, single2, single3, many1, many2, many3); Helper.UpdateFromMetas("".Split(';').ToList(), single1, single2, single3, many1, many2, many3); // GET count before int columnInt_before = 0; int columnUpdateInt_before = 0; int columnInt_Key_before = 0; int columnUpdateInt_Key_before = 0; using (var connection = Helper.GetConnection()) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany), 0)"; columnInt_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany), 0)"; columnUpdateInt_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany_Key), 0)"; columnInt_Key_before = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany_Key), 0)"; columnUpdateInt_Key_before = Convert.ToInt32(command.ExecuteScalar()); } } using (var cn = Helper.GetConnection()) { cn.Open(); // PreTest // Action cn.BulkInsert((SingleMany)null).BulkInsert(single1, x => x.Many2, x => x.Single2); } // GET count int columnInt = 0; int columnUpdateInt = 0; int columnInt_Key = 0; int columnUpdateInt_Key = 0; using (var connection = Helper.GetConnection()) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany), 0)"; columnInt = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany), 0)"; columnUpdateInt = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnInt) FROM SingleMany_Key), 0)"; columnInt_Key = Convert.ToInt32(command.ExecuteScalar()); command.CommandText = "SELECT ISNULL((SELECT SUM(ColumnUpdateInt) FROM SingleMany_Key), 0)"; columnUpdateInt_Key = Convert.ToInt32(command.ExecuteScalar()); } } // Test Assert.AreEqual(single1.ColumnInt + many2.Sum(x => x.ColumnInt) + single2.ColumnInt, columnInt); Assert.AreEqual(0, columnUpdateInt); Assert.AreEqual(0, columnInt_Key); Assert.AreEqual(0, columnUpdateInt_Key); } } }
41.475728
155
0.602294
[ "MIT" ]
VagrantKm/Dapper-Plus
src/test/Z.Test/Bulk_BulkAction/BulkInsert_SingleMixedSelector/0035.cs
4,272
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("XamarinForms.Client.Android")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XamarinForms.Client.Android")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // 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")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
37.171429
84
0.758647
[ "MIT" ]
1iveowl/CosmosResourceTokenBroker
src/sample/client/XamarinForms.Client/XamarinForms.Client.Android/Properties/AssemblyInfo.cs
1,304
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.MoveToNamespace { internal interface IMoveToNamespaceOptionsService : IWorkspaceService { MoveToNamespaceOptionsResult GetChangeNamespaceOptions( string defaultNamespace, ImmutableArray<string> availableNamespaces, ISyntaxFactsService syntaxFactsService); } }
37.117647
161
0.771791
[ "Apache-2.0" ]
20chan/roslyn
src/Features/Core/Portable/MoveToNamespace/IMoveToNamespaceOptionsService.cs
633
C#
using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using ServiceStack.Host; using ServiceStack.Text; using ServiceStack.Web; namespace ServiceStack.Testing { public class MockHttpResponse : IHttpResponse { public MockHttpResponse() { this.Headers = new NameValueCollection(); this.OutputStream = new MemoryStream(); this.TextWritten = new StringBuilder(); this.Cookies = new Cookies(this); } public object OriginalResponse { get; private set; } public int StatusCode { set; get; } public string StatusDescription { set; get; } public string ContentType { get; set; } public StringBuilder TextWritten { get; set; } public NameValueCollection Headers { get; set; } public ICookies Cookies { get; set; } public void AddHeader(string name, string value) { this.Headers.Add(name, value); } public void Redirect(string url) { this.Headers.Add(HttpHeaders.Location, url.MapServerPath()); } public Stream OutputStream { get; private set; } public void Write(string text) { this.TextWritten.Append(text); } public void Close() { this.IsClosed = true; } public void End() { Close(); } public void Flush() { OutputStream.Flush(); } public string ReadAsString() { if (!IsClosed) this.OutputStream.Seek(0, SeekOrigin.Begin); var bytes = ((MemoryStream)OutputStream).ToArray(); return bytes.FromUtf8Bytes(); } public byte[] ReadAsBytes() { if (!IsClosed) this.OutputStream.Seek(0, SeekOrigin.Begin); var ms = (MemoryStream)this.OutputStream; return ms.ToArray(); } public bool IsClosed { get; private set; } public void SetContentLength(long contentLength) { Headers[HttpHeaders.ContentLength] = contentLength.ToString(CultureInfo.InvariantCulture); } } }
27.447059
103
0.560223
[ "Apache-2.0" ]
PPPInc/ServiceStack
src/ServiceStack/Testing/MockHttpResponse.cs
2,249
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace RaptorDB { #region [ KeyStoreString ] public class RaptorDBString : IDisposable { public RaptorDBString(string filename, bool caseSensitve) { _db = KeyStore<int>.Open(filename, true); _caseSensitive = caseSensitve; } bool _caseSensitive = false; KeyStore<int> _db; public void Set(string key, string val) { Set(key, Encoding.Unicode.GetBytes(val)); } public void Set(string key, byte[] val) { string str = (_caseSensitive ? key : key.ToLower()); byte[] bkey = Encoding.Unicode.GetBytes(str); int hc = (int)Helper.MurMur.Hash(bkey); MemoryStream ms = new MemoryStream(); ms.Write(Helper.GetBytes(bkey.Length, false), 0, 4); ms.Write(bkey, 0, bkey.Length); ms.Write(val, 0, val.Length); _db.Set(hc, ms.ToArray()); } public bool Get(string key, out string val) { val = null; byte[] bval; bool b = Get(key, out bval); if (b) { val = Encoding.Unicode.GetString(bval); } return b; } public bool Get(string key, out byte[] val) { string str = (_caseSensitive ? key : key.ToLower()); val = null; byte[] bkey = Encoding.Unicode.GetBytes(str); int hc = (int)Helper.MurMur.Hash(bkey); if (_db.Get(hc, out val)) { // unpack data byte[] g = null; if (UnpackData(val, out val, out g)) { if (Helper.CompareMemCmp(bkey, g) != 0) { // if data not equal check duplicates (hash conflict) List<int> ints = new List<int>(_db.GetDuplicates(hc)); ints.Reverse(); foreach (int i in ints) { byte[] bb = _db.FetchRecordBytes(i); if (UnpackData(bb, out val, out g)) { if (Helper.CompareMemCmp(bkey, g) == 0) return true; } } return false; } return true; } } return false; } public int Count() { return (int)_db.Count(); } public int RecordCount() { return (int)_db.RecordCount(); } public bool RemoveKey(string key) { byte[] bkey = Encoding.Unicode.GetBytes(key); int hc = (int)Helper.MurMur.Hash(bkey); MemoryStream ms = new MemoryStream(); ms.Write(Helper.GetBytes(bkey.Length, false), 0, 4); ms.Write(bkey, 0, bkey.Length); return _db.Delete(hc, ms.ToArray()); } public void SaveIndex() { _db.SaveIndex(); } public void Shutdown() { _db.Shutdown(); } public void Dispose() { _db.Shutdown(); } private bool UnpackData(byte[] buffer, out byte[] val, out byte[] key) { int len = Helper.ToInt32(buffer, 0, false); key = new byte[len]; Buffer.BlockCopy(buffer, 4, key, 0, len); val = new byte[buffer.Length - 4 - len]; Buffer.BlockCopy(buffer, 4 + len, val, 0, buffer.Length - 4 - len); return true; } public string ReadData(int recnumber) { byte[] val; byte[] key; byte[] b = _db.FetchRecordBytes(recnumber); if (UnpackData(b, out val, out key)) { return Encoding.Unicode.GetString(val); } return ""; } } #endregion #region [ KeyStoreGuid ] public class RaptorDBGuid : IDisposable { public RaptorDBGuid(string filename) { _db = KeyStore<int>.Open(filename, true); } KeyStore<int> _db; public void Set(Guid key, string val) { Set(key, Encoding.Unicode.GetBytes(val)); } public int Set(Guid key, byte[] val) { byte[] bkey = key.ToByteArray(); int hc = (int)Helper.MurMur.Hash(bkey); MemoryStream ms = new MemoryStream(); ms.Write(Helper.GetBytes(bkey.Length, false), 0, 4); ms.Write(bkey, 0, bkey.Length); ms.Write(val, 0, val.Length); return _db.Set(hc, ms.ToArray()); } public bool Get(Guid key, out string val) { val = null; byte[] bval; bool b = Get(key, out bval); if (b) { val = Encoding.Unicode.GetString(bval); } return b; } public bool Get(Guid key, out byte[] val) { val = null; byte[] bkey = key.ToByteArray(); int hc = (int)Helper.MurMur.Hash(bkey); if (_db.Get(hc, out val)) { // unpack data byte[] g = null; if (UnpackData(val, out val, out g)) { if (Helper.CompareMemCmp(bkey, g) != 0) { // if data not equal check duplicates (hash conflict) List<int> ints = new List<int>(_db.GetDuplicates(hc)); ints.Reverse(); foreach (int i in ints) { byte[] bb = _db.FetchRecordBytes(i); if (UnpackData(bb, out val, out g)) { if (Helper.CompareMemCmp(bkey, g) == 0) return true; } } return false; } return true; } } return false; } public void SaveIndex() { _db.SaveIndex(); } public void Shutdown() { _db.Shutdown(); } public void Dispose() { _db.Shutdown(); } public byte[] FetchRecordBytes(int record) { return _db.FetchRecordBytes(record); } public int Count() { return (int)_db.Count(); } public int RecordCount() { return (int)_db.RecordCount(); } private bool UnpackData(byte[] buffer, out byte[] val, out byte[] key) { int len = Helper.ToInt32(buffer, 0, false); key = new byte[len]; Buffer.BlockCopy(buffer, 4, key, 0, len); val = new byte[buffer.Length - 4 - len]; Buffer.BlockCopy(buffer, 4 + len, val, 0, buffer.Length - 4 - len); return true; } internal byte[] Get(int recnumber, out Guid docid) { bool isdeleted = false; return Get(recnumber, out docid, out isdeleted); } public bool RemoveKey(Guid key) { byte[] bkey = key.ToByteArray(); int hc = (int)Helper.MurMur.Hash(bkey); MemoryStream ms = new MemoryStream(); ms.Write(Helper.GetBytes(bkey.Length, false), 0, 4); ms.Write(bkey, 0, bkey.Length); return _db.Delete(hc, ms.ToArray()); } internal byte[] Get(int recnumber, out Guid docid, out bool isdeleted) { docid = Guid.Empty; byte[] buffer = _db.FetchRecordBytes(recnumber, out isdeleted); if (buffer == null) return null; if (buffer.Length == 0) return null; byte[] key; byte[] val; // unpack data UnpackData(buffer, out val, out key); docid = new Guid(key); return val; } internal int CopyTo(StorageFile<int> backup, int start) { return _db.CopyTo(backup, start); } } #endregion public class KeyStore<T> : IDisposable where T : IComparable<T> { public KeyStore(string Filename, byte MaxKeySize, bool AllowDuplicateKeys) { Initialize(Filename, MaxKeySize, AllowDuplicateKeys); } public KeyStore(string Filename, bool AllowDuplicateKeys) { Initialize(Filename, Global.DefaultStringKeySize, AllowDuplicateKeys); } private ILog log = LogManager.GetLogger(typeof(KeyStore<T>)); private string _Path = ""; private string _FileName = ""; private byte _MaxKeySize; private StorageFile<T> _archive; private MGIndex<T> _index; private string _datExtension = ".mgdat"; private string _idxExtension = ".mgidx"; IGetBytes<T> _T = null; private System.Timers.Timer _savetimer; private BoolIndex _deleted; public static KeyStore<T> Open(string Filename, bool AllowDuplicateKeys) { return new KeyStore<T>(Filename, AllowDuplicateKeys); } public static KeyStore<T> Open(string Filename, byte MaxKeySize, bool AllowDuplicateKeys) { return new KeyStore<T>(Filename, MaxKeySize, AllowDuplicateKeys); } object _savelock = new object(); public void SaveIndex() { if (_index == null) return; lock (_savelock) { log.Debug("saving to disk"); _index.SaveIndex(); _deleted.SaveIndex(); log.Debug("index saved"); } } public IEnumerable<int> GetDuplicates(T key) { // get duplicates from index return _index.GetDuplicates(key); } public byte[] FetchRecordBytes(int record) { return _archive.ReadData(record); } public string FetchRecordString(int record) { byte[] b = _archive.ReadData(record); return Encoding.Unicode.GetString(b); } public IEnumerable<StorageData> EnumerateStorageFile() { return _archive.Enumerate(); } public IEnumerable<KeyValuePair<T, int>> Enumerate(T fromkey) { // generate a list from the start key using forward only pages return _index.Enumerate(fromkey); } public bool RemoveKey(T key) { // remove and store key in storage file byte[] bkey = _T.GetBytes(key); MemoryStream ms = new MemoryStream(); ms.Write(Helper.GetBytes(bkey.Length, false), 0, 4); ms.Write(bkey, 0, bkey.Length); return Delete(key, ms.ToArray()); } public long Count() { int c = _archive.Count(); return c - _deleted.GetBits().CountOnes() * 2; } public bool Get(T key, out string val) { byte[] b = null; val = ""; bool ret = Get(key, out b); if (ret) val = Encoding.Unicode.GetString(b); return ret; } public bool Get(T key, out byte[] val) { int off; val = null; T k = key; // search index if (_index.Get(k, out off)) { val = _archive.ReadData(off); return true; } return false; } public int Set(T key, string data) { return Set(key, Encoding.Unicode.GetBytes(data)); } public int Set(T key, byte[] data) { int recno = -1; // save to storage recno = _archive.WriteData(key, data, false); // save to index _index.Set(key, recno); return recno; } private object _shutdownlock = new object(); public void Shutdown() { lock (_shutdownlock) { if (_index != null) log.Debug("Shutting down"); else return; SaveIndex(); SaveLastRecord(); if (_deleted != null) _deleted.Shutdown(); if (_index != null) _index.Shutdown(); if (_archive != null) _archive.Shutdown(); _index = null; _archive = null; _deleted = null; log.Debug("Shutting down log"); LogManager.Shutdown(); } } public void Dispose() { Shutdown(); } #region [ P R I V A T E M E T H O D S ] private void SaveLastRecord() { // save the last record number in the index file _index.SaveLastRecordNumber(_archive.Count()); } private void Initialize(string filename, byte maxkeysize, bool AllowDuplicateKeys) { _MaxKeySize = RDBDataType<T>.GetByteSize(maxkeysize); _T = RDBDataType<T>.ByteHandler(); _Path = Path.GetDirectoryName(filename); Directory.CreateDirectory(_Path); _FileName = Path.GetFileNameWithoutExtension(filename); string db = _Path + Path.DirectorySeparatorChar + _FileName + _datExtension; string idx = _Path + Path.DirectorySeparatorChar + _FileName + _idxExtension; LogManager.Configure(_Path + Path.DirectorySeparatorChar + _FileName + ".txt", 500, false); _index = new MGIndex<T>(_Path, _FileName + _idxExtension, _MaxKeySize, Global.PageItemCount, AllowDuplicateKeys); _archive = new StorageFile<T>(db); _deleted = new BoolIndex(_Path, _FileName + "_deleted.idx"); _archive.SkipDateTime = true; log.Debug("Current Count = " + RecordCount().ToString("#,0")); CheckIndexState(); log.Debug("Starting save timer"); _savetimer = new System.Timers.Timer(); _savetimer.Elapsed += new System.Timers.ElapsedEventHandler(_savetimer_Elapsed); _savetimer.Interval = Global.SaveIndexToDiskTimerSeconds * 1000; _savetimer.AutoReset = true; _savetimer.Start(); } private void CheckIndexState() { log.Debug("Checking Index state..."); int last = _index.GetLastIndexedRecordNumber(); int count = _archive.Count(); if (last < count) { log.Debug("Rebuilding index..."); log.Debug(" last index count = " + last); log.Debug(" data items count = " + count); // check last index record and archive record // rebuild index if needed for (int i = last; i < count; i++) { bool deleted = false; T key = _archive.GetKey(i, out deleted); if (deleted == false) _index.Set(key, i); else _index.RemoveKey(key); if (i % 100000 == 0) log.Debug("100,000 items re-indexed"); } log.Debug("Rebuild index done."); } } void _savetimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { SaveIndex(); } #endregion internal int RecordCount() { return _archive.Count(); } internal byte[] FetchRecordBytes(int record, out bool isdeleted) { return _archive.ReadData(record, out isdeleted); } internal bool Delete(T id, byte[] data) { // write a delete record int rec = _archive.WriteData(id, data, true); _deleted.Set(true, rec); return _index.RemoveKey(id); } internal int CopyTo(StorageFile<int> storagefile, int start) { return _archive.CopyTo(storagefile, start); } } }
30.886726
126
0.462782
[ "MIT" ]
rasberry/HugeStructures
src/RaptorDB/KeyStore.cs
17,453
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Templates.Core.Naming; using Xunit; namespace Microsoft.Templates.Core.Test { [Collection("Unit Test Templates")] [Trait("ExecutionSet", "Minimum")] [Trait("Type", "Naming")] public class NamingTests { private readonly TemplatesFixture _fixture; public NamingTests(TemplatesFixture fixture) { _fixture = fixture; } [Fact] public void Infer_SuccessfullyAccountsForExistingNames() { Func<IEnumerable<string>> getExistingNames = () => { return new string[] { "App" }; }; var validators = new List<Validator> { new ExistingNamesValidator(getExistingNames) }; var result = NamingService.Infer("App", validators); Assert.Equal("App1", result); } [Fact] public void Infer_SuccessfullyAccountsForReservedNames() { var validators = new List<Validator> { new ReservedNamesValidator(new string[] { "Page" }) }; var result = NamingService.Infer("Page", validators); Assert.Equal("Page1", result); } [Theory] [MemberData(nameof(GetAllLanguages))] public void Infer_SuccessfullyAccountsForDefaultNames(string language) { SetUpFixtureForTesting(language); var validators = new List<Validator> { new DefaultNamesValidator() }; var result = NamingService.Infer("LiveTile", validators); Assert.Equal("LiveTile1", result); } [Fact] public void Infer_RemovesInvalidCharacters() { var result = NamingService.Infer("Blank$Page", new List<Validator>()); Assert.Equal("BlankPage", result); } [Fact] public void Infer_DoesNotRemoveNonAsciiCharacters() { var result = NamingService.Infer("ÑäöÜ!Page", new List<Validator>()); Assert.Equal("ÑäöÜPage", result); } [Fact] public void Infer_SuccessfullyHandlesSpacesAndConversionToTitleCase() { var result = NamingService.Infer("blank page", new List<Validator>()); Assert.Equal("BlankPage", result); } [Fact] public void Infer_SuccessfullyHandles_FileExistsValidator() { var testDirectory = Path.GetTempPath(); File.Create(Path.Combine(testDirectory, "TestFile")); var result = NamingService.Infer("TestFile", new List<Validator>() { new FileNameValidator(testDirectory) }); Assert.Equal("TestFile1", result); } [Fact] public void Infer_SuccessfullyHandles_SuggestedDirectoryNameValidator() { var testDirectory = Path.GetTempPath(); Directory.CreateDirectory(Path.Combine(testDirectory, "TestDir")); var result = NamingService.Infer("TestDir", new List<Validator>() { new FolderNameValidator(testDirectory) }); Assert.Equal("TestDir1", result); } [Theory] [MemberData(nameof(GetAllLanguages))] public void Validate_RecognizesValidNameAsValid(string language) { SetUpFixtureForTesting(language); var validators = new List<Validator>() { new EmptyNameValidator(), new RegExValidator(new RegExConfig() { Name = "badFormat", Pattern = "^((?!\\d)\\w+)$" }), }; var result = NamingService.Validate("Blank1", validators); Assert.True(result.IsValid); } [Fact] public void Validate_SuccessfullyIdentifiesReservedNames() { var validators = new List<Validator>() { new EmptyNameValidator(), new RegExValidator(new RegExConfig() { Name = "badFormat", Pattern = "^((?!\\d)\\w+)$" }), new ReservedNamesValidator(new string[] { "Page" }), }; var result = NamingService.Validate("Page", validators); Assert.False(result.IsValid); Assert.Equal(ValidationErrorType.ReservedName, result.Errors.FirstOrDefault()?.ErrorType); } [Fact] public void Validate_SuccessfullyIdentifies_InvalidChars() { var validators = new List<Validator>() { new EmptyNameValidator(), new RegExValidator(new RegExConfig() { Name = "badFormat", Pattern = "^((?!\\d)\\w+)$" }), }; var result = NamingService.Validate("Blank;", validators); Assert.False(result.IsValid); Assert.Equal(ValidationErrorType.Regex, result.Errors.FirstOrDefault()?.ErrorType); Assert.Equal("badFormat", result.Errors.FirstOrDefault()?.ValidatorName); } [Fact] public void Validate_SuccessfullyIdentifies_NamesThatStartWithNumbers() { var validators = new List<Validator>() { new EmptyNameValidator(), new RegExValidator(new RegExConfig() { Name = "badFormat", Pattern = "^((?!\\d)\\w+)$" }), }; var result = NamingService.Validate("1Blank", validators); Assert.False(result.IsValid); Assert.Equal(ValidationErrorType.Regex, result.Errors.FirstOrDefault()?.ErrorType); Assert.Equal("badFormat", result.Errors.FirstOrDefault()?.ValidatorName); } [Fact] public void Validate_SuccessfullyIdentifies_InvalidPageSuffix() { var validators = new List<Validator>() { new EmptyNameValidator(), new RegExValidator(new RegExConfig() { Name = "badFormat", Pattern = "^((?!\\d)\\w+)$" }), new RegExValidator(new RegExConfig() { Name = "itemEndsWithPage", Pattern = ".*(?<!page)$" }), }; var result = NamingService.Validate("BlankPage", validators); Assert.False(result.IsValid); Assert.Equal(ValidationErrorType.Regex, result.Errors.FirstOrDefault()?.ErrorType); Assert.Equal("itemEndsWithPage", result.Errors.FirstOrDefault()?.ValidatorName); } [Fact] public void Validate_SuccessfullyIdentifies_ValidPageSuffix() { var validators = new List<Validator>() { new EmptyNameValidator(), new RegExValidator(new RegExConfig() { Name = "badFormat", Pattern = "^((?!\\d)\\w+)$" }), new RegExValidator(new RegExConfig() { Name = "itemEndsWithPage", Pattern = ".*(?<!page)$" }), }; var result = NamingService.Validate("BlankView", validators); Assert.True(result.IsValid); Assert.Empty(result.Errors); } [Fact] public void Validate_SuccessfullyIdentifies_ReservedProjectName() { var validators = new List<Validator>() { new ReservedNamesValidator(new string[] { "Prism" }), }; var result = NamingService.Validate("Prism", validators); Assert.False(result.IsValid); Assert.Equal(ValidationErrorType.ReservedName, result.Errors.FirstOrDefault()?.ErrorType); } [Fact] public void Validate_SuccessfullyIdentifies_ProjectStartsWith() { var validators = new List<Validator>() { new RegExValidator(new RegExConfig() { Name = "projectStartWith$", Pattern = "^[^\\$]" }), }; var result = NamingService.Validate("$App", validators); Assert.False(result.IsValid); Assert.Equal(ValidationErrorType.Regex, result.Errors.FirstOrDefault()?.ErrorType); Assert.Equal("projectStartWith$", result.Errors.FirstOrDefault()?.ValidatorName); } [Fact] public void Validate_SuccessfullyIdentifies_ValidProjectName() { var validators = new List<Validator>() { new ReservedNamesValidator(new string[] { "Prism" }), new RegExValidator(new RegExConfig() { Name = "projectStartWith$", Pattern = "^[^\\$]" }), }; var result = NamingService.Validate("App", validators); Assert.True(result.IsValid); Assert.Empty(result.Errors); } private void SetUpFixtureForTesting(string language) { _fixture.InitializeFixture("test", language); } public static IEnumerable<object[]> GetAllLanguages() { foreach (var language in ProgrammingLanguages.GetAllLanguages()) { if (language != ProgrammingLanguages.Any) { yield return new object[] { language }; } } } } }
37.589641
123
0.567886
[ "MIT" ]
Microsoft/CoreTemplateStudio
code/test/CoreTemplateStudio.Core.Test/Naming/NamingTests.cs
9,195
C#
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using ZakupowoMobile.Services; using ZakupowoMobile.ViewModels; namespace ZakupowoMobile.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class RegistrationPage : ContentPage { public RegistrationPage() { InitializeComponent(); NavigationPage.SetHasNavigationBar(this, false); this.BindingContext = new RegistrationViewModel(); } private async void signUp_Clicked(object sender, EventArgs e) { if (string.IsNullOrEmpty(emailEntry.Text) || string.IsNullOrEmpty(loginEntry.Text) || string.IsNullOrEmpty(passwordEntry.Text) || string.IsNullOrEmpty(passwordRepeatEntry.Text) || string.IsNullOrEmpty(firstNameEntry.Text) || string.IsNullOrEmpty(lastNameEntry.Text)) { await DisplayAlert("Enter data", "Enter valid data", "Ok"); } else if (!(passwordEntry.Text).Equals(passwordRepeatEntry.Text)) { errorContent.IsVisible = true; errorMsg.Text = "Hasła się nie zgadzają"; } else { try { string date = dateEntry.Date.ToString("yyyy/MM/dd"); bool response = await Service.RegisterUserAsync(loginEntry.Text, emailEntry.Text, passwordEntry.Text,firstNameEntry.Text, lastNameEntry.Text, date); if (response) { errorContent.IsVisible = true; errorMsg.Text = "Zostałeś zarejestrowany!"; errorMsg.Background = Brush.Green; } else { errorMsg.Background = Brush.Red; errorContent.IsVisible = true; errorMsg.Text = "Uzytkownik o takim samym emailu lub loginie już istnieje!"; } }catch(AggregateException err) { foreach (var errInner in err.InnerExceptions) { Debug.WriteLine(errInner); //this will call ToString() on the inner execption and get you message, stacktrace and you could perhaps drill down further into the inner exception of it if necessary }; } } } } }
37.760563
278
0.561731
[ "MIT" ]
kamreo/Zakupowo-mobile
ZakupowoMobile/ZakupowoMobile/Views/BeforeAuth/RegistrationPage.xaml.cs
2,689
C#
using System; using System.Collections.Generic; using System.Text; namespace EscolaDeIdiomas.Domain { public class Aluno { public int Id { get; set; } public string Cpf { get; set; } public string Nome { get; set; } public DateTime DataNascimento { get; set; } public string Telefone { get; set; } public string Email { get; set; } public bool Ativo { get; set; } public Turma Turma { get; set; } public int Id_turma { get; set; } } }
17.966667
52
0.575139
[ "Apache-2.0" ]
alineBsoares/SheSharp
EscolaDeIdiomas/EscolaDeIdiomas.Domain/Aluno.cs
541
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; namespace Volo.Abp.AuditLogging { public interface IAuditLogAppService : IReadOnlyAppService<AuditLogDto, Guid, GetAuditLogDto>, IDeleteAppService<Guid> { Task DeleteManyAsync(params Guid[] ids); } }
25.933333
122
0.773779
[ "Apache-2.0" ]
AllenHongjun/tiger_admin
aspnet-core/src/Tiger.Application.Contracts/Volo/Abp/AuditLogging/IAuditLogAppService.cs
391
C#
using Csla; using System; namespace Csla.Analyzers.Tests.Targets.IsOperationMethodPublicMakeNonPublicCodeFixTests { [Serializable] public class VerifyGetFixesWhenClassIsNotSealed : BusinessBase<VerifyGetFixesWhenClassIsNotSealed> { public void DataPortal_Fetch() { } } }
24
87
0.802083
[ "MIT" ]
angtianqiang/csla
Source/Csla.Analyzers/Csla.Analyzers.Tests/Targets/IsOperationMethodPublicMakeNonPublicCodeFixTests/VerifyGetFixesWhenClassIsNotSealed.cs
290
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveCharacter : MonoBehaviour { public PathCreator3D pathObject; public float speed = 1f; public float rotation = 1f; public float spacing = 0.1f; public float resolution = 1; public bool infinite_loop = true; private int current_position; private Vector3[] points; /// <summary> Funkcja Inicjalizacji </summary> void Start () { points = pathObject.path.CalculateEvenlySpacedPoints( spacing, resolution ); } /// <summary> Funkcja Update </summary> void Update () { if ( GamePause.IsPause() ) { Stopper(); return; } rotateCamera(); moveCamera(); } /// <summary> Ruch postaci po określonej ścieżce z Waypointów </summary> public void moveCamera() { if ( !ObjectPrecisionPositioning( transform, points[current_position], 0.1f ) ) { var pos = Vector3.MoveTowards( transform.position, points[current_position], speed * Time.deltaTime ); GetComponent<Rigidbody>().MovePosition(pos); } else { if (infinite_loop) { current_position = (current_position + 1) % points.Length; } else { if (current_position < points.Length-1) { current_position++; } } } } /// <summary> Obrót postaci w kierunku następnego Waypointa </summary> public void rotateCamera() { Vector3 player = transform.position; Vector3 target = points[current_position]; player.y = 0; target.y = 0; var direction = (target - player).normalized; var lookRotation = Quaternion.LookRotation(direction); transform.rotation = Quaternion.Slerp( transform.rotation, lookRotation, rotation * Time.deltaTime ); } private void Stopper() { GetComponent<Rigidbody>().velocity = Vector3.zero; } /// <summary> Sprawdzenie czy postać (obiekt) znajduje się w granicach punktu docelowego </summary> /// <param name="subject"> Aktualna pozycja obiektu przemieszczającego się </param> /// <param name="target"> Położenie punktu docelowego </param> /// <param name="accuracy"> Tolerancja odległości </param> /// <returns> Zwraca informacje czy obiekt jest już w polu docelowym </returns> public static bool ObjectPrecisionPositioning( Transform subject, Vector3 target, float accuracy ) { float subjectX = subject.position.x; float subjectZ = subject.position.z; float targetX = target.x; float targetZ = target.z; bool positioningX = (subjectX < targetX + accuracy && subjectX > targetX - accuracy) ? true : false; bool positioningZ = (subjectZ < targetZ + accuracy && subjectZ > targetZ - accuracy) ? true : false; return (positioningX && positioningZ); } }
39.16
115
0.637045
[ "MIT" ]
Adrixop95/deathly_balloons_vr
src/smiertelne_balony_unity/Assets/Scripts/MoveCharacter.cs
2,954
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; using ModernSlavery.Core.Extensions; using ModernSlavery.WebUI.Shared.Interfaces; namespace ModernSlavery.WebUI.Shared.Classes.Attributes { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class PreventDuplicatePostAttribute : ActionFilterAttribute { private readonly bool disableCache = true; public PreventDuplicatePostAttribute(bool disableCache = true) { this.disableCache = disableCache; } public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (disableCache) context.HttpContext.DisableResponseCache(); if (context.HttpContext.Request.Form.ContainsKey("__RequestVerificationToken")) { var currentToken = context.HttpContext.Request.Form["__RequestVerificationToken"]; var session = context.HttpContext.RequestServices.GetService<IHttpSession>(); var lastToken = session["LastRequestVerificationToken"]; if (lastToken == currentToken) throw new HttpException(1150, "Duplicate post request"); session["LastRequestVerificationToken"] = currentToken; } await base.OnActionExecutionAsync(context, next); } } }
35.707317
119
0.703552
[ "MIT" ]
UKHomeOffice/Modern-Slavery-Alpha
ModernSlavery.WebUI.Shared/Classes/Attributes/PreventDuplicatePost.cs
1,466
C#
using System; using System.Linq; using System.Xml.Linq; using UnityEditor; using UnityEngine; using UnityEngine.Tilemaps; #if UNITY_2020_2_OR_NEWER using AssetImportContext = UnityEditor.AssetImporters.AssetImportContext; #else using AssetImportContext = UnityEditor.Experimental.AssetImporters.AssetImportContext; #endif // All tiled assets we want imported should use this class namespace SuperTiled2Unity.Editor { public abstract class TiledAssetImporter : SuperImporter { [SerializeField] private float m_PixelsPerUnit = 0.0f; public float PixelsPerUnit { get { return m_PixelsPerUnit; } } public float InversePPU { get { return 1.0f / PixelsPerUnit; } } [SerializeField] private int m_EdgesPerEllipse = 0; #pragma warning disable 414 [SerializeField] private int m_NumberOfObjectsImported = 0; #pragma warning restore 414 private RendererSorter m_RendererSorter; public RendererSorter RendererSorter { get { return m_RendererSorter; } } public SuperImportContext SuperImportContext { get; private set; } public void AddSuperCustomProperties(GameObject go, XElement xProperties) { AddSuperCustomProperties(go, xProperties, null); } public void AddSuperCustomProperties(GameObject go, XElement xProperties, string typeName) { AddSuperCustomProperties(go, xProperties, null, typeName); } public void AddSuperCustomProperties(GameObject go, XElement xProperties, SuperTile tile, string typeName) { // Load our "local" properties first var component = go.AddComponent<SuperCustomProperties>(); var properties = CustomPropertyLoader.LoadCustomPropertyList(xProperties); // Do we have any properties from a tile to add? if (tile != null) { properties.CombineFromSource(tile.m_CustomProperties); } // Add properties from our object type (this should be last) properties.AddPropertiesFromType(typeName, SuperImportContext); // Sort the properties alphabetically component.m_Properties = properties.OrderBy(p => p.m_Name).ToList(); AssignUnityTag(component); AssignUnityLayer(component); } public void AssignTilemapSorting(TilemapRenderer renderer) { var sortLayerName = m_RendererSorter.AssignTilemapSort(renderer); CheckSortingLayerName(sortLayerName); } public void AssignSpriteSorting(SpriteRenderer renderer) { var sortLayerName = m_RendererSorter.AssignSpriteSort(renderer); CheckSortingLayerName(sortLayerName); } public void AssignMaterial(Renderer renderer, string match) { // Do we have a registered material match? var matchedMaterial = SuperImportContext.Settings.MaterialMatchings.FirstOrDefault(m => m.m_LayerName.Equals(match, StringComparison.OrdinalIgnoreCase)); if (matchedMaterial != null) { renderer.material = matchedMaterial.m_Material; return; } // Has the user chosen to override the material used for our tilemaps and sprite objects? if (SuperImportContext.Settings.DefaultMaterial != null) { renderer.material = SuperImportContext.Settings.DefaultMaterial; } } public void ApplyTemplateToObject(XElement xObject) { var template = xObject.GetAttributeAs("template", ""); if (!string.IsNullOrEmpty(template)) { var asset = RequestAssetAtPath<ObjectTemplate>(template); if (asset != null) { xObject.CombineWithTemplate(asset.m_ObjectXml); } else { ReportError("Missing template file: {0}", template); } } } public void ApplyDefaultSettings() { var settings = ST2USettings.GetOrCreateST2USettings(); m_PixelsPerUnit = settings.PixelsPerUnit; m_EdgesPerEllipse = settings.EdgesPerEllipse; EditorUtility.SetDirty(this); } protected override void InternalOnImportAsset() { m_RendererSorter = new RendererSorter(); WrapImportContext(AssetImportContext); } protected override void InternalOnImportAssetCompleted() { m_RendererSorter = null; m_NumberOfObjectsImported = SuperImportContext.GetNumberOfObjects(); } protected void AssignUnityTag(SuperCustomProperties properties) { // Do we have a 'unity:tag' property? CustomProperty prop; if (properties.TryGetCustomProperty(StringConstants.Unity_Tag, out prop)) { string tag = prop.m_Value; CheckTagName(tag); properties.gameObject.tag = tag; } } protected void AssignUnityLayer(SuperCustomProperties properties) { // Do we have a 'unity:layer' property? CustomProperty prop; if (properties.TryGetCustomProperty(StringConstants.Unity_Layer, out prop)) { string layer = prop.m_Value; if (!UnityEditorInternal.InternalEditorUtility.layers.Contains(layer)) { string report = string.Format("Layer '{0}' is not defined in the Tags and Layers settings.", layer); ReportError(report); } else { properties.gameObject.layer = LayerMask.NameToLayer(layer); } } else { // Inherit the layer of our parent var parent = properties.gameObject.transform.parent; if (parent != null) { properties.gameObject.layer = parent.gameObject.layer; } } } private void WrapImportContext(AssetImportContext ctx) { var settings = ST2USettings.GetOrCreateST2USettings(); settings.RefreshCustomObjectTypes(); // Create a copy of our settings that we can override based on importer settings settings = Instantiate(settings); if (m_PixelsPerUnit == 0) { m_PixelsPerUnit = settings.PixelsPerUnit; } if (m_EdgesPerEllipse == 0) { m_EdgesPerEllipse = settings.EdgesPerEllipse; } settings.PixelsPerUnit = m_PixelsPerUnit; settings.EdgesPerEllipse = m_EdgesPerEllipse; SuperImportContext = new SuperImportContext(ctx, settings); } } }
35.545455
165
0.604859
[ "MIT" ]
AtriusHomelandInvasion/SuperTiled2Unity
SuperTiled2Unity/Assets/SuperTiled2Unity/Scripts/Editor/Importers/TiledAssetImporter.cs
7,040
C#
using System; using System.Diagnostics; using System.Threading; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Ray.BiliBiliTool.Console; using Ray.BiliBiliTool.Infrastructure; using Ray.Serilog.Sinks.CoolPushBatched; using Ray.Serilog.Sinks.MicrosoftTeamsBatched; using Ray.Serilog.Sinks.PushPlusBatched; using Ray.Serilog.Sinks.ServerChanBatched; using Xunit; namespace LogTest { public class TestMicrosoftTeams { private string _webhook; public TestMicrosoftTeams() { Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); Program.CreateHost(new string[] { }); _webhook = Global.ConfigurationRoot["Serilog:WriteTo:10:Args:webhook"]; } [Fact] public void Test() { var client = new MicrosoftTeamsApiClient(webhook: _webhook); var msg = LogConstants.Msg2; var result = client.PushMessage(msg); Debug.WriteLine(result.Content.ReadAsStringAsync().Result); Assert.True(result.StatusCode == System.Net.HttpStatusCode.OK); } } }
27.809524
88
0.690068
[ "MIT" ]
1040302/BiliBiliToolPro
test/LogTest/TestMicrosoftTeams.cs
1,170
C#
using Citron.Collections; using Pretune; using System.Collections.Generic; using M = Citron.CompileTime; namespace Citron.Analysis { public class FuncDict { public static FuncDict<TFuncDeclSymbol> Build<TFuncDeclSymbol>(ImmutableArray<TFuncDeclSymbol> funcDecls) where TFuncDeclSymbol : IDeclSymbolNode { var funcsDict = new Dictionary<(M.Name Name, int TypeParamCount), List<TFuncDeclSymbol>>(); var exactFuncsBuilder = ImmutableDictionary.CreateBuilder<DeclSymbolNodeName, TFuncDeclSymbol>(); foreach (var funcDecl in funcDecls) { var funcName = funcDecl.GetNodeName(); // mfunc의 typeparam이 n개면 n-1 .. 0 에도 다 넣는다 for (int i = 0; i <= funcName.TypeParamCount; i++) { var key = (funcName.Name, i); if (!funcsDict.TryGetValue(key, out var list)) { list = new List<TFuncDeclSymbol>(); funcsDict.Add(key, list); } list.Add(funcDecl); } exactFuncsBuilder.Add(funcName, funcDecl); } // funcsDict제작이 다 끝났으면 var builder = ImmutableDictionary.CreateBuilder<(M.Name Name, int TypeParamCount), ImmutableArray<TFuncDeclSymbol>>(); foreach (var keyValue in funcsDict) builder.Add(keyValue.Key, keyValue.Value.ToImmutableArray()); var funcDict = new FuncDict<TFuncDeclSymbol>(); funcDict.funcs = builder.ToImmutable(); funcDict.exactFuncs = exactFuncsBuilder.ToImmutable(); return funcDict; } } [ExcludeComparison] public partial struct FuncDict<TFuncDeclSymbol> where TFuncDeclSymbol : IDeclSymbolNode { internal ImmutableDictionary<(M.Name Name, int TypeParamCount), ImmutableArray<TFuncDeclSymbol>> funcs; internal ImmutableDictionary<DeclSymbolNodeName, TFuncDeclSymbol> exactFuncs; public ImmutableArray<TFuncDeclSymbol> Get(M.Name name, int minTypeParamCount) { return funcs.GetValueOrDefault((name, minTypeParamCount)); } public TFuncDeclSymbol? Get(DeclSymbolNodeName name) { return exactFuncs.GetValueOrDefault(name); } public IEnumerable<TFuncDeclSymbol> GetEnumerable() { return exactFuncs.Values; } } }
36.027778
131
0.585197
[ "MIT" ]
ioklo/citron
Src/Analysis.Symbol/Misc/FuncDict.cs
2,632
C#
using System; namespace DesignPatterns.BridgePattern.Example2 { public class Pearl : IMaterial { public void Activate() { Console.WriteLine("添加珍珠"); } public void Deactivate() { Console.WriteLine("去除珍珠"); } } }
17.411765
47
0.533784
[ "MIT" ]
xiangxingxing/C-Sharp-Algorithms-xx
DesignPatterns/BridgePattern/Example2/Pearl.cs
312
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Remotion.Linq.Clauses; using RomanticWeb.Entities; using RomanticWeb.Linq.Expressions; using RomanticWeb.Linq.Model; using RomanticWeb.Mapping; using RomanticWeb.Mapping.Model; using RomanticWeb.Vocabularies; namespace RomanticWeb.Linq { internal static class QueryVisitorExtensions { private static readonly IDictionary<object, object> TransformedExpressionsCache = new Dictionary<object, object>(); internal static StrongEntityAccessor GetEntityAccessor(this IQueryVisitor visitor, Remotion.Linq.Clauses.FromClauseBase sourceExpression) { StrongEntityAccessor entityAccessor = null; if (typeof(IEntity).GetTypeInfo().IsAssignableFrom(sourceExpression.ItemType)) { sourceExpression = visitor.TransformFromExpression(sourceExpression); entityAccessor = visitor.Query.FindAllComponents<StrongEntityAccessor>().FirstOrDefault(item => item.SourceExpression.EqualsTo(sourceExpression)); if (entityAccessor == null) { Identifier identifier = visitor.Query.FindAllComponents<EntityConstrain>() .Where(item => (item.TargetExpression.EqualsTo(sourceExpression.FromExpression)) && (item.Value is Identifier)) .Select(item => (Identifier)item.Value) .FirstOrDefault() ?? new Identifier(visitor.Query.CreateVariableName(sourceExpression.ItemName), sourceExpression.ItemType.FindEntityType()); entityAccessor = new StrongEntityAccessor(identifier, sourceExpression); entityAccessor.UnboundGraphName = entityAccessor.About; EntityTypeConstrain constrain = visitor.CreateTypeConstrain(sourceExpression); if ((constrain != null) && (!entityAccessor.Elements.Contains(constrain))) { entityAccessor.Elements.Add(constrain); } } } return entityAccessor; } internal static EntityTypeConstrain CreateTypeConstrain(this IQueryVisitor visitor, Remotion.Linq.Clauses.FromClauseBase sourceExpression) { EntityTypeConstrain result = null; Type entityType = sourceExpression.ItemType.FindEntityType(); if ((entityType != null) && (entityType != typeof(IEntity))) { result = visitor.CreateTypeConstrain(entityType, sourceExpression.FromExpression); } return result; } internal static EntityTypeConstrain CreateTypeConstrain(this IQueryVisitor visitor, Type entityType, System.Linq.Expressions.Expression sourceExpression) { EntityTypeConstrain result = null; if (entityType != null) { var classMappings = visitor.MappingsRepository.FindMappedClasses(entityType); if (classMappings == null) { throw new UnMappedTypeException(entityType); } if (classMappings.Any()) { Uri primaryTypeUri = classMappings.First(); IEnumerable<Type> inheritedTypes = entityType.GetImplementingTypes(); IList<Uri> inheritedTypeUris = new List<Uri>(); if (inheritedTypes.Any()) { foreach (Type inheritedType in inheritedTypes) { classMappings = visitor.MappingsRepository.FindMappedClasses(inheritedType); if (classMappings == null) { throw new UnMappedTypeException(entityType); } if (classMappings.Any()) { Uri inheritedTypeUri = classMappings.First(); if ((primaryTypeUri.AbsoluteUri != inheritedTypeUri.AbsoluteUri) && (!inheritedTypeUris.Contains(inheritedTypeUri, AbsoluteUriComparer.Default))) { inheritedTypeUris.Add(inheritedTypeUri); } } } } result = new EntityTypeConstrain(primaryTypeUri, sourceExpression, inheritedTypeUris.ToArray()); } } return result; } internal static Remotion.Linq.Clauses.FromClauseBase TransformFromExpression(this IQueryVisitor visitor, Remotion.Linq.Clauses.FromClauseBase sourceExpression) { Remotion.Linq.Clauses.FromClauseBase result = sourceExpression; System.Linq.Expressions.Expression expression = visitor.TransformUnaryExpression(sourceExpression.FromExpression); if (expression != sourceExpression.FromExpression) { object item; if (!TransformedExpressionsCache.TryGetValue(sourceExpression, out item)) { TransformedExpressionsCache[sourceExpression] = result = new AdditionalFromClause(sourceExpression.ItemName, sourceExpression.ItemType, (System.Linq.Expressions.MemberExpression)expression); } else { result = (AdditionalFromClause)item; } } return result; } internal static System.Linq.Expressions.Expression TransformUnaryExpression(this IQueryVisitor visitor, System.Linq.Expressions.Expression sourceExpression) { System.Linq.Expressions.Expression result = sourceExpression; if (sourceExpression is System.Linq.Expressions.UnaryExpression) { System.Linq.Expressions.UnaryExpression unaryExpression = (System.Linq.Expressions.UnaryExpression)sourceExpression; if (unaryExpression.NodeType == System.Linq.Expressions.ExpressionType.TypeAs) { System.Linq.Expressions.Expression expression = visitor.TransformPredicateExpression(unaryExpression.Operand); if (expression != sourceExpression) { object item; if (!TransformedExpressionsCache.TryGetValue(sourceExpression, out item)) { TransformedExpressionsCache[sourceExpression] = result = expression; } else { result = (System.Linq.Expressions.Expression)item; } } } } return result; } internal static System.Linq.Expressions.Expression TransformPredicateExpression(this IQueryVisitor visitor, System.Linq.Expressions.Expression expression) { System.Linq.Expressions.Expression result = expression; if (expression is System.Linq.Expressions.MethodCallExpression) { System.Linq.Expressions.MethodCallExpression methodCallExpression = (System.Linq.Expressions.MethodCallExpression)expression; if ((methodCallExpression.Method == typeof(EntityExtensions).GetMethod("Predicate")) && (methodCallExpression.Arguments.Count > 1) && (methodCallExpression.Arguments[1] != null) && (methodCallExpression.Arguments[1] is System.Linq.Expressions.ConstantExpression)) { object item; if (!TransformedExpressionsCache.TryGetValue(expression, out item)) { object objectValue = ((System.Linq.Expressions.ConstantExpression)methodCallExpression.Arguments[1]).Value; Uri predicate = (Uri)objectValue; Type type; string name; visitor.GetMappingDetails(predicate, methodCallExpression.Arguments[0].Type, out type, out name); System.Linq.Expressions.MemberExpression memberExpression = System.Linq.Expressions.Expression.MakeMemberAccess(methodCallExpression.Arguments[0], type.GetProperty(name)); TransformedExpressionsCache[expression] = result = memberExpression; } else { result = (System.Linq.Expressions.MemberExpression)item; } } } return result; } private static void GetMappingDetails(this IQueryVisitor visitor, Uri predicate, Type suggestedType, out Type itemType, out string itemName) { if (!predicate.IsAbsoluteUri) { predicate = new Uri(visitor.BaseUriSelector.SelectBaseUri(new EntityId(predicate)), predicate.ToString()); } itemType = null; itemName = null; if (predicate == Rdf.subject) { itemName = "Id"; itemType = typeof(IEntity); } else { IPropertyMapping propertyMapping = null; if (suggestedType != null) { IEntityMapping entityMapping = visitor.MappingsRepository.MappingFor(suggestedType); if (entityMapping != null) { propertyMapping = entityMapping.Properties.FirstOrDefault(item => item.Uri.AbsoluteUri == predicate.AbsoluteUri); } } if (propertyMapping == null) { propertyMapping = visitor.MappingsRepository.MappingForProperty(predicate); } if (propertyMapping == null) { ExceptionHelper.ThrowMappingException(predicate); } itemName = propertyMapping.Name; itemType = propertyMapping.EntityMapping.EntityType; } } } }
46.713004
195
0.573486
[ "BSD-3-Clause" ]
alien-mcl/RomanticWeb
RomanticWeb/Linq/QueryVisitorExtensions.cs
10,419
C#
namespace DesignPatterns.DDD.ValueObject { /// <summary> /// A class that pretends to create a value object for name. /// </summary> public sealed class Name { public Name(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } // Make the class immutable by removing any property setters // and only passing member values through the constructors. public string FirstName { get; } public string LastName { get; } // Override the Object.Equals method to ensure the object is // compared using business logic. public override bool Equals(object obj) { var item = obj as Name; if (obj == null || GetType() != obj.GetType()) { return false; } return FirstName == item.FirstName && LastName == item.LastName; } // Override the Object.GetHashCode method and ensure that the // hash is same for the objects who have same equality. public override int GetHashCode() { int hash = 13; hash = (hash * 7) + FirstName.GetHashCode(); hash = (hash * 7) + LastName.GetHashCode(); return hash; } // Operator overload the default behavior of == and != to use // the Equals method. public static bool operator ==(Name lhs, Name rhs) { if (object.ReferenceEquals(lhs, null)) { return object.ReferenceEquals(rhs, null); } return lhs.Equals(rhs); } public static bool operator !=(Name lhs, Name rhs) { return !(lhs == rhs); } } }
28.0625
76
0.538419
[ "MIT" ]
mika-s/Misc
CSharp/DesignPatterns/DDD/ValueObject/Name.cs
1,798
C#
using UnityEngine; using System.Collections; public class PlayButton : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnClick() { Debug.Log("clicked"); } }
13.142857
41
0.626812
[ "Apache-2.0" ]
Vrixyz/AffinityQuiz
Client/Assets/Scripts/PlayButton.cs
278
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Bicep.Core.Parsing; namespace Bicep.Core.Syntax { public class NullLiteralSyntax : ExpressionSyntax { public NullLiteralSyntax(Token nullKeyword) { AssertTokenType(nullKeyword, nameof(nullKeyword), TokenType.NullKeyword); this.NullKeyword = nullKeyword; } public Token NullKeyword { get; } public override void Accept(ISyntaxVisitor visitor) => visitor.VisitNullLiteralSyntax(this); public override TextSpan Span => this.NullKeyword.Span; } }
26.652174
100
0.686786
[ "MIT" ]
Agazoth/bicep
src/Bicep.Core/Syntax/NullLiteralSyntax.cs
613
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orneholm.RadioText.Core.Storage; namespace Orneholm.RadioText.Web.Controllers { public class EpisodeLister : IEpisodeLister { private readonly ISummaryStorage _summaryStorage; public EpisodeLister(ISummaryStorage summaryStorage) { _summaryStorage = summaryStorage; } public async Task<List<SrStoredMiniSummarizedEpisode>> List(int count, string entityName = null, string entityType = null, string keyphrase = null, string query = null, int? programId = null) { var episodes = await _summaryStorage.ListMiniSummarizedEpisode(count); var filteredEpisodes = FilterEpisodes(entityName, entityType, keyphrase, episodes, programId); var searchedEpisodes = SearchEpisodes(query, filteredEpisodes); var orderedEpisodes = OrderEpisodes(searchedEpisodes); return orderedEpisodes.ToList(); } private static IOrderedEnumerable<SrStoredMiniSummarizedEpisode> OrderEpisodes(List<SrStoredMiniSummarizedEpisode> filteredEpisodes) { return filteredEpisodes.OrderByDescending(x => x.PublishDateUtc); } private static List<SrStoredMiniSummarizedEpisode> SearchEpisodes(string query, List<SrStoredMiniSummarizedEpisode> episodes) { var filteredEpisodes = episodes; if (!string.IsNullOrWhiteSpace(query)) { filteredEpisodes = filteredEpisodes .Where(x => x.Transcription_Original.Text.Contains(query) || x.Transcription_English.Text.Contains(query)) .ToList(); } return filteredEpisodes; } private static List<SrStoredMiniSummarizedEpisode> FilterEpisodes(string entityName, string entityType, string keyphrase, List<SrStoredMiniSummarizedEpisode> episodes, int? programId) { var filteredEpisodes = episodes; if (programId.HasValue) { filteredEpisodes = filteredEpisodes .Where(x => x.ProgramId == programId) .ToList(); } if (!string.IsNullOrWhiteSpace(entityName)) { filteredEpisodes = filteredEpisodes .Where(x => x.Transcription_Original.Entities.Any(y => y.Name == entityName && (string.IsNullOrWhiteSpace(entityType) || y.Type == entityType)) || x.Transcription_English.Entities.Any(y => y.Name == entityName && (string.IsNullOrWhiteSpace(entityType) || y.Type == entityType))) .ToList(); } if (!string.IsNullOrWhiteSpace(keyphrase)) { filteredEpisodes = filteredEpisodes .Where(x => x.Transcription_Original.KeyPhrases.Contains(keyphrase) || x.Transcription_English.KeyPhrases.Contains(keyphrase)) .ToList(); } return filteredEpisodes; } } }
40.179487
199
0.624761
[ "MIT" ]
PeterOrneholm/RadioText.net
src/Orneholm.RadioText.Web/Controllers/EpisodeLister.cs
3,134
C#
using System; using NServiceBus; using NServiceBus.Persistence; using Raven.Client.Document; class Program { static void Main() { Console.Title = "Samples.RavenDB.Server"; #region Config var busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.RavenDB.Server"); busConfiguration.Transactions().DisableDistributedTransactions(); using (var documentStore = new DocumentStore { Url = "http://localhost:8080", DefaultDatabase = "RavenSimpleSample", EnlistInDistributedTransactions = false }) { documentStore.Initialize(); var persistence = busConfiguration.UsePersistence<RavenDBPersistence>(); // Only required to simplify the sample setup persistence.DoNotSetupDatabasePermissions(); persistence.SetDefaultDocumentStore(documentStore); #endregion busConfiguration.EnableInstallers(); using (var bus = Bus.Create(busConfiguration).Start()) { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } } }
29.511628
85
0.594169
[ "Apache-2.0" ]
foz1284/docs.particular.net
samples/ravendb/simple/Raven_3/Server/Program.cs
1,229
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 Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Microsoft.EntityFrameworkCore.ModelBuilding { public static class SqlServerTestModelBuilderExtensions { public static ModelBuilderTest.TestIndexBuilder<TEntity> IsClustered<TEntity>( this ModelBuilderTest.TestIndexBuilder<TEntity> builder, bool clustered = true) { switch (builder) { case IInfrastructure<IndexBuilder<TEntity>> genericBuilder: genericBuilder.Instance.IsClustered(clustered); break; case IInfrastructure<IndexBuilder> nongenericBuilder: nongenericBuilder.Instance.IsClustered(clustered); break; } return builder; } public static ModelBuilderTest.TestOwnedNavigationBuilder<TEntity, TDependentEntity> IsMemoryOptimized<TEntity, TDependentEntity>( this ModelBuilderTest.TestOwnedNavigationBuilder<TEntity, TDependentEntity> builder, bool memoryOptimized = true) where TEntity : class where TDependentEntity : class { switch (builder) { case IInfrastructure<OwnedNavigationBuilder<TEntity, TDependentEntity>> genericBuilder: genericBuilder.Instance.IsMemoryOptimized(memoryOptimized); break; case IInfrastructure<OwnedNavigationBuilder> nongenericBuilder: nongenericBuilder.Instance.IsMemoryOptimized(memoryOptimized); break; } return builder; } } }
39.102041
119
0.640397
[ "Apache-2.0" ]
0b01/efcore
test/EFCore.SqlServer.Tests/ModelBuilding/SqlServerTestModelBuilderExtensions.cs
1,916
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Lab3.ViewModels { public class StudentCourseViewModel { public StudentViewModel StudentViewModel { get; set; } public CourseViewModel CourseViewModel { get; set; } public string SortKey { get; set; } } }
24
62
0.702381
[ "MIT" ]
egnsh93/CST8256
Lab3/Lab3/ViewModels/StudentCourseViewModel.cs
338
C#
using System.ComponentModel.DataAnnotations; namespace GlobalLib.Models.V_IrpDB { public class tblCountyTW { [Key] public int ID { get; set; } public string County { get; set; } public string CountyEN { get; set; } public int List { get; set; } } }
21.642857
45
0.60066
[ "MIT" ]
LiuLyndon/ERPAPI
GlobalLib/Models/V_IrpDB/tblCountyTW.cs
305
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using System.Threading.Tasks; using FakeItEasy; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans; using Squidex.Caching; using Squidex.Domain.Apps.Core.Schemas; using Squidex.Domain.Apps.Entities.Schemas.Commands; using Squidex.Infrastructure; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.Orleans; using Squidex.Infrastructure.Validation; using Xunit; namespace Squidex.Domain.Apps.Entities.Schemas.Indexes { public class SchemasIndexTests { private readonly IGrainFactory grainFactory = A.Fake<IGrainFactory>(); private readonly ICommandBus commandBus = A.Fake<ICommandBus>(); private readonly ISchemasByAppIndexGrain index = A.Fake<ISchemasByAppIndexGrain>(); private readonly NamedId<DomainId> appId = NamedId.Of(DomainId.NewGuid(), "my-app"); private readonly NamedId<DomainId> schemaId = NamedId.Of(DomainId.NewGuid(), "my-schema"); private readonly SchemasIndex sut; public SchemasIndexTests() { A.CallTo(() => grainFactory.GetGrain<ISchemasByAppIndexGrain>(appId.Id.ToString(), null)) .Returns(index); var cache = new ReplicatedCache(new MemoryCache(Options.Create(new MemoryCacheOptions())), new SimplePubSub(A.Fake<ILogger<SimplePubSub>>()), Options.Create(new ReplicatedCacheOptions { Enable = true })); sut = new SchemasIndex(grainFactory, cache); } [Fact] public async Task Should_resolve_schema_by_name() { var expected = SetupSchema(); A.CallTo(() => index.GetIdAsync(schemaId.Name)) .Returns(schemaId.Id); var actual1 = await sut.GetSchemaByNameAsync(appId.Id, schemaId.Name, false); var actual2 = await sut.GetSchemaByNameAsync(appId.Id, schemaId.Name, false); Assert.Same(expected, actual1); Assert.Same(expected, actual2); A.CallTo(() => grainFactory.GetGrain<ISchemaGrain>(A<string>._, null)) .MustHaveHappenedTwiceExactly(); A.CallTo(() => index.GetIdAsync(A<string>._)) .MustHaveHappenedTwiceExactly(); } [Fact] public async Task Should_resolve_schema_by_name_and_id_if_cached_before() { var expected = SetupSchema(); A.CallTo(() => index.GetIdAsync(schemaId.Name)) .Returns(schemaId.Id); var actual1 = await sut.GetSchemaByNameAsync(appId.Id, schemaId.Name, true); var actual2 = await sut.GetSchemaByNameAsync(appId.Id, schemaId.Name, true); var actual3 = await sut.GetSchemaAsync(appId.Id, schemaId.Id, true); Assert.Same(expected, actual1); Assert.Same(expected, actual2); Assert.Same(expected, actual3); A.CallTo(() => grainFactory.GetGrain<ISchemaGrain>(A<string>._, null)) .MustHaveHappenedOnceExactly(); A.CallTo(() => index.GetIdAsync(A<string>._)) .MustHaveHappenedOnceExactly(); } [Fact] public async Task Should_resolve_schema_by_id() { var expected = SetupSchema(); var actual1 = await sut.GetSchemaAsync(appId.Id, schemaId.Id, false); var actual2 = await sut.GetSchemaAsync(appId.Id, schemaId.Id, false); Assert.Same(expected, actual1); Assert.Same(expected, actual2); A.CallTo(() => grainFactory.GetGrain<ISchemaGrain>(A<string>._, null)) .MustHaveHappenedTwiceExactly(); A.CallTo(() => index.GetIdAsync(A<string>._)) .MustNotHaveHappened(); } [Fact] public async Task Should_resolve_schema_by_id_and_name_if_cached_before() { var expected = SetupSchema(); var actual1 = await sut.GetSchemaAsync(appId.Id, schemaId.Id, true); var actual2 = await sut.GetSchemaAsync(appId.Id, schemaId.Id, true); var actual3 = await sut.GetSchemaByNameAsync(appId.Id, schemaId.Name, true); Assert.Same(expected, actual1); Assert.Same(expected, actual2); Assert.Same(expected, actual3); A.CallTo(() => grainFactory.GetGrain<ISchemaGrain>(A<string>._, null)) .MustHaveHappenedOnceExactly(); A.CallTo(() => index.GetIdAsync(A<string>._)) .MustNotHaveHappened(); } [Fact] public async Task Should_resolve_schemas_by_id() { var schema = SetupSchema(); A.CallTo(() => index.GetIdsAsync()) .Returns(new List<DomainId> { schema.Id }); var actual = await sut.GetSchemasAsync(appId.Id); Assert.Same(actual[0], schema); } [Fact] public async Task Should_return_empty_schemas_if_schema_not_created() { var schema = SetupSchema(EtagVersion.NotFound); A.CallTo(() => index.GetIdsAsync()) .Returns(new List<DomainId> { schema.Id }); var actual = await sut.GetSchemasAsync(appId.Id); Assert.Empty(actual); } [Fact] public async Task Should_return_schema_if_deleted() { var schema = SetupSchema(0, true); A.CallTo(() => index.GetIdsAsync()) .Returns(new List<DomainId> { schema.Id }); var actual = await sut.GetSchemasAsync(appId.Id); Assert.Same(actual[0], schema); } [Fact] public async Task Should_add_schema_to_index_on_create() { var token = RandomHash.Simple(); A.CallTo(() => index.ReserveAsync(schemaId.Id, schemaId.Name)) .Returns(token); var context = new CommandContext(Create(schemaId.Name), commandBus) .Complete(); await sut.HandleAsync(context); A.CallTo(() => index.AddAsync(token)) .MustHaveHappened(); A.CallTo(() => index.RemoveReservationAsync(A<string>._)) .MustNotHaveHappened(); } [Fact] public async Task Should_clear_reservation_when_schema_creation_failed() { var token = RandomHash.Simple(); A.CallTo(() => index.ReserveAsync(schemaId.Id, schemaId.Name)) .Returns(token); var context = new CommandContext(Create(schemaId.Name), commandBus); await sut.HandleAsync(context); A.CallTo(() => index.AddAsync(token)) .MustNotHaveHappened(); A.CallTo(() => index.RemoveReservationAsync(token)) .MustHaveHappened(); } [Fact] public async Task Should_not_add_to_index_on_create_if_name_taken() { A.CallTo(() => index.ReserveAsync(schemaId.Id, schemaId.Name)) .Returns(Task.FromResult<string?>(null)); var context = new CommandContext(Create(schemaId.Name), commandBus) .Complete(); await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context)); A.CallTo(() => index.AddAsync(A<string>._)) .MustNotHaveHappened(); A.CallTo(() => index.RemoveReservationAsync(A<string>._)) .MustNotHaveHappened(); } [Fact] public async Task Should_not_add_to_index_on_create_if_name_invalid() { var context = new CommandContext(Create("INVALID"), commandBus) .Complete(); await sut.HandleAsync(context); A.CallTo(() => index.ReserveAsync(schemaId.Id, A<string>._)) .MustNotHaveHappened(); A.CallTo(() => index.RemoveReservationAsync(A<string>._)) .MustNotHaveHappened(); } [Fact] public async Task Should_remove_schema_from_index_on_delete_when_existed_before() { var schema = SetupSchema(); var command = new DeleteSchema { SchemaId = schemaId, AppId = appId }; var context = new CommandContext(command, commandBus) .Complete(); await sut.HandleAsync(context); A.CallTo(() => index.RemoveAsync(schema.Id)) .MustHaveHappened(); } [Fact] public async Task Should_forward_call_when_rebuilding() { var schemas = new Dictionary<string, DomainId>(); await sut.RebuildAsync(appId.Id, schemas); A.CallTo(() => index.RebuildAsync(schemas)) .MustHaveHappened(); } private CreateSchema Create(string name) { return new CreateSchema { SchemaId = schemaId.Id, Name = name, AppId = appId }; } private ISchemaEntity SetupSchema(long version = 0, bool isDeleted = false) { var schemaEntity = A.Fake<ISchemaEntity>(); A.CallTo(() => schemaEntity.SchemaDef) .Returns(new Schema(schemaId.Name)); A.CallTo(() => schemaEntity.Id) .Returns(schemaId.Id); A.CallTo(() => schemaEntity.AppId) .Returns(appId); A.CallTo(() => schemaEntity.Version) .Returns(version); A.CallTo(() => schemaEntity.IsDeleted) .Returns(isDeleted); var schemaGrain = A.Fake<ISchemaGrain>(); A.CallTo(() => schemaGrain.GetStateAsync()) .Returns(J.Of(schemaEntity)); var key = DomainId.Combine(appId, schemaId.Id).ToString(); A.CallTo(() => grainFactory.GetGrain<ISchemaGrain>(key, null)) .Returns(schemaGrain); return schemaEntity; } } }
34.160131
145
0.571319
[ "MIT" ]
alastairtree/squidex
backend/tests/Squidex.Domain.Apps.Entities.Tests/Schemas/Indexes/SchemasIndexTests.cs
10,455
C#
using System.Linq; using FluentValidation; using SmartStore.Admin.Models.DataExchange; using SmartStore.Services.DataExchange.Csv; using SmartStore.Services.Localization; namespace SmartStore.Admin.Validators.DataExchange { public partial class CsvConfigurationValidator : AbstractValidator<CsvConfigurationModel> { public CsvConfigurationValidator(ILocalizationService localization) { RuleFor(x => x.Delimiter) .Must(x => !CsvConfiguration.PresetCharacters.Contains(x.ToChar(true))) .WithMessage(localization.GetResource("Admin.DataExchange.Csv.Delimiter.Validation")); RuleFor(x => x.Quote) .Must(x => !CsvConfiguration.PresetCharacters.Contains(x.ToChar(true))) .WithMessage(localization.GetResource("Admin.DataExchange.Csv.Quote.Validation")); RuleFor(x => x.Escape) .Must(x => !CsvConfiguration.PresetCharacters.Contains(x.ToChar(true))) .WithMessage(localization.GetResource("Admin.DataExchange.Csv.Escape.Validation")); RuleFor(x => x.Escape) .Must((model, x) => x != model.Delimiter) .WithMessage(localization.GetResource("Admin.DataExchange.Csv.EscapeDelimiter.Validation")); RuleFor(x => x.Quote) .Must((model, x) => x != model.Delimiter) .WithMessage(localization.GetResource("Admin.DataExchange.Csv.QuoteDelimiter.Validation")); } } }
37.714286
96
0.757576
[ "MIT" ]
jenmcquade/csharp-snippets
SmartStoreNET-3.x/src/Presentation/SmartStore.Web/Administration/Validators/DataExchange/CsvConfigurationValidator.cs
1,322
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace FibaroDotNetSDK.VirtualDevices.Model { public partial class VirtualDevice { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("roomID")] public long RoomId { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("baseType")] public string BaseType { get; set; } [JsonProperty("enabled")] public bool Enabled { get; set; } [JsonProperty("visible")] public bool Visible { get; set; } [JsonProperty("isPlugin")] public bool IsPlugin { get; set; } [JsonProperty("parentId")] public long ParentId { get; set; } [JsonProperty("remoteGatewayId")] public long RemoteGatewayId { get; set; } [JsonProperty("interfaces")] public List<string> Interfaces { get; set; } [JsonProperty("properties")] public DeviceProperties Properties { get; set; } //[JsonProperty("actions")] //public string[] Actions { get; set; } [JsonProperty("created")] public long Created { get; set; } [JsonProperty("modified")] public long Modified { get; set; } [JsonProperty("sortOrder")] public long SortOrder { get; set; } } }
25.298246
56
0.57975
[ "MIT" ]
zhouji0212/FibaroDotNET
src/FibaroDotNetSDK/VirtualDevices/Model/VirtualDevice.cs
1,444
C#
// UiSon, by Cameron Gale 2021 using System; using System.Reflection; namespace UiSon.Extension { public static partial class ExtendMemberInfo { /// <summary> /// Gets the type of the member /// </summary> public static Type GetUnderlyingType(this MemberInfo member) { switch (member.MemberType) { case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Method: return ((MethodInfo)member).ReturnType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; default: return null; } } } }
28.193548
68
0.530892
[ "MIT" ]
knackname/UiSon
UiSon.Extension/MemberInfo/GetUnderlyingType.cs
876
C#
// Copyright (c) 2011 Morten Bakkedal // This code is published under the MIT License. using System; using System.Collections.Generic; using FuncLib.Functions.Compilation; namespace FuncLib.Functions { /// <summary> /// Represents a mathematical function. Any function must derive from this class. Also includes a range /// of static method for performing operations on functions. /// </summary> [Serializable] public abstract partial class Function { private Dictionary<Variable, Function> derivatives; /// <summary> /// Evaluates the function by assigning values to the variables. /// </summary> public double Value(IPoint point) { // Evaluate using CachedEvaluation by default (usually much faster, but uses more memory). return Value(new CachedEvaluation(point)); } /// <summary> /// Evaluates the function by assigning values to the variables. /// </summary> public double Value(params VariableAssignment[] assignments) { return Value(new Point(assignments)); } /// <summary> /// Evaluates the function by assigning values to the variables. /// </summary> public double Value(IEvaluation evaluation) { double value; if (!evaluation.TryGetValue(this, out value)) { value = ComputeValue(evaluation); evaluation.AddValue(this, value); } return value; } /// <summary> /// Evaluates the function by assigning values to the variables. Override this to implement. /// </summary> protected abstract double ComputeValue(IEvaluation evaluation); /// <summary> /// Computes the partial derivative with respect to a variable. /// </summary> public Function Derivative(Variable variable) { // It's has proved very important for efficient computation that the same object is returned // if called repeatably. This is especially true if the function is compiled. if (derivatives == null) { derivatives = new Dictionary<Variable, Function>(); } Function derivative; if (!derivatives.TryGetValue(variable, out derivative)) { derivative = ComputeDerivative(variable); if (!derivative.IsZero) { // Only use memory for saving non-zero derivatives. derivatives.Add(variable, derivative); } } return derivative; } /// <summary> /// Computes the higher order partial derivative with respect to a variable. /// </summary> public Function Derivative(Variable variable, int order) { if (order < 0) { throw new ArgumentOutOfRangeException("order"); } Function f = this; for (int i = 0; i < order; i++) { f = f.Derivative(variable); } return f; } /// <summary> /// Computes the higher order partial derivative with respect to a number of variables. /// </summary> public Function Derivative(params Variable[] variables) { Function f = this; for (int i = 0; i < variables.Length; i++) { f = f.Derivative(variables[i]); } return f; } /// <summary> /// Computes the partial derivative with respect to a variable. Override this to implement. /// </summary> protected abstract Function ComputeDerivative(Variable variable); /// <summary> /// Replaces a number of variables by fixed values. Returns a function of the remaining variables. /// </summary> public virtual Function PartialValue(IPoint point) { return PartialValue(new PartialValueEvaluation(point)); } /// <summary> /// Replace a number of variables by fixed values. Returns a function of the remaining variables. /// </summary> public Function PartialValue(params VariableAssignment[] assignments) { return PartialValue(new Point(assignments)); } /// <summary> /// Replace a number of variables by fixed values. Returns a function of the remaining variables. /// </summary> public Function PartialValue(IPartialValueEvaluation evaluation) { // Reuse the same object if already computed. Function partialValue; if (!evaluation.TryGetPartialValue(this, out partialValue)) { partialValue = ComputePartialValue(evaluation); evaluation.AddPartialValue(this, partialValue); } return partialValue; } /// <summary> /// Replace a number of variables by fixed values. Override this to implement. /// </summary> protected virtual Function ComputePartialValue(IPartialValueEvaluation evaluation) { // Use slow and inefficient implementation using PartialValueFunction by default. Override to provide a more efficient implementation. return new PartialValueFunction(this, evaluation); } /// <summary> /// Returns an expression used by <see cref="CodeGenerator" /> to generate C# code representation of the function. Override this to implement. /// </summary> public virtual Expression Compile(CodeGenerator generator) { // Assume that compilation is not supported by default. throw new NotSupportedException(); } /// <summary> /// Tests if this function is known to be identically zero. Override this to express knowledge about zeroness. /// </summary> public virtual bool IsZero { get { ConstantFunction f0 = this as ConstantFunction; return f0 != null && f0.Constant == 0.0; } } [Serializable] private class PartialValueFunction : Function { private Function innerFunction; private IDictionary<Variable, double> partialValueAssignments; public PartialValueFunction(Function innerFunction, IPartialValueEvaluation partialValueEvaluation) { this.innerFunction = innerFunction; partialValueAssignments = partialValueEvaluation.ToDictionary(); } protected override double ComputeValue(IEvaluation evaluation) { IDictionary<Variable, double> assignments = evaluation.ToDictionary(); // Overwrite or extend with values defined for the partial value. foreach (KeyValuePair<Variable, double> assignment in partialValueAssignments) { assignments[assignment.Key] = assignment.Value; } return innerFunction.Value(new Point(assignments)); } protected override Function ComputeDerivative(Variable variable) { if (partialValueAssignments.ContainsKey(variable)) { // This variable is replaced by a constant. return 0.0; } return innerFunction.Derivative(variable); } } } }
28.493213
144
0.707956
[ "MIT" ]
lionpeloux/FuncLib
src/FuncLib/Functions/Function.cs
6,299
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class XmlDocumentationCommentCompletionProviderTests : AbstractCSharpCompletionProviderTests { public XmlDocumentationCommentCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override CompletionProvider CreateCompletionProvider() { return new XmlDocCommentCompletionProvider(); } private async Task VerifyItemsExistAsync(string markup, params string[] items) { foreach (var item in items) { await VerifyItemExistsAsync(markup, item); } } private async Task VerifyItemsAbsentAsync(string markup, params string[] items) { foreach (var item in items) { await VerifyItemIsAbsentAsync(markup, item); } } protected override async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem) { // We don't need to try writing comments in from of items in doc comments. await VerifyAtPositionAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem); await VerifyAtEndOfFileAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem); // Items cannot be partially written if we're checking for their absence, // or if we're verifying that the list will show up (without specifying an actual item) if (!checkForAbsence && expectedItemOrNull != null) { await VerifyAtPosition_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem); await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem); } } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AlwaysVisibleAtAnyLevelItems1() { await VerifyItemsExistAsync(@" public class goo { /// $$ public void bar() { } }", "see", "seealso", "![CDATA[", "!--"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AlwaysVisibleAtAnyLevelItems2() { await VerifyItemsExistAsync(@" public class goo { /// <summary> $$ </summary> public void bar() { } }", "see", "seealso", "![CDATA[", "!--"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AlwaysVisibleNotTopLevelItems1() { await VerifyItemsExistAsync(@" public class goo { /// <summary> $$ </summary> public void bar() { } }", "c", "code", "list", "para"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AlwaysVisibleNotTopLevelItems2() { await VerifyItemsAbsentAsync(@" public class goo { /// $$ public void bar() { } }", "c", "code", "list", "para", "paramref", "typeparamref"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AlwaysVisibleTopLevelOnlyItems1() { await VerifyItemsExistAsync(@" public class goo { /// $$ public void bar() { } }", "exception", "include", "permission"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AlwaysVisibleTopLevelOnlyItems2() { await VerifyItemsAbsentAsync(@" public class goo { /// <summary> $$ </summary> public void bar() { } }", "exception", "include", "permission"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevelSingleUseItems1() { await VerifyItemsExistAsync(@" public class goo { /// $$ public void bar() { } }", "example", "remarks", "summary"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevelSingleUseItems2() { await VerifyItemsAbsentAsync(@" public class goo { /// <summary> $$ </summary> public void bar() { } }", "example", "remarks", "summary"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevelSingleUseItems3() { await VerifyItemsAbsentAsync(@" public class goo { /// <summary> $$ </summary> /// <example></example> /// <remarks></remarks> public void bar() { } }", "example", "remarks", "summary"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyInListItems() { await VerifyItemsAbsentAsync(@" public class goo { /// <summary> $$ </summary> /// <example></example> /// <remarks></remarks> public void bar() { } }", "listheader", "item", "term", "description"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyInListItems2() { await VerifyItemsAbsentAsync(@" public class goo { /// $$ public void bar() { } }", "listheader", "item", "term", "description"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyInListItems3() { await VerifyItemsExistAsync(@" public class goo { /// <list>$$</list> public void bar() { } }", "listheader", "item", "term", "description"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyInListItems4() { await VerifyItemsExistAsync(@" public class goo { /// <list><$$</list> public void bar() { } }", "listheader", "item", "term", "description"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ListHeaderItems() { await VerifyItemsExistAsync(@" public class goo { /// <summary> /// <list><listheader> $$ </listheader></list> /// </summary> /// <example></example> /// <remarks></remarks> public void bar() { } }", "term", "description"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VoidMethodDeclarationItems() { await VerifyItemIsAbsentAsync(@" public class goo { /// $$ public void bar() { } }", "returns"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodReturns() { await VerifyItemExistsAsync(@" public class goo { /// $$ public int bar() { } }", "returns"); } [WorkItem(8627, "https://github.com/dotnet/roslyn/issues/8627")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReadWritePropertyNoReturns() { await VerifyItemIsAbsentAsync(@" public class goo { /// $$ public int bar { get; set; } }", "returns"); } [WorkItem(8627, "https://github.com/dotnet/roslyn/issues/8627")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReadWritePropertyValue() { await VerifyItemExistsAsync(@" public class goo { /// $$ public int bar { get; set; } }", "value"); } [WorkItem(8627, "https://github.com/dotnet/roslyn/issues/8627")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReadOnlyPropertyNoReturns() { await VerifyItemIsAbsentAsync(@" public class goo { /// $$ public int bar { get; } }", "returns"); } [WorkItem(8627, "https://github.com/dotnet/roslyn/issues/8627")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReadOnlyPropertyValue() { await VerifyItemExistsAsync(@" public class goo { /// $$ public int bar { get; } }", "value"); } [WorkItem(8627, "https://github.com/dotnet/roslyn/issues/8627")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WriteOnlyPropertyNoReturns() { await VerifyItemIsAbsentAsync(@" public class goo { /// $$ public int bar { set; } }", "returns"); } [WorkItem(8627, "https://github.com/dotnet/roslyn/issues/8627")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WriteOnlyPropertyValue() { await VerifyItemExistsAsync(@" public class goo { /// $$ public int bar { set; } }", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodParamTypeParam() { var text = @" public class goo<TGoo> { /// $$ public int bar<TBar>(TBar green) { } }"; await VerifyItemsExistAsync(text, "typeparam name=\"TBar\"", "param name=\"green\""); await VerifyItemsAbsentAsync(text, "typeparam name=\"TGoo\""); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IndexerParamTypeParam() { await VerifyItemsExistAsync(@" public class goo<T> { /// $$ public int this[T green] { get { } set { } } }", "param name=\"green\""); } [WorkItem(17872, "https://github.com/dotnet/roslyn/issues/17872")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodParamRefName() { var text = @" public class Outer<TOuter> { public class Inner<TInner> { /// <summary> /// $$ /// </summary> public int Method<TMethod>(T green) { } } }"; await VerifyItemsExistAsync( text, "typeparamref name=\"TOuter\"", "typeparamref name=\"TInner\"", "typeparamref name=\"TMethod\"", "paramref name=\"green\""); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ClassTypeParamRefName() { await VerifyItemsExistAsync(@" /// <summary> /// $$ /// </summary> public class goo<T> { public int bar<T>(T green) { } }", "typeparamref name=\"T\""); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ClassTypeParam() { await VerifyItemsExistAsync(@" /// $$ public class goo<T> { public int bar<T>(T green) { } }", "typeparam name=\"T\""); } [WorkItem(638802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638802")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TagsAfterSameLineClosedTag() { var text = @"/// <summary> /// <goo></goo>$$ /// /// </summary> "; await VerifyItemsExistAsync(text, "!--", "![CDATA[", "c", "code", "list", "para", "seealso", "see"); } [WorkItem(734825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734825")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMember() { var text = @"public enum z { /// <summary> /// /// </summary> /// <$$ a } "; await VerifyItemsExistAsync(text); } [WorkItem(954679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954679")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionList() { await VerifyItemExistsAsync(@" /// $$ public class goo { }", "completionlist"); } [WorkItem(775091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775091")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParamRefNames() { await VerifyItemExistsAsync(@" /// <summary> /// <paramref name=""$$""/> /// </summary> static void Main(string[] args) { } ", "args"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParamNamesInEmptyAttribute() { await VerifyItemExistsAsync(@" /// <param name=""$$""/> static void Goo(string str) { } ", "str"); } [WorkItem(17872, "https://github.com/dotnet/roslyn/issues/17872")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamRefNamesInEmptyAttribute() { var text = @" public class Outer<TOuter> { public class Inner<TInner> { /// <summary> /// <typeparamref name=""$$""/> /// </summary> public int Method<TMethod>(T green) { } } }"; await VerifyItemsExistAsync(text, "TOuter", "TInner", "TMethod"); } [WorkItem(17872, "https://github.com/dotnet/roslyn/issues/17872")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamRefNamesPartiallyTyped() { var text = @" public class Outer<TOuter> { public class Inner<TInner> { /// <summary> /// <typeparamref name=""T$$""/> /// </summary> public int Method<TMethod>(T green) { } } }"; await VerifyItemsExistAsync(text, "TOuter", "TInner", "TMethod"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamNamesInEmptyAttribute() { var text = @" public class Outer<TOuter> { public class Inner<TInner> { /// <typeparam name=""$$""/> public int Method<TMethod>(T green) { } } }"; await VerifyItemsExistAsync(text, "TMethod"); await VerifyItemsAbsentAsync(text, "TOuter", "TInner"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamNamesInWrongScope() { var text = @" public class Outer<TOuter> { public class Inner<TInner> { /// <summary> /// <typeparam name=""$$""/> /// </summary> public int Method<TMethod>(T green) { } } }"; await VerifyItemsExistAsync(text, "TMethod"); await VerifyItemsAbsentAsync(text, "TOuter", "TInner"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamNamesPartiallyTyped() { var text = @" public class Outer<TOuter> { public class Inner<TInner> { /// <typeparam name=""T$$""/> public int Method<TMethod>(T green) { } } }"; await VerifyItemsExistAsync(text, "TMethod"); await VerifyItemsAbsentAsync(text, "TOuter", "TInner"); } [WorkItem(8322, "https://github.com/dotnet/roslyn/issues/8322")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialTagCompletion() { await VerifyItemsExistAsync(@" public class goo { /// <r$$ public void bar() { } }", "!--", "![CDATA[", "completionlist", "example", "exception", "include", "permission", "remarks", "see", "seealso", "summary"); } [WorkItem(8322, "https://github.com/dotnet/roslyn/issues/8322")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialTagCompletionNestedTags() { await VerifyItemsExistAsync(@" public class goo { /// <summary> /// <r$$ /// </summary> public void bar() { } }", "!--", "![CDATA[", "c", "code", "list", "para", "see", "seealso"); } [WorkItem(11487, "https://github.com/dotnet/roslyn/issues/11487")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamAtTopLevelOnly() { await VerifyItemsAbsentAsync(@" /// <summary> /// $$ /// </summary> public class Goo<T> { }", "typeparam name=\"T\""); } [WorkItem(11487, "https://github.com/dotnet/roslyn/issues/11487")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParamAtTopLevelOnly() { await VerifyItemsAbsentAsync(@" /// <summary> /// $$ /// </summary> static void Goo(string str) { }", "param name=\"str\""); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ListAttributeNames() { await VerifyItemsExistAsync(@" class C { /// <summary> /// <list $$></list> /// </summary> static void Goo() { } }", "type"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ListTypeAttributeValue() { await VerifyItemsExistAsync(@" class C { /// <summary> /// <list type=""$$""></list> /// </summary> static void Goo() { } }", "bullet", "number", "table"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11490")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SeeAttributeNames() { await VerifyItemsExistAsync(@" class C { /// <summary> /// <see $$/> /// </summary> static void Goo() { } }", "cref", "langword"); } [WorkItem(22789, "https://github.com/dotnet/roslyn/issues/22789")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LangwordCompletionInPlainText() { await VerifyItemsExistAsync(@" class C { /// <summary> /// Some text $$ /// </summary> static void Goo() { } }", "null", "sealed", "true", "false", "await"); } [WorkItem(22789, "https://github.com/dotnet/roslyn/issues/22789")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LangwordCompletionAfterAngleBracket1() { await VerifyItemsAbsentAsync(@" class C { /// <summary> /// Some text <$$ /// </summary> static void Goo() { } }", "null", "sealed", "true", "false", "await"); } [WorkItem(22789, "https://github.com/dotnet/roslyn/issues/22789")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LangwordCompletionAfterAngleBracket2() { await VerifyItemsAbsentAsync(@" class C { /// <summary> /// Some text <s$$ /// </summary> static void Goo() { } }", "null", "sealed", "true", "false", "await"); } [WorkItem(22789, "https://github.com/dotnet/roslyn/issues/22789")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LangwordCompletionAfterAngleBracket3() { await VerifyItemsExistAsync(@" class C { /// <summary> /// Some text < $$ /// </summary> static void Goo() { } }", "null", "sealed", "true", "false", "await"); } [WorkItem(11490, "https://github.com/dotnet/roslyn/issues/11490")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SeeLangwordAttributeValue() { await VerifyItemsExistAsync(@" class C { /// <summary> /// <see langword=""$$""/> /// </summary> static void Goo() { } }", "null", "true", "false", "await"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterTagNameInIncompleteTag() { var text = @" class C { /// <exception $$ static void Goo() { } }"; await VerifyItemExistsAsync(text, "cref", usePreviousCharAsTrigger: true); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterTagNameInElementStartTag() { var text = @" class C { /// <exception $$> void Goo() { } } "; await VerifyItemExistsAsync(text, "cref"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterTagNameInEmptyElement() { var text = @" class C { /// <see $$/> void Goo() { } } "; await VerifyItemExistsAsync(text, "cref"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterTagNamePartiallyTyped() { var text = @" class C { /// <exception c$$ void Goo() { } } "; await VerifyItemExistsAsync(text, "cref"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecialCrefAttribute() { var text = @" class C { /// <summary> /// <list cref=""String"" $$ /// </summary> void Goo() { } } "; await VerifyItemExistsAsync(text, "type"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecialNameAttribute() { var text = @" class C { /// <summary> /// <list name=""goo"" $$ /// </summary> void Goo() { } } "; await VerifyItemExistsAsync(text, "type"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterTextAttribute() { var text = @" class C { /// <summary> /// <list goo="""" $$ /// </summary> void Goo() { } } "; await VerifyItemExistsAsync(text, "type"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInWrongTagTypeEmptyElement() { var text = @" class C { /// <summary> /// <list $$/> /// </summary> void Goo() { } } "; await VerifyItemExistsAsync(text, "type"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInWrongTagTypeElementStartTag() { var text = @" class C { /// <summary> /// <see $$> /// </summary> void Goo() { } } "; await VerifyItemExistsAsync(text, "langword"); } [WorkItem(11489, "https://github.com/dotnet/roslyn/issues/11489")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeValueOnQuote() { var text = @" class C { /// <summary> /// <see langword=""$$ /// </summary> static void Goo() { } }"; await VerifyItemExistsAsync(text, "await", usePreviousCharAsTrigger: true); } [WorkItem(757, "https://github.com/dotnet/roslyn/issues/757")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TermAndDescriptionInsideItem() { var text = @" class C { /// <summary> /// <list type=""table""> /// <item> /// $$ /// </item> /// </list> /// </summary> static void Goo() { } }"; await VerifyItemExistsAsync(text, "term"); await VerifyItemExistsAsync(text, "description"); } } }
27.683461
229
0.579822
[ "Apache-2.0" ]
JieCarolHu/roslyn
src/EditorFeatures/CSharpTest/Completion/CompletionProviders/XmlDocumentationCommentCompletionProviderTests.cs
25,277
C#
using Melville.Pdf.LowLevel.Model.ContentStreams; using Melville.Pdf.LowLevel.Writers.ContentStreams; using Melville.Pdf.ReferenceDocuments.Graphics; namespace Melville.Pdf.ReferenceDocuments.Text; public abstract class TextAttributeTest : Card3x5 { protected TextAttributeTest(string helpText) : base (helpText) { } private static readonly PdfName fontName = NameDirectory.Get("F1"); protected override void SetPageProperties(PageCreator page) { page.AddStandardFont(fontName, BuiltInFontName.Courier, FontEncodingName.StandardEncoding); } protected override async ValueTask DoPaintingAsync(ContentStreamWriter csw) { using (var tr = csw.StartTextBlock()) { await csw.SetStrokeRGB(1.0, 0.0, 0.0); await csw.SetFont(fontName, 70); tr.SetTextMatrix(1,0,0,1,30,25); tr.ShowString("Is Text"); SetTestedParameter(csw); tr.SetTextMatrix(1,0,0,1,30,125); tr.ShowString("Is Text"); } } protected abstract void SetTestedParameter(ContentStreamWriter csw); } public abstract class ClippingTextAttributeTest : TextAttributeTest { protected ClippingTextAttributeTest(string helpText) : base(helpText) { } protected override async ValueTask DoPaintingAsync(ContentStreamWriter csw) { await base.DoPaintingAsync(csw); await csw.SetNonstrokingRGB(0, 1, 0); csw.Rectangle(10,130, 300, 20); csw.FillPath(); } } public class CharacterSpacing: TextAttributeTest { public CharacterSpacing() : base("Set the Character Spacing") { } protected override void SetTestedParameter(ContentStreamWriter csw) { csw.SetCharSpace(30); } } public class TextRise: TextAttributeTest { public TextRise() : base("Set the TextRise") { } protected override void SetTestedParameter(ContentStreamWriter csw) { csw.SetTextRise(30); } } public class WordSpacing: TextAttributeTest { public WordSpacing() : base("Set the Word Spacing") { } protected override void SetTestedParameter(ContentStreamWriter csw) { csw.SetWordSpace(50); csw.SetCharSpace(-10); } } public class HorizontalScaling : TextAttributeTest { public HorizontalScaling() : base("Demonstrate horizontal scaling.") { } protected override void SetTestedParameter(ContentStreamWriter csw) => csw.SetHorizontalTextScaling(50); } public class StrokeText : TextAttributeTest { public StrokeText() : base("Show outline of text") { } protected override void SetTestedParameter(ContentStreamWriter csw) => csw.SetTextRender(TextRendering.Stroke); } public class StrokeAndFillText : TextAttributeTest { public StrokeAndFillText() : base("Show Filled outline of text") { } protected override void SetTestedParameter(ContentStreamWriter csw) => csw.SetTextRender(TextRendering.FillAndStroke); } public class InvisibleText : TextAttributeTest { public InvisibleText() : base("\"Show\" invisible text") { } protected override void SetTestedParameter(ContentStreamWriter csw) => csw.SetTextRender(TextRendering.Invisible); } public class StrokeAndClip : ClippingTextAttributeTest { public StrokeAndClip() : base("Stroked text as a clipping region.") { } protected override void SetTestedParameter(ContentStreamWriter csw) => csw.SetTextRender(TextRendering.StrokeAndClip); } public class FillAndClip : ClippingTextAttributeTest { public FillAndClip() : base("Filled text as a clipping region.") { } protected override void SetTestedParameter(ContentStreamWriter csw) => csw.SetTextRender(TextRendering.FillAndClip); } public class StrokeFillAndClip : ClippingTextAttributeTest { public StrokeFillAndClip() : base("Stroked, Filled text as a clipping region.") { } protected override void SetTestedParameter(ContentStreamWriter csw) => csw.SetTextRender(TextRendering.FillStrokeAndClip); } public class ClipToText : ClippingTextAttributeTest { public ClipToText() : base("Clipping region is a clipping region.") { } protected override void SetTestedParameter(ContentStreamWriter csw) => csw.SetTextRender(TextRendering.Clip); }
27.10559
115
0.705775
[ "MIT" ]
DrJohnMelville/Pdf
Src/Melville.Pdf.ReferenceDocuments/Text/TextAttributeTest.cs
4,366
C#
namespace EstateSocialSystem.Web.Infrastructure.Mapping { public interface IMapTo<T> where T : class { } }
16
56
0.65625
[ "MIT" ]
Georgegig/EstateSocialSystem
Source/EstateSocialSystem/EstateSocialSystem.Web.Infrastructure/Mapping/IMapTo.cs
130
C#
/************************************************************************************** Toolkit for WPF Copyright (C) 2007-2019 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at https://github.com/xceedsoftware/wpftoolkit/blob/master/license.md For more features, controls, and fast professional support, pick up the Plus Edition at https://xceed.com/xceed-toolkit-plus-for-wpf/ Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids *************************************************************************************/ using System.Windows.Media; using System.Windows.Controls; using System.Windows; using System; using System.Diagnostics; namespace Xceed.Wpf.Toolkit.LiveExplorer.Samples.Chart.Views { /// <summary> /// Interaction logic for ChartStylingLineSeriesView.xaml /// </summary> public partial class ChartStylingLineSeriesView : DemoView { public ChartStylingLineSeriesView() { InitializeComponent(); } } }
28.552632
102
0.623041
[ "MIT" ]
O-Debegnach/Supervisor-de-Comercio
wpftoolkit-master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit.LiveExplorer/Samples/Chart/Views/ChartStylingLineSeriesView.xaml.cs
1,087
C#
using System.Reflection; 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("AWSSDK.MQ")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AmazonMQ. This is the initial SDK release for Amazon MQ. Amazon MQ is a managed message broker service for Apache ActiveMQ that makes it easy to set up and operate message brokers in the cloud.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.0.0")]
48.0625
273
0.749675
[ "Apache-2.0" ]
Murcho/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/MQ/Properties/AssemblyInfo.cs
1,538
C#
// ----------------------------------------------------------------------- // <copyright file="RemoteProcess.cs" company="Asynkron HB"> // Copyright (C) 2015-2018 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- namespace Proto.Remote { public class RemoteProcess : Process { private readonly PID _pid; public RemoteProcess(PID pid) { _pid = pid; } protected override void SendUserMessage(PID _, object message) => Send(message); protected override void SendSystemMessage(PID _, object message) => Send(message); private void Send(object msg) { if (msg is Watch w) { var rw = new RemoteWatch(w.Watcher, _pid); EndpointManager.RemoteWatch(rw); } else if (msg is Unwatch uw) { var ruw = new RemoteUnwatch(uw.Watcher, _pid); EndpointManager.RemoteUnwatch(ruw); } else { Remote.SendMessage(_pid, msg,-1); } } } }
30.5
91
0.446721
[ "Apache-2.0" ]
Impetus-Global-Research/protoactor-dotnet
src/Proto.Remote/RemoteProcess.cs
1,220
C#
#region Copyright (c) 2014 Orcomp development team. // ------------------------------------------------------------------------------------------------------------------- // <copyright file="PrivateFieldRenameRewriter.cs" company="Orcomp development team"> // Copyright (c) 2014 Orcomp development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace SolutionValidator.CodeInspection.Refactoring { #region using... using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; #endregion public class RenamePrivateFieldsRewriter : CSharpSyntaxRewriter { private readonly SemanticModel _semanticModel; private dynamic _parameters; public RenamePrivateFieldsRewriter(dynamic parameters, SemanticModel semanticModel) { _parameters = parameters; _semanticModel = semanticModel; } public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax name) { // TODO: Hanlde initializer list correctly var symbolInfo = _semanticModel.GetSymbolInfo(name); var fieldSymbol = symbolInfo.Symbol as IFieldSymbol; if (fieldSymbol != null && fieldSymbol.DeclaredAccessibility == Accessibility.Private && !fieldSymbol.IsConst && !fieldSymbol.IsStatic) { name = name .WithIdentifier(SyntaxFactory.Identifier(GetChangedName(name.Identifier.ValueText))) .WithLeadingTrivia(name.GetLeadingTrivia()) .WithTrailingTrivia(name.GetTrailingTrivia()); } return name; } public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax field) { if (!field.Modifiers.Any(SyntaxKind.PrivateKeyword)) { return field; } if (field.Modifiers.Any(SyntaxKind.ConstKeyword)) { return field; } if (field.Modifiers.Any(SyntaxKind.StaticKeyword)) { return field; } //var variables = new List<VariableDeclaratorSyntax>(); var variables = new List<VariableDeclaratorSyntax>(); foreach (var variable in field.Declaration.Variables) { var newVariable = variable.WithIdentifier(SyntaxFactory.Identifier(GetChangedName(variable.Identifier.ValueText)) .WithLeadingTrivia(variable.Identifier.LeadingTrivia) .WithTrailingTrivia(variable.Identifier.TrailingTrivia)) .WithLeadingTrivia(variable.GetLeadingTrivia()) .WithTrailingTrivia(variable.GetTrailingTrivia()); variables.Add(newVariable); } field = field .WithDeclaration(SyntaxFactory.VariableDeclaration(field.Declaration.Type, SyntaxFactory.SeparatedList(variables))) .WithLeadingTrivia(field.GetLeadingTrivia()) .WithTrailingTrivia(field.GetTrailingTrivia()); return field; } private string GetChangedName(string oldName) { return Regex.Replace(oldName, _parameters.Find, _parameters.Replace, RegexOptions.None); } } }
30.545455
119
0.695437
[ "MIT" ]
Orcomp/SolutionValidator
src/SolutionValidator.Core/Validator/CodeInspection/Refactoring/Visitors/RenamePrivateFieldsRewriter.cs
3,026
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.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Newtonsoft.Json; using NuGet.Common; namespace NuGet.Build.Tasks { public class GetRestoreProjectJsonPathTask : Task { /// <summary> /// Full path to the msbuild project. /// </summary> [Required] public string ProjectPath { get; set; } /// <summary> /// Output path to project.json if it exists. /// </summary> [Output] public string ProjectJsonPath { get; set; } public override bool Execute() { var log = new MSBuildLogger(Log); log.LogDebug($"(in) ProjectPath '{ProjectPath}'"); var directory = Path.GetDirectoryName(ProjectPath); var projectName = Path.GetFileNameWithoutExtension(ProjectPath); // Allow project.json or projectName.project.json var path = ProjectJsonPathUtilities.GetProjectConfigPath(directory, projectName); if (File.Exists(path)) { ProjectJsonPath = path; } log.LogDebug($"(out) ProjectJsonPath '{ProjectJsonPath}'"); return true; } } }
29.595745
111
0.609633
[ "Apache-2.0" ]
BdDsl/NuGet.Client
src/NuGet.Core/NuGet.Build.Tasks/GetRestoreProjectJsonPathTask.cs
1,393
C#
/******************************************************************** * * PROPRIETARY and CONFIDENTIAL * * This file is licensed from, and is a trade secret of: * * AvePoint, Inc. * Harborside Financial Center * 9th Fl. Plaza Ten * Jersey City, NJ 07311 * United States of America * Telephone: +1-800-661-6588 * WWW: www.avepoint.com * * Refer to your License Agreement for restrictions on use, * duplication, or disclosure. * * RESTRICTED RIGHTS LEGEND * * Use, duplication, or disclosure by the Government is * subject to restrictions as set forth in subdivision * (c)(1)(ii) of the Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 (Oct. 1988) and * FAR 52.227-19 (C) (June 1987). * * Copyright © 2017-2019 AvePoint® Inc. All Rights Reserved. * * Unpublished - All rights reserved under the copyright laws of the United States. * $Revision: $ * $Author: $ * $Date: $ */ using AvePoint.Migration.Api.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace AvePoint.Migration.Samples { class AddExchangePlan : AbstractApplication { static void Main(string[] args) { new AddExchangePlan().RunAsync().Wait(); } /// <summary> /// <see cref="GetMigrationDatabase"/> /// </summary> private readonly string migrationDatabaseId = "<migration database id>"; /// <summary> /// <see cref="GetExchangeMigrationPolicy"/> /// </summary> private readonly string migrationPolicyId = "<migration policy id>"; /// <returns> /// <see cref="ServiceResponsePlanSummaryModel"/> /// </returns> protected override async Task<string> RunAsync(HttpClient client) { var mappingContent = new ExchangeMappingContentModel { Source = new ExchangeMailboxModel { Mailbox = "<source mailbox>", MailboxType = "UserMailbox", }, Destination = new ExchangeMailboxModel { Mailbox = "<destination mailbox>", MailboxType = "UserMailbox", }, ConvertToSharedMailbox = false, MigrateArchivedMailboxOrFolder = true, MigrateRecoverableItemsFolder = true, }; var mappings = new ExchangeMappingModel { Source = new ExchangeConnectionModel { OnPremisesConnectionOption = new ExchangeOnPremisesConnectionOption { BasicCredential = new BasicCredential { Username = "<user name>", Password = "<password>" }, /* ConnectionId = "<connection id>", */ ExchangeServerOption = new ExchangeServerOption { Host = "<host name or ip>", Version = "Exchange2013SP1" }, }, }, Destination = new ExchangeConnectionModel { OnlineConnectionOption = new ExchangeOnlineConnectionOption { BasicCredential = new BasicCredential { Username = "<user name>", Password = "<password>" }, /* ConnectionId = "<connection id>", */ }, }, Contents = new List<ExchangeMappingContentModel> { mappingContent }, }; var planSettings = new ExchangePlanSettingsModel { NameLabel = new PlanNameLabel { Name = $"CSharp_EX_Plan_{DateTime.Now.ToString("yyyyMMddHHmmss")}", BusinessUnit = "<BusinessUnit name>", Wave = "<Wave name>", }, PolicyId = migrationPolicyId, Schedule = new SimpleSchedule { IntervalType = "Once", StartTime = DateTime.Now.AddMinutes(2), }, DatabaseId = migrationDatabaseId, MigrateContacts = true, MigrateDistributionGroups = true, MigrateMailboxPermissions = true, MigrateMailboxRules = true, MigratePublicFolders = true, SynchronizeDeletion = true, PlanGroups = new List<string>(), }; var plan = new ExchangePlanModel { Mappings = mappings, Settings = planSettings, }; plan.Validate(); var requestContent = JsonConvert.SerializeObject(plan); var content = new StringContent(requestContent, Encoding.UTF8, "application/json"); var response = await client.PostAsync("/api/exchange/plans", content); return await response.Content.ReadAsStringAsync(); } } }
34.8
95
0.48241
[ "MIT" ]
AvePoint/FLY-Migration
WebAPI/CSharp/FLY 4.5/FLY/Exchange/AddExchangePlan.cs
5,746
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 Clinic_Full { public partial class frmDelPat : DevComponents.DotNetBar.OfficeForm { public frmDelPat() { InitializeComponent(); } Model.DB_Clinic_FullEntities objDB = new Model.DB_Clinic_FullEntities(); private void frmDelPat_Load(object sender, EventArgs e) { try { dtgPat.ColumnCount = 8; dtgPat.AutoGenerateColumns = false; dtgPat.CellBorderStyle = DataGridViewCellBorderStyle.RaisedVertical; this.dtgPat.DefaultCellStyle.ForeColor = Color.Black; this.dtgPat.DefaultCellStyle.BackColor = Color.White; this.dtgPat.DefaultCellStyle.SelectionBackColor = Color.Yellow; this.dtgPat.DefaultCellStyle.SelectionForeColor = Color.Black; dtgPat.Columns[0].Name = "ID"; dtgPat.Columns[0].DataPropertyName = "ID"; dtgPat.Columns[0].HeaderText = "شماره "; dtgPat.Columns[1].Name = "Name_Family"; dtgPat.Columns[1].DataPropertyName = "Name_Family"; dtgPat.Columns[1].HeaderText = "نام بیمار"; dtgPat.Columns[3].Name = "Tell"; dtgPat.Columns[3].DataPropertyName = "Tell"; dtgPat.Columns[3].HeaderText = "شماره همراه"; dtgPat.Columns[3].Width = 80; dtgPat.Columns[4].Name = "Adrs"; dtgPat.Columns[4].DataPropertyName = "Adrs"; dtgPat.Columns[4].HeaderText = "آدرس"; dtgPat.Columns[4].Width = 100; dtgPat.Columns[2].Name = "MeliCode"; dtgPat.Columns[2].DataPropertyName = "MeliCode"; dtgPat.Columns[2].HeaderText = "کد ملی"; dtgPat.Columns[2].Width = 80; dtgPat.Columns[5].Name = "Date"; dtgPat.Columns[5].DataPropertyName = "Date"; dtgPat.Columns[5].HeaderText = "تاریخ"; dtgPat.Columns[5].Width = 80; dtgPat.Columns[6].Name = "Time"; dtgPat.Columns[6].DataPropertyName = "Time"; dtgPat.Columns[6].HeaderText = "ساعت"; dtgPat.Columns[6].Width = 80; dtgPat.Columns[7].Name = "NCodePat"; dtgPat.Columns[7].DataPropertyName = "NCodePat"; dtgPat.Columns[7].HeaderText = "کد"; dtgPat.Columns[7].Width = 80; var user = objDB.Tbl_Patient.Where(x => x.LoginCode == Trans.NCode).ToList(); dtgPat.DataSource = user.ToList(); } catch (Exception) { DevExpress.XtraEditors.XtraMessageBox.Show(" . خطا در متصل شدن به دیتابیس ", "Connect", MessageBoxButtons.OK, MessageBoxIcon.Error); } } int GridID; private void buttonX1_Click(object sender, EventArgs e) { try { int i = objDB.SP_DelPat(GridID); if (i != 0) { DevExpress.XtraEditors.XtraMessageBox.Show(" . عملیات حذف موفق بود ", " Delete ", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { DevExpress.XtraEditors.XtraMessageBox.Show(" . عملیات حذف ناموفق بود ", " Delete ", MessageBoxButtons.OK, MessageBoxIcon.Error); } var user = objDB.Tbl_Patient.Where(x => x.LoginCode == Trans.NCode).ToList(); dtgPat.DataSource = user.ToList(); } catch (Exception) { DevExpress.XtraEditors.XtraMessageBox.Show(" . خطا در متصل شدن به دیتابیس ", "Connect", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void dtgPat_RowEnter(object sender, DataGridViewCellEventArgs e) { GridID = (int)dtgPat.Rows[e.RowIndex].Cells["ID"].Value; } private void buttonX2_Click(object sender, EventArgs e) { this.Close(); } } }
36.915254
153
0.551653
[ "MIT" ]
realQu1ck/Clinic
src/Clinic_Full/Clinic_Full/frmDelPat.cs
4,477
C#
// *********************************************************************** // Assembly : MPT.CSI.API // Author : Mark Thomas // Created : 06-13-2017 // // Last Modified By : Mark Thomas // Last Modified On : 10-08-2017 // *********************************************************************** // <copyright file="IChangeableModifiers.cs" company=""> // Copyright © 2017 // </copyright> // <summary></summary> // *********************************************************************** using MPT.CSI.API.Core.Helpers; namespace MPT.CSI.API.Core.Program.ModelBehavior { /// <summary> /// Cable object can have stiffness, weight, and mass modifiers set. /// </summary> public interface IChangeableCableModifiers { /// <summary> /// This function defines a modifier assignment. /// The default value for all modifiers is one. /// </summary> /// <param name="name">The name of an existing element or object.</param> /// <param name="modifiers">Unitless modifiers.</param> void SetModifiers(string name, CableModifier modifiers); } }
36.03125
81
0.496097
[ "MIT" ]
MarkPThomas/MPT.Net
MPT/CSI/API/MPT.CSI.API/Core/Program/ModelBehavior/IChangeableCableModifiers.cs
1,156
C#
#if !DISABLE_REACTIVE_UI using ReactiveUI; #endif using System; using System.Collections.Generic; using System.Linq; using GitHub.Collections; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading; using NUnit.Framework; using System.Reactive; using System.Threading.Tasks; using System.Reactive.Threading.Tasks; using GitHub; [TestFixture] public class TrackingTests : TestBase { const int Timeout = 2000; [Test] public void OrderByUpdatedNoFilter() { var count = 6; ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var list1 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 1")).ToList()); var list2 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, i + count, "Run 2")).ToList()); var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); count = 0; // add first items foreach (var l in list1) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(list1.Count, col.Count); list1.Sort(new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderByDescending(x => x.CreatedAt).Compare)); CollectionAssert.AreEqual(col, list1); count = 0; // replace items foreach (var l in list2) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(list2.Count, col.Count); CollectionAssert.AreEqual(col, list2); col.Dispose(); } [Test] public void OrderByUpdatedFilter() { var count = 3; ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare, (item, position, list) => true, OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare); col.ProcessingDelay = TimeSpan.Zero; var list1 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 1")).ToList()); var list2 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, i + count, "Run 2")).ToList()); var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); count = 0; // add first items foreach (var l in list1) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(list1.Count, col.Count); list1.Sort(new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderByDescending(x => x.CreatedAt).Compare)); CollectionAssert.AreEqual(col, list1); count = 0; // replace items foreach (var l in list2) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(list2.Count, col.Count); CollectionAssert.AreEqual(col, list2); col.Dispose(); } [Test] public void OnlyIndexes2To4() { var count = 6; var list1 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 1")).ToList()); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare, (item, position, list) => position >= 2 && position <= 4); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); count = 0; // add first items foreach (var l in list1) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(3, col.Count); #if DEBUG CollectionAssert.AreEqual(list1.Reverse<Thing>(), (col as TrackingCollection<Thing>).DebugInternalList); #endif CollectionAssert.AreEqual(col, new List<Thing>() { list1[3], list1[2], list1[1] }); col.Dispose(); } [Test] public void OnlyTimesEqualOrHigherThan3Minutes() { var count = 6; var list1 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 1")).ToList()); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare, (item, position, list) => item.UpdatedAt >= Now + TimeSpan.FromMinutes(3) && item.UpdatedAt <= Now + TimeSpan.FromMinutes(5)); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); count = 0; // add first items foreach (var l in list1) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(3, col.Count); #if DEBUG CollectionAssert.AreEqual(list1.Reverse<Thing>(), (col as TrackingCollection<Thing>).DebugInternalList); #endif CollectionAssert.AreEqual(col, new List<Thing>() { list1[2], list1[1], list1[0] }); col.Dispose(); } [Test] public void OrderByDescendingNoFilter() { var count = 6; var list1 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 1")).ToList()); var list2 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, i, "Run 2")).ToList()); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); count = 0; // add first items foreach (var l in list1) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(6, col.Count); #if DEBUG CollectionAssert.AreEqual(list1, (col as TrackingCollection<Thing>).DebugInternalList); #endif CollectionAssert.AreEqual(col, list1); count = 0; // add first items foreach (var l in list2) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(6, col.Count); col.Dispose(); } [Test] public void OrderByDescendingNoFilter1000() { var count = 1000; var total = 1000; var list1 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 1")).ToList()); var list2 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 2")).ToList()); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); count = 0; // add first items foreach (var l in list1) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(total, col.Count); CollectionAssert.AreEqual(col, list1); count = 0; foreach (var l in list2) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(total, col.Count); count = 0; foreach (var l in list2) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(total, col.Count); col.Dispose(); } [Test] public void NotInitializedCorrectlyThrows1() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare); Assert.Throws<InvalidOperationException>(() => col.Subscribe()); } [Test] public void NotInitializedCorrectlyThrows2() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare); Assert.Throws<InvalidOperationException>(() => col.Subscribe(_ => { }, () => { })); } [Test] public void NoChangingAfterDisposed1() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(Observable.Never<Thing>(), OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare); col.Dispose(); Assert.Throws<ObjectDisposedException>(() => col.AddItem(new Thing())); } [Test] public void NoChangingAfterDisposed2() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(Observable.Never<Thing>(), OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare); col.Dispose(); Assert.Throws<ObjectDisposedException>(() => col.RemoveItem(new Thing())); } [Test] public void FilterTitleRun2() { var count = 0; var total = 1000; var list1 = new List<Thing>(Enumerable.Range(1, total).Select(i => GetThing(i, i, i, "Run 1")).ToList()); var list2 = new List<Thing>(Enumerable.Range(1, total).Select(i => GetThing(i, i, i + 1, "Run 2")).ToList()); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( list1.ToObservable(), OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare, (item, position, list) => item.Title.Equals("Run 2")); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); evt.WaitOne(); evt.Reset(); Assert.AreEqual(total, count); Assert.AreEqual(0, col.Count); count = 0; // add new items foreach (var l in list2) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(total, count); Assert.AreEqual(total, col.Count); CollectionAssert.AreEqual(col, list2.Reverse<Thing>()); col.Dispose(); } [Test, Category("Timings")] public void OrderByDoesntMatchOriginalOrderTimings() { var count = 0; var total = 1000; var list1 = new List<Thing>(Enumerable.Range(1, total).Select(i => GetThing(i, i, i, "Run 1")).ToList()); var list2 = new List<Thing>(Enumerable.Range(1, total).Select(i => GetThing(i, i, i + 1, "Run 2")).ToList()); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( list1.ToObservable(), OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare, (item, position, list) => item.Title.Equals("Run 2")); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); var start = DateTimeOffset.UtcNow; col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); evt.WaitOne(); var time = (DateTimeOffset.UtcNow - start).TotalMilliseconds; Assert.LessOrEqual(time, 100); evt.Reset(); Assert.AreEqual(total, count); Assert.AreEqual(0, col.Count); count = 0; start = DateTimeOffset.UtcNow; // add new items foreach (var l in list2) col.AddItem(l); evt.WaitOne(); time = (DateTimeOffset.UtcNow - start).TotalMilliseconds; Assert.LessOrEqual(time, 200); evt.Reset(); Assert.AreEqual(total, count); Assert.AreEqual(total, col.Count); CollectionAssert.AreEqual(col, list2.Reverse<Thing>()); col.Dispose(); } [Test] public void OrderByMatchesOriginalOrder() { var count = 0; var total = 1000; var list1 = new List<Thing>(Enumerable.Range(1, total).Select(i => GetThing(i, i, i, "Run 1")).Reverse().ToList()); var list2 = new List<Thing>(Enumerable.Range(1, total).Select(i => GetThing(i, i, i + 1, "Run 2")).Reverse().ToList()); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( list1.ToObservable(), OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare, (item, position, list) => item.Title.Equals("Run 2")); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; count = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); evt.WaitOne(); evt.Reset(); Assert.AreEqual(total, count); Assert.AreEqual(0, col.Count); count = 0; // add new items foreach (var l in list2) col.AddItem(l); evt.WaitOne(); evt.Reset(); Assert.AreEqual(total, count); Assert.AreEqual(total, col.Count); CollectionAssert.AreEqual(col, list2); col.Dispose(); } [Test] public void SortingTest() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); // testing ADD expectedCount = 1; // add a thing with UpdatedAt=0:0:10 Add(source, GetThing(1, 10)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10) }); // testing ADD // add another thing with UpdatedAt=0:0:2 expectedCount = 2; Add(source, GetThing(2, 2)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:10,0:0:2} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), GetThing(2, 2) }); // testing MOVE // replace thing with UpdatedAt=0:0:2 to UpdatedAt=0:0:12 expectedCount = 3; Add(source, GetThing(2, 12)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(1, 10), }); // testing INSERT expectedCount = 4; Add(source, GetThing(3, 11)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:12,0:0:11,0:0:10} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), }); // testing INSERT expectedCount = 7; Add(source, GetThing(4, 5)); Add(source, GetThing(5, 14)); Add(source, GetThing(6, 13)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:13,0:0:12,0:0:11,0:0:10,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(5, 14), GetThing(6, 13), GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), GetThing(4, 5), }); // testing MOVE from top to middle expectedCount = 8; Add(source, GetThing(5, 5)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:13,0:0:12,0:0:11,0:0:10,0:0:5,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 13), GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from top to bottom expectedCount = 9; Add(source, GetThing(6, 4)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:13,0:0:12,0:0:11,0:0:10,0:0:5,0:0:4} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), GetThing(6, 4), }); // testing MOVE from bottom to top expectedCount = 10; Add(source, GetThing(6, 14)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:13,0:0:12,0:0:11,0:0:10,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from middle bottom to middle top expectedCount = 11; Add(source, GetThing(3, 14)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:12,0:0:10,0:0:5,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(3, 14), GetThing(2, 12), GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from middle top to middle bottom expectedCount = 12; Add(source, GetThing(2, 9)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:10,0:0:9,0:0:5,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(3, 14), GetThing(1, 10), GetThing(2, 9), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from middle bottom to middle top more than 1 position expectedCount = 13; Add(source, GetThing(5, 12)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:12,0:0:10,0:0:9,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(3, 14), GetThing(5, 12), GetThing(1, 10), GetThing(2, 9), GetThing(4, 5), }); expectedCount = 14; col.RemoveItem(GetThing(1, 10)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:12,0:0:9,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(3, 14), GetThing(5, 12), GetThing(2, 9), GetThing(4, 5), }); col.Dispose(); } [Test] public void SortingTestWithFilterTrue() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare, (item, position, list) => true); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); // testing ADD expectedCount = 1; // add a thing with UpdatedAt=0:0:10 Add(source, GetThing(1, 10)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10) }); // testing ADD // add another thing with UpdatedAt=0:0:2 expectedCount = 2; Add(source, GetThing(2, 2)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:10,0:0:2} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), GetThing(2, 2), }); // testing MOVE // replace thing with UpdatedAt=0:0:2 to UpdatedAt=0:0:12 expectedCount = 3; Add(source, GetThing(2, 12)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:12,0:0:10} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(1, 10), }); // testing INSERT expectedCount = 4; Add(source, GetThing(3, 11)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:12,0:0:11,0:0:10} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), }); // testing INSERT expectedCount = 7; Add(source, GetThing(4, 5)); Add(source, GetThing(5, 14)); Add(source, GetThing(6, 13)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:13,0:0:12,0:0:11,0:0:10,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(5, 14), GetThing(6, 13), GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), GetThing(4, 5), }); // testing MOVE from top to middle expectedCount = 8; Add(source, GetThing(5, 5)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:13,0:0:12,0:0:11,0:0:10,0:0:5,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 13), GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from top to bottom expectedCount = 9; Add(source, GetThing(6, 4)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:13,0:0:12,0:0:11,0:0:10,0:0:5,0:0:4} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), GetThing(6, 4), }); // testing MOVE from bottom to top expectedCount = 10; Add(source, GetThing(6, 14)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:13,0:0:12,0:0:11,0:0:10,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from middle bottom to middle top expectedCount = 11; Add(source, GetThing(3, 14)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:12,0:0:10,0:0:5,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(3, 14), GetThing(2, 12), GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from middle top to middle bottom expectedCount = 12; Add(source, GetThing(2, 9)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:10,0:0:9,0:0:5,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(3, 14), GetThing(1, 10), GetThing(2, 9), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from middle bottom to middle top more than 1 position expectedCount = 13; Add(source, GetThing(5, 12)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:12,0:0:10,0:0:9,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(3, 14), GetThing(5, 12), GetThing(1, 10), GetThing(2, 9), GetThing(4, 5), }); expectedCount = 14; col.RemoveItem(GetThing(1, 10)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:12,0:0:9,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 14), GetThing(3, 14), GetThing(5, 12), GetThing(2, 9), GetThing(4, 5), }); col.Dispose(); } [Test] public void SortingTestWithFilterBetween6And12() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare, (item, position, list) => item.UpdatedAt.Minute >= 6 && item.UpdatedAt.Minute <= 12); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); // testing ADD expectedCount = 1; // add a thing with UpdatedAt=0:0:10 Add(source, GetThing(1, 10)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), }); // testing ADD // add another thing with UpdatedAt=0:0:2 expectedCount = 2; Add(source, GetThing(2, 2)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:10,0:0:2} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), }); // testing MOVE // replace thing with UpdatedAt=0:0:2 to UpdatedAt=0:0:12 expectedCount = 3; Add(source, GetThing(2, 12)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(1, 10), }); // testing INSERT expectedCount = 4; Add(source, GetThing(3, 11)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), }); // testing INSERT expectedCount = 7; Add(source, GetThing(4, 5)); Add(source, GetThing(5, 14)); Add(source, GetThing(6, 13)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), }); // testing MOVE from top to middle expectedCount = 8; Add(source, GetThing(5, 5)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), }); // testing MOVE from top to bottom expectedCount = 9; Add(source, GetThing(6, 4)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), }); // testing MOVE from bottom to top expectedCount = 10; Add(source, GetThing(6, 14)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), }); // testing MOVE from middle bottom to middle top expectedCount = 11; Add(source, GetThing(3, 14)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(1, 10), }); // testing MOVE from middle top to middle bottom expectedCount = 12; Add(source, GetThing(2, 9)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), GetThing(2, 9), }); // testing MOVE from middle bottom to middle top more than 1 position expectedCount = 13; Add(source, GetThing(5, 12)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(5, 12), GetThing(1, 10), GetThing(2, 9), }); expectedCount = 14; col.RemoveItem(GetThing(1, 10)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(5, 12), GetThing(2, 9), }); col.Dispose(); } [Test] public void SortingTestWithFilterPosition2to4() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare, (item, position, list) => position >= 2 && position <= 4); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); // testing ADD expectedCount = 1; // add a thing with UpdatedAt=0:0:10 Add(source, GetThing(1, 10)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing>()); // testing ADD // add another thing with UpdatedAt=0:0:2 expectedCount = 2; Add(source, GetThing(2, 2)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:10,0:0:2} CollectionAssert.AreEqual(col, new List<Thing>()); // testing MOVE // replace thing with UpdatedAt=0:0:2 to UpdatedAt=0:0:12 expectedCount = 3; Add(source, GetThing(2, 12)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing>()); // testing INSERT expectedCount = 4; Add(source, GetThing(3, 11)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), }); // testing INSERT expectedCount = 7; Add(source, GetThing(4, 5)); Add(source, GetThing(5, 14)); Add(source, GetThing(6, 13)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(3, 11), GetThing(1, 10), }); // testing MOVE from top to middle expectedCount = 8; Add(source, GetThing(5, 5)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 11), GetThing(1, 10), GetThing(5, 5), }); // testing MOVE from top to bottom expectedCount = 9; Add(source, GetThing(6, 4)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from bottom to top expectedCount = 10; Add(source, GetThing(6, 14)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 11), GetThing(1, 10), GetThing(5, 5), }); // testing MOVE from middle bottom to middle top expectedCount = 11; Add(source, GetThing(3, 14)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(1, 10), GetThing(5, 5), }); // testing MOVE from middle top to middle bottom expectedCount = 12; Add(source, GetThing(2, 9)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), GetThing(2, 9), GetThing(5, 5), }); // testing MOVE from middle bottom to middle top more than 1 position expectedCount = 13; Add(source, GetThing(5, 12)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(5, 12), GetThing(1, 10), GetThing(2, 9), }); expectedCount = 14; col.RemoveItem(GetThing(1, 10)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(5, 12), GetThing(2, 9), GetThing(4, 5), }); col.Dispose(); } [Test] public void SortingTestWithFilterPosition1And3to4() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare, (item, position, list) => position == 1 || (position >= 3 && position <= 4)); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); // testing ADD expectedCount = 1; // add a thing with UpdatedAt=0:0:10 Add(source, GetThing(1, 10)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing>()); // testing ADD // add another thing with UpdatedAt=0:0:2 expectedCount = 2; Add(source, GetThing(2, 2)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:10,0:0:2} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), }); // testing MOVE // replace thing with UpdatedAt=0:0:2 to UpdatedAt=0:0:12 expectedCount = 3; Add(source, GetThing(2, 12)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 10), }); // testing INSERT expectedCount = 4; Add(source, GetThing(3, 11)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 11), }); // testing INSERT expectedCount = 7; Add(source, GetThing(4, 5)); Add(source, GetThing(5, 14)); Add(source, GetThing(6, 13)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(6, 13), GetThing(3, 11), GetThing(1, 10), }); // testing MOVE from top to middle expectedCount = 8; Add(source, GetThing(5, 5)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(1, 10), GetThing(5, 5), }); // testing MOVE from top to bottom expectedCount = 9; Add(source, GetThing(6, 4)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 11), GetThing(5, 5), GetThing(4, 5), }); // testing MOVE from bottom to top expectedCount = 10; Add(source, GetThing(6, 14)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 12), GetThing(1, 10), GetThing(5, 5), }); // testing MOVE from middle bottom to middle top expectedCount = 11; Add(source, GetThing(3, 14)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 14), GetThing(1, 10), GetThing(5, 5), }); // testing MOVE from middle top to middle bottom expectedCount = 12; Add(source, GetThing(2, 9)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 14), GetThing(2, 9), GetThing(5, 5), }); // testing MOVE from middle bottom to middle top more than 1 position expectedCount = 13; Add(source, GetThing(5, 12)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 14), GetThing(1, 10), GetThing(2, 9), }); expectedCount = 14; Add(source, GetThing(3, 13)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 13), GetThing(1, 10), GetThing(2, 9), }); expectedCount = 15; col.RemoveItem(GetThing(1, 10)); evt.WaitOne(); evt.Reset(); // check that list has {0:0:14,0:0:14,0:0:12,0:0:9,0:0:5} CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 13), GetThing(2, 9), GetThing(4, 5), }); col.Dispose(); } [Test] public void SortingTestWithFilterMoves() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare, (item, position, list) => position == 1 || position == 2 || position == 5 || position == 6 || position == 7); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); expectedCount = 9; Add(source, GetThing(1, 1)); Add(source, GetThing(2, 3)); Add(source, GetThing(3, 5)); Add(source, GetThing(4, 7)); Add(source, GetThing(5, 9)); Add(source, GetThing(6, 11)); Add(source, GetThing(7, 13)); Add(source, GetThing(8, 15)); Add(source, GetThing(9, 17)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 3), GetThing(3, 5), GetThing(6, 11), GetThing(7, 13), GetThing(8, 5), }); expectedCount = 10; Add(source, GetThing(7, 4)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(2, 3), GetThing(7, 4), GetThing(5, 9), GetThing(6, 11), GetThing(8, 5), }); expectedCount = 11; Add(source, GetThing(9, 2)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(9, 2), GetThing(2, 3), GetThing(4, 7), GetThing(5, 9), GetThing(6, 11), }); col.Dispose(); } [Test] public void ChangingItemContentRemovesItFromFilteredList() { var source = new Subject<Thing>(); var now = new DateTimeOffset(0, TimeSpan.FromTicks(0)); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderBy(x => x.CreatedAt).Compare, (item, position, list) => item.UpdatedAt < now + TimeSpan.FromMinutes(6)); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); expectedCount = 5; Add(source, GetThing(1, 1, 1)); Add(source, GetThing(3, 3, 3)); Add(source, GetThing(5, 5, 5)); Add(source, GetThing(7, 7, 7)); Add(source, GetThing(9, 9, 9)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 1, 1), GetThing(3, 3, 3), GetThing(5, 5, 5), }); expectedCount = 6; Add(source, GetThing(5, 5, 6)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 1, 1), GetThing(3, 3, 3), }); col.Dispose(); } [Test] public void ChangingItemContentRemovesItFromFilteredList2() { var source = new Subject<Thing>(); var now = new DateTimeOffset(0, TimeSpan.FromTicks(0)); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderBy(x => x.CreatedAt).Compare, (item, position, list) => item.UpdatedAt > now + TimeSpan.FromMinutes(2) && item.UpdatedAt < now + TimeSpan.FromMinutes(8)); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); expectedCount = 5; Add(source, GetThing(1, 1, 1)); Add(source, GetThing(3, 3, 3)); Add(source, GetThing(5, 5, 5)); Add(source, GetThing(7, 7, 7)); Add(source, GetThing(9, 9, 9)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 3, 3), GetThing(5, 5, 5), GetThing(7, 7, 7), }); expectedCount = 6; Add(source, GetThing(7, 7, 8)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 3, 3), GetThing(5, 5, 5), }); expectedCount = 7; Add(source, GetThing(7, 7, 7)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 3, 3), GetThing(5, 5, 5), GetThing(7, 7, 7), }); expectedCount = 8; Add(source, GetThing(3, 3, 2)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(5, 5, 5), GetThing(7, 7, 7), }); expectedCount = 9; Add(source, GetThing(3, 3, 3)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 3, 3), GetThing(5, 5, 5), GetThing(7, 7, 7), }); expectedCount = 10; Add(source, GetThing(5, 5, 1)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 3, 3), GetThing(7, 7, 7), }); col.Dispose(); } [Test] public void ChangingFilterUpdatesCollection() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare, (item, position, list) => item.UpdatedAt < Now + TimeSpan.FromMinutes(10)); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); expectedCount = 9; Add(source, GetThing(1, 1)); Add(source, GetThing(2, 2)); Add(source, GetThing(3, 3)); Add(source, GetThing(4, 4)); Add(source, GetThing(5, 5)); Add(source, GetThing(6, 6)); Add(source, GetThing(7, 7)); Add(source, GetThing(8, 8)); Add(source, GetThing(9, 9)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 1), GetThing(2, 2), GetThing(3, 3), GetThing(4, 4), GetThing(5, 5), GetThing(6, 6), GetThing(7, 7), GetThing(8, 8), GetThing(9, 9), }); col.Filter = (item, position, list) => item.UpdatedAt < Now + TimeSpan.FromMinutes(8); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(1, 1), GetThing(2, 2), GetThing(3, 3), GetThing(4, 4), GetThing(5, 5), GetThing(6, 6), GetThing(7, 7), }); col.Dispose(); } [Test] public void ChangingSortUpdatesCollection() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare, (item, position, list) => item.UpdatedAt < Now + TimeSpan.FromMinutes(10)); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var count = 0; var evt = new ManualResetEvent(false); var list1 = new List<Thing> { GetThing(1, 1), GetThing(2, 2), GetThing(3, 3), GetThing(4, 4), GetThing(5, 5), GetThing(6, 6), GetThing(7, 7), GetThing(8, 8), GetThing(9, 9), }; col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); foreach (var l in list1) Add(source, l); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, list1); col.Comparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; CollectionAssert.AreEqual(col, list1.Reverse<Thing>().ToArray()); col.Dispose(); } [Test] public void AddingItemsToCollectionManuallyThrows() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(Observable.Empty<Thing>()); Assert.Throws<InvalidOperationException>(() => col.Add(GetThing(1))); col.Dispose(); } [Test] public void InsertingItemsIntoCollectionManuallyThrows() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(Observable.Empty<Thing>()); Assert.Throws<InvalidOperationException>(() => col.Insert(0, GetThing(1))); col.Dispose(); } [Test] public void MovingItemsIntoCollectionManuallyThrows() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>(source) { ProcessingDelay = TimeSpan.Zero }; var count = 0; var expectedCount = 2; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); Add(source, GetThing(1, 1)); Add(source, GetThing(2, 2)); evt.WaitOne(); evt.Reset(); Assert.Throws<InvalidOperationException>(() => (col as TrackingCollection<Thing>).Move(0, 1)); col.Dispose(); } [Test] public void RemovingItemsFromCollectionManuallyThrows() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>(source) { ProcessingDelay = TimeSpan.Zero }; var count = 0; var expectedCount = 2; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); Add(source, GetThing(1, 1)); Add(source, GetThing(2, 2)); evt.WaitOne(); evt.Reset(); Assert.Throws<InvalidOperationException>(() => col.Remove(GetThing(1))); col.Dispose(); } [Test] public void RemovingItemsFromCollectionManuallyThrows2() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>(source) { ProcessingDelay = TimeSpan.Zero }; var count = 0; var expectedCount = 2; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); Add(source, GetThing(1, 1)); Add(source, GetThing(2, 2)); evt.WaitOne(); evt.Reset(); Assert.Throws<InvalidOperationException>(() => col.RemoveAt(0)); col.Dispose(); } [Test] public void ChangingComparers() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>(source, OrderedComparer<Thing>.OrderBy(x => x.CreatedAt).Compare); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var count = 0; var evt = new ManualResetEvent(false); var list1 = new List<Thing> { GetThing(1, 1, 9), GetThing(2, 2, 8), GetThing(3, 3, 7), GetThing(4, 4, 6), GetThing(5, 5, 5), GetThing(6, 6, 4), GetThing(7, 7, 3), GetThing(8, 8, 2), GetThing(9, 9, 1), }; col.Subscribe(t => { if (++count == list1.Count) evt.Set(); }, () => { }); foreach (var l in list1) Add(source, l); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(col, list1); col.Comparer = null; CollectionAssert.AreEqual(col, list1.Reverse<Thing>().ToArray()); col.Dispose(); } [Test] public void Removing() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source, OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare, (item, position, list) => (position > 2 && position < 5) || (position > 6 && position < 8)); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); expectedCount = 11; Add(source, GetThing(0, 0)); Add(source, GetThing(1, 1)); Add(source, GetThing(2, 2)); Add(source, GetThing(3, 3)); Add(source, GetThing(4, 4)); Add(source, GetThing(5, 5)); Add(source, GetThing(6, 6)); Add(source, GetThing(7, 7)); Add(source, GetThing(8, 8)); Add(source, GetThing(9, 9)); Add(source, GetThing(10, 10)); Assert.True(evt.WaitOne(80)); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(3, 3), GetThing(4, 4), GetThing(7, 7), }); expectedCount = 12; col.RemoveItem(GetThing(2)); Assert.True(evt.WaitOne(40)); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(4, 4), GetThing(5, 5), GetThing(8, 8), }); expectedCount = 13; col.RemoveItem(GetThing(5)); Assert.True(evt.WaitOne(40)); evt.Reset(); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(4, 4), GetThing(6, 6), GetThing(9, 9), }); col.Filter = null; expectedCount = 14; col.RemoveItem(GetThing(100)); // this one won't result in a new element from the observable col.RemoveItem(GetThing(10)); Assert.True(evt.WaitOne(40)); evt.Reset(); Assert.AreEqual(8, col.Count); CollectionAssert.AreEqual(col, new List<Thing> { GetThing(0, 0), GetThing(1, 1), GetThing(3, 3), GetThing(4, 4), GetThing(6, 6), GetThing(7, 7), GetThing(8, 8), GetThing(9, 9), }); col.Dispose(); } [Test, Category("CodeCoverageFlake")] public void RemovingFirstItemWithFilterWorks() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Range(0, 5).Select(x => GetThing(x, x)), OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare, (item, position, list) => true); col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 5; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); Assert.True(evt.WaitOne(40)); evt.Reset(); expectedCount = 6; col.RemoveItem(GetThing(0)); Assert.True(evt.WaitOne(40)); evt.Reset(); CollectionAssert.AreEqual(col, Enumerable.Range(1, 4).Select(x => GetThing(x, x))); col.Dispose(); } [Test] public void DisposingThrows() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(Observable.Empty<Thing>()); col.Dispose(); Assert.Throws<ObjectDisposedException>(() => col.Filter = null); Assert.Throws<ObjectDisposedException>(() => col.Comparer = null); Assert.Throws<ObjectDisposedException>(() => col.Subscribe()); Assert.Throws<ObjectDisposedException>(() => col.AddItem(GetThing(1))); Assert.Throws<ObjectDisposedException>(() => col.RemoveItem(GetThing(1))); } [Test, Category("Timings")] public async Task MultipleSortingAndFiltering() { var expectedTotal = 20; var rnd = new Random(214748364); var updatedAtMinutesStack = new Stack<int>(Enumerable.Range(1, expectedTotal).OrderBy(rnd.Next)); var list1 = Observable.Defer(() => Enumerable.Range(1, expectedTotal) .OrderBy(rnd.Next) .Select(x => GetThing(x, x, x, ((char)('a' + x)).ToString())) .ToObservable()) .Replay() .RefCount(); var list2 = Observable.Defer(() => Enumerable.Range(1, expectedTotal) .OrderBy(rnd.Next) .Select(x => GetThing(x, x, updatedAtMinutesStack.Pop(), ((char)('c' + x)).ToString())) .ToObservable()) .Replay() .RefCount(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( list1.Concat(list2), OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare, (item, idx, list) => idx < 5 ); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.Subscribe(); await col.OriginalCompleted.Timeout(TimeSpan.FromMilliseconds(Timeout)); // it's initially sorted by date, so id list should not match CollectionAssert.AreNotEqual(list1.Select(x => x.Number).ToEnumerable(), list2.Select(x => x.Number).ToEnumerable()); var sortlist = col.ToArray(); Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing> .OrderByDescending(x => x.UpdatedAt) .ThenByDescending(x => x.CreatedAt).Compare)); CollectionAssert.AreEqual(sortlist.Take(5), col); col.Comparer = OrderedComparer<Thing>.OrderBy(x => x.Number).Compare; sortlist = col.ToArray(); Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderBy(x => x.Number).Compare)); CollectionAssert.AreEqual(sortlist.Take(5), col); col.Comparer = OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare; sortlist = col.ToArray(); Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing> .OrderBy(x => x.UpdatedAt) .ThenBy(x => x.CreatedAt).Compare)); CollectionAssert.AreEqual(sortlist.Take(5), col); col.Comparer = OrderedComparer<Thing>.OrderByDescending(x => x.Title).Compare; sortlist = col.ToArray(); Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderByDescending(x => x.Title).Compare)); CollectionAssert.AreEqual(sortlist.Take(5), col); col.Comparer = OrderedComparer<Thing>.OrderBy(x => x.Title).Compare; sortlist = col.ToArray(); Array.Sort(sortlist, new LambdaComparer<Thing>(OrderedComparer<Thing>.OrderBy(x => x.Title).Compare)); CollectionAssert.AreEqual(sortlist.Take(5), col); col.Dispose(); } [Test] public async Task ListeningTwiceWorks() { var count = 10; ITrackingCollection<Thing> col = new TrackingCollection<Thing>(); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var list1 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, count - i, "Run 1")).ToList()); var list2 = new List<Thing>(Enumerable.Range(1, count).Select(i => GetThing(i, i, i + count, "Run 2")).ToList()); #pragma warning disable 4014 col.Listen(list1.ToObservable()); col.Subscribe(); await col.OriginalCompleted.Timeout(TimeSpan.FromMilliseconds(Timeout)); col.Listen(list2.ToObservable()); col.Subscribe(); await col.OriginalCompleted.Timeout(TimeSpan.FromMilliseconds(Timeout)); #pragma warning restore 4014 CollectionAssert.AreEqual(list2, col); } [Test] public void AddingWithNoObservableSetThrows() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(); Assert.Throws<InvalidOperationException>(() => col.AddItem(new Thing())); } [Test] public void RemovingWithNoObservableSetThrows() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(); Assert.Throws<InvalidOperationException>(() => col.RemoveItem(new Thing())); } [Test] public async Task AddingBeforeSubscribingWorks() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>(Observable.Empty<Thing>()); ReplaySubject<Thing> done = new ReplaySubject<Thing>(); col.AddItem(GetThing(1)); col.AddItem(GetThing(2)); var count = 0; done.OnNext(null); col.Subscribe(t => { done.OnNext(t); if (++count == 2) done.OnCompleted(); }, () => {}); await done.Timeout(TimeSpan.FromMilliseconds(500)); Assert.AreEqual(2, col.Count); } [Test] public void DoesNotUpdateThingIfTimeIsOlder() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); col.Subscribe(t => { evt.Set(); }, () => { }); var createdAndUpdatedTime = DateTimeOffset.Now; var olderUpdateTime = createdAndUpdatedTime.Subtract(TimeSpan.FromMinutes(1)); const string originalTitle = "Original Thing"; var originalThing = new Thing(1, originalTitle, createdAndUpdatedTime, createdAndUpdatedTime); col.AddItem(originalThing); evt.WaitOne(); evt.Reset(); Assert.AreEqual(originalTitle, col[0].Title); const string updatedTitle = "Updated Thing"; var updatedThing = new Thing(1, updatedTitle, createdAndUpdatedTime, olderUpdateTime); col.AddItem(updatedThing); evt.WaitOne(); evt.Reset(); Assert.AreEqual(originalTitle, col[0].Title); col.Dispose(); } [Test] public void DoesNotUpdateThingIfTimeIsEqual() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); col.Subscribe(t => { evt.Set(); }, () => { }); var createdAndUpdatedTime = DateTimeOffset.Now; const string originalTitle = "Original Thing"; var originalThing = new Thing(1, originalTitle, createdAndUpdatedTime, createdAndUpdatedTime); col.AddItem(originalThing); evt.WaitOne(); evt.Reset(); Assert.AreEqual(originalTitle, col[0].Title); const string updatedTitle = "Updated Thing"; var updatedThing = new Thing(1, updatedTitle, createdAndUpdatedTime, createdAndUpdatedTime); col.AddItem(updatedThing); evt.WaitOne(); evt.Reset(); Assert.AreEqual(originalTitle, col[0].Title); col.Dispose(); } [Test] public void DoesUpdateThingIfTimeIsNewer() { ITrackingCollection<Thing> col = new TrackingCollection<Thing>( Observable.Never<Thing>(), OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare); col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.ProcessingDelay = TimeSpan.Zero; var evt = new ManualResetEvent(false); col.Subscribe(t => { evt.Set(); }, () => { }); var createdAndUpdatedTime = DateTimeOffset.Now; var newerUpdateTime = createdAndUpdatedTime.Add(TimeSpan.FromMinutes(1)); const string originalTitle = "Original Thing"; var originalThing = new Thing(1, originalTitle, createdAndUpdatedTime, createdAndUpdatedTime); col.AddItem(originalThing); evt.WaitOne(); evt.Reset(); Assert.AreEqual(originalTitle, col[0].Title); const string updatedTitle = "Updated Thing"; var updatedThing = new Thing(1, updatedTitle, createdAndUpdatedTime, newerUpdateTime); col.AddItem(updatedThing); evt.WaitOne(); evt.Reset(); Assert.AreEqual(updatedTitle, col[0].Title); col.Dispose(); } [Test] public void ChangingSortingAndUpdatingItemsUpdatesSortCorrectly() { var source = new Subject<Thing>(); ITrackingCollection<Thing> col = new TrackingCollection<Thing>( source); col.Comparer = OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare; col.NewerComparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; col.Filter = (item, position, list) => position == 2 || position == 3 || position == 5 || position == 7; col.ProcessingDelay = TimeSpan.Zero; var count = 0; var expectedCount = 0; var evt = new ManualResetEvent(false); col.Subscribe(t => { if (++count == expectedCount) evt.Set(); }, () => { }); expectedCount = 9; Enumerable.Range(0, expectedCount) .Select(x => GetThing(x, x)) .ForEach(x => Add(source, x)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(new List<Thing> { GetThing(2, 2), GetThing(3, 3), GetThing(5, 5), GetThing(7, 7), }, col); expectedCount = 10; Add(source, GetThing(3, 3, 2)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(new List<Thing> { GetThing(2, 2), GetThing(3, 3), GetThing(5, 5), GetThing(7, 7), }, col); expectedCount = 11; Add(source, GetThing(3, 3, 4)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(new List<Thing> { GetThing(2, 2), GetThing(3, 3, 4), GetThing(5, 5), GetThing(7, 7), }, col); expectedCount = 12; Add(source, GetThing(3, 3, 6)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(new List<Thing> { GetThing(2, 2), GetThing(4, 4), GetThing(3, 3, 6), GetThing(7, 7), }, col); col.Comparer = OrderedComparer<Thing>.OrderByDescending(x => x.UpdatedAt).Compare; CollectionAssert.AreEqual(new List<Thing> { GetThing(3, 3, 6), GetThing(6, 6), GetThing(4, 4), GetThing(1, 1), }, col); expectedCount = 13; Add(source, GetThing(4, 4)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(new List<Thing> { GetThing(3, 3, 6), GetThing(6, 6), GetThing(4, 4), GetThing(1, 1), }, col); expectedCount = 14; Add(source, GetThing(4, 4, 6)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(new List<Thing> { GetThing(3, 3, 6), GetThing(6, 6), GetThing(5, 5), GetThing(1, 1), }, col); expectedCount = 15; Add(source, GetThing(5, 5, 6)); evt.WaitOne(); evt.Reset(); CollectionAssert.AreEqual(new List<Thing> { GetThing(3, 3, 6), GetThing(6, 6), GetThing(5, 5, 6), GetThing(1, 1), }, col); col.Dispose(); } }
30.515192
166
0.536951
[ "MIT" ]
ptoninato/VisualStudio
test/TrackingCollectionTests/TrackingCollectionTests.cs
68,295
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 15.06.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete.NullableByte.NullableByte{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Byte>; using T_DATA2 =System.Nullable<System.Byte>; using T_DATA1_U=System.Byte; using T_DATA2_U=System.Byte; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__04__NN public static class TestSet_001__fields__04__NN { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_SMALLINT"; private const string c_NameOf__COL_DATA2 ="COL2_SMALLINT"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { System.Int64? testID=Helper__InsertRow(db,null,null); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ == /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (null, r.COL_DATA1); Assert.AreEqual (null, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" = ").N("t",c_NameOf__COL_DATA2).T(") OR ((").N("t",c_NameOf__COL_DATA1).IS_NULL().T(") AND (").N("t",c_NameOf__COL_DATA2).IS_NULL().T("))) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { System.Int64? testID=Helper__InsertRow(db,null,null); var recs=db.testTable.Where(r => !(r.COL_DATA1 /*OP{*/ == /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") OR (").N("t",c_NameOf__COL_DATA1).IS_NULL().T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NULL().T(")) AND ((").N("t",c_NameOf__COL_DATA1).IS_NOT_NULL().T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NOT_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_002 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__04__NN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete.NullableByte.NullableByte
31.846154
361
0.563147
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Equal/Complete/NullableByte/NullableByte/TestSet_001__fields__04__NN.cs
5,798
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. // // Generated on 2020 October 09 04:46:29 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using atomic = go.runtime.@internal.atomic_package; using @unsafe = go.@unsafe_package; #nullable enable namespace go { public static partial class runtime_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial struct mcache { // Constructors public mcache(NilType _) { this.next_sample = default; this.local_scan = default; this.tiny = default; this.tinyoffset = default; this.local_tinyallocs = default; this.alloc = default; this.stackcache = default; this.local_largefree = default; this.local_nlargefree = default; this.local_nsmallfree = default; this.flushGen = default; } public mcache(System.UIntPtr next_sample = default, System.UIntPtr local_scan = default, System.UIntPtr tiny = default, System.UIntPtr tinyoffset = default, System.UIntPtr local_tinyallocs = default, array<ptr<mspan>> alloc = default, array<stackfreelist> stackcache = default, System.UIntPtr local_largefree = default, System.UIntPtr local_nlargefree = default, array<System.UIntPtr> local_nsmallfree = default, uint flushGen = default) { this.next_sample = next_sample; this.local_scan = local_scan; this.tiny = tiny; this.tinyoffset = tinyoffset; this.local_tinyallocs = local_tinyallocs; this.alloc = alloc; this.stackcache = stackcache; this.local_largefree = local_largefree; this.local_nlargefree = local_nlargefree; this.local_nsmallfree = local_nsmallfree; this.flushGen = flushGen; } // Enable comparisons between nil and mcache struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(mcache value, NilType nil) => value.Equals(default(mcache)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(mcache value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, mcache value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, mcache value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator mcache(NilType nil) => default(mcache); } [GeneratedCode("go2cs", "0.1.0.0")] private static mcache mcache_cast(dynamic value) { return new mcache(value.next_sample, value.local_scan, value.tiny, value.tinyoffset, value.local_tinyallocs, value.alloc, value.stackcache, value.local_largefree, value.local_nlargefree, value.local_nsmallfree, value.flushGen); } } }
43.792683
449
0.612364
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/runtime/mcache_mcacheStruct.cs
3,591
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Test { using System; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Devices.Edge.Test.Common; using Microsoft.Azure.Devices.Edge.Test.Common.Config; using Microsoft.Azure.Devices.Edge.Test.Helpers; using Microsoft.Azure.Devices.Edge.Util; using Microsoft.Azure.Devices.Edge.Util.Test.Common.NUnit; using NUnit.Framework; using Serilog; [EndToEnd] class Device : SasManualProvisioningFixture { [Test] [Category("CentOsSafe")] public async Task QuickstartCerts() { CancellationToken token = this.TestToken; await this.runtime.DeployConfigurationAsync(token, Context.Current.NestedEdge); string leafDeviceId = DeviceId.Current.Generate(); var leaf = await LeafDevice.CreateAsync( leafDeviceId, Protocol.Amqp, AuthenticationType.Sas, Option.Some(this.runtime.DeviceId), false, this.ca, this.IotHub, Context.Current.Hostname.GetOrElse(Dns.GetHostName().ToLower()), token, Option.None<string>(), Context.Current.NestedEdge); await TryFinally.DoAsync( async () => { DateTime seekTime = DateTime.Now; await leaf.SendEventAsync(token); await leaf.WaitForEventsReceivedAsync(seekTime, token); await leaf.InvokeDirectMethodAsync(token); }, async () => { await leaf.DeleteIdentityAsync(token); }); } [Test] [Category("CentOsSafe")] [Category("NestedEdgeOnly")] public async Task QuickstartChangeSasKey() { CancellationToken token = this.TestToken; await this.runtime.DeployConfigurationAsync(token, Context.Current.NestedEdge); string leafDeviceId = DeviceId.Current.Generate(); // Create leaf and send message var leaf = await LeafDevice.CreateAsync( leafDeviceId, Protocol.Amqp, AuthenticationType.Sas, Option.Some(this.runtime.DeviceId), false, this.ca, this.IotHub, Context.Current.Hostname.GetOrElse(Dns.GetHostName().ToLower()), token, Option.None<string>(), Context.Current.NestedEdge); await TryFinally.DoAsync( async () => { DateTime seekTime = DateTime.Now; await leaf.SendEventAsync(token); await leaf.WaitForEventsReceivedAsync(seekTime, token); await leaf.InvokeDirectMethodAsync(token); }, async () => { await leaf.Close(); await leaf.DeleteIdentityAsync(token); }); // Re-create the leaf with the same device ID, for our purposes this is // the equivalent of updating the SAS keys var leafUpdated = await LeafDevice.CreateAsync( leafDeviceId, Protocol.Amqp, AuthenticationType.Sas, Option.Some(this.runtime.DeviceId), false, this.ca, this.IotHub, Context.Current.Hostname.GetOrElse(Dns.GetHostName().ToLower()), token, Option.None<string>(), Context.Current.NestedEdge); await TryFinally.DoAsync( async () => { DateTime seekTime = DateTime.Now; await leafUpdated.SendEventAsync(token); await leafUpdated.WaitForEventsReceivedAsync(seekTime, token); await leafUpdated.InvokeDirectMethodAsync(token); }, async () => { await leafUpdated.Close(); await leafUpdated.DeleteIdentityAsync(token); }); } [Test] [Category("CentOsSafe")] [Category("NestedEdgeOnly")] [Category("NestedEdgeAmqpOnly")] public async Task RouteMessageL3LeafToL4Module() { CancellationToken token = this.TestToken; await this.runtime.DeployConfigurationAsync(token, Context.Current.NestedEdge); // These must match the IDs in nestededge_middleLayerBaseDeployment_amqp.json, // which defines a route that filters by deviceId to forwards the message // to the relayer module string parentDeviceId = Context.Current.ParentDeviceId.Expect(() => new InvalidOperationException("No parent device ID set!")); string leafDeviceId = "L3LeafToRelayer1"; string relayerModuleId = "relayer1"; // Create leaf and send message var leaf = await LeafDevice.CreateAsync( leafDeviceId, Protocol.Amqp, AuthenticationType.Sas, Option.Some(this.runtime.DeviceId), false, this.ca, this.IotHub, Context.Current.Hostname.GetOrElse(Dns.GetHostName().ToLower()), token, Option.None<string>(), Context.Current.NestedEdge); await TryFinally.DoAsync( async () => { // Send a message from the leaf device DateTime seekTime = DateTime.Now; await leaf.SendEventAsync(token); Log.Information($"Sent message from {leafDeviceId}"); // Verify that the message was received/resent by the relayer module on L4 await Profiler.Run( () => this.IotHub.ReceiveEventsAsync( parentDeviceId, seekTime, data => { data.SystemProperties.TryGetValue("iothub-connection-device-id", out object devId); data.SystemProperties.TryGetValue("iothub-connection-module-id", out object modId); data.Properties.TryGetValue("leaf-message-id", out object msgId); Log.Verbose($"Received event for '{devId + "/" + modId}' with message ID '{msgId}'"); return devId != null && devId.ToString().Equals(parentDeviceId) && modId.ToString().Equals(relayerModuleId); }, token), "Received events from module '{Device}' on Event Hub '{EventHub}'", parentDeviceId + "/" + relayerModuleId, this.IotHub.EntityPath); }, async () => { await leaf.Close(); await leaf.DeleteIdentityAsync(token); }); } [Test] [Category("CentOsSafe")] public async Task DisableReenableParentEdge() { CancellationToken token = this.TestToken; Log.Information("Deploying L3 Edge"); await this.runtime.DeployConfigurationAsync(token, Context.Current.NestedEdge); // Disable the parent Edge device Log.Information("Disabling Edge device"); await this.IotHub.UpdateEdgeEnableStatus(this.runtime.DeviceId, false); await Task.Delay(TimeSpan.FromSeconds(10)); // Re-enable parent Edge Log.Information("Re-enabling Edge device"); await this.IotHub.UpdateEdgeEnableStatus(this.runtime.DeviceId, true); await Task.Delay(TimeSpan.FromSeconds(10)); // Try connecting string leafDeviceId = DeviceId.Current.Generate(); var leaf = await LeafDevice.CreateAsync( leafDeviceId, Protocol.Amqp, AuthenticationType.Sas, Option.Some(this.runtime.DeviceId), false, this.ca, this.IotHub, Context.Current.Hostname.GetOrElse(Dns.GetHostName().ToLower()), token, Option.None<string>(), Context.Current.NestedEdge); await TryFinally.DoAsync( async () => { DateTime seekTime = DateTime.Now; await leaf.SendEventAsync(token); await leaf.WaitForEventsReceivedAsync(seekTime, token); await leaf.InvokeDirectMethodAsync(token); }, async () => { await leaf.DeleteIdentityAsync(token); }); } } }
38.793388
139
0.517363
[ "MIT" ]
hiroyha1/iotedge
test/Microsoft.Azure.Devices.Edge.Test/Device.cs
9,388
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameOverManager : MonoBehaviour { private void Awake() { Messenger.AddListener (GameEvent.DOOR_MOVED, OnDoorMoved); } private void OnDestroy() { Messenger.RemoveListener (GameEvent.DOOR_MOVED, OnDoorMoved); } /// <summary> /// Restart current scene when door has moved. /// </summary> private void OnDoorMoved() { SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex); } }
23.130435
68
0.759398
[ "MIT" ]
milkdoes/solitudeApp
Assets/main/scripts/GameOverManager.cs
534
C#