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;
// 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("ServiceStack.OrmLite.MySql.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ServiceStack.OrmLite.MySql.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[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("6753faeb-f6c3-4aa1-bca0-2a15d2bf1522")]
| 41.8 | 84 | 0.780861 | [
"BSD-3-Clause"
] | augustoproiete-forks/ServiceStack--ServiceStack.OrmLite | src/ServiceStack.OrmLite.MySql.Tests/Properties/AssemblyInfo.cs | 1,048 | C# |
using System;
using System.Linq;
using System.Diagnostics;
using DataStructures.Graphs;
namespace C_Sharp_Algorithms.DataStructuresTests
{
public static class Graphs_UndirectedWeightedSparseGraphTest
{
public static void DoTest()
{
var graph = new UndirectedWeightedSparseGraph<string>();
var verticesSet1 = new string[] { "a", "z", "s", "x", "d", "c", "f", "v" };
graph.AddVertices(verticesSet1);
graph.AddEdge("a", "s", 1);
graph.AddEdge("a", "z", 2);
graph.AddEdge("s", "x", 3);
graph.AddEdge("x", "d", 1);
graph.AddEdge("x", "c", 2);
graph.AddEdge("x", "a", 3);
graph.AddEdge("d", "f", 1);
graph.AddEdge("d", "c", 2);
graph.AddEdge("d", "s", 3);
graph.AddEdge("c", "f", 1);
graph.AddEdge("c", "v", 2);
graph.AddEdge("v", "f", 1);
var allEdges = graph.Edges.ToList();
Debug.Assert(graph.VerticesCount == 8, "Wrong vertices count.");
Debug.Assert(graph.EdgesCount == 12, "Wrong edges count.");
Debug.Assert(graph.EdgesCount == allEdges.Count, "Wrong edges count.");
Debug.Assert(graph.OutgoingEdges("a").ToList().Count == 3, "Wrong outgoing edges from 'a'.");
Debug.Assert(graph.OutgoingEdges("s").ToList().Count == 3, "Wrong outgoing edges from 's'.");
Debug.Assert(graph.OutgoingEdges("x").ToList().Count == 4, "Wrong outgoing edges from 'x'.");
Debug.Assert(graph.OutgoingEdges("d").ToList().Count == 4, "Wrong outgoing edges from 'd'.");
Debug.Assert(graph.OutgoingEdges("c").ToList().Count == 4, "Wrong outgoing edges from 'c'.");
Debug.Assert(graph.OutgoingEdges("v").ToList().Count == 2, "Wrong outgoing edges from 'v'.");
Debug.Assert(graph.OutgoingEdges("f").ToList().Count == 3, "Wrong outgoing edges from 'f'.");
Debug.Assert(graph.OutgoingEdges("z").ToList().Count == 1, "Wrong outgoing edges from 'z'.");
Debug.Assert(graph.IncomingEdges("a").ToList().Count == 3, "Wrong incoming edges from 'a'.");
Debug.Assert(graph.IncomingEdges("s").ToList().Count == 3, "Wrong incoming edges from 's'.");
Debug.Assert(graph.IncomingEdges("x").ToList().Count == 4, "Wrong incoming edges from 'x'.");
Debug.Assert(graph.IncomingEdges("d").ToList().Count == 4, "Wrong incoming edges from 'd'.");
Debug.Assert(graph.IncomingEdges("c").ToList().Count == 4, "Wrong incoming edges from 'c'.");
Debug.Assert(graph.IncomingEdges("v").ToList().Count == 2, "Wrong incoming edges from 'v'.");
Debug.Assert(graph.IncomingEdges("f").ToList().Count == 3, "Wrong incoming edges from 'f'.");
Debug.Assert(graph.IncomingEdges("z").ToList().Count == 1, "Wrong incoming edges from 'z'.");
Console.WriteLine("[*] Undirected Weighted Sparse Graph:");
Console.WriteLine("Graph nodes and edges:");
Console.WriteLine(graph.ToReadable() + "\r\n");
// ASSERT RANDOMLY SELECTED EDGES
var f_to_c = graph.HasEdge("f", "c");
var f_to_c_weight = graph.GetEdgeWeight("f", "c");
Debug.Assert(f_to_c == true, "Edge f->c doesn't exist.");
Debug.Assert(f_to_c_weight == 1, "Edge f->c must have a weight of 2.");
Console.WriteLine("Is there an edge from f to c? " + f_to_c + ". If yes it's weight is: " + f_to_c_weight + ".");
// ASSERT RANDOMLY SELECTED EDGES
var d_to_s = graph.HasEdge("d", "s");
var d_to_s_weight = graph.GetEdgeWeight("d", "s");
Debug.Assert(d_to_s == true, "Edge d->s doesn't exist.");
Debug.Assert(d_to_s_weight == 3, "Edge d->s must have a weight of 3.");
Console.WriteLine("Is there an edge from d to d? " + d_to_s + ". If yes it's weight is: " + d_to_s_weight + ".");
Console.WriteLine();
// TRY ADDING DUPLICATE EDGES BUT WITH DIFFERENT WEIGHTS
var add_d_to_s_status = graph.AddEdge("d", "s", 6);
Debug.Assert(add_d_to_s_status == false, "Error! Added a duplicate edge.");
var add_c_to_f_status = graph.AddEdge("c", "f", 12);
Debug.Assert(add_c_to_f_status == false, "Error! Added a duplicate edge.");
var add_s_to_x_status = graph.AddEdge("s", "x", 123);
Debug.Assert(add_s_to_x_status == false, "Error! Added a duplicate edge.");
var add_x_to_d_status = graph.AddEdge("x", "d", 34);
Debug.Assert(add_x_to_d_status == false, "Error! Added a duplicate edge.");
// TEST DELETING EDGES
graph.RemoveEdge("d", "c");
Debug.Assert(graph.HasEdge("d", "c") == false, "Error! The edge d->c was deleted.");
graph.RemoveEdge("c", "v");
Debug.Assert(graph.HasEdge("c", "v") == false, "Error! The edge c->v was deleted.");
graph.RemoveEdge("a", "z");
Debug.Assert(graph.HasEdge("a", "z") == false, "Error! The edge a->z was deleted.");
// ASSERT VERTICES AND EDGES COUNT
Debug.Assert(graph.VerticesCount == 8, "Wrong vertices count.");
Debug.Assert(graph.EdgesCount == 9, "Wrong edges count.");
Console.WriteLine("After removing edges (d-c), (c-v), (a-z):");
Console.WriteLine(graph.ToReadable() + "\r\n");
// TEST DELETING VERTICES
graph.RemoveVertex("x");
Debug.Assert(graph.HasEdge("x", "a") == false, "Error! The edge x->a was deleted because vertex x was deleted.");
// ASSERT VERTICES AND EDGES COUNT
Debug.Assert(graph.VerticesCount == 7, "Wrong vertices count.");
Debug.Assert(graph.EdgesCount == 5, "Wrong edges count.");
Console.WriteLine("After removing node (x):");
Console.WriteLine(graph.ToReadable() + "\r\n");
graph.AddVertex("x");
graph.AddEdge("s", "x", 3);
graph.AddEdge("x", "d", 1);
graph.AddEdge("x", "c", 2);
graph.AddEdge("x", "a", 3);
graph.AddEdge("d", "c", 2);
graph.AddEdge("c", "v", 2);
graph.AddEdge("a", "z", 2);
Console.WriteLine("Re-added the deleted vertices and edges to the graph.");
Console.WriteLine(graph.ToReadable() + "\r\n");
// BFS from A
Console.WriteLine("Walk the graph using BFS from A:");
var bfsWalk = graph.BreadthFirstWalk("a"); // output: (s) (a) (x) (z) (d) (c) (f) (v)
foreach (var node in bfsWalk) Console.Write(String.Format("({0})", node));
Console.WriteLine("\r\n");
// DFS from A
Console.WriteLine("Walk the graph using DFS from A:");
var dfsWalk = graph.DepthFirstWalk("a"); // output: (s) (a) (x) (z) (d) (c) (f) (v)
foreach (var node in dfsWalk) Console.Write(String.Format("({0})", node));
Console.WriteLine("\r\n");
// BFS from F
Console.WriteLine("Walk the graph using BFS from F:");
bfsWalk = graph.BreadthFirstWalk("f"); // output: (s) (a) (x) (z) (d) (c) (f) (v)
foreach (var node in bfsWalk) Console.Write(String.Format("({0})", node));
Console.WriteLine("\r\n");
// DFS from F
Console.WriteLine("Walk the graph using DFS from F:");
dfsWalk = graph.DepthFirstWalk("f"); // output: (s) (a) (x) (z) (d) (c) (f) (v)
foreach (var node in dfsWalk) Console.Write(String.Format("({0})", node));
Console.WriteLine("\r\n");
Console.ReadLine();
/********************************************************************/
Console.WriteLine("***************************************************\r\n");
graph.Clear();
Console.WriteLine("Cleared the graph from all vertices and edges.\r\n");
var verticesSet2 = new string[] { "a", "b", "c", "d", "e", "f" };
graph.AddVertices(verticesSet2);
graph.AddEdge("a", "b", 1);
graph.AddEdge("a", "d", 2);
graph.AddEdge("b", "e", 3);
graph.AddEdge("d", "b", 1);
graph.AddEdge("d", "e", 2);
graph.AddEdge("e", "c", 3);
graph.AddEdge("c", "f", 1);
graph.AddEdge("f", "f", 1);
Debug.Assert(graph.VerticesCount == 6, "Wrong vertices count.");
Debug.Assert(graph.EdgesCount == 8, "Wrong edges count.");
Console.WriteLine("[*] NEW Undirected Weighted Sparse Graph:");
Console.WriteLine("Graph nodes and edges:");
Console.WriteLine(graph.ToReadable() + "\r\n");
Console.WriteLine("Walk the graph using DFS:");
dfsWalk = graph.DepthFirstWalk(); // output: (a) (b) (e) (d) (c) (f)
foreach (var node in dfsWalk) Console.Write(String.Format("({0})", node));
Console.ReadLine();
}
}
}
| 47.108247 | 125 | 0.540212 | [
"MIT"
] | JUNLAN2015/DataStructure | MainProgram/DataStructuresTests/Graphs_UndirectedWeightedSparseGraphTest.cs | 9,141 | 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 cloudsearch-2013-01-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.CloudSearch.Model
{
/// <summary>
/// Container for the parameters to the BuildSuggesters operation.
/// Indexes the search suggestions. For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html#configuring-suggesters">Configuring
/// Suggesters</a> in the <i>Amazon CloudSearch Developer Guide</i>.
/// </summary>
public partial class BuildSuggestersRequest : AmazonCloudSearchRequest
{
private string _domainName;
/// <summary>
/// Gets and sets the property DomainName.
/// </summary>
[AWSProperty(Required=true, Min=3, Max=28)]
public string DomainName
{
get { return this._domainName; }
set { this._domainName = value; }
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this._domainName != null;
}
}
} | 32.947368 | 196 | 0.685836 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CloudSearch/Generated/Model/BuildSuggestersRequest.cs | 1,878 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.NetApp.V20200501
{
/// <summary>
/// Snapshot policy information
/// </summary>
[AzureNativeResourceType("azure-native:netapp/v20200501:SnapshotPolicy")]
public partial class SnapshotPolicy : Pulumi.CustomResource
{
/// <summary>
/// Schedule for daily snapshots
/// </summary>
[Output("dailySchedule")]
public Output<Outputs.DailyScheduleResponse?> DailySchedule { get; private set; } = null!;
/// <summary>
/// The property to decide policy is enabled or not
/// </summary>
[Output("enabled")]
public Output<bool?> Enabled { get; private set; } = null!;
/// <summary>
/// Schedule for hourly snapshots
/// </summary>
[Output("hourlySchedule")]
public Output<Outputs.HourlyScheduleResponse?> HourlySchedule { get; private set; } = null!;
/// <summary>
/// Resource location
/// </summary>
[Output("location")]
public Output<string> Location { get; private set; } = null!;
/// <summary>
/// Schedule for monthly snapshots
/// </summary>
[Output("monthlySchedule")]
public Output<Outputs.MonthlyScheduleResponse?> MonthlySchedule { get; private set; } = null!;
/// <summary>
/// Snapshot policy name
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Azure lifecycle management
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Resource tags
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Schedule for weekly snapshots
/// </summary>
[Output("weeklySchedule")]
public Output<Outputs.WeeklyScheduleResponse?> WeeklySchedule { get; private set; } = null!;
/// <summary>
/// Create a SnapshotPolicy resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public SnapshotPolicy(string name, SnapshotPolicyArgs args, CustomResourceOptions? options = null)
: base("azure-native:netapp/v20200501:SnapshotPolicy", name, args ?? new SnapshotPolicyArgs(), MakeResourceOptions(options, ""))
{
}
private SnapshotPolicy(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:netapp/v20200501:SnapshotPolicy", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200501:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-native:netapp:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:netapp:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200601:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200601:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200701:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200701:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200801:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200801:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200901:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200901:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-native:netapp/v20201101:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20201101:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-native:netapp/v20201201:SnapshotPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20201201:SnapshotPolicy"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing SnapshotPolicy resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static SnapshotPolicy Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new SnapshotPolicy(name, id, options);
}
}
public sealed class SnapshotPolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the NetApp account
/// </summary>
[Input("accountName", required: true)]
public Input<string> AccountName { get; set; } = null!;
/// <summary>
/// Schedule for daily snapshots
/// </summary>
[Input("dailySchedule")]
public Input<Inputs.DailyScheduleArgs>? DailySchedule { get; set; }
/// <summary>
/// The property to decide policy is enabled or not
/// </summary>
[Input("enabled")]
public Input<bool>? Enabled { get; set; }
/// <summary>
/// Schedule for hourly snapshots
/// </summary>
[Input("hourlySchedule")]
public Input<Inputs.HourlyScheduleArgs>? HourlySchedule { get; set; }
/// <summary>
/// Resource location
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// Schedule for monthly snapshots
/// </summary>
[Input("monthlySchedule")]
public Input<Inputs.MonthlyScheduleArgs>? MonthlySchedule { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the snapshot policy target
/// </summary>
[Input("snapshotPolicyName")]
public Input<string>? SnapshotPolicyName { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
/// <summary>
/// Schedule for weekly snapshots
/// </summary>
[Input("weeklySchedule")]
public Input<Inputs.WeeklyScheduleArgs>? WeeklySchedule { get; set; }
public SnapshotPolicyArgs()
{
}
}
}
| 39.292453 | 140 | 0.583673 | [
"Apache-2.0"
] | sebtelko/pulumi-azure-native | sdk/dotnet/NetApp/V20200501/SnapshotPolicy.cs | 8,330 | 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.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Test.Helpers;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Microsoft.AspNetCore.Components.Test
{
public class PageDisplayTest
{
private TestRenderer _renderer = new TestRenderer();
private PageDisplay _pageDisplayComponent = new PageDisplay();
private int _pageDisplayComponentId;
public PageDisplayTest()
{
_renderer = new TestRenderer();
_pageDisplayComponent = new PageDisplay();
_pageDisplayComponentId = _renderer.AssignRootComponentId(_pageDisplayComponent);
}
[Fact]
public void DisplaysComponentInsideLayout()
{
// Arrange/Act
_renderer.Dispatcher.InvokeAsync(() => _pageDisplayComponent.SetParametersAsync(ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(PageDisplay.Page), typeof(ComponentWithLayout) }
})));
// Assert
var batch = _renderer.Batches.Single();
Assert.Collection(batch.DiffsInOrder,
diff =>
{
// First is the LayoutDisplay component, which contains a RootLayout
var singleEdit = diff.Edits.Single();
Assert.Equal(RenderTreeEditType.PrependFrame, singleEdit.Type);
AssertFrame.Component<RootLayout>(
batch.ReferenceFrames[singleEdit.ReferenceFrameIndex]);
},
diff =>
{
// ... then a RootLayout which contains a ComponentWithLayout
// First is the LayoutDisplay component, which contains a RootLayout
Assert.Collection(diff.Edits,
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"RootLayout starts here");
},
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<ComponentWithLayout>(
batch.ReferenceFrames[edit.ReferenceFrameIndex]);
},
edit =>
{
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Text(
batch.ReferenceFrames[edit.ReferenceFrameIndex],
"RootLayout ends here");
});
},
diff =>
{
// ... then the ComponentWithLayout
var singleEdit = diff.Edits.Single();
Assert.Equal(RenderTreeEditType.PrependFrame, singleEdit.Type);
AssertFrame.Text(
batch.ReferenceFrames[singleEdit.ReferenceFrameIndex],
$"{nameof(ComponentWithLayout)} is here.");
});
}
[Fact]
public void DisplaysComponentInsideNestedLayout()
{
// Arrange/Act
_renderer.Dispatcher.InvokeAsync(() => _pageDisplayComponent.SetParametersAsync(ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(PageDisplay.Page), typeof(ComponentWithNestedLayout) }
})));
// Assert
var batch = _renderer.Batches.Single();
Assert.Collection(batch.DiffsInOrder,
// First, a LayoutDisplay containing a RootLayout
diff => AssertFrame.Component<RootLayout>(
batch.ReferenceFrames[diff.Edits[0].ReferenceFrameIndex]),
// Then a RootLayout containing a NestedLayout
diff => AssertFrame.Component<NestedLayout>(
batch.ReferenceFrames[diff.Edits[1].ReferenceFrameIndex]),
// Then a NestedLayout containing a ComponentWithNestedLayout
diff => AssertFrame.Component<ComponentWithNestedLayout>(
batch.ReferenceFrames[diff.Edits[1].ReferenceFrameIndex]),
// Then the ComponentWithNestedLayout
diff => AssertFrame.Text(
batch.ReferenceFrames[diff.Edits[0].ReferenceFrameIndex],
$"{nameof(ComponentWithNestedLayout)} is here."));
}
[Fact]
public void CanChangeDisplayedPageWithSameLayout()
{
// Arrange
_renderer.Dispatcher.InvokeAsync(() => _pageDisplayComponent.SetParametersAsync(ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(PageDisplay.Page), typeof(ComponentWithLayout) }
})));
// Act
_renderer.Dispatcher.InvokeAsync(() => _pageDisplayComponent.SetParametersAsync(ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(PageDisplay.Page), typeof(DifferentComponentWithLayout) }
})));
// Assert
Assert.Equal(2, _renderer.Batches.Count);
var batch = _renderer.Batches[1];
Assert.Equal(1, batch.DisposedComponentIDs.Count); // Disposed only the inner page component
Assert.Collection(batch.DiffsInOrder,
diff => Assert.Empty(diff.Edits), // LayoutDisplay rerendered, but with no changes
diff =>
{
// RootLayout rerendered
Assert.Collection(diff.Edits,
edit =>
{
// Removed old page
Assert.Equal(RenderTreeEditType.RemoveFrame, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
},
edit =>
{
// Inserted new one
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
AssertFrame.Component<DifferentComponentWithLayout>(
batch.ReferenceFrames[edit.ReferenceFrameIndex]);
});
},
diff =>
{
// New page rendered
var singleEdit = diff.Edits.Single();
Assert.Equal(RenderTreeEditType.PrependFrame, singleEdit.Type);
AssertFrame.Text(
batch.ReferenceFrames[singleEdit.ReferenceFrameIndex],
$"{nameof(DifferentComponentWithLayout)} is here.");
});
}
[Fact]
public void CanChangeDisplayedPageWithDifferentLayout()
{
// Arrange
_renderer.Dispatcher.InvokeAsync(() => _pageDisplayComponent.SetParametersAsync(ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(PageDisplay.Page), typeof(ComponentWithLayout) }
})));
// Act
_renderer.Dispatcher.InvokeAsync(() => _pageDisplayComponent.SetParametersAsync(ParameterView.FromDictionary(new Dictionary<string, object>
{
{ nameof(PageDisplay.Page), typeof(ComponentWithNestedLayout) }
})));
// Assert
Assert.Equal(2, _renderer.Batches.Count);
var batch = _renderer.Batches[1];
Assert.Equal(1, batch.DisposedComponentIDs.Count); // Disposed only the inner page component
Assert.Collection(batch.DiffsInOrder,
diff => Assert.Empty(diff.Edits), // LayoutDisplay rerendered, but with no changes
diff =>
{
// RootLayout rerendered
Assert.Collection(diff.Edits,
edit =>
{
// Removed old page
Assert.Equal(RenderTreeEditType.RemoveFrame, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
},
edit =>
{
// Inserted new nested layout
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
Assert.Equal(1, edit.SiblingIndex);
AssertFrame.Component<NestedLayout>(
batch.ReferenceFrames[edit.ReferenceFrameIndex]);
});
},
diff =>
{
// New nested layout rendered
var edit = diff.Edits[1];
Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type);
AssertFrame.Component<ComponentWithNestedLayout>(
batch.ReferenceFrames[edit.ReferenceFrameIndex]);
},
diff =>
{
// New inner page rendered
var singleEdit = diff.Edits.Single();
Assert.Equal(RenderTreeEditType.PrependFrame, singleEdit.Type);
AssertFrame.Text(
batch.ReferenceFrames[singleEdit.ReferenceFrameIndex],
$"{nameof(ComponentWithNestedLayout)} is here.");
});
}
private class RootLayout : AutoRenderComponent
{
[Parameter]
public RenderFragment Body { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddContent(0, "RootLayout starts here");
builder.AddContent(1, Body);
builder.AddContent(2, "RootLayout ends here");
}
}
[Layout(typeof(RootLayout))]
private class NestedLayout : AutoRenderComponent
{
[Parameter]
public RenderFragment Body { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.AddContent(0, "NestedLayout starts here");
builder.AddContent(1, Body);
builder.AddContent(2, "NestedLayout ends here");
}
}
[Layout(typeof(RootLayout))]
private class ComponentWithLayout : AutoRenderComponent
{
protected override void BuildRenderTree(RenderTreeBuilder builder)
=> builder.AddContent(0, $"{nameof(ComponentWithLayout)} is here.");
}
[Layout(typeof(RootLayout))]
private class DifferentComponentWithLayout : AutoRenderComponent
{
protected override void BuildRenderTree(RenderTreeBuilder builder)
=> builder.AddContent(0, $"{nameof(DifferentComponentWithLayout)} is here.");
}
[Layout(typeof(NestedLayout))]
private class ComponentWithNestedLayout : AutoRenderComponent
{
protected override void BuildRenderTree(RenderTreeBuilder builder)
=> builder.AddContent(0, $"{nameof(ComponentWithNestedLayout)} is here.");
}
}
}
| 44.203704 | 151 | 0.534562 | [
"Apache-2.0"
] | 303248153/AspNetCore | src/Components/Components/test/PageDisplayTest.cs | 11,935 | C# |
using System;
using Util.Datas.Queries;
using Util.Datas.Sql.Builders;
namespace Util.Datas.Sql {
/// <summary>
/// From子句扩展
/// </summary>
public static partial class Extensions {
/// <summary>
/// 内连接
/// </summary>
/// <param name="source">源</param>
/// <param name="table">表名</param>
/// <param name="alias">别名</param>
public static T Join<T>( this T source, string table, string alias = null ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.Join( table, alias );
return source;
}
/// <summary>
/// 内连接子查询
/// </summary>
/// <param name="source">源</param>
/// <param name="builder">Sql生成器</param>
/// <param name="alias">表别名</param>
public static T Join<T>( this T source, ISqlBuilder builder, string alias ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.Join( builder, alias );
return source;
}
/// <summary>
/// 内连接子查询
/// </summary>
/// <param name="source">源</param>
/// <param name="action">子查询操作</param>
/// <param name="alias">表别名</param>
public static T Join<T>( this T source, Action<ISqlBuilder> action, string alias ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.Join( action, alias );
return source;
}
/// <summary>
/// 添加到内连接子句
/// </summary>
/// <param name="source">源</param>
/// <param name="sql">Sql语句,说明:原样添加到Sql中,不会进行任何处理</param>
public static T AppendJoin<T>( this T source, string sql ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.AppendJoin( sql );
return source;
}
/// <summary>
/// 添加到内连接子句
/// </summary>
/// <param name="source">源</param>
/// <param name="sql">Sql语句,说明:原样添加到Sql中,不会进行任何处理</param>
/// <param name="condition">该值为true时添加Sql,否则忽略</param>
public static T AppendJoin<T>( this T source, string sql, bool condition ) where T : IJoin {
return condition ? AppendJoin( source, sql ) : source;
}
/// <summary>
/// 左外连接
/// </summary>
/// <param name="source">源</param>
/// <param name="table">表名</param>
/// <param name="alias">别名</param>
public static T LeftJoin<T>( this T source, string table, string alias = null ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.LeftJoin( table, alias );
return source;
}
/// <summary>
/// 左外连接子查询
/// </summary>
/// <param name="source">源</param>
/// <param name="builder">Sql生成器</param>
/// <param name="alias">表别名</param>
public static T LeftJoin<T>( this T source, ISqlBuilder builder, string alias ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.LeftJoin( builder, alias );
return source;
}
/// <summary>
/// 左外连接子查询
/// </summary>
/// <param name="source">源</param>
/// <param name="action">子查询操作</param>
/// <param name="alias">表别名</param>
public static T LeftJoin<T>( this T source, Action<ISqlBuilder> action, string alias ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.LeftJoin( action, alias );
return source;
}
/// <summary>
/// 添加到左外连接子句
/// </summary>
/// <param name="source">源</param>
/// <param name="sql">Sql语句,说明:原样添加到Sql中,不会进行任何处理</param>
public static T AppendLeftJoin<T>( this T source, string sql ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.AppendLeftJoin( sql );
return source;
}
/// <summary>
/// 添加到左外连接子句
/// </summary>
/// <param name="source">源</param>
/// <param name="sql">Sql语句,说明:原样添加到Sql中,不会进行任何处理</param>
/// <param name="condition">该值为true时添加Sql,否则忽略</param>
public static T AppendLeftJoin<T>( this T source, string sql, bool condition ) where T : IJoin {
return condition ? AppendLeftJoin( source, sql ) : source;
}
/// <summary>
/// 右外连接
/// </summary>
/// <param name="source">源</param>
/// <param name="table">表名</param>
/// <param name="alias">别名</param>
public static T RightJoin<T>( this T source, string table, string alias = null ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.RightJoin( table, alias );
return source;
}
/// <summary>
/// 右外连接子查询
/// </summary>
/// <param name="source">源</param>
/// <param name="builder">Sql生成器</param>
/// <param name="alias">表别名</param>
public static T RightJoin<T>( this T source, ISqlBuilder builder, string alias ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.RightJoin( builder, alias );
return source;
}
/// <summary>
/// 右外连接子查询
/// </summary>
/// <param name="source">源</param>
/// <param name="action">子查询操作</param>
/// <param name="alias">表别名</param>
public static T RightJoin<T>( this T source, Action<ISqlBuilder> action, string alias ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.RightJoin( action, alias );
return source;
}
/// <summary>
/// 添加到右外连接子句
/// </summary>
/// <param name="source">源</param>
/// <param name="sql">Sql语句,说明:原样添加到Sql中,不会进行任何处理</param>
public static T AppendRightJoin<T>( this T source, string sql ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.AppendRightJoin( sql );
return source;
}
/// <summary>
/// 添加到右外连接子句
/// </summary>
/// <param name="source">源</param>
/// <param name="sql">Sql语句,说明:原样添加到Sql中,不会进行任何处理</param>
/// <param name="condition">该值为true时添加Sql,否则忽略</param>
public static T AppendRightJoin<T>( this T source, string sql, bool condition ) where T : IJoin {
return condition ? AppendRightJoin( source, sql ) : source;
}
/// <summary>
/// 设置连接条件
/// </summary>
/// <param name="source">源</param>
/// <param name="condition">连接条件</param>
public static T On<T>( this T source, ICondition condition ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.On( condition );
return source;
}
/// <summary>
/// 设置连接条件
/// </summary>
/// <param name="source">源</param>
/// <param name="column">列名</param>
/// <param name="value">值</param>
/// <param name="operator">运算符</param>
public static T On<T>( this T source, string column, object value, Operator @operator = Operator.Equal ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.On( column, value, @operator );
return source;
}
/// <summary>
/// 添加到On子句
/// </summary>
/// <param name="source">源</param>
/// <param name="sql">Sql语句</param>
public static T AppendOn<T>( this T source, string sql ) where T : IJoin {
if( source == null )
throw new ArgumentNullException( nameof( source ) );
if( source is IClauseAccessor accessor )
accessor.JoinClause.AppendOn( sql );
return source;
}
}
} | 39.239837 | 130 | 0.532995 | [
"MIT"
] | 12321/Util | src/Util.Datas/Sql/Extensions.IJoin.cs | 10,389 | C# |
using UnityEngine.Events;
using UnityEngine.Serialization;
namespace CustomAvatar
{
public class EveryNthComboFilter : EventFilterBehaviour
{
public int ComboStep = 50;
public UnityEvent NthComboReached;
private void OnEnable()
{
EventManager.OnComboChanged.AddListener(OnComboStep);
}
private void OnDisable()
{
EventManager.OnComboChanged.RemoveListener(OnComboStep);
}
private void OnComboStep(int combo)
{
if (combo % ComboStep == 0 && combo != 0)
{
NthComboReached.Invoke();
}
}
}
public class ComboReachedEvent : EventFilterBehaviour
{
public int ComboTarget = 50;
[FormerlySerializedAs("NthComboReached")]
public UnityEvent ComboReached;
private void OnEnable()
{
EventManager.OnComboChanged.AddListener(OnComboReached);
}
private void OnDisable()
{
EventManager.OnComboChanged.RemoveListener(OnComboReached);
}
private void OnComboReached(int combo)
{
if (combo == ComboTarget)
{
ComboReached.Invoke();
}
}
}
} | 18.833333 | 62 | 0.718781 | [
"MIT"
] | Assistant/CustomAvatarsPlugin | CustomAvatar/EventFilters.cs | 1,019 | C# |
namespace StyleChecker.Spacing.NoSingleSpaceAfterTripleSlash
{
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using R = Resources;
/// <summary>
/// NoSingleSpaceAfterTripleSlash analyzer.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class Analyzer : AbstractAnalyzer
{
/// <summary>
/// The ID of this analyzer.
/// </summary>
public const string DiagnosticId
= nameof(NoSingleSpaceAfterTripleSlash);
private const string Category = Categories.Spacing;
private static readonly DiagnosticDescriptor Rule = NewRule();
private static readonly ImmutableHashSet<char> WhitespaceCharSet
= ImmutableHashSet.Create(' ', '\t');
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor>
SupportedDiagnostics => ImmutableArray.Create(Rule);
/// <inheritdoc/>
private protected override void Register(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.RegisterSyntaxTreeAction(SyntaxTreeAction);
}
private static DiagnosticDescriptor NewRule()
{
var localize = Localizers.Of<R>(R.ResourceManager);
return new DiagnosticDescriptor(
DiagnosticId,
localize(nameof(R.Title)),
localize(nameof(R.MessageFormat)),
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: localize(nameof(R.Description)),
helpLinkUri: HelpLink.ToUri(DiagnosticId));
}
private static void SyntaxTreeAction(SyntaxTreeAnalysisContext context)
{
static bool IsSldcTrivia(SyntaxNode t)
=> t.Kind() is SyntaxKind.SingleLineDocumentationCommentTrivia;
static bool IsDceTrivia(SyntaxTrivia t)
=> t.Kind() is SyntaxKind.DocumentationCommentExteriorTrivia;
static bool IsSingleSpace(SyntaxTrivia t)
=> t.Kind() is SyntaxKind.WhitespaceTrivia
&& t.Span.Length is 1;
static XmlNodeSyntax? GetNextElement(
DocumentationCommentTriviaSyntax s,
XmlTextSyntax t)
{
var all = s.Content;
var k = all.IndexOf(t);
if (k is -1)
{
throw new ArgumentException("t");
}
if (k == all.Count - 1)
{
return null;
}
return all[k + 1];
}
static bool IsNextTokenNewLine(
XmlTextSyntax s, SyntaxToken t)
{
var all = s.TextTokens;
var k = all.IndexOf(t);
if (k is -1)
{
throw new ArgumentException("t");
}
if (k == all.Count - 1)
{
return false;
}
return all[k + 1].Kind()
is SyntaxKind.XmlTextLiteralNewLineToken;
}
static bool DoesTokenHaveGoodSpace(SyntaxToken t)
{
var text = t.Text;
var p = t.Parent;
if (!(p is XmlTextSyntax child))
{
return false;
}
if (!WhitespaceCharSet.Contains(text[0]))
{
return false;
}
if (!(child.Parent is DocumentationCommentTriviaSyntax top)
|| !IsSldcTrivia(top))
{
return true;
}
var next = GetNextElement(top, child);
if (next is null)
{
return true;
}
if (IsNextTokenNewLine(child, t))
{
return true;
}
return text.Length is 1;
}
static bool DoesTokenStartWithWhiteSpace(SyntaxToken t)
{
var k = t.Kind();
return k is SyntaxKind.XmlTextLiteralNewLineToken
|| (k is SyntaxKind.XmlTextLiteralToken
&& DoesTokenHaveGoodSpace(t));
}
static bool IsNextSiblingTriviaSingleSpace(SyntaxTrivia t)
{
var a = t.Token.LeadingTrivia;
var n = a.IndexOf(t);
return a.Count >= n + 2
&& IsSingleSpace(a[n + 1]);
}
static bool DoesTokenHaveSingleLeadingTrivia(SyntaxTrivia t)
{
var p = t.Token;
var a = p.LeadingTrivia;
return DoesTokenStartWithWhiteSpace(p)
&& a.Last() == t;
}
var tree = context.Tree;
var root = tree.GetCompilationUnitRoot(
context.CancellationToken);
var all = root.DescendantNodes(descendIntoTrivia: true)
.OfType<DocumentationCommentTriviaSyntax>()
.Where(t => IsSldcTrivia(t))
.SelectMany(t => t.DescendantTrivia())
.Where(t => IsDceTrivia(t)
&& !DoesTokenHaveSingleLeadingTrivia(t)
&& !IsNextSiblingTriviaSingleSpace(t));
/*
Case 1a:
XmlTextLiteralNewLineToken
+ Lead: DocumentationCommentExteriorTrivia
Case 1b:
SingleLineDocumentationCommentTrivia
+ ...
+ XmlText
| + ...
| + XmlTextLiteralToken (equals " ")
| + Lead: ...
| + Lead: DocumentationCommentExteriorTrivia
+ ...
+ [...]
+ XmlElement
+ ...
+ XmlText
+ ...
+ XmlTextLiteralToken (starts with " "...)
+ Lead: ...
+ Lead: DocumentationCommentExteriorTrivia
Case 2:
Token
+ Lead: ...
+ Lead: DocumentationCommentExteriorTrivia
+ Lead: WhiteSpaceTrivia
+ Lead: ...
*/
foreach (var t in all)
{
var w = Location.Create(tree, t.Token.Span);
context.ReportDiagnostic(Diagnostic.Create(Rule, w));
}
}
/*
StyleCop.Analyzers (1.1.118) emits SA1004 to the following code:
/// <seealso cref="LineBreakInsideAttribute
/// (string, string)"/>
/// <seealso cref="LineBreakInsideAttribute(
/// string, string)"/>
/// <seealso cref="LineBreakInsideAttribute(string,
/// string)"/>
/// <seealso cref="LineBreakInsideAttribute(string, string
/// )"/>
private void LineBreakInsideAttribute(string a, string b)
{
}
*/
}
}
| 31.959459 | 79 | 0.513319 | [
"BSD-2-Clause"
] | MatthewL246/StyleChecker | StyleChecker/StyleChecker/Spacing/NoSingleSpaceAfterTripleSlash/Analyzer.cs | 7,095 | 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.Linq;
using NuGet.Server.Infrastructure;
namespace NuGet.Server.DataServices
{
public class PackageContext
{
private readonly IServerPackageRepository _repository;
public PackageContext(IServerPackageRepository repository)
{
_repository = repository;
}
public IQueryable<ODataPackage> Packages
{
get
{
return _repository
.GetPackages()
.Select(package => package.AsODataPackage())
.AsQueryable()
.InterceptWith(new NormalizeVersionInterceptor());
}
}
}
}
| 28.366667 | 112 | 0.599295 | [
"ECL-2.0",
"Apache-2.0"
] | MerickOWA/NuGet.Server | src/NuGet.Server/DataServices/PackageContext.cs | 851 | 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.Kafka
{
/// <summary>
/// A resource for managing Kafka ACLs.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Kafka = Pulumi.Kafka;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var test = new Kafka.Acl("test", new Kafka.AclArgs
/// {
/// AclResourceName = "syslog",
/// AclResourceType = "Topic",
/// AclPrincipal = "User:Alice",
/// AclHost = "*",
/// AclOperation = "Write",
/// AclPermissionType = "Deny",
/// });
/// }
///
/// }
/// ```
/// </summary>
[KafkaResourceType("kafka:index/acl:Acl")]
public partial class Acl : Pulumi.CustomResource
{
/// <summary>
/// Host from which principal listed in `acl_principal`
/// will have access.
/// </summary>
[Output("aclHost")]
public Output<string> AclHost { get; private set; } = null!;
/// <summary>
/// Operation that is being allowed or denied. Valid
/// values are `Unknown`, `Any`, `All`, `Read`, `Write`, `Create`, `Delete`, `Alter`,
/// `Describe`, `ClusterAction`, `DescribeConfigs`, `AlterConfigs`, `IdempotentWrite`.
/// </summary>
[Output("aclOperation")]
public Output<string> AclOperation { get; private set; } = null!;
/// <summary>
/// Type of permission. Valid values are `Unknown`,
/// `Any`, `Allow`, `Deny`.
/// </summary>
[Output("aclPermissionType")]
public Output<string> AclPermissionType { get; private set; } = null!;
/// <summary>
/// Principal that is being allowed or denied.
/// </summary>
[Output("aclPrincipal")]
public Output<string> AclPrincipal { get; private set; } = null!;
/// <summary>
/// The name of the resource.
/// </summary>
[Output("aclResourceName")]
public Output<string> AclResourceName { get; private set; } = null!;
/// <summary>
/// The type of resource. Valid values are `Unknown`,
/// `Any`, `Topic`, `Group`, `Cluster`, `TransactionalID`.
/// </summary>
[Output("aclResourceType")]
public Output<string> AclResourceType { get; private set; } = null!;
/// <summary>
/// The pattern filter. Valid values
/// are `Prefixed`, `Any`, `Match`, `Literal`.
/// </summary>
[Output("resourcePatternTypeFilter")]
public Output<string?> ResourcePatternTypeFilter { get; private set; } = null!;
/// <summary>
/// Create a Acl resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Acl(string name, AclArgs args, CustomResourceOptions? options = null)
: base("kafka:index/acl:Acl", name, args ?? new AclArgs(), MakeResourceOptions(options, ""))
{
}
private Acl(string name, Input<string> id, AclState? state = null, CustomResourceOptions? options = null)
: base("kafka:index/acl:Acl", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Acl resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Acl Get(string name, Input<string> id, AclState? state = null, CustomResourceOptions? options = null)
{
return new Acl(name, id, state, options);
}
}
public sealed class AclArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Host from which principal listed in `acl_principal`
/// will have access.
/// </summary>
[Input("aclHost", required: true)]
public Input<string> AclHost { get; set; } = null!;
/// <summary>
/// Operation that is being allowed or denied. Valid
/// values are `Unknown`, `Any`, `All`, `Read`, `Write`, `Create`, `Delete`, `Alter`,
/// `Describe`, `ClusterAction`, `DescribeConfigs`, `AlterConfigs`, `IdempotentWrite`.
/// </summary>
[Input("aclOperation", required: true)]
public Input<string> AclOperation { get; set; } = null!;
/// <summary>
/// Type of permission. Valid values are `Unknown`,
/// `Any`, `Allow`, `Deny`.
/// </summary>
[Input("aclPermissionType", required: true)]
public Input<string> AclPermissionType { get; set; } = null!;
/// <summary>
/// Principal that is being allowed or denied.
/// </summary>
[Input("aclPrincipal", required: true)]
public Input<string> AclPrincipal { get; set; } = null!;
/// <summary>
/// The name of the resource.
/// </summary>
[Input("aclResourceName", required: true)]
public Input<string> AclResourceName { get; set; } = null!;
/// <summary>
/// The type of resource. Valid values are `Unknown`,
/// `Any`, `Topic`, `Group`, `Cluster`, `TransactionalID`.
/// </summary>
[Input("aclResourceType", required: true)]
public Input<string> AclResourceType { get; set; } = null!;
/// <summary>
/// The pattern filter. Valid values
/// are `Prefixed`, `Any`, `Match`, `Literal`.
/// </summary>
[Input("resourcePatternTypeFilter")]
public Input<string>? ResourcePatternTypeFilter { get; set; }
public AclArgs()
{
}
}
public sealed class AclState : Pulumi.ResourceArgs
{
/// <summary>
/// Host from which principal listed in `acl_principal`
/// will have access.
/// </summary>
[Input("aclHost")]
public Input<string>? AclHost { get; set; }
/// <summary>
/// Operation that is being allowed or denied. Valid
/// values are `Unknown`, `Any`, `All`, `Read`, `Write`, `Create`, `Delete`, `Alter`,
/// `Describe`, `ClusterAction`, `DescribeConfigs`, `AlterConfigs`, `IdempotentWrite`.
/// </summary>
[Input("aclOperation")]
public Input<string>? AclOperation { get; set; }
/// <summary>
/// Type of permission. Valid values are `Unknown`,
/// `Any`, `Allow`, `Deny`.
/// </summary>
[Input("aclPermissionType")]
public Input<string>? AclPermissionType { get; set; }
/// <summary>
/// Principal that is being allowed or denied.
/// </summary>
[Input("aclPrincipal")]
public Input<string>? AclPrincipal { get; set; }
/// <summary>
/// The name of the resource.
/// </summary>
[Input("aclResourceName")]
public Input<string>? AclResourceName { get; set; }
/// <summary>
/// The type of resource. Valid values are `Unknown`,
/// `Any`, `Topic`, `Group`, `Cluster`, `TransactionalID`.
/// </summary>
[Input("aclResourceType")]
public Input<string>? AclResourceType { get; set; }
/// <summary>
/// The pattern filter. Valid values
/// are `Prefixed`, `Any`, `Match`, `Literal`.
/// </summary>
[Input("resourcePatternTypeFilter")]
public Input<string>? ResourcePatternTypeFilter { get; set; }
public AclState()
{
}
}
}
| 36.893443 | 123 | 0.554877 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-kafka | sdk/dotnet/Acl.cs | 9,002 | C# |
using System;
using System.Collections.Generic;
using DSIS.CellImageBuilder.Shared;
using DSIS.Scheme.Ctx;
using DSIS.Scheme.Impl.Actions.Files;
using DSIS.Utils;
namespace DSIS.Scheme.Impl.Actions.Console
{
public class DumpMethodAction : IntegerCoordinateSystemActionBase2
{
protected override ICollection<ContextMissmatchCheck> Check<T, Q>(T system, Context ctx)
{
return ColBase(base.Check<T, Q>(system, ctx), Create(Keys.SubdivisionKey), Create(Keys.CellImageBuilderKey));
}
protected override void Apply<T, Q>(T system, Context input, Context output)
{
ICellImageBuilderIntegerCoordinatesSettings sets = Keys.CellImageBuilderKey.Get(input);
Logger.Instance(input).Write("Method: {0}", sets.Create<Q>().PresentableName);
}
}
} | 33.541667 | 116 | 0.72795 | [
"Apache-2.0"
] | jonnyzzz/phd-project | dsis/src/Scheme.Impl.Tests/src/Actions/Console/DumpMethodAction.cs | 805 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System.Runtime.Serialization;
namespace Microsoft.WindowsAzurePack.ApiClients.DataContracts
{
/// <summary>
/// Usage Notification Event Type
/// </summary>
public enum UsageEventType
{
/// <summary>
/// Represents a Plan
/// </summary>
[EnumMember]
Plan,
/// <summary>
/// Represents a Subscription
/// </summary>
[EnumMember]
Subscription,
/// <summary>
/// Represents an add-on
/// </summary>
[EnumMember]
AddOn,
/// <summary>
/// Represents a change in association between a Plan and an add-on
/// </summary>
[EnumMember]
PlanAddOn,
/// <summary>
/// Represents a change in association between a Subscription and an add-on
/// </summary>
[EnumMember]
SubscriptionAddOn,
/// <summary>
/// Represents a change in association between a Resource Provider and a Plan
/// </summary>
[EnumMember]
PlanService,
/// <summary>
/// Represents a change in association between a Resource Provider and an add-on
/// </summary>
[EnumMember]
AddOnService,
}
}
| 25.964286 | 88 | 0.502063 | [
"MIT"
] | Bhaskers-Blu-Org2/dpm2012r2wap | AzurePackClient/DataContracts/UsageEventType.cs | 1,456 | C# |
/*===================================================================================
*
* Copyright (c) Userware/OpenSilver.net
*
* This file is part of the OpenSilver Runtime (https://opensilver.net), which is
* licensed under the MIT license: https://opensource.org/licenses/MIT
*
* As stated in the MIT license, "the above copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software."
*
\*====================================================================================*/
using System;
#if MIGRATION
namespace System.Windows.Data
#else
namespace Windows.UI.Xaml.Data
#endif
{
internal abstract class PropertyPathNode : IPropertyPathNode
{
private IPropertyPathNodeListener _nodeListener;
protected PropertyPathNode()
{
Value = DependencyProperty.UnsetValue;
}
public object Source { get; private set; }
public object Value { get; private set; }
public bool IsBroken { get; private set; }
public IPropertyPathNode Next { get; set; }
internal abstract Type TypeImpl { get; }
internal void UpdateValueAndIsBroken(object newValue, bool isBroken)
{
IsBroken = isBroken;
Value = newValue;
IPropertyPathNodeListener listener = _nodeListener;
if (listener != null)
{
listener.ValueChanged(this);
}
}
internal abstract void OnSourceChanged(object oldSource, object newSource);
internal abstract void UpdateValue();
internal abstract void SetValue(object value);
Type IPropertyPathNode.Type => TypeImpl;
void IPropertyPathNode.SetSource(object source)
{
object oldSource = Source;
Source = source;
if (oldSource != Source)
{
OnSourceChanged(oldSource, Source);
}
UpdateValue();
if (Next != null)
{
Next.SetSource(Value == DependencyProperty.UnsetValue ? null : Value);
}
}
void IPropertyPathNode.SetValue(object value)
{
SetValue(value);
}
void IPropertyPathNode.Listen(IPropertyPathNodeListener listener)
{
_nodeListener = listener;
}
void IPropertyPathNode.Unlisten(IPropertyPathNodeListener listener)
{
if (_nodeListener == listener)
{
_nodeListener = null;
}
}
}
}
| 26.908163 | 88 | 0.54873 | [
"MIT"
] | Barjonp/OpenSilver | src/Runtime/Runtime/System.Windows.Data/PropertyPathNode.cs | 2,639 | C# |
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Xml.Linq;
using Kudu.Client.Infrastructure;
using Kudu.Core.Infrastructure;
namespace Kudu.TestHarness
{
public class KuduUtils
{
public static void DownloadDump(string serviceUrl, string zippedLogsPath, NetworkCredential credentials = null)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(zippedLogsPath));
var clientHandler = HttpClientHelper.CreateClientHandler(serviceUrl, credentials);
var client = new HttpClient(clientHandler);
var result = client.GetAsync(serviceUrl + "api/dump").Result;
if (result.IsSuccessStatusCode)
{
using (Stream stream = result.Content.ReadAsStreamAsync().Result)
{
using (FileStream fs = File.Open(zippedLogsPath, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fs);
}
}
}
}
catch (Exception ex)
{
TestTracer.Trace("Failed to download dump - {0}", ex.GetBaseException().Message);
}
}
public static void KillKuduProcess(string serviceUrl, NetworkCredential credentials = null)
{
try
{
var clientHandler = HttpClientHelper.CreateClientHandler(serviceUrl, credentials);
var client = new HttpClient(clientHandler);
client.DeleteAsync(serviceUrl + "api/processes/0").Wait();
}
catch (Exception)
{
// no-op
}
}
public static XDocument GetServerProfile(string serviceUrl, string logsTempPath, string appName, NetworkCredential credentials = null)
{
var zippedLogsPath = Path.Combine(logsTempPath, appName + ".zip");
var unzippedLogsPath = Path.Combine(logsTempPath, appName);
var profileLogPath = Path.Combine(unzippedLogsPath, "trace", "trace.xml");
XDocument document = null;
DownloadDump(serviceUrl, zippedLogsPath, credentials);
if (File.Exists(zippedLogsPath))
{
ZipUtils.Unzip(zippedLogsPath, unzippedLogsPath);
using (var stream = File.OpenRead(profileLogPath))
{
document = XDocument.Load(stream);
}
}
return document;
}
public static string SiteReusedForAllTests
{
get
{
string siteName = GetTestSetting("SiteReusedForAllTests");
if (String.IsNullOrEmpty(siteName))
{
return Environment.MachineName;
}
// Append the machine name to the site to avoid conflicting with other users running tests
return String.Format("{0}{1}", siteName, Environment.MachineName);
}
}
public static bool StopAfterFirstTestFailure
{
get
{
return GetBooleanTestSetting("StopAfterFirstTestFailure");
}
}
public static bool DisableRetry
{
get
{
return GetBooleanTestSetting("DisableRetry");
}
}
public static bool GetBooleanTestSetting(string settingName)
{
bool retValue;
if (bool.TryParse(GetTestSetting(settingName), out retValue))
{
return retValue;
}
return false;
}
public static string GetTestSetting(string settingName)
{
// If value exists as an environment setting use that otherwise try to get from app settings (for usage of the ci)
string environmentValue = Environment.GetEnvironmentVariable(settingName);
if (!String.IsNullOrEmpty(environmentValue))
{
return environmentValue;
}
else
{
return ConfigurationManager.AppSettings[settingName];
}
}
public static IDisposable MockAzureEnvironment()
{
Environment.SetEnvironmentVariable("WEBSITE_INSTANCE_ID", "1234");
return new DisposableAction(() => Environment.SetEnvironmentVariable("WEBSITE_INSTANCE_ID", null));
}
}
}
| 33.352518 | 142 | 0.552416 | [
"Apache-2.0"
] | AzureMentor/kudu | Kudu.TestHarness/KuduUtils.cs | 4,638 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace book_manager_app
{
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>();
});
}
}
| 25.851852 | 70 | 0.647564 | [
"MIT"
] | yyaddaden/asp.net-intro-demo | book-manager-app/book-manager-app/Program.cs | 698 | C# |
using Felinesoft.UmbracoCodeFirst;
using Felinesoft.UmbracoCodeFirst.ContentTypes;
using Felinesoft.UmbracoCodeFirst.DataTypes;
using Felinesoft.UmbracoCodeFirst.DataTypes.BuiltIn;
using Felinesoft.UmbracoCodeFirst.Attributes;
using Felinesoft.UmbracoCodeFirst.Extensions;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Umbraco.Core.Models;
using System;
namespace UmbracoCodeFirst.GeneratedTypes
{
[DataType("AngularGoogleMaps", "Google Map")]
[PreValue("1", @"")]
[PreValue("2", @"400")]
[PreValue("1", @"")]
[PreValue("1", @"")]
[PreValue("5", @"2")]
public class GoogleMap : IUmbracoNtextDataType
{
//TODO implement the properties and serialisation logic for the AngularGoogleMaps property editor's values
/// <summary>
/// Initialises the instance from the db value
/// </summary>
public void Initialise(string dbValue)
{
throw new NotImplementedException();
}
/// <summary>
/// Serialises the instance to the db value
/// </summary>
public string Serialise()
{
throw new NotImplementedException();
}
}
} | 28.761905 | 114 | 0.663907 | [
"MIT"
] | DanMannMann/UmbracoCodeFirst | Felinesoft.UmbracoCodeFirst.TestTarget/types/DataTypes/GoogleMap.cs | 1,208 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Telerik.Data.Core.Layouts
{
internal class CompactLayout : BaseLayout
{
internal Dictionary<object, GroupInfo> itemInfoTable = new Dictionary<object, GroupInfo>();
internal IndexToValueTable<bool> collapsedSlotsTable;
internal double averageItemLength;
private IndexToValueTable<GroupInfo> groupHeadersTable;
private IHierarchyAdapter hierarchyAdapter;
private IRenderInfo renderInfo;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "These virtual calls do not rely on uninitialized base state.")]
public CompactLayout(IHierarchyAdapter adapter, double defaultItemLength)
{
if (adapter == null)
{
throw new ArgumentNullException("adapter", "Adapter cannot be null.");
}
this.DefaultItemLength = defaultItemLength;
this.hierarchyAdapter = adapter;
this.averageItemLength = defaultItemLength;
this.collapsedSlotsTable = new IndexToValueTable<bool>();
this.groupHeadersTable = new IndexToValueTable<GroupInfo>();
this.LayoutStrategies.Add(new ItemsLayoutStrategy());
this.renderInfo = new IndexStorage(this.TotalSlotCount, this.DefaultItemLength);
}
public override int GroupCount
{
get
{
return this.groupHeadersTable.IndexCount;
}
}
internal int RenderInfoCount
{
get
{
return this.renderInfo != null ? this.RenderInfo.Count : 0;
}
}
protected override IRenderInfo RenderInfo
{
get
{
if (this.renderInfo == null)
{
this.renderInfo = new IndexStorage(this.TotalSlotCount, this.DefaultItemLength);
}
return this.renderInfo;
}
}
protected IHierarchyAdapter HierarchyAdapter
{
get
{
return this.hierarchyAdapter;
}
}
protected IndexToValueTable<GroupInfo> GroupHeadersTable
{
get
{
return this.groupHeadersTable;
}
}
protected Dictionary<object, GroupInfo> ItemInfoTable
{
get
{
return this.itemInfoTable;
}
}
public override IEnumerable<Group> GetGroupsByKey(object key)
{
if (key == null)
{
yield break;
}
foreach (var pair in this.itemInfoTable)
{
var group = pair.Key as Group;
if (group != null && key.Equals(group.Name))
{
yield return group;
}
}
}
public override IEnumerable<IList<ItemInfo>> GetLines(int line, bool forward)
{
if (this.VisibleLineCount == 0 || line < 0 || line >= this.VisibleLineCount)
{
yield break;
}
int slot = this.GetVisibleSlot(line);
while (true)
{
IList<ItemInfo> itemInfos = null;
foreach (var strategy in this.LayoutStrategies)
{
itemInfos = strategy.BuildItemInfos(this, line, slot);
if (itemInfos != null && itemInfos.Count > 0)
{
break;
}
}
if (itemInfos == null || itemInfos.Count == 0)
{
yield break;
}
yield return itemInfos;
slot = forward ? this.GetNextVisibleSlot(slot) : this.GetPreviousVisibleSlot(slot);
line += forward ? 1 : -1;
}
}
public override void Expand(object item)
{
var groupInfo = this.GetGroupInfo(item);
bool isCollapsed = groupInfo != null ? !groupInfo.IsExpanded : false;
if (isCollapsed)
{
groupInfo.IsExpanded = true;
if (groupInfo.IsVisible())
{
int groupSlot = 0;
int groupSlotSpan = 0;
this.GetCollapseRange(groupInfo, out groupSlot, out groupSlotSpan);
this.collapsedSlotsTable.RemoveValues(groupSlot, groupSlotSpan);
int expandedCount = groupSlotSpan;
foreach (var collapsedGroup in this.CollapsedChildItems(groupInfo.Item))
{
int slot;
int slotSpan;
this.GetCollapseRange(collapsedGroup, out slot, out slotSpan);
expandedCount -= slotSpan;
this.collapsedSlotsTable.AddValues(slot, slotSpan, true);
}
this.VisibleLineCount += expandedCount;
this.RaiseExpanded(new ExpandCollapseEventArgs(item, groupSlot, groupSlotSpan));
}
}
}
public override void Collapse(object item)
{
var groupInfo = this.GetGroupInfo(item);
if (groupInfo != null && groupInfo.IsExpanded && this.IsCollapsible(groupInfo))
{
groupInfo.IsExpanded = false;
if (groupInfo.IsVisible())
{
this.CollapseCore(groupInfo, true);
}
}
}
public override bool IsCollapsed(object item)
{
var groupInfo = this.GetGroupInfo(item);
return groupInfo != null ? !groupInfo.IsExpanded : false;
}
internal static void UpdateParentGroupInfosLastSlot(int count, GroupInfo groupInfo)
{
GroupInfo parentGroupInfo = groupInfo != null ? groupInfo.Parent : null;
while (parentGroupInfo != null)
{
parentGroupInfo.LastSubItemSlot += count;
parentGroupInfo = parentGroupInfo.Parent;
}
}
internal override int IndexFromSlot(int slotToRequest)
{
return slotToRequest;
}
internal override void RefreshRenderInfo(bool force)
{
if (force || (this.renderInfo != null && this.VisibleLineCount != this.renderInfo.Count))
{
this.renderInfo = null;
}
}
internal override AddRemoveLayoutResult AddItem(object changedItem, object addRemoveItem, int addRemoveItemIndex)
{
int count = 1;
bool isVisible = true;
var groupInfo = this.GetGroupInfo(changedItem);
bool changedGroupIsRoot = groupInfo == null;
int slot = addRemoveItemIndex;
int level = changedGroupIsRoot ? 0 : groupInfo.Level + 1;
// We added/removed group so we need to index all subgroups.
if (addRemoveItem is IGroup && changedItem != addRemoveItem)
{
slot = this.GetInsertedGroupSlot(changedItem, addRemoveItemIndex);
isVisible = groupInfo != null ? (groupInfo.IsExpanded && groupInfo.IsVisible()) : true;
// We give a list in which to insert groups so that we can manually correct the indexes in groupHeadersTable.
List<GroupInfo> insertedGroups = new List<GroupInfo>();
count = this.CountAndPopulateTables(addRemoveItem, slot, level, this.GroupLevels, groupInfo, false, insertedGroups);
bool first = true;
int innerMostSlot = slot;
foreach (var newGroupInfo in insertedGroups)
{
int groupInfoToInsertSpan = newGroupInfo.GetLineSpan();
if (first)
{
first = false;
this.groupHeadersTable.InsertIndexes(newGroupInfo.Index, groupInfoToInsertSpan);
if (isVisible)
{
this.collapsedSlotsTable.InsertIndexes(slot, count);
this.VisibleLineCount += count;
}
else
{
this.collapsedSlotsTable.InsertIndexesAndValues(slot, count, false);
}
}
this.groupHeadersTable.AddValue(newGroupInfo.Index, newGroupInfo);
// We get the inner most group so that we update groups after inner most (the upper one are newly created and their index and last slot count are correct.
// We get it only if the change is in the root group. In existing groups we know the correct slot.
if (changedGroupIsRoot)
{
innerMostSlot = newGroupInfo.Index;
}
}
// Update groups after current one.
this.UpdateGroupHeadersTable(innerMostSlot, count);
if (groupInfo != null)
{
// Update the group last slot.
groupInfo.LastSubItemSlot += count;
}
}
else
{
// We added new item (not group) into root group.
if (changedGroupIsRoot)
{
if (isVisible)
{
this.VisibleLineCount += count;
}
// slot should be already correct.
// No need to correct collapsed slots. They should be empty (e.g. no groups to collapse).
System.Diagnostics.Debug.Assert(this.groupHeadersTable.IsEmpty, "GroupHeaders table should be empty.");
System.Diagnostics.Debug.Assert(this.collapsedSlotsTable.IsEmpty, "CollapsedSlots table should be empty since we don't have groups.");
}
else
{
// We added new item (not group) into existing bottom level group (not root group).
slot = groupInfo.Index + 1 + addRemoveItemIndex;
// Update the group last slot.
groupInfo.LastSubItemSlot += count;
this.groupHeadersTable.InsertIndex(slot);
isVisible = groupInfo.IsExpanded && groupInfo.IsVisible();
if (isVisible)
{
this.collapsedSlotsTable.InsertIndexes(slot, count);
this.VisibleLineCount += count;
}
else
{
this.collapsedSlotsTable.InsertIndexesAndValues(slot, count, false);
}
this.UpdateGroupHeadersTable(groupInfo.Index, count);
}
}
// Update parent groups last slot.
UpdateParentGroupInfosLastSlot(count, groupInfo);
// Update TotalCount.
this.TotalSlotCount += count;
// Update Visible line count if not collapsed.
double length = isVisible ? this.averageItemLength : 0;
// Insert new records into IndexTree.
this.RenderInfo.InsertRange(slot, IndexStorage.UnknownItemLength, count);
var layoutResult = new AddRemoveLayoutResult(slot, count);
foreach (var strategy in this.LayoutStrategies)
{
strategy.OnItemAdded(layoutResult);
}
// return result indexes so that changed can be reflected to UI.
return layoutResult;
}
internal override AddRemoveLayoutResult RemoveItem(object changedItem, object addRemoveItem, int addRemoveItemIndex)
{
int count = 1;
bool isVisible = true;
GroupInfo changedGroupInfo = this.GetGroupInfo(changedItem);
bool changedGroupIsRoot = changedGroupInfo == null;
int slot = addRemoveItemIndex;
int level = changedGroupIsRoot ? 0 : changedGroupInfo.Level + 1;
IGroup removedGroup = addRemoveItem as IGroup;
// We added/removed group so we need to index all subgroups.
if (removedGroup != null && changedItem != addRemoveItem)
{
GroupInfo groupInfo = this.GetGroupInfo(addRemoveItem);
System.Diagnostics.Debug.Assert(groupInfo != null, "Cannot remove group that are not indexed.");
slot = groupInfo.Index;
isVisible = groupInfo.IsVisible();
count = groupInfo.GetLineSpan();
if (!removedGroup.HasItems)
{
foreach (var nextGroupIndex in this.groupHeadersTable.GetIndexes(slot + 1))
{
GroupInfo nextGroupInfo = this.groupHeadersTable.GetValueAt(nextGroupIndex);
if (nextGroupInfo.Level <= groupInfo.Level)
{
break;
}
this.RemoveGroupInfo(nextGroupInfo);
}
}
this.UpdateGroupHeadersTable(groupInfo.Index, -count);
this.itemInfoTable.Remove(removedGroup);
this.groupHeadersTable.RemoveIndexesAndValues(slot, count);
if (isVisible)
{
if (groupInfo.IsExpanded)
{
int collapsedItems = count - this.GetCollapsedSlotsCount(slot, slot + count - 1);
this.VisibleLineCount -= collapsedItems;
}
else
{
this.VisibleLineCount -= 1;
}
}
this.collapsedSlotsTable.RemoveIndexesAndValues(slot, count);
if (changedGroupInfo != null)
{
// Update the group last slot.
changedGroupInfo.LastSubItemSlot -= count;
}
}
else
{
// We added new item (not group) into root group.
if (changedGroupIsRoot)
{
if (isVisible)
{
this.VisibleLineCount -= count;
}
// slot should be already correct.
// No need to correct collapsed slots. They should be empty (e.g. no groups to collapse).
System.Diagnostics.Debug.Assert(this.groupHeadersTable.IsEmpty, "GroupHeaders table should be empty.");
System.Diagnostics.Debug.Assert(this.collapsedSlotsTable.IsEmpty, "CollapsedSlots table should be empty since we don't have groups.");
}
else
{
// We added new item (not group) into existing bottom level group (not root group).
slot = changedGroupInfo.Index + 1 + addRemoveItemIndex;
// Update the group last slot.
changedGroupInfo.LastSubItemSlot -= count;
this.groupHeadersTable.RemoveIndex(slot);
isVisible = changedGroupInfo.IsExpanded && changedGroupInfo.IsVisible();
if (isVisible)
{
this.collapsedSlotsTable.RemoveIndexes(slot, count);
this.VisibleLineCount -= count;
}
else
{
this.collapsedSlotsTable.RemoveIndexesAndValues(slot, count);
}
this.UpdateGroupHeadersTable(changedGroupInfo.Index, -count);
}
}
// Update parent groups last slot.
UpdateParentGroupInfosLastSlot(-count, changedGroupInfo);
// Update TotalCount.
this.TotalSlotCount -= count;
// Insert new records into IndexTree.
this.RenderInfo.RemoveRange(slot, count);
var layoutResult = new AddRemoveLayoutResult(slot, count);
foreach (var strategy in this.LayoutStrategies)
{
strategy.OnItemRemoved(layoutResult);
}
// return result indexes so that changed can be reflected to UI.
return layoutResult;
}
internal override int GetNextVisibleSlot(int slot)
{
return this.collapsedSlotsTable.GetNextGap(slot);
}
internal override bool IsItemCollapsed(int slot)
{
return this.collapsedSlotsTable.Contains(slot);
}
internal override IRenderInfoState GetRenderLoadState()
{
return new LayoutRenderInfoState(this.collapsedSlotsTable);
}
internal int GetPreviousVisibleSlot(int slot)
{
return this.collapsedSlotsTable.GetPreviousGap(slot);
}
internal virtual int GetLayoutLevel(ItemInfo itemInfo, GroupInfo parentGroupInfo)
{
return 0;
}
internal virtual int GetIndent(ItemInfo itemInfo, GroupInfo parentGroupInfo)
{
if (itemInfo.ItemType == GroupType.Subtotal)
{
if (parentGroupInfo != null && !parentGroupInfo.IsExpanded)
{
return this.AggregatesLevel;
}
else
{
return itemInfo.Level - 1;
}
}
return itemInfo.Level;
}
internal override int GetVisibleSlot(int index)
{
return this.collapsedSlotsTable.CountNextNotIncludedIndexes(0, index);
}
internal override int GetCollapsedSlotsCount(int startSlot, int endSlot)
{
return this.collapsedSlotsTable.GetIndexCount(startSlot, endSlot);
}
internal override GroupInfo GetGroupInfo(object item)
{
GroupInfo groupInfo;
if (this.itemInfoTable != null && this.itemInfoTable.TryGetValue(item, out groupInfo))
{
return groupInfo;
}
return null;
}
internal override double SlotFromPhysicalOffset(double physicalOffset, bool includeCollapsed = false)
{
var logicalOffset = this.RenderInfo.IndexFromOffset(physicalOffset);
double offset;
if (logicalOffset > 0)
{
double currentItemWidth = this.RenderInfo.ValueForIndex(logicalOffset);
if (currentItemWidth == 0)
{
currentItemWidth = this.DefaultItemLength;
}
var previousItemOffset = this.RenderInfo.OffsetFromIndex(logicalOffset - 1);
if (!includeCollapsed)
{
var collapsedSlotCount = this.GetCollapsedSlotsCount(0, logicalOffset);
logicalOffset -= collapsedSlotCount;
}
offset = logicalOffset + (physicalOffset - previousItemOffset) / currentItemWidth;
}
else
{
offset = this.RenderInfo.OffsetFromIndex(logicalOffset);
offset = physicalOffset / Math.Max(offset, 1);
}
return offset;
}
internal override void UpdateAverageLength(int startIndex, int endIndex)
{
int generated = endIndex - startIndex + 1;
if (generated == 1)
{
this.averageItemLength = this.RenderInfo.ValueForIndex(startIndex);
}
else
{
double endOffset = this.RenderInfo.OffsetFromIndex(endIndex);
double startOffset = startIndex > 0 ? this.RenderInfo.OffsetFromIndex(startIndex - 1) : 0;
this.averageItemLength = (endOffset - startOffset) / generated;
}
}
internal override int CountAndPopulateTables(object item, int rootSlot, int level, int levels, GroupInfo parent, bool shouldIndexItem, List<GroupInfo> insert, ref int totalLines)
{
return this.CountAndPopulateTables(item, rootSlot, level, levels, parent, shouldIndexItem, insert);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2233:OperationsShouldNotOverflow", Justification = "Not a real issue.")]
internal int CountAndPopulateTables(object item, int rootSlot, int level, int levels, GroupInfo parent, bool shouldIndexItem, List<GroupInfo> insert)
{
int treeCount = 1;
var subItems = this.hierarchyAdapter.GetItems(item);
IGroup group = item as IGroup;
GroupInfo itemGroupInfo = null;
if (level <= levels - 1)
{
bool shouldIndexChildren = false;
foreach (var subItem in subItems)
{
if (itemGroupInfo == null)
{
itemGroupInfo = new GroupInfo(item, parent, true, level, rootSlot, rootSlot + treeCount - 1);
}
int childrenCount = this.CountAndPopulateTables(subItem, rootSlot + treeCount, level + 1, levels, itemGroupInfo, shouldIndexChildren, insert);
shouldIndexChildren = shouldIndexChildren || childrenCount > 1;
treeCount += childrenCount;
}
}
shouldIndexItem = shouldIndexItem || treeCount > 1;
if (shouldIndexItem)
{
if (itemGroupInfo == null)
{
itemGroupInfo = new GroupInfo(item, parent, true, level, rootSlot, rootSlot + treeCount - 1);
}
else
{
itemGroupInfo.LastSubItemSlot = rootSlot + treeCount - 1;
}
if (insert == null)
{
this.groupHeadersTable.AddValue(rootSlot, itemGroupInfo);
}
else
{
insert.Insert(0, itemGroupInfo);
}
if (this.itemInfoTable == null)
{
this.itemInfoTable = new Dictionary<object, GroupInfo>();
}
this.itemInfoTable.Add(item, itemGroupInfo);
}
return treeCount;
}
internal int GetInsertedGroupSlot(object changedItem, int itemIndex)
{
GroupInfo changedItemInfo = this.GetGroupInfo(changedItem);
if (itemIndex == 0)
{
return changedItemInfo != null ? changedItemInfo.Index + 1 : itemIndex;
}
// We get the previous group GroupInfo and then calculate the Slot because the new one is not indexed yet.
var group = this.hierarchyAdapter.GetItemAt(changedItem, itemIndex - 1);
var groupInfo = this.GetGroupInfo(group);
return groupInfo.LastSubItemSlot + 1;
}
internal void UpdateGroupHeadersTable(int groupIndex, int count)
{
// Update groups after current one.
foreach (var nextGroupIndex in this.groupHeadersTable.GetIndexes(groupIndex + 1))
{
GroupInfo nextGroupInfo = this.groupHeadersTable.GetValueAt(nextGroupIndex);
nextGroupInfo.Index += count;
nextGroupInfo.LastSubItemSlot += count;
}
}
internal override IList<ItemInfo> GetItemInfosAtSlot(int visibleLine, int slot)
{
List<ItemInfo> items = new List<ItemInfo>();
ItemInfo itemInfo = new ItemInfo();
itemInfo.IsDisplayed = true;
GroupInfo groupInfo;
int lowerBound;
int itemsCount = 0;
foreach (var item in this.groupHeadersTable)
{
itemsCount = Math.Max(item.Value.LastSubItemSlot, itemsCount);
}
if (this.groupHeadersTable.TryGetValue(slot, out groupInfo, out lowerBound) && slot <= itemsCount)
{
if (lowerBound != slot)
{
int childIndex = slot - lowerBound - 1;
itemInfo.Id = groupInfo.Index + childIndex + 1;
itemInfo.Item = this.hierarchyAdapter.GetItemAt(groupInfo.Item, childIndex);
itemInfo.Level = groupInfo.Level + 1;
itemInfo.Slot = itemInfo.Id;
itemInfo.IsCollapsible = false;
itemInfo.IsCollapsed = false;
itemInfo.ItemType = BaseLayout.GetItemType(itemInfo.Item);
itemInfo.IsSummaryVisible = itemInfo.ItemType == GroupType.Subtotal && this.IsCollapsed(groupInfo.Item);
items.Add(itemInfo);
var parentItemInfo = new ItemInfo();
parentItemInfo.IsDisplayed = false;
parentItemInfo.Id = groupInfo.Index;
parentItemInfo.Item = groupInfo.Item;
parentItemInfo.Level = groupInfo.Level;
parentItemInfo.Slot = groupInfo.Index;
parentItemInfo.IsCollapsible = this.IsCollapsible(groupInfo);
parentItemInfo.IsCollapsed = !groupInfo.IsExpanded;
parentItemInfo.ItemType = BaseLayout.GetItemType(groupInfo.Item);
parentItemInfo.IsSummaryVisible = parentItemInfo.ItemType == GroupType.Subtotal && groupInfo.Parent != null && this.IsCollapsed(groupInfo.Parent.Item);
items.Insert(0, parentItemInfo);
}
else
{
itemInfo.Id = groupInfo.Index;
itemInfo.Item = groupInfo.Item;
itemInfo.Level = groupInfo.Level;
itemInfo.Slot = itemInfo.Id;
itemInfo.IsCollapsible = this.IsCollapsible(groupInfo);
itemInfo.IsCollapsed = !groupInfo.IsExpanded;
itemInfo.ItemType = BaseLayout.GetItemType(itemInfo.Item);
itemInfo.IsSummaryVisible = itemInfo.ItemType == GroupType.Subtotal && groupInfo.Parent != null && this.IsCollapsed(groupInfo.Parent.Item);
items.Add(itemInfo);
}
var parentGroupInfo = groupInfo.Parent;
while (parentGroupInfo != null)
{
var parentItemInfo = new ItemInfo();
parentItemInfo.IsDisplayed = false;
parentItemInfo.Id = parentGroupInfo.Index;
parentItemInfo.Item = parentGroupInfo.Item;
parentItemInfo.Level = parentGroupInfo.Level;
parentItemInfo.Slot = parentGroupInfo.Index;
parentItemInfo.IsCollapsible = this.IsCollapsible(parentGroupInfo);
parentItemInfo.IsCollapsed = !parentGroupInfo.IsExpanded;
parentItemInfo.ItemType = BaseLayout.GetItemType(parentGroupInfo.Item);
parentItemInfo.IsSummaryVisible = parentItemInfo.ItemType == GroupType.Subtotal && parentGroupInfo.Parent != null && this.IsCollapsed(parentGroupInfo.Parent.Item);
items.Insert(0, parentItemInfo);
parentGroupInfo = parentGroupInfo.Parent;
}
}
else if (this.ItemsSource != null && visibleLine < this.ItemsSource.Count)
{
itemInfo.Item = this.ItemsSource[visibleLine];
itemInfo.Level = 0;
itemInfo.Id = slot;
itemInfo.Slot = itemInfo.Id;
itemInfo.IsCollapsible = false;
itemInfo.IsCollapsed = false;
itemInfo.ItemType = BaseLayout.GetItemType(itemInfo.Item);
itemInfo.IsSummaryVisible = false;
items.Add(itemInfo);
}
return items;
}
protected override void SetItemsSourceOverride(IReadOnlyList<object> source, bool restoreCollapsed)
{
this.collapsedSlotsTable.Clear();
this.groupHeadersTable.Clear();
HashSet<object> collapsedGroups = null;
var canRestoreCollapsedState = this.itemInfoTable != null && restoreCollapsed;
if (this.itemInfoTable != null)
{
if (restoreCollapsed)
{
collapsedGroups = this.CopyCollapsedStates();
}
this.itemInfoTable.Clear();
}
int slotsCount = 0;
int temp = 0;
foreach (var strategy in this.LayoutStrategies)
{
slotsCount += strategy.CalculateAppendedSlotsCount(this, slotsCount, ref temp);
}
this.TotalSlotCount = this.VisibleLineCount = slotsCount;
this.RefreshRenderInfo(false);
if (canRestoreCollapsedState)
{
foreach (var pair in this.itemInfoTable)
{
if (collapsedGroups.Contains(pair.Key))
{
this.Collapse(pair.Key);
}
}
}
}
private HashSet<object> CopyCollapsedStates()
{
HashSet<object> hashSet = new HashSet<object>();
foreach (var pair in this.itemInfoTable)
{
if (!pair.Value.IsExpanded)
{
hashSet.Add(pair.Key);
}
}
return hashSet;
}
private bool IsCollapsible(GroupInfo groupInfo)
{
int itemLevel = groupInfo.Level;
bool hasItems = Enumerable.Any(this.hierarchyAdapter.GetItems(groupInfo.Item));
{
return hasItems;
}
}
private void GetCollapseRange(GroupInfo groupInfo, out int slot, out int slotSpan)
{
int itemSlot = groupInfo.Index;
int itemLevel = groupInfo.Level;
slot = itemSlot + 1;
slotSpan = groupInfo.GetLineSpan() - 1;
int aggregatesLevel = this.ShowAggregateValuesInline ? this.AggregatesLevel - 1 : this.AggregatesLevel;
}
private void CollapseCore(GroupInfo info, bool raiseExpanded)
{
info.IsExpanded = false;
int slot = 0;
int slotSpan = 0;
this.GetCollapseRange(info, out slot, out slotSpan);
int collapsedItems = slotSpan - this.GetCollapsedSlotsCount(slot, slot + slotSpan - 1);
this.collapsedSlotsTable.AddValues(slot, slotSpan, true);
this.VisibleLineCount -= collapsedItems;
if (raiseExpanded)
{
this.RaiseCollapsed(new ExpandCollapseEventArgs(info.Item, slot, slotSpan));
}
}
private IEnumerable<GroupInfo> CollapsedChildItems(object item)
{
var groupInfo = this.GetGroupInfo(item);
if (groupInfo == null)
{
yield break;
}
else if (!groupInfo.IsExpanded)
{
yield return groupInfo;
}
else if (Enumerable.Any(this.hierarchyAdapter.GetItems(item)) && groupInfo.Level < this.GroupLevels - 1)
{
var items = this.hierarchyAdapter.GetItems(item);
foreach (var childGroup in items)
{
foreach (var collapsedChildGroup in this.CollapsedChildItems(childGroup))
{
yield return collapsedChildGroup;
}
}
}
}
private void RemoveGroupInfo(GroupInfo groupInfo)
{
this.itemInfoTable.Remove(groupInfo.Item);
}
}
}
| 37.378286 | 208 | 0.530453 | [
"Apache-2.0"
] | HaoLife/Uno.Telerik.UI-For-UWP | Controls/DataControls/DataControls.UWP/ListView/Layout/CompactLayout.cs | 32,708 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Games.GrumpyBear.LevelManagement
{
[CreateAssetMenu(menuName = "Grumpy Bear Games/Level Management/Location Manager")]
public class LocationManager: ScriptableObject
{
public static event Action<Location> OnLocationChanged;
[SerializeField] private List<SceneReference> _globalScenes = new List<SceneReference>();
public IReadOnlyList<SceneReference> GlobalScenes => _globalScenes;
public void Load(Location location) => LocationManagerHelper.Instance.StartCoroutine(Load_CO(location));
public IEnumerator Load_CO(Location location)
{
var sceneReferencesToLoad = location.Scenes.Concat(_globalScenes).Select(scene => scene.ScenePath);
yield return SceneLoader.LoadExactlyByScenePath(sceneReferencesToLoad, location.ActiveScene.ScenePath);
OnLocationChanged?.Invoke(location);
}
}
}
| 36.821429 | 115 | 0.732299 | [
"Apache-2.0"
] | Grumpy-Bear-Games/Unity-Level-Management | RunTime/LocationManager.cs | 1,031 | C# |
using System.Collections.Generic;
using Binance.API.Csharp.Client.Models.Market;
namespace Binance.API.Csharp.Client.Models.WebSocket
{
public class DepthMessage : IWebSocketMessage
{
public string EventType { get; set; }
public long EventTime { get; set; }
public string Symbol { get; set; }
public int UpdateId { get; set; }
public IEnumerable<OrderBookOffer> Bids { get; set; }
public IEnumerable<OrderBookOffer> Asks { get; set; }
}
} | 33.333333 | 61 | 0.67 | [
"MIT"
] | Rastorguev/Binance.API.Csharp.Client | Binance.API.Csharp.Client.Models/WebSocket/DepthMessage.cs | 502 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using HomeAccounting.Data.Base;
using HomeAccounting.Data.Context;
using HomeAccounting.Data.Entities;
using HomeAccounting.Data.Extensions;
using HomeAccounting.Data.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace HomeAccounting.Data.Repositories
{
public class CurrenciesRepository : BaseRepository<CurrencyEntity>, ICurrenciesRepository
{
public CurrenciesRepository(AccountingDbContext dbContext, ICurrentUserProvider currentUserProvider) : base(dbContext, currentUserProvider)
{
}
public Task<List<CurrencyEntity>> GetAllAsync(bool withTracking, CancellationToken token)
=> Query(withTracking).NotDeleted().ToListAsync(token);
public Task<CurrencyEntity> GetByIdAsync(int currencyId, bool withTracking, CancellationToken token)
=> Query(withTracking).NotDeleted().FirstOrDefaultAsync(x => x.Id == currencyId, token);
public Task<CurrencyEntity> GetByNameAsync(string name, bool withTracking, CancellationToken token)
=> Query(withTracking).FirstOrDefaultAsync(x => x.Name == name, token);
public Task<bool> IsNameOrCodeInUseAsync(string name, string code, CancellationToken token)
=> Query(false).AnyAsync(x => x.Name == name || x.CurrencyCode == code, token);
public Task<List<CurrencyEntity>> GetAllWithUserBalancesAsync(CancellationToken token)
=> Query(false)
.NotDeleted()
.Include(c => c.Balances.Where(b => b.UserId == CurrentUserProvider.UserId && !b.Deleted))
.ToListAsync(token);
}
}
| 43.794872 | 147 | 0.721897 | [
"MIT"
] | PainkillerFS/home-accounting-backend | HomeAccounting.Data/Repositories/CurrenciesRepository.cs | 1,710 | C# |
/*
* Copyright 2018 JDCLOUD.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.
*
* CoreWebConsoleAPI
* 控制台开放API
*
* OpenAPI spec version: v2
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
namespace JDCloudSDK.Iotcore.Apis
{
/// <summary>
/// 设备控制接口
/// </summary>
public class SetDevicePropertyResponse : JdcloudResponse<SetDevicePropertyResult>
{
}
} | 25.487805 | 85 | 0.723445 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Iotcore/Apis/SetDevicePropertyResponse.cs | 1,067 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Dul.Tests
{
[TestClass]
public class SqlUtilityTest
{
[TestMethod]
public void EncodeSqlStringTest()
{
Console.WriteLine(SqlUtility.EncodeSqlString("@'_%"));
}
}
}
| 18.875 | 66 | 0.625828 | [
"MIT"
] | VisualAcademy/Dul | Dul.Tests/03_String/SqlUtilityTest.cs | 304 | C# |
using System;
using JetBrains.Annotations;
using UnityEngine;
namespace FlexiTween.Extensions
{
public static class TransformExtensions
{
public static Config<Vector3> TweenPosition([NotNull] this Transform transform)
{
if (transform == null) throw new ArgumentNullException("transform");
return Tween
.From(transform.position)
.OnUpdate(position => transform.position = position);
}
public static Config<Vector3> TweenLocalPosition([NotNull] this Transform transform)
{
if (transform == null) throw new ArgumentNullException("transform");
return Tween
.From(transform.localPosition)
.OnUpdate(position => transform.localPosition = position);
}
public static Config<Quaternion> TweenRotation([NotNull] this Transform transform)
{
if (transform == null) throw new ArgumentNullException("transform");
return Tween
.From(transform.rotation)
.OnUpdate(rotation => transform.rotation = rotation);
}
public static Config<Quaternion> TweenLocalRotation([NotNull] this Transform transform)
{
if (transform == null) throw new ArgumentNullException("transform");
return Tween
.From(transform.localRotation)
.OnUpdate(rotation => transform.localRotation = rotation);
}
public static Config<Vector3> TweenLocalScale([NotNull] this Transform transform)
{
if (transform == null) throw new ArgumentNullException("transform");
return Tween
.From(transform.localScale)
.OnUpdate(scale => transform.localScale = scale);
}
}
} | 33.888889 | 95 | 0.610929 | [
"MIT"
] | russelljahn/FlexiTween | FlexiTween/Assets/FlexiTween/Extensions/TransformExtensions.cs | 1,832 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JsonApiDotNetCore.Resources;
using RightType = System.Type;
namespace JsonApiDotNetCore.Hooks.Internal.Traversal
{
/// <summary>
/// Child node in the tree
/// </summary>
/// <typeparam name="TResource"></typeparam>
internal sealed class ChildNode<TResource> : IResourceNode where TResource : class, IIdentifiable
{
private readonly IdentifiableComparer _comparer = IdentifiableComparer.Instance;
/// <inheritdoc />
public RightType ResourceType { get; }
/// <inheritdoc />
public RelationshipProxy[] RelationshipsToNextLayer { get; }
/// <inheritdoc />
public IEnumerable UniqueResources
{
get
{
return new HashSet<TResource>(_relationshipsFromPreviousLayer.SelectMany(relationshipGroup => relationshipGroup.RightResources));
}
}
/// <inheritdoc />
public IRelationshipsFromPreviousLayer RelationshipsFromPreviousLayer => _relationshipsFromPreviousLayer;
private readonly RelationshipsFromPreviousLayer<TResource> _relationshipsFromPreviousLayer;
public ChildNode(RelationshipProxy[] nextLayerRelationships, RelationshipsFromPreviousLayer<TResource> prevLayerRelationships)
{
ResourceType = typeof(TResource);
RelationshipsToNextLayer = nextLayerRelationships;
_relationshipsFromPreviousLayer = prevLayerRelationships;
}
/// <inheritdoc />
public void UpdateUnique(IEnumerable updated)
{
List<TResource> cast = updated.Cast<TResource>().ToList();
foreach (var group in _relationshipsFromPreviousLayer)
{
group.RightResources = new HashSet<TResource>(group.RightResources.Intersect(cast, _comparer).Cast<TResource>());
}
}
/// <summary>
/// Reassignment is done according to provided relationships
/// </summary>
public void Reassign(IResourceFactory resourceFactory, IEnumerable updated = null)
{
var unique = (HashSet<TResource>)UniqueResources;
foreach (var group in _relationshipsFromPreviousLayer)
{
var proxy = group.Proxy;
var leftResources = group.LeftResources;
foreach (IIdentifiable left in leftResources)
{
var currentValue = proxy.GetValue(left);
if (currentValue is IEnumerable<IIdentifiable> relationshipCollection)
{
var intersection = relationshipCollection.Intersect(unique, _comparer);
IEnumerable typedCollection = TypeHelper.CopyToTypedCollection(intersection, relationshipCollection.GetType());
proxy.SetValue(left, typedCollection, resourceFactory);
}
else if (currentValue is IIdentifiable relationshipSingle)
{
if (!unique.Intersect(new HashSet<IIdentifiable> { relationshipSingle }, _comparer).Any())
{
proxy.SetValue(left, null, resourceFactory);
}
}
}
}
}
}
}
| 40.47619 | 145 | 0.612647 | [
"MIT"
] | DumpsterDoofus/JsonApiDotNetCore | src/JsonApiDotNetCore/Hooks/Internal/Traversal/ChildNode.cs | 3,400 | 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("Binance.Client.Websocket.Sample.WinForms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Binance.Client.Websocket.Sample.WinForms")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("40434847-b21b-42ab-a689-66b81c42100a")]
// 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")]
| 39.135135 | 84 | 0.752072 | [
"Apache-2.0"
] | ColossusFX/binance-client-websocket | test_integration/Binance.Client.Websocket.Sample.WinForms/Properties/AssemblyInfo.cs | 1,451 | 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.
*/
namespace Kafka.Client.ZooKeeperIntegration.Events
{
using log4net;
using System.Linq;
using Utils;
/// <summary>
/// Represents methods that will handle a ZooKeeper data events
/// </summary>
internal class DataChangedEventItem
{
public static log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(DataChangedEventItem));
private ZooKeeperClient.ZooKeeperEventHandler<ZooKeeperDataChangedEventArgs> dataChanged;
private ZooKeeperClient.ZooKeeperEventHandler<ZooKeeperDataChangedEventArgs> dataDeleted;
/// <summary>
/// Occurs when znode data changes
/// </summary>
public event ZooKeeperClient.ZooKeeperEventHandler<ZooKeeperDataChangedEventArgs> DataChanged
{
add
{
this.dataChanged -= value;
this.dataChanged += value;
}
remove
{
this.dataChanged -= value;
}
}
/// <summary>
/// Occurs when znode data deletes
/// </summary>
public event ZooKeeperClient.ZooKeeperEventHandler<ZooKeeperDataChangedEventArgs> DataDeleted
{
add
{
this.dataDeleted -= value;
this.dataDeleted += value;
}
remove
{
this.dataDeleted -= value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DataChangedEventItem"/> class.
/// </summary>
/// <param name="logger">
/// The logger.
/// </param>
/// <remarks>
/// Should use external logger to keep same format of all event logs
/// </remarks>
public DataChangedEventItem()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataChangedEventItem"/> class.
/// </summary>
/// <param name="logger">
/// The logger.
/// </param>
/// <param name="changedHandler">
/// The changed handler.
/// </param>
/// <param name="deletedHandler">
/// The deleted handler.
/// </param>
/// <remarks>
/// Should use external logger to keep same format of all event logs
/// </remarks>
public DataChangedEventItem(
ZooKeeperClient.ZooKeeperEventHandler<ZooKeeperDataChangedEventArgs> changedHandler,
ZooKeeperClient.ZooKeeperEventHandler<ZooKeeperDataChangedEventArgs> deletedHandler)
{
this.DataChanged += changedHandler;
this.DataDeleted += deletedHandler;
}
/// <summary>
/// Invokes subscribed handlers for ZooKeeeper data changes event
/// </summary>
/// <param name="e">
/// The event data.
/// </param>
public void OnDataChanged(ZooKeeperDataChangedEventArgs e)
{
var handlers = this.dataChanged;
if (handlers == null)
{
return;
}
foreach (var handler in handlers.GetInvocationList())
{
Logger.Debug(e + " sent to " + handler.Target);
}
handlers(e);
}
/// <summary>
/// Invokes subscribed handlers for ZooKeeeper data deletes event
/// </summary>
/// <param name="e">
/// The event data.
/// </param>
public void OnDataDeleted(ZooKeeperDataChangedEventArgs e)
{
var handlers = this.dataDeleted;
if (handlers == null)
{
return;
}
foreach (var handler in handlers.GetInvocationList())
{
Logger.Debug(e + " sent to " + handler.Target);
}
handlers(e);
}
/// <summary>
/// Gets the total count of subscribed handlers
/// </summary>
public int TotalCount
{
get
{
return (this.dataChanged != null ? this.dataChanged.GetInvocationList().Length : 0) +
(this.dataDeleted != null ? this.dataDeleted.GetInvocationList().Length : 0);
}
}
}
}
| 31.349693 | 103 | 0.562818 | [
"Apache-2.0"
] | Bhaskers-Blu-Org2/CSharpClient-for-Kafka | src/KafkaNET.Library/ZooKeeperIntegration/Events/DataChangedEventItem.cs | 5,112 | C# |
using System;
namespace JustERP.Authentication.External
{
public class ExternalLoginProviderInfo
{
public string Name { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public Type ProviderApiType { get; set; }
public ExternalLoginProviderInfo(string name, string clientId, string clientSecret, Type providerApiType)
{
Name = name;
ClientId = clientId;
ClientSecret = clientSecret;
ProviderApiType = providerApiType;
}
}
}
| 24.416667 | 113 | 0.62116 | [
"MIT"
] | linqtosql/JustERP | aspnet-core/src/JustERP.Web.Core/Authentication/External/ExternalLoginProviderInfo.cs | 588 | C# |
using System.Collections.Generic;
using Alipay.AopSdk.Core.Response;
namespace Alipay.AopSdk.Core.Request
{
/// <summary>
/// AOP API: koubei.quality.test.cloudacpt.checkresult.submit
/// </summary>
public class
KoubeiQualityTestCloudacptCheckresultSubmitRequest : IAopRequest<KoubeiQualityTestCloudacptCheckresultSubmitResponse>
{
/// <summary>
/// 云验收检测结果提交
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "koubei.quality.test.cloudacpt.checkresult.submit";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AopDictionary();
parameters.Add("biz_content", BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
} | 18.122951 | 119 | 0.708277 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk.Core/Request/KoubeiQualityTestCloudacptCheckresultSubmitRequest.cs | 2,229 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace com.csutil.progress {
public class ProgressManager {
public static void SetupSingleton() {
var pm = new ProgressManager();
IoC.inject.SetSingleton(pm);
// Enable that pm reacts to injection requests for IProgress:
IoC.inject.RegisterInjector(pm, pm.ProgressInjectionRequest);
}
public event EventHandler<IProgress> OnProgressUpdate;
private IDictionary<string, IProgress> trackedProgress = new Dictionary<string, IProgress>();
public DateTime latestChangeTime { get; private set; }
public IProgress latestUpdatedProgress { get; private set; }
public double combinedCount { get; private set; }
public double combinedTotalCount { get; private set; }
public double combinedPercent { get; private set; }
public double combinedAvgPercent { get; private set; }
public int totalTasks { get; private set; }
public int finishedTasks { get; private set; }
public IProgress ProgressInjectionRequest(object caller, bool createIfNull) {
AssertV2.IsNotNull(caller, "caller");
if (caller is string id) { return GetOrAddProgress(id, 0, createIfNull); }
if (caller is KeyValuePair<string, double> p) { return GetOrAddProgress(p.Key, p.Value, createIfNull); }
throw new ArgumentException($"Cant handle caller='{caller}'");
}
public void RemoveProcesses(IEnumerable<KeyValuePair<string, IProgress>> processes) {
foreach (var p in processes) { trackedProgress.Remove(p); }
OnProgressChanged(null);
}
public IEnumerable<KeyValuePair<string, IProgress>> GetCompletedProgresses() {
return trackedProgress.Filter(x => x.Value.IsComplete()).ToList();
}
public void CalcLatestStats() {
double percentSum = 0;
double countSum = 0;
double totalCountSum = 0;
int finishedTasksCounter = 0;
foreach (var p in trackedProgress.Values) {
percentSum += p.GetCappedPercent();
countSum += p.GetCount();
totalCountSum += p.totalCount;
if (p.percent >= 100) { finishedTasksCounter++; }
}
totalTasks = trackedProgress.Count;
combinedAvgPercent = totalTasks > 0 ? percentSum / totalTasks : 0;
combinedCount = countSum;
combinedTotalCount = totalCountSum;
combinedPercent = 100d * combinedCount / combinedTotalCount;
finishedTasks = finishedTasksCounter;
}
public IProgress GetOrAddProgress(string id, double totalCount, bool createIfNull) {
id.ThrowErrorIfNullOrEmpty("id");
if (trackedProgress.TryGetValue(id, out IProgress existingProgress)) { return existingProgress; }
if (!createIfNull) { throw new KeyNotFoundException($"Porgess '{id}' NOT found and createIfNull is false"); }
var newProgress = new ProgressV2(id, totalCount);
trackedProgress.Add(id, newProgress);
newProgress.ProgressChanged += (o, e) => { OnProgressChanged(newProgress); };
OnProgressChanged(newProgress);
return newProgress;
}
public IProgress GetProgress(string id) {
id.ThrowErrorIfNullOrEmpty("id");
if (trackedProgress.TryGetValue(id, out IProgress p)) { return p; }
throw new KeyNotFoundException("No Progress found with id " + id);
}
private void OnProgressChanged(IProgress progressThatJustChanged) {
latestChangeTime = DateTimeV2.UtcNow;
if (progressThatJustChanged != null) { latestUpdatedProgress = progressThatJustChanged; }
CalcLatestStats();
OnProgressUpdate?.Invoke(this, progressThatJustChanged);
}
}
} | 43.758242 | 121 | 0.636364 | [
"Apache-2.0"
] | cs-util-com/cscore | CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/logging/progress/ProgressManager.cs | 3,984 | C# |
namespace Norml.Repositories.Constants
{
public static class Tables
{
public const string CategoryTypes = "dbo.CategoryTypes";
public const string CategoryTypeNames = "dbo.CategoryTypeNames";
public const string Locales = "dbo.Locales";
public const string ContentArticles = "dbo.ContentArticles";
public const string ContentArticleData = "dbo.ContentArticleData";
public const string ContentArticleNotes = "dbo.ContentArticleNotes";
public const string ContentArticleRevisions = "dbo.ContentArticleRevisions";
public const string ContentItems = "dbo.ContentItems";
public const string Ingredients = "dbo.Ingredients";
public const string IngredientCategories = "dbo.IngredientCategories";
public const string IngredientComments = "dbo.IngredientComments";
public const string IngredientRatings = "dbo.IngredientRatings";
public const string ItemLinks = "dbo.ItemLinks";
public const string IngredientRatingTexts = "dbo.IngredientRatingTexts";
public const string Links = "dbo.Links";
public const string Menus = "dbo.Menus";
public const string MenuItems = "dbo.MenuItems";
public const string MenuItemTexts = "dbo.MenuItemTexts";
public const string MenuTexts = "dbo.MenuTexts";
public const string MessageCampaigns = "dbo.MessageCampaigns";
public const string MessageTemplates = "dbo.MessageTemplates";
public const string Companies = "dbo.Companies";
public const string Countries = "dbo.Countries";
public const string CompanyRelationships = "dbo.CompanyRelationships";
public const string ContactInfos = "dbo.ContactInfos";
public const string CompanyPositions = "dbo.CompanyPositions";
public const string Addresses = "dbo.Addresses";
public const string Coordinates = "dbo.Coordinates";
public const string EmailAddresses = "dbo.EmailAddresses";
public const string Locations = "dbo.Locations";
public const string Manufacturers = "dbo.Manufacturers";
public const string Markets = "dbo.Markets";
public const string People = "dbo.People";
public const string Asides = "dbo.Asides";
public const string Brands = "dbo.Brands";
public const string CompanyTypes = "dbo.CompanyTypes";
public const string Copyrights = "dbo.Copyrights";
}
}
| 55.772727 | 84 | 0.701711 | [
"MIT"
] | joncrump/norml | Libraries/Repositories/TightlyCurly.Com.Repositories/Constants/Tables.cs | 2,456 | C# |
#region License
// Copyright (c) 2011, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This software is licensed under the Open Software License v3.0.
// For the complete license, see http://www.clearcanvas.ca/OSLv3.0
#endregion
using System;
using System.Collections.Generic;
using ClearCanvas.Common;
using ClearCanvas.Dicom;
using ClearCanvas.Dicom.Utilities.Command;
using ClearCanvas.Enterprise.Core;
using ClearCanvas.ImageServer.Common.Command;
using ClearCanvas.ImageServer.Common.Utilities;
using ClearCanvas.ImageServer.Core.Data;
using ClearCanvas.ImageServer.Model;
using ClearCanvas.ImageServer.Model.Brokers;
using ClearCanvas.ImageServer.Model.EntityBrokers;
using ClearCanvas.ImageServer.Model.Parameters;
namespace ClearCanvas.ImageServer.Core.Reconcile
{
public class InsertOrUpdateEntryCommand:ServerDatabaseCommand
{
private readonly string _groupId;
private readonly DicomFile _file;
private readonly StudyStorageLocation _studyLocation;
private readonly string _relativePath;
private readonly List<DicomAttributeComparisonResult> _reasons;
private readonly string _duplicateStoragePath;
public InsertOrUpdateEntryCommand(String groupId,
StudyStorageLocation studyLocation,
DicomFile file, String duplicateStoragePath, String relativePath,
List<DicomAttributeComparisonResult> reasons)
: base("Insert Duplicate Queue Entry Command")
{
Platform.CheckForNullReference(groupId, "groupId");
Platform.CheckForNullReference(studyLocation, "studyLocation");
Platform.CheckForNullReference(file, "file");
_file = file;
_studyLocation = studyLocation;
_groupId = groupId;
_duplicateStoragePath = duplicateStoragePath;
_relativePath = relativePath;
_reasons = reasons;
}
protected override void OnExecute(CommandProcessor theProcessor, IUpdateContext updateContext)
{
var broker = updateContext.GetBroker<IInsertDuplicateSopReceivedQueue>();
var parms = new InsertDuplicateSopReceivedQueueParameters
{
GroupID = _groupId,
ServerPartitionKey = _studyLocation.ServerPartitionKey,
StudyStorageKey = _studyLocation.Key,
StudyInstanceUid = _file.DataSet[DicomTags.StudyInstanceUid].ToString(),
SeriesDescription = _file.DataSet[DicomTags.SeriesDescription].ToString(),
SeriesInstanceUid = _file.DataSet[DicomTags.SeriesInstanceUid].ToString(),
SopInstanceUid = _file.MediaStorageSopInstanceUid
};
ReconcileStudyQueueDescription queueDesc = CreateQueueEntryDescription(_file);
parms.Description = queueDesc != null ? queueDesc.ToString() : String.Empty;
var queueData = new DuplicateSIQQueueData
{
StoragePath = _duplicateStoragePath,
Details = new ImageSetDetails(_file.DataSet),
TimeStamp = Platform.Time
};
if (_reasons != null && _reasons.Count>0)
{
queueData.ComparisonResults = _reasons;
}
var imageSet = new ImageSetDescriptor(_file.DataSet);
parms.StudyData = XmlUtils.SerializeAsXmlDoc(imageSet);
parms.Details = XmlUtils.SerializeAsXmlDoc(queueData);
parms.UidRelativePath = _relativePath;
IList<DuplicateSopReceivedQueue> entries = broker.Find(parms);
Platform.CheckForNullReference(entries, "entries");
Platform.CheckTrue(entries.Count == 1, "entries.Count==1");
DuplicateSopReceivedQueue queueEntry = entries[0];
var data = XmlUtils.Deserialize<DuplicateSIQQueueData>(queueEntry.Details);
data.Details.InsertFile(_file);
queueEntry.Details = XmlUtils.SerializeAsXmlDoc(data);
var siqBroker = updateContext.GetBroker<IStudyIntegrityQueueEntityBroker>();
if (!siqBroker.Update(queueEntry))
throw new ApplicationException("Unable to update duplicate queue entry");
}
private ReconcileStudyQueueDescription CreateQueueEntryDescription(DicomFile file)
{
using(var context = new ServerExecutionContext())
{
Study study = _studyLocation.LoadStudy(context.PersistenceContext);
if (study!=null)
{
var desc = new ReconcileStudyQueueDescription
{
ExistingPatientId = study.PatientId,
ExistingPatientName = study.PatientsName,
ExistingAccessionNumber = study.AccessionNumber,
ConflictingPatientName = file.DataSet[DicomTags.PatientsName].ToString(),
ConflictingPatientId = file.DataSet[DicomTags.PatientId].ToString(),
ConflictingAccessionNumber = file.DataSet[DicomTags.AccessionNumber].ToString()
};
return desc;
}
return null;
}
}
}
} | 43.535433 | 119 | 0.626696 | [
"Apache-2.0"
] | SNBnani/Xian | ImageServer/Core/Reconcile/InsertOrUpdateEntryCommand.cs | 5,529 | C# |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function AssetInspector::onAdd(%this)
{
%this.titlebar = new GuiControl()
{
HorizSizing="width";
VertSizing="top";
Position="0 0";
Extent="700 34";
MinExtent="350 34";
Text = "";
};
ThemeManager.setProfile(%this.titlebar, "panelProfile");
%this.add(%this.titlebar);
%this.titleDropDown = new GuiDropDownCtrl()
{
Position = "5 3";
Extent = 320 SPC 26;
ConstantThumbHeight = false;
ScrollBarThickness = 12;
ShowArrowButtons = true;
Visible = false;
};
ThemeManager.setProfile(%this.titleDropDown, "dropDownProfile");
ThemeManager.setProfile(%this.titleDropDown, "dropDownItemProfile", "listBoxProfile");
ThemeManager.setProfile(%this.titleDropDown, "emptyProfile", "backgroundProfile");
ThemeManager.setProfile(%this.titleDropDown, "scrollingPanelProfile", "ScrollProfile");
ThemeManager.setProfile(%this.titleDropDown, "scrollingPanelThumbProfile", "ThumbProfile");
ThemeManager.setProfile(%this.titleDropDown, "scrollingPanelTrackProfile", "TrackProfile");
ThemeManager.setProfile(%this.titleDropDown, "scrollingPanelArrowProfile", "ArrowProfile");
%this.titlebar.add(%this.titleDropDown);
%this.deleteAssetButton = new GuiButtonCtrl()
{
HorizSizing = "left";
Class = "EditorIconButton";
Frame = 48;
Position = "660 5";
Command = %this.getId() @ ".deleteAsset();";
Tooltip = "Delete Asset";
Visible = false;
};
ThemeManager.setProfile(%this.deleteAssetButton, "iconButtonProfile");
%this.add(%this.deleteAssetButton);
%this.emitterButtonBar = new GuiChainCtrl()
{
Class = "EditorButtonBar";
Position = "340 5";
Extent = "0 24";
ChildSpacing = 4;
IsVertical = false;
Tool = %this;
Visible = false;
};
ThemeManager.setProfile(%this.emitterButtonBar, "emptyProfile");
%this.add(%this.emitterButtonBar);
%this.emitterButtonBar.addButton("AddEmitter", 25, "Add Emitter", "");
%this.emitterButtonBar.addButton("MoveEmitterBackward", 27, "Move Emitter Backward", "getMoveEmitterBackwardEnabled");
%this.emitterButtonBar.addButton("MoveEmitterForward", 28, "Move Emitter Forward", "getMoveEmitterForwardEnabled");
%this.emitterButtonBar.addButton("RemoveEmitter", 23, "Remove Emitter", "getRemoveEmitterEnabled");
%this.tabBook = new GuiTabBookCtrl()
{
Class = AssetInspectorTabBook;
HorizSizing = width;
VertSizing = height;
Position = "0 34";
Extent = "700 290";
MinExtent="350 290";
TabPosition = top;
Visible = false;
};
ThemeManager.setProfile(%this.tabBook, "smallTabBookProfile");
ThemeManager.setProfile(%this.tabBook, "smallTabProfile", "TabProfile");
%this.add(%this.tabBook);
//Inspector Tab
%this.insPage = %this.createTabPage("Inspector", "");
%this.tabBook.add(%this.insPage);
%this.insScroller = %this.createScroller();
%this.insPage.add(%this.insScroller);
%this.inspector = %this.createInspector();
%this.insScroller.add(%this.inspector);
//Particle Graph Tool
%this.scaleGraphPage = %this.createTabPage("Scale Graph", "AssetParticleGraphTool", "");
//Emitter Graph Tool
%this.emitterGraphPage = %this.createTabPage("Emitter Graph", "AssetParticleGraphEmitterTool", "AssetParticleGraphTool");
}
function AssetInspector::createTabPage(%this, %name, %class, %superClass)
{
%page = new GuiTabPageCtrl()
{
Class = %class;
SuperClass = %superClass;
HorizSizing = width;
VertSizing = height;
Position = "0 0";
Extent = "700 290";
Text = %name;
};
ThemeManager.setProfile(%page, "tabPageProfile");
return %page;
}
function AssetInspector::createScroller(%this)
{
%scroller = new GuiScrollCtrl()
{
HorizSizing="width";
VertSizing="height";
Position="0 0";
Extent="700 290";
hScrollBar="alwaysOff";
vScrollBar="alwaysOn";
constantThumbHeight="0";
showArrowButtons="1";
scrollBarThickness="14";
};
ThemeManager.setProfile(%scroller, "scrollingPanelProfile");
ThemeManager.setProfile(%scroller, "scrollingPanelThumbProfile", "ThumbProfile");
ThemeManager.setProfile(%scroller, "scrollingPanelTrackProfile", "TrackProfile");
ThemeManager.setProfile(%scroller, "scrollingPanelArrowProfile", "ArrowProfile");
return %scroller;
}
function AssetInspector::createInspector(%this)
{
%inspector = new GuiInspector()
{
HorizSizing="width";
VertSizing="height";
Position="0 0";
Extent="686 290";
FieldCellSize="300 40";
ControlOffset="10 18";
ConstantThumbHeight=false;
ScrollBarThickness=12;
ShowArrowButtons=true;
};
ThemeManager.setProfile(%inspector, "emptyProfile");
ThemeManager.setProfile(%inspector, "panelProfile", "GroupPanelProfile");
ThemeManager.setProfile(%inspector, "emptyProfile", "GroupGridProfile");
ThemeManager.setProfile(%inspector, "labelProfile", "LabelProfile");
ThemeManager.setProfile(%inspector, "textEditProfile", "textEditProfile");
ThemeManager.setProfile(%inspector, "dropDownProfile", "dropDownProfile");
ThemeManager.setProfile(%inspector, "dropDownItemProfile", "dropDownItemProfile");
ThemeManager.setProfile(%inspector, "emptyProfile", "backgroundProfile");
ThemeManager.setProfile(%inspector, "scrollingPanelProfile", "ScrollProfile");
ThemeManager.setProfile(%inspector, "scrollingPanelThumbProfile", "ThumbProfile");
ThemeManager.setProfile(%inspector, "scrollingPanelTrackProfile", "TrackProfile");
ThemeManager.setProfile(%inspector, "scrollingPanelArrowProfile", "ArrowProfile");
ThemeManager.setProfile(%inspector, "checkboxProfile", "checkboxProfile");
ThemeManager.setProfile(%inspector, "buttonProfile", "buttonProfile");
ThemeManager.setProfile(%inspector, "tipProfile", "tooltipProfile");
return %inspector;
}
function AssetInspector::hideInspector(%this)
{
%this.titlebar.setText("");
%this.titleDropDown.visible = false;
%this.tabBook.Visible = false;
%this.emitterButtonBar.visible = false;
%this.deleteAssetButton.visible = false;
}
function AssetInspector::resetInspector(%this)
{
%this.titlebar.setText("");
%this.titleDropDown.visible = false;
%this.tabBook.Visible = true;
%this.tabBook.selectPage(0);
if(%this.tabBook.isMember(%this.scaleGraphPage))
{
%this.tabBook.remove(%this.scaleGraphPage);
}
if(%this.tabBook.isMember(%this.emitterGraphPage))
{
%this.tabBook.remove(%this.emitterGraphPage);
}
%this.emitterButtonBar.visible = false;
%this.deleteAssetButton.visible = true;
}
function AssetInspector::loadImageAsset(%this, %imageAsset, %assetID)
{
%this.resetInspector();
%this.titlebar.setText("Image Asset:" SPC %imageAsset.AssetName);
%this.inspector.clearHiddenFields();
%this.inspector.addHiddenField("hidden");
%this.inspector.addHiddenField("locked");
%this.inspector.addHiddenField("AssetInternal");
%this.inspector.addHiddenField("AssetPrivate");
%this.inspector.addHiddenField("ExplicitMode");
%this.inspector.inspect(%imageAsset);
%this.inspector.openGroupByIndex(0);
}
function AssetInspector::loadAnimationAsset(%this, %animationAsset, %assetID)
{
%this.resetInspector();
%this.titlebar.setText("Animation Asset:" SPC %animationAsset.AssetName);
%this.inspector.clearHiddenFields();
%this.inspector.addHiddenField("hidden");
%this.inspector.addHiddenField("locked");
%this.inspector.addHiddenField("AssetInternal");
%this.inspector.addHiddenField("AssetPrivate");
%this.inspector.inspect(%animationAsset);
%this.inspector.openGroupByIndex(0);
}
function AssetInspector::loadParticleAsset(%this, %particleAsset, %assetID)
{
%this.resetInspector();
%this.titleDropDown.visible = true;
%this.refreshParticleTitleDropDown(%particleAsset, 0);
%this.titleDropDown.Command = %this.getId() @ ".onChooseParticleAsset(" @ %particleAsset.getId() @ ");";
%this.onChooseParticleAsset(%particleAsset);
}
function AssetInspector::refreshParticleTitleDropDown(%this, %particleAsset, %index)
{
%this.titleDropDown.clearItems();
%this.titleDropDown.addItem("Particle Asset:" SPC %particleAsset.AssetName);
for(%i = 0; %i < %particleAsset.getEmitterCount(); %i++)
{
%emitter = %particleAsset.getEmitter(%i);
%this.titleDropDown.addItem("Emitter:" SPC %emitter.EmitterName);
%this.titleDropDown.setItemColor(%i + 1, ThemeManager.activeTheme.color5);
}
%this.titleDropDown.setCurSel(%index);
}
function AssetInspector::onChooseParticleAsset(%this, %particleAsset)
{
%index = %this.titleDropDown.getSelectedItem();
%this.inspector.clearHiddenFields();
%curSel = %this.tabBook.getSelectedPage();
if(%index == 0)
{
%this.inspector.addHiddenField("hidden");
%this.inspector.addHiddenField("locked");
%this.inspector.addHiddenField("AssetInternal");
%this.inspector.addHiddenField("AssetPrivate");
%this.inspector.inspect(%particleAsset);
if(%this.tabBook.isMember(%this.emitterGraphPage))
{
%this.tabBook.remove(%this.emitterGraphPage);
}
%this.tabBook.add(%this.scaleGraphPage);
%this.scaleGraphPage.inspect(%particleAsset);
}
else if(%index > 0)
{
%this.inspector.addHiddenField("hidden");
%this.inspector.addHiddenField("locked");
%this.inspector.inspect(%particleAsset.getEmitter(%index - 1));
if(%this.tabBook.isMember(%this.scaleGraphPage))
{
%this.tabBook.remove(%this.scaleGraphPage);
}
%this.tabBook.add(%this.emitterGraphPage);
%this.emitterGraphPage.inspect(%particleAsset, %index - 1);
}
%this.tabBook.selectPage(%curSel);
%this.inspector.openGroupByIndex(0);
%this.emitterButtonBar.visible = true;
%this.emitterButtonBar.refreshEnabled();
}
function AssetInspector::loadFontAsset(%this, %fontAsset, %assetID)
{
%this.resetInspector();
%this.titlebar.setText("Font Asset:" SPC %fontAsset.AssetName);
%this.inspector.clearHiddenFields();
%this.inspector.addHiddenField("hidden");
%this.inspector.addHiddenField("locked");
%this.inspector.addHiddenField("AssetInternal");
%this.inspector.addHiddenField("AssetPrivate");
%this.inspector.inspect(%fontAsset);
%this.inspector.openGroupByIndex(0);
}
function AssetInspector::loadAudioAsset(%this, %audioAsset, %assetID)
{
%this.resetInspector();
%this.titlebar.setText("Audio Asset:" SPC %audioAsset.AssetName);
%this.inspector.clearHiddenFields();
%this.inspector.addHiddenField("hidden");
%this.inspector.addHiddenField("locked");
%this.inspector.addHiddenField("AssetInternal");
%this.inspector.addHiddenField("AssetPrivate");
%this.inspector.inspect(%audioAsset);
%this.inspector.openGroupByIndex(0);
}
function AssetInspector::loadSpineAsset(%this, %spineAsset, %assetID)
{
%this.resetInspector();
%this.titlebar.setText("Spine Asset:" SPC %spineAsset.AssetName);
%this.inspector.clearHiddenFields();
%this.inspector.addHiddenField("hidden");
%this.inspector.addHiddenField("locked");
%this.inspector.addHiddenField("AssetInternal");
%this.inspector.addHiddenField("AssetPrivate");
%this.inspector.inspect(%spineAsset);
%this.inspector.openGroupByIndex(0);
}
function AssetInspector::deleteAsset(%this)
{
%asset = %this.inspector.getInspectObject();
if(%this.titleDropDown.visible && %this.titleDropDown.getSelectedItem() != 0)
{
%asset = %asset.getOwner();
}
%width = 700;
%height = 230;
%dialog = new GuiControl()
{
class = "DeleteAssetDialog";
superclass = "EditorDialog";
dialogSize = (%width + 8) SPC (%height + 8);
dialogCanClose = true;
dialogText = "Delete Asset";
doomedAsset = %asset;
};
%dialog.init(%width, %height);
Canvas.pushDialog(%dialog);
}
function AssetInspector::addEmitter(%this)
{
%asset = %this.inspector.getInspectObject();
if(%this.titleDropDown.getSelectedItem() != 0)
{
%asset = %asset.getOwner();
}
%width = 700;
%height = 230;
%dialog = new GuiControl()
{
class = "NewParticleEmitterDialog";
superclass = "EditorDialog";
dialogSize = (%width + 8) SPC (%height + 8);
dialogCanClose = true;
dialogText = "New Particle Emitter";
parentAsset = %asset;
};
%dialog.init(%width, %height);
Canvas.pushDialog(%dialog);
}
function AssetInspector::MoveEmitterForward(%this)
{
%emitter = %this.inspector.getInspectObject();
%asset = %emitter.getOwner();
%index = %this.titleDropDown.getSelectedItem();
%asset.moveEmitter(%index-1, %index);
%this.refreshParticleTitleDropDown(%asset, %index+1);
%asset.refreshAsset();
}
function AssetInspector::MoveEmitterBackward(%this)
{
%emitter = %this.inspector.getInspectObject();
%asset = %emitter.getOwner();
%index = %this.titleDropDown.getSelectedItem();
%asset.moveEmitter(%index-1, %index-2);
%this.refreshParticleTitleDropDown(%asset, %index-1);
%asset.refreshAsset();
}
function AssetInspector::RemoveEmitter(%this)
{
%emitter = %this.inspector.getInspectObject();
%asset = %emitter.getOwner();
%asset.RemoveEmitter(%emitter, true);
%index = %this.titleDropDown.getSelectedItem();
%this.titleDropDown.deleteItem(%index);
if(%this.titleDropDown.getItemCount() <= %index)
{
%index = %this.titleDropDown.getItemCount() - 1;
}
%this.titleDropDown.setCurSel(%index);
%this.inspector.inspect(%asset.getEmitter(%index - 1));
%this.emitterGraphPage.inspect(%asset, %index - 1);
%this.emitterButtonBar.refreshEnabled();
%asset.refreshAsset();
}
function AssetInspector::getMoveEmitterForwardEnabled(%this)
{
if(isObject(%this.titleDropDown) && %this.titleDropDown.getSelectedItem() <= 0)
{
return false;
}
if(isObject(%this.inspector))
{
%asset = %this.inspector.getInspectObject();
%emitterID = %this.emitterGraphPage.emitterID;
return %emitterID != (%asset.getOwner().getEmitterCount() - 1);
}
return false;
}
function AssetInspector::getMoveEmitterBackwardEnabled(%this)
{
if(isObject(%this.titleDropDown) && %this.titleDropDown.getSelectedItem() <= 0)
{
return false;
}
if(isObject(%this.inspector))
{
return %this.emitterGraphPage.emitterID != 0;
}
return false;
}
function AssetInspector::getRemoveEmitterEnabled(%this)
{
if(isObject(%this.titleDropDown) && %this.titleDropDown.getSelectedItem() <= 0)
{
return false;
}
if(isObject(%this.inspector))
{
%asset = %this.inspector.getInspectObject();
return %asset.getOwner().getEmitterCount() > 1;
}
return false;
}
| 31.227926 | 122 | 0.734745 | [
"MIT"
] | JLA02/Torque2D | editor/AssetAdmin/AssetInspector.cs | 15,208 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using System.Threading.Tasks;
namespace Discord.Commands
{
internal static class CommandParser
{
private enum ParserPart
{
None,
Parameter,
QuotedParameter
}
public static async Task<ParseResult> ParseArgsAsync(CommandInfo command, ICommandContext context, bool ignoreExtraArgs, IServiceProvider services, string input, int startPos, IReadOnlyDictionary<char, char> aliasMap)
{
ParameterInfo curParam = null;
StringBuilder argBuilder = new StringBuilder(input.Length);
int endPos = input.Length;
var curPart = ParserPart.None;
int lastArgEndPos = int.MinValue;
var argList = ImmutableArray.CreateBuilder<TypeReaderResult>();
var paramList = ImmutableArray.CreateBuilder<TypeReaderResult>();
bool isEscaping = false;
char c, matchQuote = '\0';
// local helper functions
bool IsOpenQuote(IReadOnlyDictionary<char, char> dict, char ch)
{
// return if the key is contained in the dictionary if it is populated
if (dict.Count != 0)
return dict.ContainsKey(ch);
// or otherwise if it is the default double quote
return c == '\"';
}
char GetMatch(IReadOnlyDictionary<char, char> dict, char ch)
{
// get the corresponding value for the key, if it exists
// and if the dictionary is populated
if (dict.Count != 0 && dict.TryGetValue(c, out var value))
return value;
// or get the default pair of the default double quote
return '\"';
}
for (int curPos = startPos; curPos <= endPos; curPos++)
{
if (curPos < endPos)
c = input[curPos];
else
c = '\0';
//If this character is escaped, skip it
if (isEscaping)
{
if (curPos != endPos)
{
argBuilder.Append(c);
isEscaping = false;
continue;
}
}
//Are we escaping the next character?
if (c == '\\' && (curParam == null || !curParam.IsRemainder))
{
isEscaping = true;
continue;
}
//If we're processing an remainder parameter, ignore all other logic
if (curParam != null && curParam.IsRemainder && curPos != endPos)
{
argBuilder.Append(c);
continue;
}
//If we're not currently processing one, are we starting the next argument yet?
if (curPart == ParserPart.None)
{
if (char.IsWhiteSpace(c) || curPos == endPos)
continue; //Skip whitespace between arguments
else if (curPos == lastArgEndPos)
return ParseResult.FromError(CommandError.ParseFailed, "There must be at least one character of whitespace between arguments.");
else
{
if (curParam == null)
curParam = command.Parameters.Count > argList.Count ? command.Parameters[argList.Count] : null;
if (curParam != null && curParam.IsRemainder)
{
argBuilder.Append(c);
continue;
}
if (IsOpenQuote(aliasMap, c))
{
curPart = ParserPart.QuotedParameter;
matchQuote = GetMatch(aliasMap, c);
continue;
}
curPart = ParserPart.Parameter;
}
}
//Has this parameter ended yet?
string argString = null;
if (curPart == ParserPart.Parameter)
{
if (curPos == endPos || char.IsWhiteSpace(c))
{
argString = argBuilder.ToString();
lastArgEndPos = curPos;
}
else
argBuilder.Append(c);
}
else if (curPart == ParserPart.QuotedParameter)
{
if (c == matchQuote)
{
argString = argBuilder.ToString(); //Remove quotes
lastArgEndPos = curPos + 1;
}
else
argBuilder.Append(c);
}
if (argString != null)
{
if (curParam == null)
{
if (command.IgnoreExtraArgs)
break;
else
return ParseResult.FromError(CommandError.BadArgCount, "The input text has too many parameters.");
}
var typeReaderResult = await curParam.ParseAsync(context, argString, services).ConfigureAwait(false);
if (!typeReaderResult.IsSuccess && typeReaderResult.Error != CommandError.MultipleMatches)
return ParseResult.FromError(typeReaderResult);
if (curParam.IsMultiple)
{
paramList.Add(typeReaderResult);
curPart = ParserPart.None;
}
else
{
argList.Add(typeReaderResult);
curParam = null;
curPart = ParserPart.None;
}
argBuilder.Clear();
}
}
if (curParam != null && curParam.IsRemainder)
{
var typeReaderResult = await curParam.ParseAsync(context, argBuilder.ToString(), services).ConfigureAwait(false);
if (!typeReaderResult.IsSuccess)
return ParseResult.FromError(typeReaderResult);
argList.Add(typeReaderResult);
}
if (isEscaping)
return ParseResult.FromError(CommandError.ParseFailed, "Input text may not end on an incomplete escape.");
if (curPart == ParserPart.QuotedParameter)
return ParseResult.FromError(CommandError.ParseFailed, "A quoted parameter is incomplete.");
//Add missing optionals
for (int i = argList.Count; i < command.Parameters.Count; i++)
{
var param = command.Parameters[i];
if (param.IsMultiple)
continue;
if (!param.IsOptional)
return ParseResult.FromError(CommandError.BadArgCount, "The input text has too few parameters.");
argList.Add(TypeReaderResult.FromSuccess(param.DefaultValue));
}
return ParseResult.FromSuccess(argList.ToImmutable(), paramList.ToImmutable());
}
}
}
| 40.378947 | 225 | 0.469108 | [
"MIT"
] | AndyDingo/Discord.Net | src/Discord.Net.Commands/CommandParser.cs | 7,674 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsLro
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// LRORetrysOperations operations.
/// </summary>
internal partial class LRORetrysOperations : Microsoft.Rest.IServiceOperations<AutoRestLongRunningOperationTestService>, ILRORetrysOperations
{
/// <summary>
/// Initializes a new instance of the LRORetrysOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LRORetrysOperations(AutoRestLongRunningOperationTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestLongRunningOperationTestService
/// </summary>
public AutoRestLongRunningOperationTestService Client { get; private set; }
/// <summary>
/// Long running put request, service returns a 500, then a 201 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’.
/// Polls return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Product>> Put201CreatingSucceeded200WithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send Request
Microsoft.Rest.Azure.AzureOperationResponse<Product> _response = await BeginPut201CreatingSucceeded200WithHttpMessagesAsync(
product, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Long running put request, service returns a 500, then a 201 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’.
/// Polls return this value until the last poll returns a ‘200’ with
/// ProvisioningState=’Succeeded’
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Product>> BeginPut201CreatingSucceeded200WithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginPut201CreatingSucceeded200", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/put/201/creating/succeeded/200").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running put request, service returns a 500, then a 200 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Product,LRORetrysPutAsyncRelativeRetrySucceededHeaders>> PutAsyncRelativeRetrySucceededWithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send Request
Microsoft.Rest.Azure.AzureOperationResponse<Product,LRORetrysPutAsyncRelativeRetrySucceededHeaders> _response = await BeginPutAsyncRelativeRetrySucceededWithHttpMessagesAsync(
product, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Long running put request, service returns a 500, then a 200 to the initial
/// request, with an entity that contains ProvisioningState=’Creating’. Poll
/// the endpoint indicated in the Azure-AsyncOperation header for operation
/// status
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Product,LRORetrysPutAsyncRelativeRetrySucceededHeaders>> BeginPutAsyncRelativeRetrySucceededWithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginPutAsyncRelativeRetrySucceeded", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/putasync/retry/succeeded").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Product,LRORetrysPutAsyncRelativeRetrySucceededHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPutAsyncRelativeRetrySucceededHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains
/// ProvisioningState=’Accepted’. Polls return this value until the last
/// poll returns a ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Product,LRORetrysDeleteProvisioning202Accepted200SucceededHeaders>> DeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send request
Microsoft.Rest.Azure.AzureOperationResponse<Product,LRORetrysDeleteProvisioning202Accepted200SucceededHeaders> _response = await BeginDeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(
customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains
/// ProvisioningState=’Accepted’. Polls return this value until the last
/// poll returns a ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Product,LRORetrysDeleteProvisioning202Accepted200SucceededHeaders>> BeginDeleteProvisioning202Accepted200SucceededWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginDeleteProvisioning202Accepted200Succeeded", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/delete/provisioning/202/accepted/200/succeeded").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Product,LRORetrysDeleteProvisioning202Accepted200SucceededHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 202)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDeleteProvisioning202Accepted200SucceededHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Polls return this value until the last poll returns a
/// ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysDelete202Retry200Headers>> Delete202Retry200WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send request
Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysDelete202Retry200Headers> _response = await BeginDelete202Retry200WithHttpMessagesAsync(
customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Polls return this value until the last poll returns a
/// ‘200’ with ProvisioningState=’Succeeded’
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysDelete202Retry200Headers>> BeginDelete202Retry200WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginDelete202Retry200", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/delete/202/retry/200").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysDelete202Retry200Headers>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDelete202Retry200Headers>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Poll the endpoint indicated in the Azure-AsyncOperation
/// header for operation status
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeaders>> DeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send request
Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeaders> _response = await BeginDeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(
customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Long running delete request, service returns a 500, then a 202 to the
/// initial request. Poll the endpoint indicated in the Azure-AsyncOperation
/// header for operation status
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeaders>> BeginDeleteAsyncRelativeRetrySucceededWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginDeleteAsyncRelativeRetrySucceeded", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/deleteasync/retry/succeeded").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysDeleteAsyncRelativeRetrySucceededHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysDeleteAsyncRelativeRetrySucceededHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the
/// initial request, with 'Location' and 'Retry-After' headers, Polls return
/// a 200 with a response body after success
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysPost202Retry200Headers>> Post202Retry200WithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send request
Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysPost202Retry200Headers> _response = await BeginPost202Retry200WithHttpMessagesAsync(
product, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the
/// initial request, with 'Location' and 'Retry-After' headers, Polls return
/// a 200 with a response body after success
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysPost202Retry200Headers>> BeginPost202Retry200WithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginPost202Retry200", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/post/202/retry/200").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysPost202Retry200Headers>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPost202Retry200Headers>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains
/// ProvisioningState=’Creating’. Poll the endpoint indicated in the
/// Azure-AsyncOperation header for operation status
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeaders>> PostAsyncRelativeRetrySucceededWithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Send request
Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeaders> _response = await BeginPostAsyncRelativeRetrySucceededWithHttpMessagesAsync(
product, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// Long running post request, service returns a 500, then a 202 to the
/// initial request, with an entity that contains
/// ProvisioningState=’Creating’. Poll the endpoint indicated in the
/// Azure-AsyncOperation header for operation status
/// </summary>
/// <param name='product'>
/// Product to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeaders>> BeginPostAsyncRelativeRetrySucceededWithHttpMessagesAsync(Product product = default(Product), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginPostAsyncRelativeRetrySucceeded", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/retryerror/postasync/retry/succeeded").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<LRORetrysPostAsyncRelativeRetrySucceededHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LRORetrysPostAsyncRelativeRetrySucceededHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 52.63925 | 451 | 0.601606 | [
"MIT"
] | fhoering/autorest | src/generator/AutoRest.CSharp.Azure.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs | 73,038 | C# |
using Incoding.Core.Block.Scheduler.Command;
using Incoding.Core.Block.Scheduler.Persistence;
using Incoding.Core.Block.Scheduler.Query;
using Incoding.Core.Extensions;
namespace Incoding.UnitTest
{
#region << Using >>
using System;
using Incoding.UnitTests.MSpec;
using Machine.Specifications;
using Moq;
using It = Machine.Specifications.It;
#endregion
[Subject(typeof(ChangeSchedulerStatusCommand))]
public class When_change_delay_to_schedule_to_success
{
private Establish establish = () =>
{
var command = Pleasure.Generator.Invent<ChangeSchedulerStatusCommand>(dsl => dsl.Tuning(s => s.Status, DelayOfStatus.Success));
var instance = Pleasure.Generator.Invent<ChangeSchedulerStatusCommand>();
DateTime? nextDt = Pleasure.Generator.DateTime();
lastStartOn = Pleasure.Generator.DateTime();
recurrency = Pleasure.Generator.Invent<GetRecurrencyDateQuery>(dsl => dsl.Tuning(s => s.NowDate, lastStartOn)
.Tuning(r => r.StartDate, lastStartOn));
delay = Pleasure.MockStrict<DelayToScheduler>(mock =>
{
mock.SetupGet(r => r.StartsOn).Returns(lastStartOn);
mock.SetupGet(r => r.Priority).Returns(Pleasure.Generator.PositiveNumber());
mock.SetupSet(r => r.Status = command.Status);
mock.SetupSet(r => r.Description = command.Description);
mock.SetupGet(r => r.Recurrence).Returns(recurrency);
mock.SetupGet(r => r.Command).Returns(instance.ToJsonString());
mock.SetupGet(r => r.Type)
.Returns(typeof(ChangeSchedulerStatusCommand).AssemblyQualifiedName);
mock.SetupGet(r => r.UID).Returns(Guid.NewGuid().ToString);
});
Action<ICompareFactoryDsl<ScheduleCommand, ScheduleCommand>> compare
= dsl => dsl.ForwardToAction(r => r.Recurrency, schedulerCommand => schedulerCommand.Recurrency.ShouldEqualWeak(recurrency,
factoryDsl => factoryDsl.ForwardToValue(r => r.NowDate, null)
.ForwardToValue(r => r.RepeatCount, recurrency.RepeatCount - 1)
.ForwardToValue(r => r.StartDate, lastStartOn)));
var newRecurrency = new GetRecurrencyDateQuery
{
EndDate = recurrency.EndDate,
RepeatCount = recurrency.RepeatCount - 1,
RepeatDays = recurrency.RepeatDays,
RepeatInterval = recurrency.RepeatInterval,
StartDate = lastStartOn,
Type = recurrency.Type,
NowDate = lastStartOn
};
var lastRecurrency = new GetRecurrencyDateQuery
{
EndDate = recurrency.EndDate,
RepeatCount = recurrency.RepeatCount - 1,
RepeatDays = recurrency.RepeatDays,
RepeatInterval = recurrency.RepeatInterval,
StartDate = nextDt,
Type = recurrency.Type,
NowDate = lastStartOn
};
mockCommand = MockCommand<ChangeSchedulerStatusCommand>
.When(command)
.StubGetById(command.Id, delay.Object)
.StubQuery(newRecurrency, nextDt)
.StubPush(new ScheduleCommand(delay.Object)
{
UID = delay.Object.UID,
Priority = delay.Object.Priority,
Recurrency = lastRecurrency
});
//.StubPush(dsl => dsl.Tuning(r => r.UID, delay.Object.UID)
// .Tuning(r => r.Command, instance)
// .Tuning(r => r.Priority, delay.Object.Priority), compare);
};
Because of = () => mockCommand.Execute();
It should_be_update_start_on = () => recurrency.NowDate.ShouldEqual(lastStartOn);
It should_be_verify = () => delay.VerifyAll();
#region Establish value
static MockMessage<ChangeSchedulerStatusCommand, object> mockCommand;
static Mock<DelayToScheduler> delay;
static DateTime lastStartOn;
static GetRecurrencyDateQuery recurrency;
#endregion
}
} | 63.436893 | 241 | 0.392256 | [
"Apache-2.0"
] | Incoding-Software/Incoding-Framework-Core | src/Incoding.UnitTestsCore/Block/Scheduler Factory/When_change_delay_to_schedule_to_success.cs | 6,536 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EXE
{
class exe
{
static void Main(string[] args)
{
}
}
}
| 13.764706 | 39 | 0.594017 | [
"MIT"
] | NedkoNedevv/Fundamentals | Exercises Array and List Algorithms/EXE/exe.cs | 236 | C# |
namespace PlayersBay.Web.Areas.Administrator.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlayersBay.Web.Controllers;
[Area("Administrator")]
[Authorize(Roles = Common.GlobalConstants.AdministratorRoleName)]
public class AdministratorController : BaseController
{
}
}
| 27 | 69 | 0.754986 | [
"MIT"
] | simeeon/PlayersBay | src/Web/PlayersBay.Web/Areas/Administrator/Controllers/AdministratorController.cs | 353 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiByValue(fqn: "aws.Wafv2RuleGroupRuleStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchBody")]
public class Wafv2RuleGroupRuleStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchBody : aws.IWafv2RuleGroupRuleStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchBody
{
}
}
| 39.25 | 227 | 0.876858 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/Wafv2RuleGroupRuleStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchBody.cs | 471 | C# |
using System;
using System.Collections.Generic;
using Mirage.Logging;
using Mirage.Serialization;
using UnityEngine;
namespace Mirage
{
public class MessageHandler : IMessageReceiver
{
static readonly ILogger logger = LogFactory.GetLogger(typeof(MessageHandler));
readonly bool disconnectOnException;
readonly IObjectLocator objectLocator;
/// <summary>
/// Handles network messages on client and server
/// </summary>
/// <param name="player"></param>
/// <param name="reader"></param>
internal delegate void NetworkMessageDelegate(INetworkPlayer player, NetworkReader reader);
internal readonly Dictionary<int, NetworkMessageDelegate> messageHandlers = new Dictionary<int, NetworkMessageDelegate>();
public MessageHandler(IObjectLocator objectLocator, bool disconnectOnException)
{
this.disconnectOnException = disconnectOnException;
this.objectLocator = objectLocator;
}
private static NetworkMessageDelegate MessageWrapper<T>(MessageDelegateWithPlayer<T> handler)
{
void AdapterFunction(INetworkPlayer player, NetworkReader reader)
{
T message = NetworkDiagnostics.ReadWithDiagnostics<T>(reader);
handler.Invoke(player, message);
}
return AdapterFunction;
}
/// <summary>
/// Register a handler for a particular message type.
/// <para>There are several system message types which you can add handlers for. You can also add your own message types.</para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="handler">Function handler which will be invoked for when this message type is received.</param>
public void RegisterHandler<T>(MessageDelegateWithPlayer<T> handler)
{
int msgType = MessagePacker.GetId<T>();
if (logger.filterLogType == LogType.Log && messageHandlers.ContainsKey(msgType))
{
logger.Log($"RegisterHandler replacing {msgType}");
}
messageHandlers[msgType] = MessageWrapper(handler);
}
/// <summary>
/// Register a handler for a particular message type.
/// <para>There are several system message types which you can add handlers for. You can also add your own message types.</para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="handler">Function handler which will be invoked for when this message type is received.</param>
public void RegisterHandler<T>(MessageDelegate<T> handler)
{
RegisterHandler<T>((_, value) => { handler(value); });
}
/// <summary>
/// Unregister a handler for a particular message type.
/// <para>Note: Messages dont need to be unregister when server or client stops as MessageHandler will be re-created next time server or client starts</para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
public void UnregisterHandler<T>()
{
int msgType = MessagePacker.GetId<T>();
messageHandlers.Remove(msgType);
}
/// <summary>
/// Clear all registered callback handlers.
/// </summary>
public void ClearHandlers()
{
messageHandlers.Clear();
}
internal void InvokeHandler(INetworkPlayer player, int msgType, NetworkReader reader)
{
if (messageHandlers.TryGetValue(msgType, out NetworkMessageDelegate msgDelegate))
{
msgDelegate.Invoke(player, reader);
}
else
{
if (MessagePacker.MessageTypes.TryGetValue(msgType, out Type type))
{
// this means we received a Message that has a struct, but no handler, It is likely that the developer forgot to register a handler or sent it by mistake
// we want this to be warning level
if (logger.WarnEnabled()) logger.LogWarning($"Unexpected message {type} received from {player}. Did you register a handler for it?");
}
else
{
// todo maybe we should handle it differently? we dont want someone spaming ids to find a handler they can do stuff with...
if (logger.LogEnabled()) logger.Log($"Unexpected message ID {msgType} received from {player}. May be due to no existing RegisterHandler for this message.");
}
}
}
public void HandleMessage(INetworkPlayer player, ArraySegment<byte> packet)
{
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(packet, objectLocator))
{
// protect against attackers trying to send invalid data packets
// exception could be throw if:
// - invalid headers
// - invalid message ids
// - invalid data causing exceptions
// - negative ReadBytesAndSize prefixes
// - invalid utf8 strings
// - etc.
//
// if exception is caught, disconnect the attacker to stop any further attacks
try
{
int msgType = MessagePacker.UnpackId(networkReader);
InvokeHandler(player, msgType, networkReader);
}
catch (Exception e)
{
string disconnectMessage = disconnectOnException ? $", Closed connection: {player}" : "";
logger.LogError($"{e.GetType()} in Message handler (see stack below){disconnectMessage}\n{e}");
if (disconnectOnException)
{
player.Disconnect();
}
}
}
}
}
}
| 42 | 176 | 0.588342 | [
"MIT"
] | SoftwareGuy/Mirage | Assets/Mirage/Runtime/MessageHandler.cs | 6,090 | C# |
using Bearded.Graphics.Textures;
using OpenTK.Graphics.OpenGL;
namespace Bearded.Graphics.RenderSettings
{
public sealed class ArrayTextureUniform : Uniform<ArrayTexture>
{
public TextureUnit Unit { get; }
public ArrayTextureUniform(string name, TextureUnit unit, ArrayTexture texture)
: base(name, texture)
{
Unit = unit;
}
protected override void SetAtLocation(int location)
{
GL.ActiveTexture(Unit);
Value.Bind();
GL.Uniform1(location, Unit - TextureUnit.Texture0);
}
}
}
| 25.25 | 87 | 0.620462 | [
"MIT"
] | amulware/awgraphics | Bearded.Graphics/Core/RenderSettings/ArrayTextureUniform.cs | 606 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Metastore.V1Beta.Snippets
{
// [START metastore_v1beta_generated_DataprocMetastore_UpdateMetadataImport_async]
using Google.Cloud.Metastore.V1Beta;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;
public sealed partial class GeneratedDataprocMetastoreClientSnippets
{
/// <summary>Snippet for UpdateMetadataImportAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task UpdateMetadataImportRequestObjectAsync()
{
// Create client
DataprocMetastoreClient dataprocMetastoreClient = await DataprocMetastoreClient.CreateAsync();
// Initialize request argument(s)
UpdateMetadataImportRequest request = new UpdateMetadataImportRequest
{
UpdateMask = new FieldMask(),
MetadataImport = new MetadataImport(),
RequestId = "",
};
// Make the request
Operation<MetadataImport, OperationMetadata> response = await dataprocMetastoreClient.UpdateMetadataImportAsync(request);
// Poll until the returned long-running operation is complete
Operation<MetadataImport, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
MetadataImport result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<MetadataImport, OperationMetadata> retrievedResponse = await dataprocMetastoreClient.PollOnceUpdateMetadataImportAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
MetadataImport retrievedResult = retrievedResponse.Result;
}
}
}
// [END metastore_v1beta_generated_DataprocMetastore_UpdateMetadataImport_async]
}
| 45.753846 | 156 | 0.694351 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Metastore.V1Beta/Google.Cloud.Metastore.V1Beta.GeneratedSnippets/DataprocMetastoreClient.UpdateMetadataImportRequestObjectAsyncSnippet.g.cs | 2,974 | C# |
using System.Threading.Tasks;
namespace Lion.AbpProNuget.Data
{
public interface IAbpProNugetDbSchemaMigrator
{
Task MigrateAsync();
}
}
| 15.8 | 49 | 0.708861 | [
"MIT"
] | WangJunZzz/abp-vnext-pro-nuget | aspnet-core/services/src/Lion.AbpProNuget.Domain/Data/IAbpProNugetDbSchemaMigrator.cs | 158 | C# |
using Application.Classrooms.Commands.JoinClassroom;
using Application.Common;
using Application.Common.Interfaces;
using Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Threading.Tasks;
namespace Application.Classrooms {
/// <summary>
/// Allows a user to join a classroom with an invite link.
/// </summary>
public class JoinClassroomCommandHandler : IRequestHandler<JoinClassroomCommand, Result<Unit>> {
private readonly Persistence.ApplicationContext _context;
private readonly IUserAccessor _userAccessor;
public JoinClassroomCommandHandler(Persistence.ApplicationContext context, IUserAccessor userAccessor) {
_context = context;
_userAccessor = userAccessor;
}
// TODO: Need to check for expired tokens/invite links.
// TODO: Need to update the 'Hits' column in the InviteLinks table whenever a token gets used successfully.
public async Task<Result<Unit>> Handle(JoinClassroomCommand request, CancellationToken cancellationToken) {
// Get the invite link and the related classroom id.
var inviteLink = await _context.InviteLinks.SingleOrDefaultAsync(x =>
x.Token == request.Token);
// Get the classroom.
var classroom = await _context.Classrooms.FindAsync(inviteLink.Classroom.Id);
// No classroom was found with the given id.
if (classroom is null) {
Result<Unit>.Failure("Unable to find classroom.");
}
// Get the currently authorized user.
var user = await _context.Users.SingleOrDefaultAsync(x =>
x.UserName == _userAccessor.GetCurrentUsername());
var student = await _context.ApplicationUserClassrooms
.SingleOrDefaultAsync(x => x.ClassroomId == classroom.Id &&
x.ApplicationUserId == user.Id);
// User is already attending this classroom.
if (student != null) {
return Result<Unit>.Failure("User is already participating in this classroom.");
}
// Create a new entry in the UserClassroom table.
student = new ApplicationUserClassroom(user.Id, classroom.Id, true, user, classroom);
_context.ApplicationUserClassrooms.Add(student);
// Save changes to the database.
var success = await _context.SaveChangesAsync() > 0;
// Return the final response.
if (success) return Result<Unit>.Success(Unit.Value);
return Result<Unit>.Failure("There was a problem saving changes.");
}
}
}
| 42.46875 | 115 | 0.654893 | [
"MIT"
] | mrodrigues95/ClassroomChat | api/Application/Classrooms/Commands/JoinClassroom/JoinClassroomCommandHandler.cs | 2,720 | C# |
using System;
namespace MShared
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ExpandAttribute : Attribute
{
}
}
| 16.6 | 70 | 0.710843 | [
"MIT"
] | manureini/MShared | MShared/MShared/ExpandAttribute.cs | 168 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\shared\d3dkmddi.h(2663,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct _DXGK_QUERYSEGMENTMEMORYSTATE__union_0
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public byte[] __bits;
public uint NumInvalidMemoryRanges { get => InteropRuntime.GetUInt32(__bits, 0, 32); set { if (__bits == null) __bits = new byte[4]; InteropRuntime.SetUInt32(value, __bits, 0, 32); } }
public uint NumUEFIFrameBufferRanges { get => InteropRuntime.GetUInt32(__bits, 0, 32); set { if (__bits == null) __bits = new byte[4]; InteropRuntime.SetUInt32(value, __bits, 0, 32); } }
}
}
| 51.588235 | 195 | 0.706956 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/_DXGK_QUERYSEGMENTMEMORYSTATE__union_0.cs | 879 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cs_sdk.Exceptions
{
class KoreanbotsHttpException : Exception
{
public KoreanbotsHttpException(string message) : base(message){}
}
}
| 20.071429 | 72 | 0.747331 | [
"MIT"
] | koreanbots/cs-sdk | cs-sdk/Exceptions/KoreanbotsHttpException.cs | 283 | C# |
//
// Ghost : Sprite Class
// Created 16/10/2021
//
// WinForms PacMan v0.0.1
// Aardhyn Lavender 2021
//
// A Sprite that moves about the maze and chooses a new
// direction at intersections based on AI implimented in
// child classes. Provides functionality shared across
// all ghosts such as target tile Pathfinding, and mode
// switching and subsequent functionality augmentation
//
// Ghosts can be in multiple MODEs
//
// * CHASE mode, where they follow their
// implimented target tile finding algorithms.
// * SCATTER mode, where their targe tile
// is set to an constant implimented in derived
// classes.
//
// * EATEN mode, where their target tile is set to
// their home tile which implimented in derived
// classes. Thier texture is set to the EATEN
// varients defined.
//
// * FRIGHTEND mode, where their movements are based
// on random turns at intersections rather than
// a target tile. Ghosts use the FRIGHTENED texture
// in this mode
//
// Ghosts change from CHASE || SCATTER to FRIGHTENED when
// PacMan:sprite types enter the same tile as Energizer:TileObject
// types, and remain in said mode until 'Eaten()', or the FrightenedTime
// elapsed since 'Frighten()'ed;
//
// Ghosts can be eaten by Pacman:sprite types which triggers
// the mode from FRIGHTEND to EATEN, reverting back to CHASE
// when the Ghost has returned to its Home Tile.
//
using System;
using System.Linq;
using System.Collections.Generic;
using FormsPixelGameEngine.Render;
using FormsPixelGameEngine.Utility;
namespace FormsPixelGameEngine.GameObjects.Sprites.Ghosts
{
abstract class Ghost : Sprite
{
// CONSTANT AND STATIC MEMBERS
private const int INFINITY = 1000;
protected const int DIRECTIONS = 4;
protected const int SIZE = 2;
private const int TUNNEL_DIVISOR = 2;
private const int FRIGHTENED_DIVISOR = 2;
protected const int ANIMATIONS = 2;
protected const int ANIMATION_SPEED = Time.HUNDREDTH_SECOND;
protected const int FRIGHTENED = 504;
protected const int EATEN_RIGHT = 512;
protected const int EATEN_LEFT = 514;
protected const int EATEN_UP = 516;
protected const int EATEN_DOWN = 518;
private const int PSEUDO_WALLS = 4;
private const int GATE_TILES = 2;
protected const int OFFSET_X = 4;
private const int OFFSET_Y = 3;
private const int DEBUG_Z = 200;
private const int SELECTOR_ANIMATIONS = 7;
private const int SELECTOR_RATE = Time.TWENTYTH_SECOND;
// directional trajectories
protected static readonly Vector2D[] Directions =
new Vector2D[DIRECTIONS]
{
new Vector2D(0,-1),
new Vector2D(1,0),
new Vector2D(0,1),
new Vector2D(-1,0)
};
// tiles that ghosts can't turn UP into
private static readonly Vector2D[] PseudoWall =
new Vector2D[PSEUDO_WALLS]
{
new Vector2D(12,13),
new Vector2D(15,13),
new Vector2D(12,25),
new Vector2D(15,25)
};
// tiles that ghosts can't turn DOWN into
private static readonly Vector2D[] monsterGate =
new Vector2D[GATE_TILES]
{
new Vector2D(13,15),
new Vector2D(14,15)
};
private static readonly int[] eatenTextures =
new int[DIRECTIONS]
{
EATEN_UP,
EATEN_RIGHT,
EATEN_DOWN,
EATEN_LEFT
};
// FIELDS
protected PacMan pacman;
private Mode mode;
private int updateDiv;
protected Vector2D targetTile;
protected Vector2D scatterTile;
protected Vector2D homeTile;
private GameObject tileSelector;
private Animation SelectorRotation;
protected int preferenceRank;
private int pelletLimit;
private int pelletCounter;
protected Colour Colour;
protected Animation frightened;
private Animation flashing;
protected Animation right;
protected Animation left;
protected Animation up;
protected Animation down;
protected Animation[] directionalAnimations;
// CONSTRUCTOR
public Ghost(float x, float y, int index, int pelletLimit, int tileTexture, World world, PacMan pacman, Colour colour)
: base(x, y, index, SIZE, SIZE, new Vector2D(), world)
{
// initalize fields
this.pacman = pacman;
this.pelletLimit = pelletLimit;
Colour = colour;
locked = true;
mode = Mode.SCATTER;
offsetX = 0;
offsetY = OFFSET_Y;
homeTile = world.GetTile(this);
AtHome = true;
// create frightened animation
frightened = new Animation(game, tileset, this, SIZE, FRIGHTENED, 2, Time.TENTH_SECOND);
// create the frightened flashing animation
flashing = new Animation(game, tileset, this, SIZE, FRIGHTENED, 4, Time.TENTH_SECOND);
if (game.Debug)
{
tileSelector = game.AddGameObject(new GameObject(0, 0, tileTexture, DEBUG_Z, 1, 1));
SelectorRotation = Game.AddAnimation(new Animation(game, tileset, tileSelector, 1, tileTexture, SELECTOR_ANIMATIONS, SELECTOR_RATE));
SelectorRotation.Start();
}
}
// PROPERTIES
public Vector2D TargetTile
=> targetTile;
public Mode Mode
=> mode;
public bool AtHome;
// The personal count of dots pacman has eaten while being 'prefered ghost'
public int PelletCounter
=> pelletCounter;
// The dots to count before permited leaving the ghost house
public int PelletLimit
=> pelletLimit;
// How the ghost ranks against other ghost types
public int PreferenceRank
=> preferenceRank;
// METHODS
// prints debugging infomation
protected virtual void debugDraw()
{
if (mode != Mode.FRIGHTENED && !locked)
{
// fetch current and target tiles
Vector2D a = world.GetCoordinate(currentTile);
Vector2D b = world.GetCoordinate(targetTile);
// offset tiles to centroids
a.X += OFFSET_X;
b.X += OFFSET_X;
a.Y += OFFSET_X;
b.Y += OFFSET_X;
// draw a line
game.DrawLine(a, b, Colour);
// update target tile selector
world.PlaceObject(tileSelector, targetTile);
}
}
// removes animation and tileselector
public override void OnFreeGameObject()
{
if (game.Debug)
{
game.QueueFree(tileSelector);
Game.RemoveAnimation(SelectorRotation);
}
}
// calculate the target tile
protected abstract Vector2D GetTargetTile();
// place the ghost in its original position
public virtual void Reset()
{
Vector2D start = world.GetCoordinate(homeTile);
x = start.X;
y = start.Y;
Trajectory.Zero();
Show();
}
// reverse direction and set target tile to
// applicable map corner
public void Scatter()
{
if (mode == Mode.EATEN && !currentTile.Equals(homeTile)) ;
else
{
CurrentAnimation.Start();
mode = Mode.SCATTER;
speed = 1.0f;
reverseDirection();
}
}
// sets mode to chase
public void Chase()
{
if (mode == Mode.EATEN && !currentTile.Equals(homeTile)) ;
else
{
CurrentAnimation.Start();
mode = Mode.CHASE;
speed = 1.0f;
reverseDirection();
}
}
// reverse direction and set mode to FRIGHTENED
public void Frighten()
{
if (mode != Mode.FRIGHTENED)
{
mode = Mode.FRIGHTENED;
reverseDirection();
}
CurrentAnimation = frightened;
frightened.Start();
}
// set mode to EATEN
public void Eat()
{
if (mode != Mode.EATEN) ;
{
CurrentAnimation.Stop();
mode = Mode.EATEN;
game.ConsumeGhost();
game.PlaySound(Properties.Resources.eat_ghost);
}
}
// reverts the ghosts back to either CHASE or SCATTER
public void Revert()
{
if (game.CurrentMode == Mode.CHASE)
Chase();
else
Scatter();
}
// flashes the ghost indicating a mode switch from FRIGHTENED
public void Flash()
{
CurrentAnimation = flashing;
CurrentAnimation.Start();
}
// checks if a ghost is within the ghost house
private bool InGhostHouse()
=> currentTile.X >= 10
&& currentTile.X <= 17
&& currentTile.Y >= 15
&& currentTile.Y <= 19;
// increments pellet counter and returns if within the limit
public bool IncrementPelletCounter()
=> ++pelletCounter < PelletLimit;
// inverts trajectory
private void reverseDirection()
{
// reverse direction
if (!inTunnel)
{
Trajectory.X *= -1;
Trajectory.Y *= -1;
}
}
// UPDATING
// updates tiles, position, trajectory, animations, and mode specific infomation
public override void Update()
{
if (inTunnel)
updateDiv = TUNNEL_DIVISOR;
else if (mode == Mode.FRIGHTENED)
updateDiv = FRIGHTENED_DIVISOR;
else
updateDiv = 1;
// round position
int x = (int)Math.Round(this.x);
int y = (int)Math.Round(this.y);
// teleport in tunnel
if (x < world.X && Direction == Direction.LEFT)
X = world.Width;
if (x > world.X + world.Width && Direction == Direction.RIGHT)
X = world.X;
// get the ghosts current tile
currentTile = world.GetTile(x, y);
// eat if occupying the same tile as pacman
if (currentTile.Equals(pacman.CurrentTile))
{
if (mode == Mode.FRIGHTENED)
Eat();
else if (mode != Mode.EATEN && !game.Debug)
pacman.Kill();
}
// revert to standard mode when home after being eaten
if (mode == Mode.EATEN && currentTile.Equals(homeTile))
Revert();
// update target tile if centered on a tile
if (x % tileset.Size == 0
&& y % tileset.Size == 0
&& x < world.X + world.Width
&& x > world.X)
{
if (InGhostHouse() && mode != Mode.EATEN)
{
offsetX = 0;
targetTile = AtHome ? homeTile : new Vector2D(13, 14);
}
// update target tile based on mode
else
{
if (offsetX == 0)
{
offsetX = OFFSET_X;
X += OFFSET_X;
}
switch (mode)
{
case Mode.CHASE:
// chase pacman
targetTile = GetTargetTile();
speed = 1.0f;
break;
case Mode.SCATTER:
// scatter to corner
targetTile = scatterTile;
speed = 1.0f;
break;
case Mode.EATEN:
// return to ghost house
targetTile = homeTile;
speed = 2.0f;
break;
default: break;
}
}
// store distances to 'target tile' from tiles ajacant to the 'current tile'
List<int> distances = new List<int>(DIRECTIONS);
// loop ajacant tiles in order
for (int i = 0; i < DIRECTIONS; i++)
{
Vector2D directionTrajectory = Directions[i];
Vector2D adjacent = new Vector2D(CurrentTile.X + directionTrajectory.X, CurrentTile.Y + directionTrajectory.Y);
// get ajacant tile distance
int distance = (int)Vector2D.GetAbsDistance(world.GetCoordinate(adjacent), world.GetCoordinate(targetTile));
// set distance to INFINITY if the ajacant tile is a wall, 'pseudowall', gate, or flank direction tile
if (world.GetTileObject(adjacent).Wall || Trajectory.Invert().Equals(directionTrajectory)
|| (CurrentTile.Y > adjacent.Y && PseudoWall.Contains(adjacent))
|| (CurrentTile.Y < adjacent.Y && mode != Mode.EATEN && monsterGate.Contains(adjacent)))
{
distance = INFINITY;
}
distances.Add(distance);
}
// set the ghosts trajectory
if (!inTunnel)
{
int directionIndex;
if (mode == Mode.FRIGHTENED)
// pick a random tile that is not an INFINITE distance from pacman
do
directionIndex = game.Random.Next(DIRECTIONS);
while (distances[directionIndex] == INFINITY);
else
// pick the first closest tile to PacMan
directionIndex = distances.IndexOf(distances.Min());
Trajectory = Directions[directionIndex];
direction = (Direction)directionIndex;
}
// set animation / texture
if (mode == Mode.EATEN)
sourceRect = tileset.GetTileSourceRect(eatenTextures[(int)direction], SIZE, SIZE);
else if (mode != Mode.FRIGHTENED)
CurrentAnimation = directionalAnimations[(int)direction];
}
// debug
if (game.Debug)
debugDraw();
// update if div is 0
if (!locked && game.Tick % updateDiv == 0)
base.Update();
}
}
} | 31.201597 | 152 | 0.505246 | [
"MIT"
] | AardhynLavender/WinFormsPacman | Pacman/GameObjects/Sprites/Ghosts/Ghost.cs | 15,634 | C# |
// Copyright (c) MadDonkeySoftware
namespace Common
{
/// <summary>
/// Struct to hold
/// </summary>
public struct JobStatuses
{
public const string New = "New";
public const string Queued = "Queued";
public const string Running = "Running";
public const string Failed = "Failed";
public const string Successful = "Successful";
}
} | 24.8125 | 54 | 0.604534 | [
"MIT"
] | MadDonkeySoftware/corp-hq | app/common/JobStatuses.cs | 397 | C# |
using EcommerceStore.Carrinho.API.Configuration;
using EcommerceStore.WebApi.Core.Identidade;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace EcommerceStore.Carrinho.API
{
// install-package microsoft.entityframeworkcore -version 3.1.3
// install-package microsoft.entityframeworkcore.abstractions -version 3.1.3
// install-package microsoft.entityframeworkcore.relational -version 3.1.3
// install-package microsoft.entityframeworkcore.sqlserver -version 3.1.3
// install-package microsoft.entityframeworkcore.design -version 3.1.3
// install-package swashbuckle.aspnetcore -version 5.3.3
// install-package mediatr.extensions.microsoft.dependencyinjection -version 8.0.0 -- para registrar o mediatr no startup
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IWebHostEnvironment hostEnvironment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(hostEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostEnvironment.EnvironmentName}.json")
.AddEnvironmentVariables();
if (hostEnvironment.IsDevelopment())
builder.AddUserSecrets<Startup>();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddConfigurationApi(Configuration);
services.AddConfigurationJwt(Configuration);
services.AddConfigurationSwagger(Configuration);
services.RegisterServices();
services.AddMessageBusConfiguraiton(Configuration);
//services.AddMediatR(typeof(Startup));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseConfigurationSwagger();
app.UseConfigurationApi(env);
}
}
}
| 35.716667 | 125 | 0.69342 | [
"MIT"
] | notfoundimpactaadsnoturno/ecommerce-store | EcommerceStore/src/services/EcommerceStore.Carrinho.API/Startup.cs | 2,143 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using CadastrodeClientes.Models;
namespace CadastrodeClientes.Controllers
{ //Criação de controller do jeito mais pratico usando o EntityFramework
public class ClientesController : Controller
{
private readonly Contexto _context;
public ClientesController(Contexto context)
{
_context = context;
}
// GET: Clientes
public async Task<IActionResult> Index()
{
return View(await _context.Clientes.ToListAsync());
}
// GET: Clientes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var cliente = await _context.Clientes
.FirstOrDefaultAsync(m => m.Id == id);
if (cliente == null)
{
return NotFound();
}
return View(cliente);
}
// GET: Clientes/Create
public IActionResult Create()
{
return View();
}
// POST: Clientes/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Nome,Telefone,Email")] Cliente cliente)
{
if (ModelState.IsValid)
{
_context.Add(cliente);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(cliente);
}
// GET: Clientes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var cliente = await _context.Clientes.FindAsync(id);
if (cliente == null)
{
return NotFound();
}
return View(cliente);
}
// POST: Clientes/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Nome,Telefone,Email")] Cliente cliente)
{
if (id != cliente.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(cliente);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClienteExists(cliente.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(cliente);
}
// GET: Clientes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var cliente = await _context.Clientes
.FirstOrDefaultAsync(m => m.Id == id);
if (cliente == null)
{
return NotFound();
}
return View(cliente);
}
// POST: Clientes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var cliente = await _context.Clientes.FindAsync(id);
_context.Clientes.Remove(cliente);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ClienteExists(int id)
{
return _context.Clientes.Any(e => e.Id == id);
}
}
}
| 28.856209 | 104 | 0.506002 | [
"MIT"
] | Alexandrade01/Cadastro_Clientes_AspNet | CadastrodeClientes/Controllers/ClientesController.cs | 4,419 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources.Models;
namespace Azure.ResourceManager.Resources
{
/// <summary>
/// A Class representing an ArmDeploymentScript along with the instance operations that can be performed on it.
/// If you have a <see cref="ResourceIdentifier" /> you can construct an <see cref="ArmDeploymentScriptResource" />
/// from an instance of <see cref="ArmClient" /> using the GetArmDeploymentScriptResource method.
/// Otherwise you can get one from its parent resource <see cref="ResourceGroupResource" /> using the GetArmDeploymentScript method.
/// </summary>
public partial class ArmDeploymentScriptResource : ArmResource
{
/// <summary> Generate the resource identifier of a <see cref="ArmDeploymentScriptResource"/> instance. </summary>
public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string scriptName)
{
var resourceId = $"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}";
return new ResourceIdentifier(resourceId);
}
private readonly ClientDiagnostics _armDeploymentScriptDeploymentScriptsClientDiagnostics;
private readonly DeploymentScriptsRestOperations _armDeploymentScriptDeploymentScriptsRestClient;
private readonly ClientDiagnostics _scriptLogDeploymentScriptsClientDiagnostics;
private readonly DeploymentScriptsRestOperations _scriptLogDeploymentScriptsRestClient;
private readonly ArmDeploymentScriptData _data;
/// <summary> Initializes a new instance of the <see cref="ArmDeploymentScriptResource"/> class for mocking. </summary>
protected ArmDeploymentScriptResource()
{
}
/// <summary> Initializes a new instance of the <see cref = "ArmDeploymentScriptResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="data"> The resource that is the target of operations. </param>
internal ArmDeploymentScriptResource(ArmClient client, ArmDeploymentScriptData data) : this(client, data.Id)
{
HasData = true;
_data = data;
}
/// <summary> Initializes a new instance of the <see cref="ArmDeploymentScriptResource"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal ArmDeploymentScriptResource(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_armDeploymentScriptDeploymentScriptsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ResourceType.Namespace, Diagnostics);
TryGetApiVersion(ResourceType, out string armDeploymentScriptDeploymentScriptsApiVersion);
_armDeploymentScriptDeploymentScriptsRestClient = new DeploymentScriptsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, armDeploymentScriptDeploymentScriptsApiVersion);
_scriptLogDeploymentScriptsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", ScriptLogResource.ResourceType.Namespace, Diagnostics);
TryGetApiVersion(ScriptLogResource.ResourceType, out string scriptLogDeploymentScriptsApiVersion);
_scriptLogDeploymentScriptsRestClient = new DeploymentScriptsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, scriptLogDeploymentScriptsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
/// <summary> Gets the resource type for the operations. </summary>
public static readonly ResourceType ResourceType = "Microsoft.Resources/deploymentScripts";
/// <summary> Gets whether or not the current instance has data. </summary>
public virtual bool HasData { get; }
/// <summary> Gets the data representing this Feature. </summary>
/// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
public virtual ArmDeploymentScriptData Data
{
get
{
if (!HasData)
throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
return _data;
}
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
}
/// <summary> Gets an object representing a ScriptLogResource along with the instance operations that can be performed on it in the ArmDeploymentScript. </summary>
/// <returns> Returns a <see cref="ScriptLogResource" /> object. </returns>
public virtual ScriptLogResource GetScriptLog()
{
return new ScriptLogResource(Client, new ResourceIdentifier(Id.ToString() + "/logs/default"));
}
/// <summary>
/// Gets a deployment script with a given name.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Get
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<ArmDeploymentScriptResource>> GetAsync(CancellationToken cancellationToken = default)
{
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.Get");
scope.Start();
try
{
var response = await _armDeploymentScriptDeploymentScriptsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new ArmDeploymentScriptResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets a deployment script with a given name.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Get
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<ArmDeploymentScriptResource> Get(CancellationToken cancellationToken = default)
{
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.Get");
scope.Start();
try
{
var response = _armDeploymentScriptDeploymentScriptsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new ArmDeploymentScriptResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes a deployment script. When operation completes, status code 200 returned without content.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Delete
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.Delete");
scope.Start();
try
{
var response = await _armDeploymentScriptDeploymentScriptsRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
var operation = new ResourcesArmOperation(response);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Deletes a deployment script. When operation completes, status code 200 returned without content.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Delete
/// </summary>
/// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default)
{
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.Delete");
scope.Start();
try
{
var response = _armDeploymentScriptDeploymentScriptsRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
var operation = new ResourcesArmOperation(response);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletionResponse(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates deployment script tags with specified values.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Update
/// </summary>
/// <param name="patch"> Deployment script resource with the tags to be updated. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception>
public virtual async Task<Response<ArmDeploymentScriptResource>> UpdateAsync(ArmDeploymentScriptPatch patch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(patch, nameof(patch));
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.Update");
scope.Start();
try
{
var response = await _armDeploymentScriptDeploymentScriptsRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new ArmDeploymentScriptResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Updates deployment script tags with specified values.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Update
/// </summary>
/// <param name="patch"> Deployment script resource with the tags to be updated. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception>
public virtual Response<ArmDeploymentScriptResource> Update(ArmDeploymentScriptPatch patch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(patch, nameof(patch));
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.Update");
scope.Start();
try
{
var response = _armDeploymentScriptDeploymentScriptsRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken);
return Response.FromValue(new ArmDeploymentScriptResource(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets deployment script logs for a given deployment script name.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs
/// Operation Id: DeploymentScripts_GetLogs
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="ScriptLogResource" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<ScriptLogResource> GetLogsAsync(CancellationToken cancellationToken = default)
{
async Task<Page<ScriptLogResource>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _scriptLogDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.GetLogs");
scope.Start();
try
{
var response = await _scriptLogDeploymentScriptsRestClient.GetLogsAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new ScriptLogResource(Client, value)), null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
}
/// <summary>
/// Gets deployment script logs for a given deployment script name.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}/logs
/// Operation Id: DeploymentScripts_GetLogs
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="ScriptLogResource" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<ScriptLogResource> GetLogs(CancellationToken cancellationToken = default)
{
Page<ScriptLogResource> FirstPageFunc(int? pageSizeHint)
{
using var scope = _scriptLogDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.GetLogs");
scope.Start();
try
{
var response = _scriptLogDeploymentScriptsRestClient.GetLogs(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new ScriptLogResource(Client, value)), null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
}
/// <summary>
/// Add a tag to the current resource.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Get
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="value"> The value for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
public virtual async Task<Response<ArmDeploymentScriptResource>> AddTagAsync(string key, string value, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
Argument.AssertNotNull(value, nameof(value));
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.AddTag");
scope.Start();
try
{
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues[key] = value;
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _armDeploymentScriptDeploymentScriptsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new ArmDeploymentScriptResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Add a tag to the current resource.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Get
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="value"> The value for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception>
public virtual Response<ArmDeploymentScriptResource> AddTag(string key, string value, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
Argument.AssertNotNull(value, nameof(value));
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.AddTag");
scope.Start();
try
{
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues[key] = value;
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _armDeploymentScriptDeploymentScriptsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return Response.FromValue(new ArmDeploymentScriptResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Replace the tags on the resource with the given set.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Get
/// </summary>
/// <param name="tags"> The set of tags to use as replacement. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
public virtual async Task<Response<ArmDeploymentScriptResource>> SetTagsAsync(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tags, nameof(tags));
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.SetTags");
scope.Start();
try
{
await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues.ReplaceWith(tags);
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _armDeploymentScriptDeploymentScriptsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new ArmDeploymentScriptResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Replace the tags on the resource with the given set.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Get
/// </summary>
/// <param name="tags"> The set of tags to use as replacement. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception>
public virtual Response<ArmDeploymentScriptResource> SetTags(IDictionary<string, string> tags, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(tags, nameof(tags));
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.SetTags");
scope.Start();
try
{
GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken);
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues.ReplaceWith(tags);
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _armDeploymentScriptDeploymentScriptsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return Response.FromValue(new ArmDeploymentScriptResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Removes a tag by key from the resource.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Get
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
public virtual async Task<Response<ArmDeploymentScriptResource>> RemoveTagAsync(string key, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.RemoveTag");
scope.Start();
try
{
var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false);
originalTags.Value.Data.TagValues.Remove(key);
await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false);
var originalResponse = await _armDeploymentScriptDeploymentScriptsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new ArmDeploymentScriptResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Removes a tag by key from the resource.
/// Request Path: /subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deploymentScripts/{scriptName}
/// Operation Id: DeploymentScripts_Get
/// </summary>
/// <param name="key"> The key for the tag. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception>
public virtual Response<ArmDeploymentScriptResource> RemoveTag(string key, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(key, nameof(key));
using var scope = _armDeploymentScriptDeploymentScriptsClientDiagnostics.CreateScope("ArmDeploymentScriptResource.RemoveTag");
scope.Start();
try
{
var originalTags = GetTagResource().Get(cancellationToken);
originalTags.Value.Data.TagValues.Remove(key);
GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken);
var originalResponse = _armDeploymentScriptDeploymentScriptsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken);
return Response.FromValue(new ArmDeploymentScriptResource(Client, originalResponse.Value), originalResponse.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 58.665988 | 488 | 0.669398 | [
"MIT"
] | ChenTanyi/azure-sdk-for-net | sdk/resources/Azure.ResourceManager.Resources/src/Generated/ArmDeploymentScriptResource.cs | 28,805 | C# |
/*
* Copyright (c) 2019 ETH Zürich, Educational Development and Technology (LET)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System.ComponentModel;
namespace SafeExamBrowser.UserInterface.Contracts.Shell.Events
{
/// <summary>
/// Event handler used to define the control flow when the <see cref="ITaskbar"/>'s quit button is clicked.
/// </summary>
public delegate void QuitButtonClickedEventHandler(CancelEventArgs args);
}
| 33.666667 | 108 | 0.739274 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | junbaor/seb-win-refactoring | SafeExamBrowser.UserInterface.Contracts/Shell/Events/QuitButtonClickedEventHandler.cs | 609 | 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("ILDeobfuscator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ILDeobfuscator")]
[assembly: AssemblyCopyright("")]
[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("2cb6730b-5336-4471-8a8a-a71c368224b6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.27027 | 84 | 0.748368 | [
"MIT"
] | kookmin-cat/AgentTeslaDeob | ILDeobfuscator/Properties/AssemblyInfo.cs | 1,381 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cats.Models.Mapping
{
public class UserDashboardPreferenceMap : EntityTypeConfiguration<UserDashboardPreference>
{
public UserDashboardPreferenceMap()
{
// Primary Key
this.HasKey(t => t.UserDashboardPreferenceID);
// Properties
this.Property(t => t.OrderNo);
// Table & Column Mappings
this.ToTable("UserDashboardPreference");
this.Property(t => t.UserDashboardPreferenceID).HasColumnName("UserDashboardPreferenceID");
this.Property(t => t.UserID).HasColumnName("UserID");
this.Property(t => t.DashboardWidgetID).HasColumnName("DashboardWidgetID");
this.Property(t => t.OrderNo).HasColumnName("OrderNo");
// Relationships
this.HasRequired(t => t.DashboardWidget)
.WithMany(t => t.UserDashboardPreferences)
.HasForeignKey(d => d.DashboardWidgetID);
this.HasRequired(t => t.User)
.WithMany(t => t.UserDashboardPreferences)
.HasForeignKey(d => d.UserID);
}
}
}
| 34.461538 | 103 | 0.637649 | [
"Apache-2.0"
] | IYoni/cats | Models/Cats.Models/Mapping/UserDashboardPreferenceMap.cs | 1,346 | C# |
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Models.ContentEditing
{
[DataContract(Name = "scriptFile", Namespace = "")]
public class CodeFileDisplay : INotificationModel, IValidatableObject
{
public CodeFileDisplay()
{
Notifications = new List<BackOfficeNotification>();
}
/// <summary>
/// VirtualPath is the path to the file on disk
/// /views/partials/file.cshtml
/// </summary>
[DataMember(Name = "virtualPath", IsRequired = true)]
public string VirtualPath { get; set; }
/// <summary>
/// Path represents the path used by the backoffice tree
/// For files stored on disk, this is a URL encoded, comma separated
/// path to the file, always starting with -1.
///
/// -1,Partials,Parials%2FFolder,Partials%2FFolder%2FFile.cshtml
/// </summary>
[DataMember(Name = "path")]
[ReadOnly(true)]
public string Path { get; set; }
[DataMember(Name = "name", IsRequired = true)]
public string Name { get; set; }
[DataMember(Name = "content", IsRequired = true)]
public string Content { get; set; }
[DataMember(Name = "fileType", IsRequired = true)]
public string FileType { get; set; }
[DataMember(Name = "snippet")]
[ReadOnly(true)]
public string Snippet { get; set; }
[DataMember(Name = "id")]
[ReadOnly(true)]
public string Id { get; set; }
public List<BackOfficeNotification> Notifications { get; private set; }
/// <summary>
/// Some custom validation is required for valid file names
/// </summary>
/// <param name="validationContext"></param>
/// <returns></returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var illegalChars = System.IO.Path.GetInvalidFileNameChars();
if (Name.ContainsAny(illegalChars))
{
yield return new ValidationResult(
"The file name cannot contain illegal characters",
new[] { "Name" });
}
else if (System.IO.Path.GetFileNameWithoutExtension(Name).IsNullOrWhiteSpace())
{
yield return new ValidationResult(
"The file name cannot be empty",
new[] { "Name" });
}
}
}
}
| 34.324675 | 91 | 0.58305 | [
"MIT"
] | Ambertvu/Umbraco-CMS | src/Umbraco.Core/Models/ContentEditing/CodeFileDisplay.cs | 2,645 | C# |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor.IMGUI.Controls
{
public class AdvancedDropdownItem : IComparable
{
string m_Name;
Texture2D m_Icon;
int m_Id;
int m_ElementIndex = -1;
bool m_Enabled = true;
List<AdvancedDropdownItem> m_Children = new List<AdvancedDropdownItem>();
public string name
{
get { return m_Name; }
set { m_Name = value; }
}
internal virtual string displayName
{
get { return m_Name; }
}
public Texture2D icon
{
get { return m_Icon; }
set { m_Icon = value; }
}
public int id
{
get
{
return m_Id;
}
set { m_Id = value; }
}
internal int elementIndex
{
get { return m_ElementIndex; }
set { m_ElementIndex = value; }
}
public bool enabled
{
get { return m_Enabled; }
set { m_Enabled = value; }
}
public IEnumerable<AdvancedDropdownItem> children => m_Children;
public void AddChild(AdvancedDropdownItem child)
{
m_Children.Add(child);
}
static readonly AdvancedDropdownItem k_SeparatorItem = new SeparatorDropdownItem();
public AdvancedDropdownItem(string name)
{
m_Name = name;
m_Id = name.GetHashCode();
}
public virtual int CompareTo(object o)
{
return name.CompareTo((o as AdvancedDropdownItem).name);
}
public void AddSeparator()
{
AddChild(k_SeparatorItem);
}
internal bool IsSeparator()
{
return k_SeparatorItem == this;
}
public override string ToString()
{
return m_Name;
}
class SeparatorDropdownItem : AdvancedDropdownItem
{
public SeparatorDropdownItem() : base("SEPARATOR")
{
}
}
}
}
| 22.881188 | 91 | 0.531372 | [
"Unlicense"
] | HelloWindows/AccountBook | client/framework/UnityCsReference-master/Editor/Mono/Inspector/AdvancedDropdown/AdvancedDropdownItem.cs | 2,311 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
using Niconicome.Extensions.System;
using Niconicome.Extensions.System.List;
using Niconicome.Models.Const;
using Niconicome.Models.Domain.Local.IO;
using Niconicome.Models.Domain.Local.Store.Types;
using Niconicome.Models.Domain.Utils;
using Niconicome.Models.Helper.Result;
using Reactive.Bindings.ObjectExtensions;
using Const = Niconicome.Models.Const;
namespace Niconicome.Models.Domain.Local.Addons.Core.Installer
{
public interface IAddonInstaller
{
/// <summary>
/// アドオンをインストールする
/// </summary>
/// <param name="tmpPath">一時フォルダーのパス</param>
/// <param name="updateInfomation">アップデートの場合、引数でデータを与える</param>
/// <returns></returns>
IAttemptResult<AddonInfomation> Install(string tmpPath, AddonInfomation? updateInfomation = null);
/// <summary>
/// アドオンを一時フォルダーに解凍する
/// </summary>
/// <param name="path">アドオンパス</param>
/// <returns></returns>
IAttemptResult<string> Extract(string path);
/// <summary>
/// マニフェストを読み込む
/// </summary>
/// <param name="tmpPath">一時フォルダーのパス</param>
/// <returns></returns>
IAttemptResult<AddonInfomation> LoadManifest(string tmpPath);
/// <summary>
/// インストール時に作成された一時ファイルを書き換える
/// </summary>
/// <returns></returns>
IAttemptResult ReplaceTemporaryFiles();
}
public class AddonInstaller : IAddonInstaller
{
public AddonInstaller(ILogger logger, IManifestLoader manifestLoader, INicoFileIO fileIO, INicoDirectoryIO directoryIO, IAddonStoreHandler storeHandler, IAddonInfomationsContainer container, IAddonUninstaller uninstaller)
{
this.logger = logger;
this.manifestLoader = manifestLoader;
this.fileIO = fileIO;
this.directoryIO = directoryIO;
this.storeHandler = storeHandler;
this.container = container;
this.uninstaller = uninstaller;
}
#region field
private readonly ILogger logger;
private readonly IManifestLoader manifestLoader;
private readonly INicoFileIO fileIO;
private readonly INicoDirectoryIO directoryIO;
private readonly IAddonStoreHandler storeHandler;
private readonly IAddonInfomationsContainer container;
private readonly IAddonUninstaller uninstaller;
#endregion
/// <summary>
/// インストールする
/// </summary>
/// <param name="tempPath"></param>
/// <returns></returns>
public IAttemptResult<AddonInfomation> Install(string tempPath, AddonInfomation? updateInfomation = null)
{
if (!this.directoryIO.Exists(tempPath))
{
return new AttemptResult<AddonInfomation>() { Message = "指定した一時フォルダーは存在しません。" };
}
string packageID = updateInfomation?.PackageID.Value ?? Path.GetFileName(tempPath);
//マニフェスト読み込み
IAttemptResult<AddonInfomation> mResult = this.LoadManifest(tempPath);
if (!mResult.IsSucceeded || mResult.Data is null)
{
return new AttemptResult<AddonInfomation>() { Message = mResult.Message, Exception = mResult.Exception };
}
this.UninstallIfAble(mResult.Data);
//DBに保存
IAttemptResult<int> sResult;
mResult.Data.PackageID.Value = packageID;
AddonInfomation addon;
if (updateInfomation is not null)
{
mResult.Data.ID.Value = updateInfomation.ID.Value;
mResult.Data.Identifier.Value = updateInfomation.Identifier.Value;
sResult = this.storeHandler.Update(mResult.Data);
}
else
{
sResult = this.storeHandler.StoreAddon(mResult.Data);
}
if (!sResult.IsSucceeded)
{
return new AttemptResult<AddonInfomation>() { Message = sResult.Message, Exception = sResult.Exception };
}
else
{
mResult.Data.ID.Value = sResult.Data;
addon = this.container.GetAddon(sResult.Data);
addon.SetData(mResult.Data);
}
string? iconFileName = Path.GetFileName(updateInfomation?.IconPathRelative.Value);
//移動
IAttemptResult mvResult = this.MoveAddon(tempPath, Path.Combine(FileFolder.AddonsFolder, packageID), iconFileName);
if (!mvResult.IsSucceeded)
{
return new AttemptResult<AddonInfomation>() { Message = mvResult.Message, Exception = mvResult.Exception };
}
//一時フォルダーを削除
IAttemptResult dResult = this.DeleteTempFolder(tempPath);
if (!dResult.IsSucceeded)
{
return new AttemptResult<AddonInfomation>() { Message = dResult.Message, Exception = dResult.Exception };
}
return new AttemptResult<AddonInfomation>() { IsSucceeded = true, Data = addon };
}
/// <summary>
/// 解凍する
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public IAttemptResult<string> Extract(string path)
{
if (!this.fileIO.Exists(path))
{
return new AttemptResult<string>() { Message = "指定したアドオンファイルは存在しません。" };
}
string packageID = Guid.NewGuid().ToString("D");
string targetPath = Path.Combine("tmp", packageID);
//解凍
IAttemptResult exResult = this.ExtractAddon(path, targetPath);
return new AttemptResult<string>() { Data = targetPath, IsSucceeded = exResult.IsSucceeded, Message = exResult.Message, Exception = exResult.Exception };
}
/// <summary>
/// マニフェストを読み込む
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public IAttemptResult<AddonInfomation> LoadManifest(string path)
{
string manifestPath = Path.Combine(path, "manifest.json");
if (!this.fileIO.Exists(manifestPath))
{
return new AttemptResult<AddonInfomation>() { Message = "指定したアドオンファイルは存在しません。" };
}
//マニフェスト読み込み
return this.manifestLoader.LoadManifest(manifestPath);
}
public IAttemptResult ReplaceTemporaryFiles()
{
List<string> files;
try
{
files = this.directoryIO.GetFiles(FileFolder.AddonsFolder, "*.tmp", true);
}
catch (Exception e)
{
this.logger.Error("一時ファイルの一覧を取得できませんでした。", e);
return new AttemptResult<string>() { Message = "一時ファイルの一覧を取得できませんでした。", Exception = e };
}
foreach (string file in files)
{
if (!file.EndsWith(".tmp")) continue;
string newPath = Regex.Replace(file, @"\.tmp$", "");
try
{
this.fileIO.Move(file, newPath, true);
}
catch (Exception e)
{
this.logger.Error($"一時ファイルの移動に失敗しました。(旧:{file}, 新:{newPath})", e);
return new AttemptResult<string>() { Message = $"一時ファイルの移動に失敗しました。(旧:{file}, 新:{newPath})", Exception = e };
}
}
return new AttemptResult<string>() { IsSucceeded = true };
}
#region private
/// <summary>
/// アドオンを解凍する
/// </summary>
/// <param name="path"></param>
/// <param name="targetPath"></param>
/// <returns></returns>
private IAttemptResult ExtractAddon(string path, string targetPath)
{
if (!this.directoryIO.Exists(targetPath))
{
try
{
this.directoryIO.Create(targetPath);
}
catch (Exception e)
{
this.logger.Error("アドオン解凍先ディレクトリの作成に失敗しました。", e);
return new AttemptResult() { Message = "アドオン解凍先ディレクトリの作成に失敗しました。", Exception = e };
}
}
try
{
ZipFile.ExtractToDirectory(path, targetPath);
}
catch (Exception e)
{
this.logger.Error("アドオンの展開に失敗しました。", e);
return new AttemptResult() { Message = "アドオンの展開に失敗しました。", Exception = e };
}
return new AttemptResult() { IsSucceeded = true };
}
/// <summary>
/// アドオンを移動する
/// </summary>
/// <param name="sourcePath"></param>
/// <param name="targetPath"></param>
/// <returns></returns>
private IAttemptResult MoveAddon(string sourcePath, string targetPath, string? iconFileName)
{
if (!this.directoryIO.Exists(targetPath))
{
try
{
this.directoryIO.Create(targetPath);
}
catch (Exception e)
{
this.logger.Error("アドオンの移動先ディレクトリの作成に失敗しました。", e);
return new AttemptResult() { Message = "アドオンの移動先ディレクトリの作成に失敗しました。", Exception = e };
}
}
bool isIconUsed = iconFileName is not null;
try
{
this.directoryIO.MoveAllFiles(sourcePath, targetPath, p =>
{
if (!isIconUsed) return p;
return Regex.IsMatch(p, $"^.*{iconFileName}$") ? p + ".tmp" : p;
});
}
catch (Exception e)
{
this.logger.Error("アドオンの移動に失敗しました。", e);
return new AttemptResult() { Message = "アドオンの移動に失敗しました。", Exception = e };
}
return new AttemptResult() { IsSucceeded = true };
}
private IAttemptResult DeleteTempFolder(string tempPath)
{
try
{
this.directoryIO.Delete(tempPath);
}
catch (Exception e)
{
this.logger.Error("アドオン一時フォルダーの削除に失敗しました。", e);
return new AttemptResult() { Exception = e, Message = "アドオン一時フォルダーの削除に失敗しました。" };
}
return new AttemptResult() { IsSucceeded = true };
}
/// <summary>
/// インストール済みで、実体のないアドオンをアンインストールする
/// </summary>
/// <returns></returns>
private void UninstallIfAble(AddonInfomation addon)
{
var isIdNull = string.IsNullOrEmpty(addon.Identifier.Value);
if (!this.storeHandler.IsInstallled(db => isIdNull ? db.Name == addon.Name.Value : db.Identifier == addon.Identifier.Value))
{
return;
}
AddonInfomation? info = this.storeHandler.GetAddon(db
=> isIdNull ? db.Name == addon.Name.Value : db.Identifier == addon.Identifier.Value);
if (info is null)
{
return;
}
else
{
this.uninstaller.Uninstall(info.ID.Value);
}
}
#endregion
}
}
| 33.561047 | 229 | 0.544651 | [
"MIT"
] | Hayao-H/Niconicome | Niconicome/Models/Domain/Local/Addons/Core/Installer/AddonInstaller.cs | 12,669 | 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 alexaforbusiness-2017-11-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.AlexaForBusiness.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.AlexaForBusiness.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetConferenceProvider operation
/// </summary>
public class GetConferenceProviderResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetConferenceProviderResponse response = new GetConferenceProviderResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("ConferenceProvider", targetDepth))
{
var unmarshaller = ConferenceProviderUnmarshaller.Instance;
response.ConferenceProvider = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonAlexaForBusinessException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static GetConferenceProviderResponseUnmarshaller _instance = new GetConferenceProviderResponseUnmarshaller();
internal static GetConferenceProviderResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetConferenceProviderResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.455446 | 171 | 0.665874 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/AlexaForBusiness/Generated/Model/Internal/MarshallTransformations/GetConferenceProviderResponseUnmarshaller.cs | 3,783 | 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("OddOccurences")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OddOccurences")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("18a27697-7790-4680-8959-5e75d2df140e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.675676 | 84 | 0.748207 | [
"MIT"
] | AgalexBG/ProgrammingFundamentals-Extended | DictionariesAndLINQ-Lab/OddOccurences/Properties/AssemblyInfo.cs | 1,397 | C# |
using System;
using System.Text.RegularExpressions;
using log4net.Appender;
using log4net.Core;
namespace IdealistViewer
{
/// <summary>
/// Writes log information out onto the console
/// </summary>
public class IdealistViewerAppender : AnsiColorTerminalAppender
{
override protected void Append(LoggingEvent le)
{
try
{
string loggingMessage = RenderLoggingEvent(le);
string regex = @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)";
Regex RE = new Regex(regex, RegexOptions.Multiline);
MatchCollection matches = RE.Matches(loggingMessage);
// Get some direct matches $1 $4 is a
if (matches.Count == 1)
{
System.Console.Write(matches[0].Groups["Front"].Value);
System.Console.Write("[");
WriteColorText(DeriveColor(matches[0].Groups["Category"].Value), matches[0].Groups["Category"].Value);
System.Console.Write("]:");
if (le.Level == Level.Error)
{
WriteColorText(ConsoleColor.Red, matches[0].Groups["End"].Value);
}
else if (le.Level == Level.Warn)
{
WriteColorText(ConsoleColor.Yellow, matches[0].Groups["End"].Value);
}
else
{
System.Console.Write(matches[0].Groups["End"].Value);
}
System.Console.WriteLine();
}
else
{
System.Console.Write(loggingMessage);
}
}
catch (Exception e)
{
System.Console.WriteLine("Couldn't write out log message", e.ToString());
}
}
private void WriteColorText(ConsoleColor color, string sender)
{
try
{
lock (this)
{
try
{
System.Console.ForegroundColor = color;
System.Console.Write(sender);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(sender);
}
}
}
catch (ObjectDisposedException)
{
}
}
private static ConsoleColor DeriveColor(string input)
{
int colIdx = (input.ToUpper().GetHashCode() % 6) + 9;
return (ConsoleColor)colIdx;
}
}
}
| 33.483146 | 123 | 0.435906 | [
"BSD-3-Clause"
] | eudaimonent/IdealistViewer | IdealistViewer/Util/IdealistViewerAppender.cs | 2,980 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using EntityChangeTracking_AspNetCore_3._0.Data;
using EntityChangeTracking_AspNetCore_3._0.Models;
using Microsoft.AspNetCore.Authorization;
namespace EntityChangeTracking_AspNetCore_3._0.Controllers
{
[Authorize]
public class ExamplesController : Controller
{
private readonly ApplicationDbContext _context;
public ExamplesController(ApplicationDbContext context)
{
_context = context;
}
// GET: Examples
public async Task<IActionResult> Index()
{
return View(await _context.Example.ToListAsync());
}
// GET: Examples/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var example = await _context.Example
.FirstOrDefaultAsync(m => m.Id == id);
if (example == null)
{
return NotFound();
}
return View(example);
}
// GET: Examples/Create
public IActionResult Create()
{
return View();
}
// POST: Examples/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("FieldA,FieldB,FieldC,FieldD")] Example example)
{
if (ModelState.IsValid)
{
_context.Add(example);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(example);
}
// GET: Examples/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var example = await _context.Example.FindAsync(id);
if (example == null)
{
return NotFound();
}
return View(example);
}
// POST: Examples/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,FieldA,FieldB,FieldC,FieldD")] Example example)
{
if (id != example.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(example);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ExampleExists(example.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(example);
}
// GET: Examples/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var example = await _context.Example
.FirstOrDefaultAsync(m => m.Id == id);
if (example == null)
{
return NotFound();
}
return View(example);
}
// POST: Examples/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var example = await _context.Example.FindAsync(id);
_context.Example.Remove(example);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ExampleExists(int id)
{
return _context.Example.Any(e => e.Id == id);
}
}
}
| 29.032051 | 111 | 0.51667 | [
"MIT"
] | Connor-R-McNeely/AspNetCore-Entity-Change-Tracking | EntityChangeTracking_AspNetCore-3.0/EntityChangeTracking_AspNetCore-3.0/Controllers/ExamplesController.cs | 4,531 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DevTestLabs
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PolicySetsOperations operations.
/// </summary>
internal partial class PolicySetsOperations : IServiceOperations<DevTestLabsClient>, IPolicySetsOperations
{
/// <summary>
/// Initializes a new instance of the PolicySetsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PolicySetsOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// Evaluates lab policy.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the policy set.
/// </param>
/// <param name='evaluatePoliciesRequest'>
/// Request body for evaluating a policy set.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<EvaluatePoliciesResponse>> EvaluatePoliciesWithHttpMessagesAsync(string resourceGroupName, string labName, string name, EvaluatePoliciesRequest evaluatePoliciesRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (evaluatePoliciesRequest == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "evaluatePoliciesRequest");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("evaluatePoliciesRequest", evaluatePoliciesRequest);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "EvaluatePolicies", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{name}/evaluatePolicies").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", System.Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", System.Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(evaluatePoliciesRequest != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(evaluatePoliciesRequest, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<EvaluatePoliciesResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<EvaluatePoliciesResponse>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 44.317518 | 338 | 0.576546 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/devtestlabs/Microsoft.Azure.Management.DevTestLabs/src/Generated/PolicySetsOperations.cs | 12,143 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrdenesDeTrabajo.BL
{
public class ClientesBL
{
Contexto _contexto;
public List<Clientes> ListadeClientes { get; set; }
public ClientesBL()
{
_contexto = new Contexto();
ListadeClientes = new List<Clientes>();
}
public List<Clientes> ObtenerClientes()
{
ListadeClientes = _contexto.Clientes
.OrderBy(r => r.Nombre)
.ToList();
return ListadeClientes;
}
public List<Clientes> ObtenerClientesActivos()
{
ListadeClientes = _contexto.Clientes
.Where(r => r.Activo == true)
.OrderBy(r => r.Nombre)
.ToList();
return ListadeClientes;
}
public void GuardarCliente(Clientes cliente)
{
if (cliente.Id == 0)
{
_contexto.Clientes.Add(cliente);
}
else
{
var clienteExistente = _contexto.Clientes.Find(cliente.Id);
clienteExistente.Nombre = cliente.Nombre;
clienteExistente.Telefono = cliente.Telefono;
clienteExistente.Direccion = cliente.Direccion;
clienteExistente.Activo = cliente.Activo;
}
_contexto.SaveChanges();
}
public Clientes ObtenerCliente(int id)
{
var cliente = _contexto.Clientes.Find(id);
return cliente;
}
public void EliminarCliente(int id)
{
var cliente = _contexto.Clientes.Find(id);
_contexto.Clientes.Remove(cliente);
_contexto.SaveChanges();
}
}
}
| 24.853333 | 75 | 0.534335 | [
"MIT"
] | Lyndar98/OrdenesdeTrabajo | OrdenesDeTrabajo/OrdenesDeTrabajo.BL/ClientesBL.cs | 1,866 | 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.Diagnostics;
using System.Net;
using System.Text;
using System.Runtime.InteropServices;
namespace System.DirectoryServices.Protocols
{
public partial class LdapConnection
{
// Linux doesn't support setting FQDN so we mark the flag as if it is already set so we don't make a call to set it again.
private bool _setFQDNDone = true;
private void InternalInitConnectionHandle(string hostname)
{
if ((LdapDirectoryIdentifier)_directoryIdentifier == null)
{
throw new NullReferenceException();
}
_ldapHandle = new ConnectionHandle($"ldap://{hostname}:{((LdapDirectoryIdentifier)_directoryIdentifier).PortNumber}");
}
private int InternalConnectToServer()
{
// In Linux you don't have to call Connect after calling init. You
// directly call bind. However, we set the URI for the connection
// here instead of during initialization because we need access to
// the SessionOptions property to properly define it, which is not
// available during init.
Debug.Assert(!_ldapHandle.IsInvalid);
string scheme;
LdapDirectoryIdentifier directoryIdentifier = (LdapDirectoryIdentifier)_directoryIdentifier;
if (directoryIdentifier.Connectionless)
{
scheme = "cldap://";
}
else if (SessionOptions.SecureSocketLayer)
{
scheme = "ldaps://";
}
else
{
scheme = "ldap://";
}
string uris = null;
string[] servers = directoryIdentifier.Servers;
if (servers != null && servers.Length != 0)
{
StringBuilder temp = new StringBuilder(200);
for (int i = 0; i < servers.Length; i++)
{
if (i != 0)
{
temp.Append(' ');
}
temp.Append(scheme);
temp.Append(servers[i]);
temp.Append(':');
temp.Append(directoryIdentifier.PortNumber);
}
if (temp.Length != 0)
{
uris = temp.ToString();
}
}
else
{
uris = $"{scheme}:{directoryIdentifier.PortNumber}";
}
return LdapPal.SetStringOption(_ldapHandle, LdapOption.LDAP_OPT_URI, uris);
}
private int InternalBind(NetworkCredential tempCredential, SEC_WINNT_AUTH_IDENTITY_EX cred, BindMethod method)
{
int error;
if (LocalAppContextSwitches.UseBasicAuthFallback)
{
if (tempCredential == null && (AuthType == AuthType.External || AuthType == AuthType.Kerberos))
{
error = BindSasl();
}
else
{
error = LdapPal.BindToDirectory(_ldapHandle, cred.user, cred.password);
}
}
else
{
if (method == BindMethod.LDAP_AUTH_NEGOTIATE)
{
if (tempCredential == null)
{
error = BindSasl();
}
else
{
// Explicit credentials were provided. If we call ldap_bind_s it will
// return LDAP_NOT_SUPPORTED, so just skip the P/Invoke.
error = (int)LdapError.NotSupported;
}
}
else
{
// Basic and Anonymous are handled elsewhere.
Debug.Assert(AuthType != AuthType.Anonymous && AuthType != AuthType.Basic);
error = (int)LdapError.AuthUnknown;
}
}
return error;
}
private int BindSasl()
{
SaslDefaultCredentials defaults = GetSaslDefaults();
IntPtr ptrToDefaults = Marshal.AllocHGlobal(Marshal.SizeOf(defaults));
Marshal.StructureToPtr(defaults, ptrToDefaults, false);
try
{
return Interop.Ldap.ldap_sasl_interactive_bind(_ldapHandle, null, Interop.KerberosDefaultMechanism, IntPtr.Zero, IntPtr.Zero, Interop.LDAP_SASL_QUIET, LdapPal.SaslInteractionProcedure, ptrToDefaults);
}
finally
{
GC.KeepAlive(defaults); //Making sure we keep it in scope as we will still use ptrToDefaults
Marshal.FreeHGlobal(ptrToDefaults);
}
}
private SaslDefaultCredentials GetSaslDefaults()
{
var defaults = new SaslDefaultCredentials { mech = Interop.KerberosDefaultMechanism };
IntPtr outValue = IntPtr.Zero;
int error = Interop.Ldap.ldap_get_option_ptr(_ldapHandle, LdapOption.LDAP_OPT_X_SASL_REALM, ref outValue);
if (error == 0 && outValue != IntPtr.Zero)
{
defaults.realm = Marshal.PtrToStringAnsi(outValue);
}
error = Interop.Ldap.ldap_get_option_ptr(_ldapHandle, LdapOption.LDAP_OPT_X_SASL_AUTHCID, ref outValue);
if (error == 0 && outValue != IntPtr.Zero)
{
defaults.authcid = Marshal.PtrToStringAnsi(outValue);
}
error = Interop.Ldap.ldap_get_option_ptr(_ldapHandle, LdapOption.LDAP_OPT_X_SASL_AUTHZID, ref outValue);
if (error == 0 && outValue != IntPtr.Zero)
{
defaults.authzid = Marshal.PtrToStringAnsi(outValue);
}
return defaults;
}
}
}
| 37.993711 | 216 | 0.530707 | [
"MIT"
] | 333fred/runtime | src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.Linux.cs | 6,041 | C# |
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace BTDB.IL;
class ILDynamicMethodImpl : IILDynamicMethod, IILDynamicMethodWithThis
{
readonly Type _delegateType;
int _expectedLength;
IILGen? _gen;
readonly DynamicMethod _dynamicMethod;
public ILDynamicMethodImpl(string name, Type delegateType, Type? thisType)
{
_delegateType = delegateType;
_expectedLength = 64;
var mi = delegateType.GetMethod("Invoke");
Type[] parameterTypes;
if (thisType == null)
{
parameterTypes = mi!.GetParameters().Select(pi => pi.ParameterType).ToArray();
}
else
{
parameterTypes = new[] { thisType }.Concat(mi!.GetParameters().Select(pi => pi.ParameterType)).ToArray();
}
_dynamicMethod = new DynamicMethod(name, mi.ReturnType, parameterTypes, true);
}
public void ExpectedLength(int length)
{
_expectedLength = length;
}
public bool InitLocals
{
get => _dynamicMethod.InitLocals;
set => _dynamicMethod.InitLocals = value;
}
public IILGen Generator => _gen ??= new ILGenImpl(_dynamicMethod.GetILGenerator(_expectedLength), new IilGenForbiddenInstructionsGodPowers());
public object Create()
{
return _dynamicMethod.CreateDelegate(_delegateType);
}
public void FinalizeCreation()
{
}
public object Create(object @this)
{
return _dynamicMethod.CreateDelegate(_delegateType, @this);
}
public MethodInfo TrueMethodInfo => _delegateType.GetMethod("Invoke")!;
}
class ILDynamicMethodImpl<TDelegate> : ILDynamicMethodImpl, IILDynamicMethod<TDelegate> where TDelegate : Delegate
{
public ILDynamicMethodImpl(string name) : base(name, typeof(TDelegate), null)
{
}
public new TDelegate Create()
{
return (TDelegate)base.Create();
}
}
| 26.60274 | 146 | 0.669928 | [
"MIT"
] | Jumik/BTDB | BTDB/IL/ILDynamicMethodImpl.cs | 1,942 | C# |
/// <summary>**************************************************************************
///
/// $Id: ICCProfileException.java,v 1.2 2002/08/08 14:08:13 grosbois Exp $
///
/// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650
/// $Date $
/// ***************************************************************************
/// </summary>
using System;
namespace CSJ2K.Icc
{
/// <summary> This exception is thrown when the content of a profile
/// is incorrect.
///
/// </summary>
/// <seealso cref="jj2000.j2k.icc.ICCProfile">
/// </seealso>
/// <version> 1.0
/// </version>
/// <author> Bruce A. Kern
/// </author>
public class ICCProfileException:System.Exception
{
/// <summary> Contruct with message</summary>
/// <param name="msg">returned by getMessage()
/// </param>
public ICCProfileException(System.String msg):base(msg)
{
}
/// <summary> Empty constructor</summary>
public ICCProfileException()
{
}
}
} | 25.051282 | 87 | 0.534289 | [
"MIT"
] | opensatelliteproject/grbdump | CSJ2K/Icc/ICCProfileException.cs | 977 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace FlixOne.BookStore.CustomerService.Models
{
/// <summary>
///
/// </summary>
public class Customer : BaseEntity
{
[Required]
[Column("FirstName")]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
[DataType(DataType.Date)]
[Column("JoinedOn")]
public DateTime MemberSince { get; set; }
[Column("WalletBalance")]
public decimal Wallet { get; set; }
[Display(Name = "Full Name")]
public string FullName => LastName + " " + FirstName;
}
}
| 25.147059 | 61 | 0.622222 | [
"MIT"
] | John-Cassidy/Hands-On-Microservices-with-CSharp-8-and-.NET-Core-3-Third-Edition | Chapter 10/Shared-Database/FlixOne.BookStore.CustomerService/Models/Customer.cs | 857 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using Marten.Events.Projections.Async;
using Marten.Schema.Identity;
using System.Linq.Expressions;
using Marten.Storage;
namespace Marten.Events.Projections
{
public class ViewProjection<TView, TId> : DocumentProjection<TView>, IDocumentProjection
where TView : class, new()
{
private readonly Func<DocumentSession, TId[], IReadOnlyList<TView>> _sessionLoadMany;
public ViewProjection()
{
var loadManyMethod = typeof(DocumentSession).GetMethods()
.FirstOrDefault(x => x.Name == "LoadMany" && x.GetParameters().Any(y => y.ParameterType == typeof(TId[])));
if (loadManyMethod == null)
{
throw new ArgumentException($"{typeof(TId)} is not supported.");
}
var sessionParameter = Expression.Parameter(typeof(DocumentSession), "a");
var idParameter = Expression.Parameter(typeof(TId[]), "e");
var body = Expression.Call(sessionParameter, loadManyMethod.MakeGenericMethod(typeof(TView)), idParameter);
var lambda = Expression.Lambda<Func<DocumentSession, TId[], IReadOnlyList<TView>>>(body, sessionParameter, idParameter);
_sessionLoadMany = lambda.Compile();
}
private class EventHandler
{
public Func<IDocumentSession, object, Guid, TId> IdSelector { get; }
public Func<IDocumentSession, object, Guid, List<TId>> IdsSelector { get; }
public Func<IDocumentSession, TView, object, Task> Handler { get; }
public Func<IDocumentSession, TView, object, Task<bool>> ShouldDelete { get; }
public ProjectionEventType Type { get; set; }
public EventHandler(
Func<IDocumentSession, object, Guid, TId> idSelector,
Func<IDocumentSession, object, Guid, List<TId>> idsSelector,
Func<IDocumentSession, TView, object, Task> handler,
Func<IDocumentSession, TView, object, Task<bool>> shouldDelete,
ProjectionEventType type)
{
IdSelector = idSelector;
IdsSelector = idsSelector;
Handler = handler;
ShouldDelete = shouldDelete ?? defaultShouldDelete;
Type = type;
}
private Task<bool> defaultShouldDelete(IDocumentSession session, TView view, object @event) => Task.FromResult(true);
}
private class EventProjection
{
public TId ViewId { get; }
public Func<IDocumentSession, TView, Task> ProjectTo { get; }
public Func<IDocumentSession, TView, Task<bool>> ShouldDelete { get; }
public ProjectionEventType Type { get; set; }
public EventProjection(EventHandler eventHandler, TId viewId, IEvent @event, object projectionEvent)
{
ViewId = viewId;
Type = eventHandler.Type;
if (Type == ProjectionEventType.Delete)
{
ShouldDelete = (session, view) => eventHandler.ShouldDelete(session, view, projectionEvent ?? @event.Data);
}
else
{
ProjectTo = (session, view) => eventHandler.Handler(session, view, projectionEvent ?? @event.Data);
}
}
}
public enum ProjectionEventType
{
Modify,
Delete
}
private readonly IDictionary<Type, EventHandler> _handlers = new ConcurrentDictionary<Type, EventHandler>();
public Type[] Consumes => getUniqueEventTypes();
public AsyncOptions AsyncOptions { get; } = new AsyncOptions();
public ViewProjection<TView, TId> DeleteEvent<TEvent>() where TEvent : class
=> projectEvent<TEvent>(
(session, @event, streamId) => convertToTId(streamId),
null,
null,
null,
ProjectionEventType.Delete);
public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<TView, TEvent, bool> shouldDelete) where TEvent : class
=> projectEvent<TEvent>(
(session, @event, streamId) => convertToTId(streamId),
null,
null,
(_, view, @event) => Task.FromResult(shouldDelete(view, @event)),
ProjectionEventType.Delete);
public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class
=> projectEvent<TEvent>(
(session, @event, streamId) => convertToTId(streamId),
null,
null,
(session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)),
ProjectionEventType.Delete);
public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<TEvent, TId> viewIdSelector) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(@event as TEvent),
null,
null,
null,
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<TEvent, TId> viewIdSelector,
Func<TView, TEvent, bool> shouldDelete) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(@event as TEvent),
null,
null,
(_, view, @event) => Task.FromResult(shouldDelete(view, @event)),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<TEvent, TId> viewIdSelector,
Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(@event as TEvent),
null,
null,
(session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(session, @event as TEvent),
null,
null,
null,
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<IDocumentSession, TEvent, TId> viewIdSelector,
Func<TView, TEvent, bool> shouldDelete) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(session, @event as TEvent),
null,
null,
(_, view, @event) => Task.FromResult(shouldDelete(view, @event)),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<IDocumentSession, TEvent, TId> viewIdSelector,
Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(session, @event as TEvent),
null,
null,
(session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<TEvent, List<TId>> viewIdsSelector) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(@event as TEvent),
null,
null,
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<TEvent, List<TId>> viewIdsSelector,
Func<TView, TEvent, bool> shouldDelete) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(@event as TEvent),
null,
(_, view, @event) => Task.FromResult(shouldDelete(view, @event)),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<TEvent, List<TId>> viewIdsSelector,
Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(@event as TEvent),
null,
(session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(session, @event as TEvent),
null,
null,
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector,
Func<TView, TEvent, bool> shouldDelete) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(session, @event as TEvent),
null,
(_, view, @event) => Task.FromResult(shouldDelete(view, @event)),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector,
Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(session, @event as TEvent),
null,
(session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
=> projectEvent<TEvent>(
(session, @event, streamId) => convertToTId(streamId),
null,
null,
(_, view, @event) => shouldDelete(view, @event),
ProjectionEventType.Delete);
public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(
Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
=> projectEvent<TEvent>(
(session, @event, streamId) => convertToTId(streamId),
null,
null,
shouldDelete,
ProjectionEventType.Delete);
public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(
Func<TEvent, TId> viewIdSelector,
Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(@event as TEvent),
null,
null,
(_, view, @event) => shouldDelete(view, @event),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(
Func<TEvent, TId> viewIdSelector,
Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(@event as TEvent),
null,
null,
shouldDelete,
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(
Func<IDocumentSession, TEvent, TId> viewIdSelector,
Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(session, @event as TEvent),
null,
null,
(_, view, @event) => shouldDelete(view, @event),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(
Func<IDocumentSession, TEvent, TId> viewIdSelector,
Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent<TEvent>(
(session, @event, streamId) => viewIdSelector(session, @event as TEvent),
null,
null,
shouldDelete,
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(
Func<TEvent, List<TId>> viewIdsSelector,
Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(@event as TEvent),
null,
(_, view, @event) => shouldDelete(view, @event),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<TEvent, List<TId>> viewIdsSelector,
Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(@event as TEvent),
null,
shouldDelete,
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(
Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector,
Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(session, @event as TEvent),
null,
(_, view, @event) => shouldDelete(view, @event),
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> DeleteEvent<TEvent>(
Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector,
Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent<TEvent>(
null,
(session, @event, streamId) => viewIdsSelector(session, @event as TEvent),
null,
shouldDelete,
ProjectionEventType.Delete);
}
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Action<TView, TEvent> handler) where TEvent : class
=> projectEvent(
(session, @event, streamId) => convertToTId(streamId),
null,
(IDocumentSession _, TView view, TEvent @event) =>
{
handler(view, @event);
return Task.CompletedTask;
});
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Action<IDocumentSession, TView, TEvent> handler) where TEvent : class
=> projectEvent(
(session, @event, streamId) => convertToTId(streamId),
null,
(IDocumentSession session, TView view, TEvent @event) =>
{
handler(session, view, @event);
return Task.CompletedTask;
});
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector, Action<TView, TEvent> handler) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent(
(session, @event, streamId) => viewIdSelector(session, @event as TEvent),
null,
(IDocumentSession _, TView view, TEvent @event) =>
{
handler(view, @event);
return Task.CompletedTask;
});
}
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector, Action<IDocumentSession, TView, TEvent> handler) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent(
(session, @event, streamId) => viewIdSelector(session, @event as TEvent),
null,
(IDocumentSession session, TView view, TEvent @event) =>
{
handler(session, view, @event);
return Task.CompletedTask;
});
}
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<TEvent, TId> viewIdSelector, Action<TView, TEvent> handler) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent(
(session, @event, streamId) => viewIdSelector(@event as TEvent),
null,
(IDocumentSession _, TView view, TEvent @event) =>
{
handler(view, @event);
return Task.CompletedTask;
});
}
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<TEvent, TId> viewIdSelector, Action<IDocumentSession, TView, TEvent> handler) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent(
(session, @event, streamId) => viewIdSelector(@event as TEvent),
null,
(IDocumentSession session, TView view, TEvent @event) =>
{
handler(session, view, @event);
return Task.CompletedTask;
});
}
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Action<TView, TEvent> handler) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent(
null,
(session, @event, streamId) => viewIdsSelector(session, @event as TEvent),
(IDocumentSession _, TView view, TEvent @event) =>
{
handler(view, @event);
return Task.CompletedTask;
});
}
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Action<IDocumentSession, TView, TEvent> handler) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent(
null,
(session, @event, streamId) => viewIdsSelector(session, @event as TEvent),
(IDocumentSession session, TView view, TEvent @event) =>
{
handler(session, view, @event);
return Task.CompletedTask;
});
}
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<TEvent, List<TId>> viewIdsSelector, Action<TView, TEvent> handler) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent(
null,
(session, @event, streamId) => viewIdsSelector(@event as TEvent),
(IDocumentSession _, TView view, TEvent @event) =>
{
handler(view, @event);
return Task.CompletedTask;
});
}
public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<TEvent, List<TId>> viewIdsSelector, Action<IDocumentSession, TView, TEvent> handler) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent(
null,
(session, @event, streamId) => viewIdsSelector(@event as TEvent),
(IDocumentSession session, TView view, TEvent @event) =>
{
handler(session, view, @event);
return Task.CompletedTask;
});
}
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TView, TEvent, Task> handler) where TEvent : class
=> projectEvent(
(session, @event, streamId) => convertToTId(streamId),
null,
(IDocumentSession _, TView view, TEvent @event) => handler(view, @event));
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TView, TEvent, Task> handler) where TEvent : class
=> projectEvent((session, @event, streamId) => convertToTId(streamId), null, handler);
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector, Func<TView, TEvent, Task> handler) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent(
(session, @event, streamId) => viewIdSelector(session, @event as TEvent),
null,
(IDocumentSession _, TView view, TEvent @event) => handler(view, @event));
}
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector, Func<IDocumentSession, TView, TEvent, Task> handler) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent((session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, handler);
}
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TEvent, TId> viewIdSelector, Func<TView, TEvent, Task> handler) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent(
(session, @event, streamId) => viewIdSelector(@event as TEvent),
null,
(IDocumentSession _, TView view, TEvent @event) => handler(view, @event));
}
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TEvent, TId> viewIdSelector, Func<IDocumentSession, TView, TEvent, Task> handler) where TEvent : class
{
if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector));
return projectEvent((session, @event, streamId) => viewIdSelector(@event as TEvent), null, handler);
}
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Func<TView, TEvent, Task> handler) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent(
null,
(session, @event, streamId) => viewIdsSelector(session, @event as TEvent),
(IDocumentSession _, TView view, TEvent @event) => handler(view, @event));
}
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, Task> handler) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent(null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), handler);
}
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TEvent, List<TId>> viewIdsSelector, Func<TView, TEvent, Task> handler) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent(
null,
(session, @event, streamId) => viewIdsSelector(@event as TEvent),
(IDocumentSession _, TView view, TEvent @event) => handler(view, @event));
}
public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TEvent, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, Task> handler) where TEvent : class
{
if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector));
return projectEvent(null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), handler);
}
private ViewProjection<TView, TId> projectEvent<TEvent>(
Func<IDocumentSession, object, Guid, TId> viewIdSelector,
Func<IDocumentSession, object, Guid, List<TId>> viewIdsSelector,
Func<IDocumentSession, TView, TEvent, Task> handler,
Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete = null,
ProjectionEventType type = ProjectionEventType.Modify) where TEvent : class
{
if (viewIdSelector == null && viewIdsSelector == null)
throw new ArgumentException($"{nameof(viewIdSelector)} or {nameof(viewIdsSelector)} must be provided.");
if (handler == null && type == ProjectionEventType.Modify)
throw new ArgumentNullException(nameof(handler));
EventHandler eventHandler;
if (type == ProjectionEventType.Modify)
{
eventHandler = new EventHandler(
viewIdSelector,
viewIdsSelector,
(session, view, @event) => handler(session, view, @event as TEvent),
null,
type);
}
else
{
eventHandler = new EventHandler(
viewIdSelector,
viewIdsSelector,
null,
shouldDelete == null
? (Func<IDocumentSession, TView, object, Task<bool>>)null
: (session, view, @event) => shouldDelete(session, view, @event as TEvent),
type);
}
_handlers.Add(typeof(TEvent), eventHandler);
return this;
}
private TId convertToTId(Guid streamId)
{
if (streamId is TId)
{
return (TId)Convert.ChangeType(streamId, typeof(TId));
}
else
{
throw new InvalidOperationException("IdSelector must be used if Id type is different than Guid.");
}
}
void IProjection.Apply(IDocumentSession session, EventPage page)
{
var projections = getEventProjections(session, page);
var viewIds = projections.Select(projection => projection.ViewId).Distinct().ToArray();
if (viewIds.Length > 0)
{
var views = _sessionLoadMany((DocumentSession)session, viewIds);
applyProjections(session, projections, views);
}
}
async Task IProjection.ApplyAsync(IDocumentSession session, EventPage page, CancellationToken token)
{
var projections = getEventProjections(session, page);
var viewIds = projections.Select(projection => projection.ViewId).Distinct().ToArray();
if (viewIds.Length > 0)
{
var views = _sessionLoadMany((DocumentSession)session, viewIds);
await applyProjectionsAsync(session, projections, views);
}
}
private void applyProjections(IDocumentSession session, ICollection<EventProjection> projections, IEnumerable<TView> views)
{
var viewMap = createViewMap(session, projections, views);
foreach (var eventProjection in projections)
{
var view = viewMap[eventProjection.ViewId];
using(Util.NoSynchronizationContextScope.Enter())
{
if (eventProjection.Type == ProjectionEventType.Delete)
{
var shouldDeleteTask = eventProjection.ShouldDelete(session, view);
shouldDeleteTask.Wait();
if (shouldDeleteTask.Result)
{
session.Delete(view);
}
}
else
{
eventProjection.ProjectTo(session, view).Wait();
}
}
}
}
private async Task applyProjectionsAsync(IDocumentSession session, ICollection<EventProjection> projections, IEnumerable<TView> views)
{
var viewMap = createViewMap(session, projections, views);
foreach (var eventProjection in projections)
{
var view = viewMap[eventProjection.ViewId];
if (eventProjection.Type == ProjectionEventType.Delete)
{
if (await eventProjection.ShouldDelete(session, view))
{
session.Delete(view);
}
}
else
{
await eventProjection.ProjectTo(session, view);
}
}
}
private IDictionary<TId, TView> createViewMap(IDocumentSession session, IEnumerable<EventProjection> projections, IEnumerable<TView> views)
{
var idAssigner = session.Tenant.IdAssignmentFor<TView>();
var resolver = session.Tenant.StorageFor<TView>();
var viewMap = views.ToDictionary(view => (TId)resolver.Identity(view), view => view);
foreach (var projection in projections)
{
var viewId = projection.ViewId;
TView view;
if (!viewMap.TryGetValue(viewId, out view))
{
view = newView(session.Tenant, idAssigner, viewId);
viewMap.Add(viewId, view);
}
if (projection.Type == ProjectionEventType.Modify)
{
session.Store(view);
}
}
return viewMap;
}
private static TView newView(ITenant tenant, IdAssignment<TView> idAssigner, TId id)
{
var view = new TView();
idAssigner.Assign(tenant, view, id);
return view;
}
private IList<EventProjection> getEventProjections(IDocumentSession session, EventPage page)
{
var projections = new List<EventProjection>();
foreach (var streamEvent in page.Events)
{
EventHandler handler;
var eventType = streamEvent.Data.GetType();
if (_handlers.TryGetValue(eventType, out handler))
{
appendProjections(projections, handler, session, streamEvent, eventType, false);
}
else
{
var genericEventType = typeof(ProjectionEvent<>).MakeGenericType(eventType);
if (_handlers.TryGetValue(genericEventType, out handler))
{
appendProjections(projections, handler, session, streamEvent, genericEventType, true);
}
}
}
return projections;
}
private void appendProjections(List<EventProjection> projections, EventHandler handler, IDocumentSession session, IEvent streamEvent, Type eventType, bool isProjectionEvent)
{
object projectionEvent = null;
if (isProjectionEvent)
{
var timestamp = streamEvent.Timestamp.UtcDateTime;
projectionEvent = Activator.CreateInstance(
eventType,
streamEvent.Id,
streamEvent.Version,
// Inline projections don't have the timestamp set, set it manually
timestamp == default(DateTime) ? DateTime.UtcNow : timestamp,
streamEvent.Data);
}
if (handler.IdSelector != null)
{
var viewId = handler.IdSelector(session, isProjectionEvent ? projectionEvent : streamEvent.Data, streamEvent.StreamId);
projections.Add(new EventProjection(handler, viewId, streamEvent, projectionEvent));
}
else
{
foreach (var viewId in handler.IdsSelector(session, isProjectionEvent ? projectionEvent : streamEvent.Data, streamEvent.StreamId))
{
projections.Add(new EventProjection(handler, viewId, streamEvent, projectionEvent));
}
}
}
private Type[] getUniqueEventTypes()
{
return _handlers.Keys
.Distinct()
.Select(type =>
{
var genericType = type.GenericTypeArguments.FirstOrDefault();
if (genericType == null)
{
return type;
}
else
{
return genericType;
}
})
.ToArray();
}
}
public class ProjectionEvent<T>
{
public Guid Id { get; protected set; }
public int Version { get; protected set; }
public DateTime Timestamp { get; protected set; }
public T Data { get; protected set; }
public ProjectionEvent(Guid id, int version, DateTime timestamp, T data)
{
Id = id;
Version = version;
Timestamp = timestamp;
Data = data;
}
}
} | 45.355422 | 200 | 0.568044 | [
"MIT"
] | kerobs/marten | src/Marten/Events/Projections/ViewProjection.cs | 37,647 | C# |
using System;
using System.IO;
namespace Org.BouncyCastle.Crypto.IO
{
public class SignerStream
: Stream
{
protected readonly Stream stream;
protected readonly ISigner inSigner;
protected readonly ISigner outSigner;
public SignerStream(
Stream stream,
ISigner readSigner,
ISigner writeSigner)
{
this.stream = stream;
this.inSigner = readSigner;
this.outSigner = writeSigner;
}
public virtual ISigner ReadSigner()
{
return inSigner;
}
public virtual ISigner WriteSigner()
{
return outSigner;
}
public override int Read(
byte[] buffer,
int offset,
int count)
{
int n = stream.Read(buffer, offset, count);
if (inSigner != null)
{
if (n > 0)
{
inSigner.BlockUpdate(buffer, offset, n);
}
}
return n;
}
public override int ReadByte()
{
int b = stream.ReadByte();
if (inSigner != null)
{
if (b >= 0)
{
inSigner.Update((byte)b);
}
}
return b;
}
public override void Write(
byte[] buffer,
int offset,
int count)
{
if (outSigner != null)
{
if (count > 0)
{
outSigner.BlockUpdate(buffer, offset, count);
}
}
stream.Write(buffer, offset, count);
}
public override void WriteByte(
byte b)
{
if (outSigner != null)
{
outSigner.Update(b);
}
stream.WriteByte(b);
}
public override bool CanRead
{
get { return stream.CanRead; }
}
public override bool CanWrite
{
get { return stream.CanWrite; }
}
public override bool CanSeek
{
get { return stream.CanSeek; }
}
public override long Length
{
get { return stream.Length; }
}
public override long Position
{
get { return stream.Position; }
set { stream.Position = value; }
}
public override void Close()
{
stream.Close();
}
public override void Flush()
{
stream.Flush();
}
public override long Seek(
long offset,
SeekOrigin origin)
{
return stream.Seek(offset, origin);
}
public override void SetLength(
long length)
{
stream.SetLength(length);
}
}
}
| 15.246377 | 50 | 0.616445 | [
"BSD-3-Clause"
] | ConnectionMaster/OutlookPrivacyPlugin | 3rdParty/bccrypto-net-05282015/crypto/src/crypto/io/SignerStream.cs | 2,104 | C# |
using System;
namespace Toms_Puzzle.Interfaces
{
public interface IDecoder
{
Span<byte> Decode(string payload);
}
} | 15.222222 | 42 | 0.664234 | [
"MIT"
] | Schalasoft/Toms-Puzzle | Toms Puzzle/Interfaces/IDecoder.cs | 139 | C# |
namespace SAAI.Controls
{
partial class EnhnacedProgressBar
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// UserControl1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Name = "UserControl1";
this.Size = new System.Drawing.Size(187, 22);
this.ResumeLayout(false);
}
#endregion
}
}
| 27.083333 | 104 | 0.609231 | [
"MIT"
] | Ken98045/On-Guard | src/AIDisplay/Controls/EnhnacedProgressBar.Designer.cs | 1,302 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net.Mail;
using System.Net.Mime;
using FeuerwehrCloud.Mime.Decode;
namespace FeuerwehrCloud.Mime.Header
{
/// <summary>
/// Class that holds all headers for a message<br/>
/// Headers which are unknown the the parser will be held in the <see cref="UnknownHeaders"/> collection.<br/>
/// <br/>
/// This class cannot be instantiated from outside the library.
/// </summary>
/// <remarks>
/// See <a href="http://tools.ietf.org/html/rfc4021">RFC 4021</a> for a large list of headers.<br/>
/// </remarks>
internal sealed class MessageHeader
{
#region Properties
/// <summary>
/// All headers which were not recognized and explicitly dealt with.<br/>
/// This should mostly be custom headers, which are marked as X-[name].<br/>
/// <br/>
/// This list will be empty if all headers were recognized and parsed.
/// </summary>
/// <remarks>
/// If you as a user, feels that a header in this collection should
/// be parsed, feel free to notify the developers.
/// </remarks>
public NameValueCollection UnknownHeaders { get; private set; }
/// <summary>
/// A human readable description of the body<br/>
/// <br/>
/// <see langword="null"/> if no Content-Description header was present in the message.
/// </summary>
public string ContentDescription { get; private set; }
/// <summary>
/// ID of the content part (like an attached image). Used with MultiPart messages.<br/>
/// <br/>
/// <see langword="null"/> if no Content-ID header field was present in the message.
/// </summary>
/// <see cref="MessageId">For an ID of the message</see>
public string ContentId { get; private set; }
/// <summary>
/// Message keywords<br/>
/// <br/>
/// The list will be empty if no Keywords header was present in the message
/// </summary>
public List<string> Keywords { get; private set; }
/// <summary>
/// A List of emails to people who wishes to be notified when some event happens.<br/>
/// These events could be email:
/// <list type="bullet">
/// <item>deletion</item>
/// <item>printing</item>
/// <item>received</item>
/// <item>...</item>
/// </list>
/// The list will be empty if no Disposition-Notification-To header was present in the message
/// </summary>
/// <remarks>See <a href="http://tools.ietf.org/html/rfc3798">RFC 3798</a> for details</remarks>
public List<RfcMailAddress> DispositionNotificationTo { get; private set; }
/// <summary>
/// This is the Received headers. This tells the path that the email went.<br/>
/// <br/>
/// The list will be empty if no Received header was present in the message
/// </summary>
public List<Received> Received { get; private set; }
/// <summary>
/// Importance of this email.<br/>
/// <br/>
/// The importance level is set to normal, if no Importance header field was mentioned or it contained
/// unknown information. This is the expected behavior according to the RFC.
/// </summary>
public MailPriority Importance { get; private set; }
/// <summary>
/// This header describes the Content encoding during transfer.<br/>
/// <br/>
/// If no Content-Transfer-Encoding header was present in the message, it is set
/// to the default of <see cref="Header.ContentTransferEncoding.SevenBit">SevenBit</see> in accordance to the RFC.
/// </summary>
/// <remarks>See <a href="http://tools.ietf.org/html/rfc2045#section-6">RFC 2045 section 6</a> for details</remarks>
public ContentTransferEncoding ContentTransferEncoding { get; private set; }
/// <summary>
/// Carbon Copy. This specifies who got a copy of the message.<br/>
/// <br/>
/// The list will be empty if no Cc header was present in the message
/// </summary>
public List<RfcMailAddress> Cc { get; private set; }
/// <summary>
/// Blind Carbon Copy. This specifies who got a copy of the message, but others
/// cannot see who these persons are.<br/>
/// <br/>
/// The list will be empty if no Received Bcc was present in the message
/// </summary>
public List<RfcMailAddress> Bcc { get; private set; }
/// <summary>
/// Specifies who this mail was for<br/>
/// <br/>
/// The list will be empty if no To header was present in the message
/// </summary>
public List<RfcMailAddress> To { get; private set; }
/// <summary>
/// Specifies who sent the email<br/>
/// <br/>
/// <see langword="null"/> if no From header field was present in the message
/// </summary>
public RfcMailAddress From { get; private set; }
/// <summary>
/// Specifies who a reply to the message should be sent to<br/>
/// <br/>
/// <see langword="null"/> if no Reply-To header field was present in the message
/// </summary>
public RfcMailAddress ReplyTo { get; private set; }
/// <summary>
/// The message identifier(s) of the original message(s) to which the
/// current message is a reply.<br/>
/// <br/>
/// The list will be empty if no In-Reply-To header was present in the message
/// </summary>
public List<string> InReplyTo { get; private set; }
/// <summary>
/// The message identifier(s) of other message(s) to which the current
/// message is related to.<br/>
/// <br/>
/// The list will be empty if no References header was present in the message
/// </summary>
public List<string> References { get; private set; }
/// <summary>
/// This is the sender of the email address.<br/>
/// <br/>
/// <see langword="null"/> if no Sender header field was present in the message
/// </summary>
/// <remarks>
/// The RFC states that this field can be used if a secretary
/// is sending an email for someone she is working for.
/// The email here will then be the secretary's email, and
/// the Reply-To field would hold the address of the person she works for.<br/>
/// RFC states that if the Sender is the same as the From field,
/// sender should not be included in the message.
/// </remarks>
public RfcMailAddress Sender { get; private set; }
/// <summary>
/// The Content-Type header field.<br/>
/// <br/>
/// If not set, the ContentType is created by the default "text/plain; charset=us-ascii" which is
/// defined in <a href="http://tools.ietf.org/html/rfc2045#section-5.2">RFC 2045 section 5.2</a>.<br/>
/// If set, the default is overridden.
/// </summary>
public ContentType ContentType { get; private set; }
/// <summary>
/// Used to describe if a <see cref="MessagePart"/> is to be displayed or to be though of as an attachment.<br/>
/// Also contains information about filename if such was sent.<br/>
/// <br/>
/// <see langword="null"/> if no Content-Disposition header field was present in the message
/// </summary>
public ContentDisposition ContentDisposition { get; private set; }
/// <summary>
/// The Date when the email was sent.<br/>
/// This is the raw value. <see cref="DateSent"/> for a parsed up <see cref="DateTime"/> value of this field.<br/>
/// <br/>
/// <see langword="DateTime.MinValue"/> if no Date header field was present in the message or if the date could not be parsed.
/// </summary>
/// <remarks>See <a href="http://tools.ietf.org/html/rfc5322#section-3.6.1">RFC 5322 section 3.6.1</a> for more details</remarks>
public string Date { get; private set; }
/// <summary>
/// The Date when the email was sent.<br/>
/// This is the parsed equivalent of <see cref="Date"/>.<br/>
/// Notice that the <see cref="TimeZone"/> of the <see cref="DateTime"/> object is in UTC and has NOT been converted
/// to local <see cref="TimeZone"/>.
/// </summary>
/// <remarks>See <a href="http://tools.ietf.org/html/rfc5322#section-3.6.1">RFC 5322 section 3.6.1</a> for more details</remarks>
public DateTime DateSent { get; private set; }
/// <summary>
/// An ID of the message that is SUPPOSED to be in every message according to the RFC.<br/>
/// The ID is unique.<br/>
/// <br/>
/// <see langword="null"/> if no Message-ID header field was present in the message
/// </summary>
public string MessageId { get; private set; }
/// <summary>
/// The Mime Version.<br/>
/// This field will almost always show 1.0<br/>
/// <br/>
/// <see langword="null"/> if no Mime-Version header field was present in the message
/// </summary>
public string MimeVersion { get; private set; }
/// <summary>
/// A single <see cref="RfcMailAddress"/> with no username inside.<br/>
/// This is a trace header field, that should be in all messages.<br/>
/// Replies should be sent to this address.<br/>
/// <br/>
/// <see langword="null"/> if no Return-Path header field was present in the message
/// </summary>
public RfcMailAddress ReturnPath { get; private set; }
/// <summary>
/// The subject line of the message in decoded, one line state.<br/>
/// This should be in all messages.<br/>
/// <br/>
/// <see langword="null"/> if no Subject header field was present in the message
/// </summary>
public string Subject { get; private set; }
#endregion
/// <summary>
/// Parses a <see cref="NameValueCollection"/> to a MessageHeader
/// </summary>
/// <param name="headers">The collection that should be traversed and parsed</param>
/// <returns>A valid MessageHeader object</returns>
/// <exception cref="ArgumentNullException">If <paramref name="headers"/> is <see langword="null"/></exception>
internal MessageHeader(NameValueCollection headers)
{
if (headers == null)
throw new ArgumentNullException("headers");
// Create empty lists as defaults. We do not like null values
// List with an initial capacity set to zero will be replaced
// when a corrosponding header is found
To = new List<RfcMailAddress>(0);
Cc = new List<RfcMailAddress>(0);
Bcc = new List<RfcMailAddress>(0);
Received = new List<Received>();
Keywords = new List<string>();
InReplyTo = new List<string>(0);
References = new List<string>(0);
DispositionNotificationTo = new List<RfcMailAddress>();
UnknownHeaders = new NameValueCollection();
// Default importancetype is Normal (assumed if not set)
Importance = MailPriority.Normal;
// 7BIT is the default ContentTransferEncoding (assumed if not set)
ContentTransferEncoding = ContentTransferEncoding.SevenBit;
// text/plain; charset=us-ascii is the default ContentType
ContentType = new ContentType("text/plain; charset=us-ascii");
// Now parse the actual headers
ParseHeaders(headers);
}
/// <summary>
/// Parses a <see cref="NameValueCollection"/> to a <see cref="MessageHeader"/>
/// </summary>
/// <param name="headers">The collection that should be traversed and parsed</param>
/// <returns>A valid <see cref="MessageHeader"/> object</returns>
/// <exception cref="ArgumentNullException">If <paramref name="headers"/> is <see langword="null"/></exception>
private void ParseHeaders(NameValueCollection headers)
{
if (headers == null)
throw new ArgumentNullException("headers");
// Now begin to parse the header values
foreach (string headerName in headers.Keys)
{
string[] headerValues = headers.GetValues(headerName);
if (headerValues != null)
{
foreach (string headerValue in headerValues)
{
ParseHeader(headerName, headerValue);
}
}
}
}
#region Header fields parsing
/// <summary>
/// Parses a single header and sets member variables according to it.
/// </summary>
/// <param name="headerName">The name of the header</param>
/// <param name="headerValue">The value of the header in unfolded state (only one line)</param>
/// <exception cref="ArgumentNullException">If <paramref name="headerName"/> or <paramref name="headerValue"/> is <see langword="null"/></exception>
private void ParseHeader(string headerName, string headerValue)
{
if(headerName == null)
throw new ArgumentNullException("headerName");
if (headerValue == null)
throw new ArgumentNullException("headerValue");
switch (headerName.ToUpperInvariant())
{
// See http://tools.ietf.org/html/rfc5322#section-3.6.3
case "TO":
To = RfcMailAddress.ParseMailAddresses(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.3
case "CC":
Cc = RfcMailAddress.ParseMailAddresses(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.3
case "BCC":
Bcc = RfcMailAddress.ParseMailAddresses(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.2
case "FROM":
// There is only one MailAddress in the from field
From = RfcMailAddress.ParseMailAddress(headerValue);
break;
// http://tools.ietf.org/html/rfc5322#section-3.6.2
// The implementation here might be wrong
case "REPLY-TO":
// This field may actually be a list of addresses, but no
// such case has been encountered
ReplyTo = RfcMailAddress.ParseMailAddress(headerValue);
break;
// http://tools.ietf.org/html/rfc5322#section-3.6.2
case "SENDER":
Sender = RfcMailAddress.ParseMailAddress(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.5
// RFC 5322:
// The "Keywords:" field contains a comma-separated list of one or more
// words or quoted-strings.
// The field are intended to have only human-readable content
// with information about the message
case "KEYWORDS":
string[] keywordsTemp = headerValue.Split(',');
foreach (string keyword in keywordsTemp)
{
// Remove the quotes if there is any
Keywords.Add(Utility.RemoveQuotesIfAny(keyword.Trim()));
}
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.7
case "RECEIVED":
// Simply add the value to the list
Received.Add(new Received(headerValue.Trim()));
break;
case "IMPORTANCE":
Importance = HeaderFieldParser.ParseImportance(headerValue.Trim());
break;
// See http://tools.ietf.org/html/rfc3798#section-2.1
case "DISPOSITION-NOTIFICATION-TO":
DispositionNotificationTo = RfcMailAddress.ParseMailAddresses(headerValue);
break;
case "MIME-VERSION":
MimeVersion = headerValue.Trim();
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.5
case "SUBJECT":
Subject = EncodedWord.Decode(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.7
case "RETURN-PATH":
// Return-paths does not include a username, but we
// may still use the address parser
ReturnPath = RfcMailAddress.ParseMailAddress(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.4
// Example Message-ID
// <33cdd74d6b89ab2250ecd75b40a41405@nfs.eksperten.dk>
case "MESSAGE-ID":
MessageId = HeaderFieldParser.ParseId(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.4
case "IN-REPLY-TO":
InReplyTo = HeaderFieldParser.ParseMultipleIDs(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.4
case "REFERENCES":
References = HeaderFieldParser.ParseMultipleIDs(headerValue);
break;
// See http://tools.ietf.org/html/rfc5322#section-3.6.1))
case "DATE":
Date = headerValue.Trim();
DateSent = Rfc2822DateTime.StringToDate(headerValue);
break;
// See http://tools.ietf.org/html/rfc2045#section-6
// See ContentTransferEncoding class for more details
case "CONTENT-TRANSFER-ENCODING":
ContentTransferEncoding = HeaderFieldParser.ParseContentTransferEncoding(headerValue.Trim());
break;
// See http://tools.ietf.org/html/rfc2045#section-8
case "CONTENT-DESCRIPTION":
// Human description of for example a file. Can be encoded
ContentDescription = EncodedWord.Decode(headerValue.Trim());
break;
// See http://tools.ietf.org/html/rfc2045#section-5.1
// Example: Content-type: text/plain; charset="us-ascii"
case "CONTENT-TYPE":
ContentType = HeaderFieldParser.ParseContentType(headerValue);
break;
// See http://tools.ietf.org/html/rfc2183
case "CONTENT-DISPOSITION":
ContentDisposition = HeaderFieldParser.ParseContentDisposition(headerValue);
break;
// See http://tools.ietf.org/html/rfc2045#section-7
// Example: <foo4*foo1@bar.net>
case "CONTENT-ID":
ContentId = HeaderFieldParser.ParseId(headerValue);
break;
default:
// This is an unknown header
// Custom headers are allowed. That means headers
// that are not mentionen in the RFC.
// Such headers start with the letter "X"
// We do not have any special parsing of such
// Add it to unknown headers
UnknownHeaders.Add(headerName, headerValue);
break;
}
}
#endregion
}
} | 38.04814 | 151 | 0.653784 | [
"MIT"
] | bhuebschen/feuerwehrcloud-deiva | FeuerwehrCloud.Input.IMAP4/Mime/Header/MessageHeader.cs | 17,390 | C# |
using System;
namespace OrgFlow.CliWrap.Internal
{
internal class Observable<T> : IObservable<T>
{
private readonly Func<IObserver<T>, IDisposable> _subscribe;
public Observable(Func<IObserver<T>, IDisposable> subscribe) => _subscribe = subscribe;
public IDisposable Subscribe(IObserver<T> observer) => _subscribe(observer);
}
internal static class Observable
{
public static IObservable<T> Create<T>(Func<IObserver<T>, IDisposable> subscribe) =>
new Observable<T>(subscribe);
}
} | 29.105263 | 95 | 0.679928 | [
"MIT"
] | OrgFlow/CliWrap | CliWrap/Internal/Observable.cs | 555 | C# |
using EducacionAvanzada.BL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EducacionAvanzada.WebAdmin.Controllers
{
[Authorize]
public class MateriasController : Controller
{
materiaBL _materiasBL;
public MateriasController()
{
_materiasBL = new materiaBL();
}
// GET: Materias
public ActionResult Index()
{
var ListadeMaterias = _materiasBL.Obtenermaterias();
return View(ListadeMaterias);
}
public ActionResult Crear()
{
var nuevaMateria = new Materia();
return View(nuevaMateria);
}
[HttpPost]
public ActionResult Crear(Materia materia)
{
if (ModelState.IsValid)
{
if (materia.Descripcion != materia.Descripcion.Trim())
{
ModelState.AddModelError("Descripcion", "No debe haber espacios al inicio o al final");
return View(materia);
}
_materiasBL.GuardarMateria(materia);
return RedirectToAction("Index");
}
return View(materia);
}
public ActionResult Editar(int id)
{
var materia = _materiasBL.ObtenerMaterias(id);
return View(materia);
}
[HttpPost]
public ActionResult Editar(Materia materia)
{
_materiasBL.GuardarMateria(materia);
return RedirectToAction("Index");
}
public ActionResult Detalle(int id)
{
var materia = _materiasBL.ObtenerMaterias(id);
return View(materia);
}
public ActionResult Eliminar(int id)
{
var materia = _materiasBL.ObtenerMaterias(id);
return View(materia);
}
[HttpPost]
public ActionResult Eliminar(Materia materia)
{
_materiasBL.EliminarMateria(materia.Id);
return RedirectToAction("Index");
}
}
} | 22.925532 | 107 | 0.548028 | [
"MIT"
] | astridiscua/EducacionAvanzadaFinal | educacionavanzada-master/EducacionAvanzada/EducacionAvanzada.WebAdmin/Controllers/MateriasController.cs | 2,157 | C# |
namespace ParcInfo.ucControls
{
partial class userHistory
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lblVarchar = new System.Windows.Forms.Label();
this.pnlBottom = new System.Windows.Forms.Panel();
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.leftLine = new ParcInfo.Classes.GradientPanel();
this.SuspendLayout();
//
// lblVarchar
//
this.lblVarchar.AutoSize = true;
this.lblVarchar.Location = new System.Drawing.Point(9, 12);
this.lblVarchar.Name = "lblVarchar";
this.lblVarchar.Size = new System.Drawing.Size(35, 13);
this.lblVarchar.TabIndex = 1;
this.lblVarchar.Text = "label1";
//
// pnlBottom
//
this.pnlBottom.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(227)))), ((int)(((byte)(227)))), ((int)(((byte)(227)))));
this.pnlBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
this.pnlBottom.Location = new System.Drawing.Point(0, 35);
this.pnlBottom.Name = "pnlBottom";
this.pnlBottom.Size = new System.Drawing.Size(483, 1);
this.pnlBottom.TabIndex = 2;
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(227)))), ((int)(((byte)(227)))), ((int)(((byte)(227)))));
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(483, 1);
this.panel1.TabIndex = 3;
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(229)))), ((int)(((byte)(229)))), ((int)(((byte)(229)))));
this.panel2.Dock = System.Windows.Forms.DockStyle.Right;
this.panel2.Location = new System.Drawing.Point(482, 1);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(1, 34);
this.panel2.TabIndex = 4;
//
// leftLine
//
this.leftLine.Angle = 0F;
this.leftLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(71)))), ((int)(((byte)(87)))));
this.leftLine.ColorBottom = System.Drawing.Color.Empty;
this.leftLine.ColorTop = System.Drawing.Color.Empty;
this.leftLine.Dock = System.Windows.Forms.DockStyle.Left;
this.leftLine.Location = new System.Drawing.Point(0, 1);
this.leftLine.Margin = new System.Windows.Forms.Padding(0);
this.leftLine.Name = "leftLine";
this.leftLine.Size = new System.Drawing.Size(2, 34);
this.leftLine.TabIndex = 5;
//
// userHistory
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.Controls.Add(this.leftLine);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Controls.Add(this.pnlBottom);
this.Controls.Add(this.lblVarchar);
this.Margin = new System.Windows.Forms.Padding(0, 3, 0, 3);
this.Name = "userHistory";
this.Size = new System.Drawing.Size(483, 36);
this.Load += new System.EventHandler(this.userHistory_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblVarchar;
private System.Windows.Forms.Panel pnlBottom;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private Classes.GradientPanel leftLine;
}
}
| 43.27193 | 141 | 0.559903 | [
"MIT"
] | driwand/ParcInfo-Dev | ParcInfo/ucControls/userHistory.Designer.cs | 4,935 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Blog.Models
{
public class Category
{
private ICollection<Article> articles;
public Category()
{
this.articles = new HashSet<Article>();
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Article> Articles
{
get { return this.articles; }
set { this.articles = value; }
}
}
} | 20.777778 | 52 | 0.557932 | [
"MIT"
] | nemss/Team-Projects | FilmBoxBg/Blog/Models/Category.cs | 563 | C# |
#region Copyright & License
// Copyright © 2012 - 2013 François Chabot, Yves Dierick
//
// 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 Be.Stateless.BizTalk.Schemas.Xml;
using Be.Stateless.BizTalk.Tracking;
using Microsoft.BizTalk.Streaming;
namespace Be.Stateless.BizTalk.Streaming.Extensions
{
public interface IProbeStream
{
/// <summary>
/// Probes the current <see cref="MarkableForwardOnlyEventingReadStream"/> for the message type.
/// </summary>
/// <returns>
/// The message type if probing is successful, <c>null</c> otherwise.
/// </returns>
string MessageType { get; }
}
internal interface IProbeBatchContentStream
{
/// <summary>
/// Probes the current <see cref="MarkableForwardOnlyEventingReadStream"/> for a <see cref="BatchDescriptor"/>.
/// </summary>
/// <returns>
/// The <see cref="BatchDescriptor"/> if probing is successful, <c>null</c> otherwise.
/// </returns>
/// <remarks>
/// Probing will be successful only if the <see cref="MarkableForwardOnlyEventingReadStream"/>'s content is an
/// instance of the <see cref="Batch.Content"/> schema — only the <see cref="BTS.MessageType"/> is
/// verified,— and its <c>EnvelopeSpecName</c> element is not null nor empty.
/// </remarks>
BatchDescriptor BatchDescriptor { get; }
BatchTrackingContext BatchTrackingContext { get; }
}
}
| 35.925926 | 114 | 0.699485 | [
"Apache-2.0"
] | icraftsoftware/BizTalk.Factory | src/BizTalk.Common/Streaming/Extensions/IProbeStream.cs | 1,944 | C# |
/*===================================================================================
*
* Copyright (c) Userware/OpenSilver.net
*
* This file is part of the OpenSilver Runtime (https://opensilver.net), which is
* licensed under the MIT license: https://opensource.org/licenses/MIT
*
* As stated in the MIT license, "the above copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software."
*
\*====================================================================================*/
using CSHTML5;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
#if MIGRATION
using System.Windows.Input;
using Microsoft.Windows;
#else
using System.Windows;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Input;
#endif
namespace System.Windows.Interactivity
{
/// <summary>
/// A trigger that listens for a specified event on its source and fires when that event is fired.
///
/// </summary>
public partial class EventTrigger : EventTriggerBase<object>
{
public static readonly DependencyProperty EventNameProperty =
DependencyProperty.Register("EventName", typeof(string), typeof(EventTrigger), new PropertyMetadata("Loaded", new PropertyChangedCallback(EventTrigger.OnEventNameChanged)));
/// <summary>
/// Gets or sets the name of the event to listen for. This is a dependency property.
/// </summary>
///
/// <value>
/// The name of the event.
/// </value>
public string EventName
{
get
{
return (string)this.GetValue(EventTrigger.EventNameProperty);
}
set
{
this.SetValue(EventTrigger.EventNameProperty, (object)value);
}
}
static EventTrigger()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Windows.Interactivity.EventTrigger"/> class.
/// </summary>
public EventTrigger()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Windows.Interactivity.EventTrigger"/> class.
/// </summary>
/// <param name="eventName">Name of the event.</param>
public EventTrigger(string eventName)
{
this.EventName = eventName;
}
private static void OnEventNameChanged(object sender, DependencyPropertyChangedEventArgs args)
{
((EventTrigger)sender).OnEventNameChanged((string)args.OldValue, (string)args.NewValue);
}
protected override string GetEventName()
{
return this.EventName;
}
}
} | 30.836957 | 185 | 0.58724 | [
"MIT"
] | KeyurJP/OpenSilver | src/Runtime/Runtime/System.Windows.Interactivity/EventTrigger.cs | 2,839 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
using Pulumi.Utilities;
namespace Pulumi.GoogleNative.File.V1Beta1
{
public static class GetSnapshot
{
/// <summary>
/// Gets the details of a specific snapshot.
/// </summary>
public static Task<GetSnapshotResult> InvokeAsync(GetSnapshotArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetSnapshotResult>("google-native:file/v1beta1:getSnapshot", args ?? new GetSnapshotArgs(), options.WithVersion());
/// <summary>
/// Gets the details of a specific snapshot.
/// </summary>
public static Output<GetSnapshotResult> Invoke(GetSnapshotInvokeArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetSnapshotResult>("google-native:file/v1beta1:getSnapshot", args ?? new GetSnapshotInvokeArgs(), options.WithVersion());
}
public sealed class GetSnapshotArgs : Pulumi.InvokeArgs
{
[Input("instanceId", required: true)]
public string InstanceId { get; set; } = null!;
[Input("location", required: true)]
public string Location { get; set; } = null!;
[Input("project")]
public string? Project { get; set; }
[Input("snapshotId", required: true)]
public string SnapshotId { get; set; } = null!;
public GetSnapshotArgs()
{
}
}
public sealed class GetSnapshotInvokeArgs : Pulumi.InvokeArgs
{
[Input("instanceId", required: true)]
public Input<string> InstanceId { get; set; } = null!;
[Input("location", required: true)]
public Input<string> Location { get; set; } = null!;
[Input("project")]
public Input<string>? Project { get; set; }
[Input("snapshotId", required: true)]
public Input<string> SnapshotId { get; set; } = null!;
public GetSnapshotInvokeArgs()
{
}
}
[OutputType]
public sealed class GetSnapshotResult
{
/// <summary>
/// The time when the snapshot was created.
/// </summary>
public readonly string CreateTime;
/// <summary>
/// A description of the snapshot with 2048 characters or less. Requests with longer descriptions will be rejected.
/// </summary>
public readonly string Description;
/// <summary>
/// The amount of bytes needed to allocate a full copy of the snapshot content
/// </summary>
public readonly string FilesystemUsedBytes;
/// <summary>
/// Resource labels to represent user provided metadata.
/// </summary>
public readonly ImmutableDictionary<string, string> Labels;
/// <summary>
/// The resource name of the snapshot, in the format `projects/{project_id}/locations/{location_id}/instances/{instance_id}/snapshots/{snapshot_id}`.
/// </summary>
public readonly string Name;
/// <summary>
/// The snapshot state.
/// </summary>
public readonly string State;
[OutputConstructor]
private GetSnapshotResult(
string createTime,
string description,
string filesystemUsedBytes,
ImmutableDictionary<string, string> labels,
string name,
string state)
{
CreateTime = createTime;
Description = description;
FilesystemUsedBytes = filesystemUsedBytes;
Labels = labels;
Name = name;
State = state;
}
}
}
| 32.638655 | 170 | 0.6138 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/File/V1Beta1/GetSnapshot.cs | 3,884 | C# |
using System;
using System.Collections.Generic;
namespace Factory.StoreWeb.Models
{
public class DashboardViewModel
{
public int RateVisitors { get; set; }
public int RatePageViews { get; set; }
public int RateUsers { get; set; }
public int RateOrders { get; set; }
public List<Tuple<int, string, string, string>> Users;
public List<Tuple<int, string, string, string>> Orders;
public List<Tuple<int, string, string, string>> Clients;
public List<Tuple<int, DateTime, Double>> Invoices;
}
} | 24.913043 | 64 | 0.643979 | [
"Apache-2.0"
] | kostyrin/Store | Factory.StoreWeb/Models/DashboardViewModel.cs | 575 | C# |
using System.Collections.Generic;
namespace GR.Core.Extensions
{
public static class DictionaryExtensions
{
/// <summary>
/// Add range new props to dictionary
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="context"></param>
/// <param name="newItems"></param>
/// <returns></returns>
public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> context, Dictionary<TKey, TValue> newItems)
{
if (context == null) context = new Dictionary<TKey, TValue>();
foreach (var item in newItems)
{
if (context.ContainsKey(item.Key))
{
context[item.Key] = item.Value;
}
else
{
context.Add(item.Key, item.Value);
}
}
return context;
}
/// <summary>
/// Remove keys
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="dict"></param>
/// <param name="keys"></param>
/// <returns></returns>
public static Dictionary<TKey, TValue> RemoveKeys<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<TKey> keys)
{
foreach (var key in keys)
{
if (dict.ContainsKey(key))
{
dict.Remove(key);
}
}
return dict;
}
}
}
| 30.814815 | 143 | 0.481971 | [
"MIT"
] | indrivo/GEAR | src/GR.Extensions/GR.Core.Extension/GR.Core/Extensions/DictionaryExtensions.cs | 1,666 | C# |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Autofac;
using Deploy.Appliction.Config;
using Deploy.Appliction.Extensions;
using Deploy.Appliction.Internal;
using Deploy.Appliction.Internal.Model;
using Microsoft.Extensions.Logging;
namespace Deploy.Wpf.Views
{
public partial class FrontPage
{
public Action<string> FrontTextBoxCallback;
private readonly ILogger<FrontPage> _logger;
private readonly ISftp _sftp;
private readonly ISsh _ssh;
public FrontPage()
{
InitializeComponent();
Init(AppConfig.Default.Deploy);
_logger = Utils.Current.Resolve<ILogger<FrontPage>>();
Utils.TextBoxCallback = DispatcherInvoke;
_sftp = Utils.Current.ResolveNamed<ISftp>(StrategyDll.SSHNET.ToString());
_ssh = Utils.Current.ResolveNamed<ISsh>(StrategyDll.SSHNET.ToString());
}
private void Init(DeployOption deploy)
{
Host.Text = deploy.Host;
Port.Text = deploy.MapperPort;
UserName.Text = deploy.Root;
RemotePath.Text = deploy.RemotePath;
Password.Text = deploy.Password;
LocalPath.Text = deploy.LocalPath;
Display.Text = "";
}
private void DispatcherInvoke(string appendText)
{
FrontTextBoxCallback = item => { Display.AppendText(appendText + Environment.NewLine); };
Display.Dispatcher.Invoke(FrontTextBoxCallback, appendText);
}
private void Execute()
{
// _logger.LogInformation("正在初始化 创建ssh,sftp 链接 ...");
// var ssh = Utils.Current.Resolve<ISsh>();
if (!FileExists())
return;
var config = AppConfig.Default.Deploy;
//todo 同步本地目录到远程目录
_sftp.SyncTreeUpload(config.RemotePath, config.LocalPath);
// //todo 开始执行shell 命令
_ssh.ExecuteFrontCmd("mytest", "mytest");
}
private void Deploy_Click(object sender, RoutedEventArgs e)
{
Display.Text = "";
Task.Factory.StartNew(Execute);
}
private bool FileExists()
{
var frontPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory ?? string.Empty, "Config", "front");
if (!Directory.Exists(frontPath))
Directory.CreateDirectory(frontPath);
//todo 判断dockerfile文件跟 nginx 配置文件是否存在
if (!File.Exists(Path.Combine(frontPath, "Dockerfile")))
{
_logger.LogInformation("dockerfile文件不存在");
return false;
}
if (!File.Exists(Path.Combine(frontPath, "nginx.conf")))
{
_logger.LogInformation("nginx.conf文件不存在");
return false;
}
return true;
}
}
} | 29.838384 | 115 | 0.591063 | [
"MIT"
] | simple-gr/deploy | Deploy.Wpf/Views/FrontPage.xaml.cs | 3,052 | C# |
using Web.Dto;
using System.Collections.Generic;
using MediatR;
using Application.Entities.Catalogs;
using Application.Entities.Baskets;
namespace Web.Response.ResponseBasket
{
public class DeleteBasketById : IRequest<IEnumerable<BasketDto>>
{
public DeleteBasketById(Basket catalog, uint id)
{
this.catalog = catalog;
this.id = id;
}
public Basket catalog{get;}
public uint id{get;}
}
} | 23.25 | 68 | 0.662366 | [
"MIT"
] | natividadejoao/eShopOnWeb | Web/Response/ResponseBasket/DeleteBasketById.cs | 465 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Actors;
using Microsoft.ServiceFabric.Actors.Runtime;
using Microsoft.ServiceFabric.Actors.Client;
using OrchestrationActor.Interfaces;
using GameOfLifeModel;
using CellActor.Interfaces;
using CellActor;
namespace OrchestrationActor
{
/// <remarks>
/// This class represents an actor.
/// Every ActorID maps to an instance of this class.
/// The StatePersistence attribute determines persistence and replication of actor state:
/// - Persisted: State is written to disk and replicated.
/// - Volatile: State is kept in memory only and replicated.
/// - None: State is kept in memory only and not replicated.
/// </remarks>
[StatePersistence(StatePersistence.Persisted)]
internal class OrchestrationActor : Actor, IOrchestrationActor
{
private int _ysize;
private int _xsize;
public async Task<TimeSpan> BigBang(int xsize, int ysize)
{
Stopwatch watch = Stopwatch.StartNew();
this._xsize = xsize;
this._ysize = ysize;
Random random = new Random(DateTime.Now.Millisecond);
int threshold = 30;
for (int j = 0; j < _ysize; j++)
{
for (int i = 0; i < _xsize; i++)
{
await CreateCellActor(i, j, (CellState)(random.Next(1, 100)<threshold ? 1 : 0));
}
}
return watch.Elapsed;
}
private Task CreateCellActor(int x, int y, CellState cellState)
{
var cellActor = GetCellActor(x, y);
// This will invoke a method on the actor. If an actor with the given ID does not exist, it will be activated by this method call.
return cellActor.GetAlive(x, y, cellState);
}
private static ICellActor GetCellActor(int x, int y)
{
ActorId actorId = new ActorId($"cell_{x}_{y}");
// This only creates a proxy object, it does not activate an actor or invoke any methods yet.
ICellActor cellActor = ActorProxy.Create<ICellActor>(actorId, new Uri("fabric:/SFGameOfLife/CellActorService"));
return cellActor;
}
public async Task<List<int>> GetCellStates()
{
var status = new List<int>();
for (int j = 0; j < _ysize; j++)
{
for (int i = 0; i < _xsize; i++)
{
var cellActor = GetCellActor(i, j);
var state = await cellActor.GetState();
status.Add(state);
}
}
for (int j = 0; j < _ysize; j++)
{
for (int i = 0; i < _xsize; i++)
{
var neighbourCoords = GetNeighbourCoords(i, j);
var neighbourStates = new List<int>();
foreach (var coord in neighbourCoords)
{
int state;
if (coord.Key < 0 || coord.Value < 0 || coord.Key >= _xsize || coord.Value >= _ysize)
{
state = 0;
}
else
{
state = status[coord.Value*_xsize + coord.Key];
}
neighbourStates.Add(state);
}
var myCellActor = GetCellActor(i, j);
var newStatus = await myCellActor.ComputeNewState(neighbourStates);
status[j * _xsize + i] = newStatus;
}
}
return status;
}
public KeyValuePair<int, int>[] GetNeighbourCoords(int X, int Y)
{
List<KeyValuePair<int, int>> result = new List<KeyValuePair<int, int>>();
result.Add(new KeyValuePair<int, int>(X + 1, Y));
result.Add(new KeyValuePair<int, int>(X + 1, Y + 1));
result.Add(new KeyValuePair<int, int>(X, Y + 1));
result.Add(new KeyValuePair<int, int>(X - 1, Y + 1));
result.Add(new KeyValuePair<int, int>(X - 1, Y));
result.Add(new KeyValuePair<int, int>(X - 1, Y - 1));
result.Add(new KeyValuePair<int, int>(X, Y - 1));
result.Add(new KeyValuePair<int, int>(X + 1, Y - 1));
//TODO Loop over the array and fix the boundary overflow problem
return result.ToArray();
}
/// <summary>
/// This method is called whenever an actor is activated.
/// An actor is activated the first time any of its methods are invoked.
/// </summary>
protected override async Task OnActivateAsync()
{
ActorEventSource.Current.ActorMessage(this, "Actor activated.");
// The StateManager is this actor's private state store.
// Data stored in the StateManager will be replicated for high-availability for actors that use volatile or persisted state storage.
// Any serializable object can be saved in the StateManager.
// For more information, see http://aka.ms/servicefabricactorsstateserialization
//return this.StateManager.TryAddStateAsync("count", 0);
}
}
}
| 39.035714 | 144 | 0.54785 | [
"MIT"
] | kreuzhofer/sf_gameoflife | src/SFGameOfLife/OrchestrationActor/OrchestrationActor.cs | 5,467 | C# |
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using EventPlanning.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Http;
using System;
using Microsoft.Extensions.Logging;
namespace EventPlanning.Controllers
{
[Authorize]
public class HomeController : Controller
{
public HomeController(ILogger<HomeController> logger)
{
this._logger = logger;
}
public ILogger<HomeController> _logger;
public IActionResult Index()
{
return View();
}
/// <summary>
/// Toggle localization
/// </summary>
/// <param name="culture"></param>
/// <param name="returnUrl"></param>
/// <returns></returns>
public IActionResult SetLanguage(string culture, string returnUrl = "/")
{
if (string.IsNullOrEmpty(culture))
{
_logger.LogError("Culture is empty.");
return BadRequest();
}
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) });
_logger.LogDebug("Culture '{0}' enabled with url: {1}.", culture, returnUrl);
return LocalRedirect(returnUrl);
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 29.785714 | 112 | 0.609113 | [
"MIT"
] | VladTsiukin/TheEventsCalendar | EventPlanning/Controllers/HomeController.cs | 1,670 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Microsoft.EntityFrameworkCore.Diagnostics
{
/// <summary>
/// <para>
/// Contains placeholders for caching of <see cref="EventDefinitionBase" />.
/// </para>
/// <para>
/// This class is public so that it can be inherited by database providers
/// to add caching for their events. It should not be used for any other purpose.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-providers">Implementation of database providers and extensions</see>
/// for more information.
/// </remarks>
public abstract class RelationalLoggingDefinitions : LoggingDefinitions
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogTransactionError;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBoolWithDefaultWarning;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOpeningConnection;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOpenedConnection;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogClosingConnection;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogClosedConnection;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogConnectionError;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBeginningTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBeganTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogUsingTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommittingTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRollingBackTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommittedTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRolledBackTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCreatingTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRollingBackToTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCreatedTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRolledBackToTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogReleasingTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogReleasedTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogDisposingTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogDisposingDataReader;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogAmbientTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogPossibleUnintendedUseOfEquals;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
[Obsolete]
public EventDefinitionBase? LogQueryPossibleExceptionWithAggregateOperatorWarning;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogGeneratingDown;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogGeneratingUp;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogApplyingMigration;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRevertingMigration;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogMigrating;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNoMigrationsApplied;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNoMigrationsFound;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogKeyHasDefaultValue;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommandCreating;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommandCreated;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogExecutingCommand;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogExecutedCommand;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommandFailed;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogConnectionErrorAsDebug;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogAmbientTransactionEnlisted;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogExplicitTransactionEnlisted;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBatchSmallerThanMinBatchSize;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBatchReadyForExecution;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogMigrationAttributeMissingWarning;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNamedIndexAllPropertiesNotToMappedToAnyTable;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogUnnamedIndexAllPropertiesNotToMappedToAnyTable;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNamedIndexPropertiesBothMappedAndNotMappedToTable;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogUnnamedIndexPropertiesBothMappedAndNotMappedToTable;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNamedIndexPropertiesMappedToNonOverlappingTables;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogUnnamedIndexPropertiesMappedToNonOverlappingTables;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogForeignKeyPropertiesMappedToUnrelatedTables;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogMultipleCollectionIncludeWarning;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBatchExecutorFailedToRollbackToSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBatchExecutorFailedToReleaseSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOptionalDependentWithoutIdentifyingProperty;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOptionalDependentWithAllNullProperties;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOptionalDependentWithAllNullPropertiesSensitive;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogDuplicateColumnOrders;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogColumnOrderIgnoredWarning;
}
}
| 65.165171 | 122 | 0.68496 | [
"MIT"
] | CameronAavik/efcore | src/EFCore.Relational/Diagnostics/RelationalLoggingDefinitions.cs | 36,297 | C# |
using System;
using Framework.Cache.Interfaces;
namespace Framework.Cache.Business
{
public class MemoryCacheBusiness : CacheBusiness<Framework.Cache.Entities.CacheEntry, IMemoryCacheRepository>
{
public override Lazy<IMemoryCacheRepository> Repository
{
get
{
if (base._repository == null)
base._repository = new Lazy<IMemoryCacheRepository>(() => new Framework.Cache.Repositories.MemoryCacheRepository());
return base._repository;
}
set
{
throw new NotImplementedException();
}
}
public void Trim(int percent)
{
Repository.Value.Trim(percent);
}
}
}
| 27.448276 | 137 | 0.55402 | [
"MIT"
] | jmirancid/TropicalNet.Framework | Framework.Cache/Business/MemoryCacheBusiness.cs | 798 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Modele;
using static Modele.Themes;
using static Modele.Constante;
namespace UnitTests
{
public partial class UnitTestManager
{
public (Leaf, Leaf, Leaf, Leaf, Leaf, Leaf, Composite, Composite,
Composite, Composite, Composite, Composite, Composite, Composite,
Composite, User, User, Manager) CreatTestRendreListeOeuvres()
{
var man = new Manager();
var date = new DateTime(1985, 04, 15);
man.CreerUser("Admin", "Admin", out var user);
user.IsAdmin = true;
man.CreerUser("Ambi", "Satan", out var user2);
man.ChangerInfos(user2, "Satan", "Ambi", "image", true, new List<Plateformes>());
var film = man.CreerLeaf(user, "Film", "Fight Club", date, "image", "synopsis", Themes.Action, true);
var film2 = man.CreerLeaf(user, "Film", "Club", date, "image", "synopsis", Themes.Action, true);
var film3 = man.CreerLeaf(user, "Film", "Fight Club3", date, "image", "synopsis", Aventure, true);
var film4 = man.CreerLeaf(user, "Film", "Fight Club4", date, "image", "synopsis", Aventure, false);
var episode = man.CreerLeaf(user, "Épisode", "Fight Club", date, "image", "synopsis", Themes.Action, false);
var episode2 = man.CreerLeaf(user, "Épisode", "Club", date, "image", "synopsis", Themes.Action, true);
var trilogie = man.CreerComposite(user, "Trilogie", "Fight Club", date, "image", "synopsis", Themes.Action,
false, new List<Oeuvre> { film2, film3, film4 });
var trilogie2 = man.CreerComposite(user, "Trilogie", "Fight Club2", date, "image", "synopsis", Themes.Action,
true, new List<Oeuvre> { film, film2, film3 });
var trilogie3 = man.CreerComposite(user, "Trilogie", "Club2", date, "image", "synopsis", Themes.Action,
true, new List<Oeuvre> { film, film, film });
var serie = man.CreerComposite(user, "Série", "Fight Club", date, "image", "synopsis", Themes.Action,
false, new List<Oeuvre> { episode });
var serie2 = man.CreerComposite(user, "Série", "Fight Club2", date, "image", "synopsis", Themes.Action,
true, new List<Oeuvre> { episode2 });
var serie3 = man.CreerComposite(user, "Série", "Club2", date, "image", "synopsis", Themes.Action,
true, new List<Oeuvre> { episode2 });
var univers = man.CreerComposite(user, "Univers", "Fight Club", date, "image", "synopsis", Themes.Action,
false, new List<Oeuvre> { trilogie, serie });
var univers2 = man.CreerComposite(user, "Univers", "Fight Club2", date, "image", "synopsis", Themes.Action,
true, new List<Oeuvre> { trilogie2, serie2 });
var univers3 = man.CreerComposite(user, "Univers", "Club2", date, "image", "synopsis", Themes.Action,
true, new List<Oeuvre> { trilogie2, serie2 });
return (film, film2, film3, film4, episode, episode2, trilogie, trilogie2, trilogie3, serie, serie2, serie3,
univers, univers2, univers3, user, user2, man);
}
[Fact]
public void TestManager_RendreTheme()
{
var man = new Manager();
var themes = Manager.RendreTousThemes().ToList();
Assert.DoesNotContain("Inconnu", themes);
Assert.Contains("Action", themes);
Assert.Contains("Suspense", themes);
Assert.Contains("Thriller", themes);
Assert.Contains("Horreur", themes);
Assert.Contains("Comédie", themes);
Assert.Contains("Aventure", themes);
Assert.Contains("Sf", themes);
Assert.Contains("Drame", themes);
Assert.Contains("Documentaire", themes);
}
[Fact]
public void TestManager_RendreListeOeuvres()
{
var man = new Manager();
var date = new DateTime(1985, 04, 15);
man.CreerUser("Admin", "Admin", out var user);
user.IsAdmin = true;
man.CreerUser("Ambi", "Satan", out var user2);
man.ChangerInfos(user2, "Satan", "Ambi", "image", true, new List<Plateformes>());
var film = man.CreerLeaf(user, "Film", "Fight Club", date, "image", "synopsis", Themes.Action, true);
var film2 = man.CreerLeaf(user, "Film", "Fight Club2", date, "image", "synopsis", Themes.Action, false);
var episode = man.CreerLeaf(user, "Episode", "Fight Club", date, "image", "synopsis", Themes.Action, false);
var oe = man.RendreListeOeuvres().ToList();
Assert.Contains(film, oe);
Assert.Contains(film2, oe);
Assert.DoesNotContain(episode, oe);
oe = man.RendreListeOeuvres(user).ToList();
Assert.Contains(film, oe);
Assert.Contains(film2, oe);
Assert.DoesNotContain(episode, oe);
oe = man.RendreListeOeuvres(user2).ToList();
Assert.Contains(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(episode, oe);
}
[Fact]
public void TestManager_RendreListePopulaire()
{
var man = new Manager();
var date = new DateTime(1985, 04, 15);
var avis = new Avis(4.5f, "oui");
var avis2 = new Avis(4f, "oui");
man.CreerUser("Admin", "Admin", out var user);
user.IsAdmin = true;
man.CreerUser("Ambi", "Satan", out var user2);
man.ChangerInfos(user2, "Satan", "Ambi", "image", true, new List<Plateformes>());
var film = man.CreerLeaf(user, "Film", "Fight Club", date, "image", "synopsis", Themes.Action, true);
var film2 = man.CreerLeaf(user, "Film", "Fight Club2", date, "image", "synopsis", Themes.Action, false);
var film3 = man.CreerLeaf(user, "Film", "Fight Club3", date, "image", "synopsis", Themes.Action, false);
var film4 = man.CreerLeaf(user, "Film", "Fight Club4", date, "image", "synopsis", Themes.Action, false);
var film5 = man.CreerLeaf(user, "Film", "Fight Club5", date, "image", "synopsis", Themes.Action, true);
var film6 = man.CreerLeaf(user, "Film", "Fight Club6", date, "image", "synopsis", Themes.Action, false);
var film7 = man.CreerLeaf(user, "Film", "Fight Club7", date, "image", "synopsis", Themes.Action, false);
var film8 = man.CreerLeaf(user, "Film", "Fight Club8", date, "image", "synopsis", Themes.Action, true);
var film9 = man.CreerLeaf(user, "Film", "Fight Club9", date, "image", "synopsis", Themes.Action, false);
var film10 = man.CreerLeaf(user, "Film", "Fight Club10", date, "image", "synopsis", Themes.Action, false);
var film11 = man.CreerLeaf(user, "Film", "Fight Club11", date, "image", "synopsis", Themes.Action, true);
var episode = man.CreerLeaf(user, "Episode", "Fight Club", date, "image", "synopsis", Themes.Action, false);
film.AjouterAvis(user, avis);
film2.AjouterAvis(user, avis);
film3.AjouterAvis(user, avis2);
film4.AjouterAvis(user, avis);
film5.AjouterAvis(user, avis2);
film6.AjouterAvis(user, avis2);
film7.AjouterAvis(user, avis);
film8.AjouterAvis(user, avis);
film9.AjouterAvis(user, avis);
film10.AjouterAvis(user, avis2);
film11.AjouterAvis(user, avis);
var oe = man.RendreListePopulaire().ToList(); // test de la classification par note
Assert.Contains(film, oe);
Assert.Contains(film2, oe);
Assert.Contains(film3, oe);
Assert.Contains(film4, oe);
Assert.Contains(film5, oe);
Assert.Contains(film6, oe);
Assert.Contains(film7, oe);
Assert.Contains(film8, oe);
Assert.Contains(film9, oe);
Assert.DoesNotContain(film10, oe);
Assert.Contains(film11, oe);
Assert.DoesNotContain(episode, oe);
oe = man.RendreListePopulaire(user).ToList(); // classification pour un user sans mode famille
Assert.Contains(film, oe);
Assert.Contains(film2, oe);
Assert.Contains(film3, oe);
Assert.Contains(film4, oe);
Assert.Contains(film5, oe);
Assert.Contains(film6, oe);
Assert.Contains(film7, oe);
Assert.Contains(film8, oe);
Assert.Contains(film9, oe);
Assert.DoesNotContain(film10, oe);
Assert.Contains(film11, oe);
Assert.DoesNotContain(episode, oe);
oe = man.RendreListePopulaire(user2).ToList(); // classification pour un user avec mode famille
Assert.Contains(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.Contains(film5, oe);
Assert.DoesNotContain(film6, oe);
Assert.DoesNotContain(film7, oe);
Assert.Contains(film8, oe);
Assert.DoesNotContain(film9, oe);
Assert.DoesNotContain(film10, oe);
Assert.Contains(film11, oe);
Assert.DoesNotContain(episode, oe);
}
[Fact]
public void TestManager_RendreListeOeuvresTheme()
{
var man = new Manager();
var date = new DateTime(1985, 04, 15);
man.CreerUser("Admin", "Admin", out var user);
user.IsAdmin = true;
man.CreerUser("Ambi", "Satan", out var user2);
man.ChangerInfos(user2, "Satan", "Ambi", "image", true, new List<Plateformes>());
var film = man.CreerLeaf(user, "Film", "Fight Club", date, "image", "synopsis", Themes.Action, false);
var film2 = man.CreerLeaf(user, "Film", "Fight Club2", date, "image", "synopsis", Themes.Action, true);
var film3 = man.CreerLeaf(user, "Film", "Fight Club3", date, "image", "synopsis", Aventure, true);
var episode = man.CreerLeaf(user, "Episode", "Fight Club", date, "image", "synopsis", Themes.Action, false);
var oe = man.RendreListeOeuvresTheme(Themes.Action).ToList();
Assert.Contains(film, oe);
Assert.Contains(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(episode, oe);
}
[Fact]
public void TestManager_RendreListeOeuvresThemeUser()
{
var man = new Manager();
var date = new DateTime(1985, 04, 15);
man.CreerUser("Admin", "Admin", out var user);
user.IsAdmin = true;
man.CreerUser("Ambi", "Satan", out var user2);
man.ChangerInfos(user2, "Satan", "Ambi", "image", true, new List<Plateformes>());
var film = man.CreerLeaf(user, "Film", "Fight Club", date, "image", "synopsis", Themes.Action, false);
var film2 = man.CreerLeaf(user, "Film", "Fight Club2", date, "image", "synopsis", Themes.Action, true);
var film3 = man.CreerLeaf(user, "Film", "Fight Club3", date, "image", "synopsis", Aventure, true);
var episode = man.CreerLeaf(user, "Episode", "Fight Club", date, "image", "synopsis", Themes.Action, false);
var oe = man.RendreListeOeuvresTheme(Themes.Action, user).ToList();
Assert.Contains(film, oe);
Assert.Contains(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(episode, oe);
oe = man.RendreListeOeuvresTheme(Themes.Action, user2).ToList();
Assert.DoesNotContain(film, oe);
Assert.Contains(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(episode, oe);
}
[Fact]
public void TestManager_RendreListeOeuvresSearchOeuvre()
{
Manager man;
User user, user2;
Leaf film, film2, film3, film4, episode, episode2;
Composite trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3;
(film, film2, film3, film4,
episode, episode2,
trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3,
user, user2,
man) = CreatTestRendreListeOeuvres();
var oe = man.RendreListeOeuvresSearch("Oeuvre","Fight").ToList();
Assert.Contains(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.Contains(film3, oe);
Assert.Contains(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.Contains(trilogie, oe);
Assert.Contains(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.Contains(serie, oe);
Assert.Contains(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.Contains(univers, oe);
Assert.Contains(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Oeuvre", "Fight", user).ToList();
Assert.Contains(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.Contains(film3, oe);
Assert.Contains(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.Contains(trilogie, oe);
Assert.Contains(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.Contains(serie, oe);
Assert.Contains(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.Contains(univers, oe);
Assert.Contains(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Oeuvre", "Fight", user2).ToList();
Assert.Contains(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.Contains(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.Contains(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.Contains(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.Contains(univers2, oe);
Assert.DoesNotContain(univers3, oe);
}
[Fact]
public void TestManager_RendreListeOeuvresSearchFilm()
{
Manager man;
User user, user2;
Leaf film, film2, film3, film4, episode, episode2;
Composite trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3;
(film, film2, film3, film4,
episode, episode2,
trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3,
user, user2,
man) = CreatTestRendreListeOeuvres();
var oe = man.RendreListeOeuvresSearch("Film", "Fight").ToList();
Assert.Contains(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.Contains(film3, oe);
Assert.Contains(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Film", "Fight", user).ToList();
Assert.Contains(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.Contains(film3, oe);
Assert.Contains(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Film", "Fight", user2).ToList();
Assert.Contains(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.Contains(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
}
[Fact]
public void TestManager_RendreListeOeuvresSearchTrilogie()
{
Manager man;
User user, user2;
Leaf film, film2, film3, film4, episode, episode2;
Composite trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3;
(film, film2, film3, film4,
episode, episode2,
trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3,
user, user2,
man) = CreatTestRendreListeOeuvres();
var oe = man.RendreListeOeuvresSearch("Trilogie", "Fight").ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.Contains(trilogie, oe);
Assert.Contains(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Trilogie", "Fight", user).ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.Contains(trilogie, oe);
Assert.Contains(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Trilogie", "Fight", user2).ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.Contains(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
}
[Fact]
public void TestManager_RendreListeOeuvresSearchSerie()
{
Manager man;
User user, user2;
Leaf film, film2, film3, film4, episode, episode2;
Composite trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3;
(film, film2, film3, film4,
episode, episode2,
trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3,
user, user2,
man) = CreatTestRendreListeOeuvres();
var oe = man.RendreListeOeuvresSearch("Série", "Fight").ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.Contains(serie, oe);
Assert.Contains(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Série", "Fight", user).ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.Contains(serie, oe);
Assert.Contains(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Série", "Fight", user2).ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.Contains(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.DoesNotContain(univers2, oe);
Assert.DoesNotContain(univers3, oe);
}
[Fact]
public void TestManager_RendreListeOeuvresSearchUnivers()
{
Manager man;
User user, user2;
Leaf film, film2, film3, film4, episode, episode2;
Composite trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3;
(film, film2, film3, film4,
episode, episode2,
trilogie, trilogie2, trilogie3,
serie, serie2, serie3,
univers, univers2, univers3,
user, user2,
man) = CreatTestRendreListeOeuvres();
var oe = man.RendreListeOeuvresSearch("Univers", "Fight").ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.Contains(univers, oe);
Assert.Contains(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Univers", "Fight", user).ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.Contains(univers, oe);
Assert.Contains(univers2, oe);
Assert.DoesNotContain(univers3, oe);
oe = man.RendreListeOeuvresSearch("Univers", "Fight", user2).ToList();
Assert.DoesNotContain(film, oe);
Assert.DoesNotContain(film2, oe);
Assert.DoesNotContain(film3, oe);
Assert.DoesNotContain(film4, oe);
Assert.DoesNotContain(episode, oe);
Assert.DoesNotContain(episode2, oe);
Assert.DoesNotContain(trilogie, oe);
Assert.DoesNotContain(trilogie2, oe);
Assert.DoesNotContain(trilogie3, oe);
Assert.DoesNotContain(serie, oe);
Assert.DoesNotContain(serie2, oe);
Assert.DoesNotContain(serie3, oe);
Assert.DoesNotContain(univers, oe);
Assert.Contains(univers2, oe);
Assert.DoesNotContain(univers3, oe);
}
[Fact]
public void TestManager_RendreListeActeurs()
{
var man = new Manager();
var date = new DateTime(1985, 04, 15);
man.CreerUser("Admin", "Admin", out var user);
user.IsAdmin = true;
var pers = man.CreerPersonne(user, "Brad", "Pitt", "oui", "Américain", "image", date);
var pers2 = man.CreerPersonne(user, "Leonardo", "DiCaprio", "oui", "Américain", "image", date);
man.CreerLeaf(user, "Film", "Fight Club", date, "image", "synopsis", Themes.Action, false,
new Dictionary<string, IEnumerable<KeyValuePair<Personne, string>>>{["Acteur"] = new Dictionary<Personne, string> {[pers] = "Roger"}});
var per = man.RendreListeActeurs().ToList();
Assert.Contains(pers, per);
Assert.DoesNotContain(pers2, per);
}
[Fact]
public void TestManager_RendreListeActeursSearch()
{
var man = new Manager();
var date = new DateTime(1985, 04, 15);
man.CreerUser("Admin", "Admin", out var user);
user.IsAdmin = true;
var pers = man.CreerPersonne(user, "Brad", "Pitt", "oui", "Américain", "image", date);
var pers2 = man.CreerPersonne(user, "Leonardo", "DiCaprio", "oui", "Américain", "image", date);
var pers3 = man.CreerPersonne(user, "Michel", "Du Pont", "oui", "Américain", "image", date);
man.CreerLeaf(user, "Film", "Fight Club", date, "image", "synopsis", Themes.Action, false,
new Dictionary<string, IEnumerable<KeyValuePair<Personne, string>>>{["Acteur"] = new Dictionary<Personne, string> {[pers] = "Roger", [pers2] = "Michel"}});
var per = man.RendreListeActeursSearch(ACTEUR, "Brad").ToList();
Assert.Contains(pers, per);
Assert.DoesNotContain(pers2, per);
Assert.DoesNotContain(pers3, per);
per = man.RendreListeActeursSearch(ACTEUR ,"Pitt").ToList();
Assert.Contains(pers, per);
Assert.DoesNotContain(pers2, per);
Assert.DoesNotContain(pers3, per);
per = man.RendreListeActeursSearch(ACTEUR, "Brad", "Pitt").ToList();
Assert.Contains(pers, per);
Assert.DoesNotContain(pers2, per);
Assert.DoesNotContain(pers3, per);
per = man.RendreListeActeursSearch(ACTEUR, "Pitt", "Brad").ToList();
Assert.Contains(pers, per);
Assert.DoesNotContain(pers2, per);
Assert.DoesNotContain(pers3, per);
}
[Fact]
public void TestManager_RendreListeAvis()
{
var man = new Manager();
var date = new DateTime(1985, 04, 15);
man.CreerUser("Admin", "Admin", out var user);
user.IsAdmin = true;
man.CreerUser("Ambi", "Satan", out var user2);
var film = man.CreerLeaf(user, "Film", "Fight Club", date, "image", "synopsis", Themes.Action, false);
var film2 = man.CreerLeaf(user, "Film", "Fight Club2", date, "image", "synopsis", Themes.Action, false);
var film3 = man.CreerLeaf(user, "Film", "Fight Club3", date, "image", "synopsis", Themes.Action, false);
var avis1 = new Avis(4.5f, "cool");
var avis2 = new Avis(3.5f, "nul");
var avis3 = new Avis(4f, "ouii");
var avis4 = new Avis(4.5f, "non");
var avis5 = new Avis(4.5f, "noice");
film.AjouterAvis(user, avis1);
film.AjouterAvis(user2, avis2);
film2.AjouterAvis(user, avis3);
film2.AjouterAvis(user2, avis4);
film3.AjouterAvis(user2, avis5);
var avis = man.RendreListeAvis(user, out var nbA).ToDictionary(oe => oe.Key, av => av.Value);
Assert.Equal(2, avis.Count);
Assert.Contains(film, avis.Keys);
Assert.Contains(avis1, avis.Values);
Assert.DoesNotContain(avis2, avis.Values);
Assert.Contains(film2, avis.Keys);
Assert.Contains(avis3, avis.Values);
Assert.DoesNotContain(avis4, avis.Values);
Assert.DoesNotContain(film3, avis.Keys);
Assert.DoesNotContain(avis5, avis.Values);
}
}
} | 41.990617 | 171 | 0.575802 | [
"MIT"
] | iShoFen/Cinema | Source/Cinema/UnitTests/UnitTestManager.cs | 31,341 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Brewery.MVC.Areas.Identity.Pages.Account.Manage
{
public class ExternalLoginsModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public ExternalLoginsModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationScheme> OtherLogins { get; set; }
public bool ShowRemoveButton { get; set; }
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID 'user.Id'.");
}
CurrentLogins = await _userManager.GetLoginsAsync(user);
OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
.Where(auth => CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
.ToList();
ShowRemoveButton = user.PasswordHash != null || CurrentLogins.Count > 1;
return Page();
}
public async Task<IActionResult> OnPostRemoveLoginAsync(string loginProvider, string providerKey)
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID 'user.Id'.");
}
var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey);
if (!result.Succeeded)
{
StatusMessage = "The external login was not removed.";
return RedirectToPage();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "The external login was removed.";
return RedirectToPage();
}
public async Task<IActionResult> OnPostLinkLoginAsync(string provider)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Page("./ExternalLogins", pageHandler: "LinkLoginCallback");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return new ChallengeResult(provider, properties);
}
public async Task<IActionResult> OnGetLinkLoginCallbackAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID 'user.Id'.");
}
var info = await _signInManager.GetExternalLoginInfoAsync(user.Id);
if (info == null)
{
throw new InvalidOperationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
}
var result = await _userManager.AddLoginAsync(user, info);
if (!result.Succeeded)
{
StatusMessage = "The external login was not added. External logins can only be associated with one account.";
return RedirectToPage();
}
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
StatusMessage = "The external login was added.";
return RedirectToPage();
}
}
}
| 38.318182 | 140 | 0.623962 | [
"MIT"
] | edrmonteiro/FSdotnetAngular | Brewery/Brewery.MVC/Areas/Identity/Pages/Account/Manage/ExternalLogins.cshtml.cs | 4,217 | C# |
using Milvasoft.Helpers.DataAccess.EfCore.Abstract.Entity;
using MongoDB.Bson;
namespace Milvasoft.Helpers.DataAccess.MongoDB.Entity.Abstract;
/// <summary>
/// Base interface for most obk entities.
/// </summary>
public interface IDocumentBase : IAuditable<ObjectId>
{
}
| 22.916667 | 63 | 0.778182 | [
"MIT"
] | Milvasoft/Milvasoft | Milvasoft.Helpers/DataAccess/MongoDB/Entity/Abstract/IDocumentBase.cs | 277 | C# |
using Bamboo.ScriptEngine;
using Bamboo.ScriptEngine.CSharp;
using System.Diagnostics;
using Xunit;
namespace Test.Bamboo.ScriptEngine.CSharp
{
public class Demo
{
[Trait("desc", "执行受信任的脚本 execute trasted code")]
[Fact]
public void Execute()
{
IScriptEngine scriptEngineProvider = new CSharpScriptEngine();
DynamicScript script = new DynamicScript();
script.Language = DynamicScriptLanguage.CSharp;
script.Script =
@"
using System;
public class Test
{
public int GetA(int a)
{
return a;
}
}
";
script.ClassFullName = "Test";
script.FunctionName = "GetA";
script.Parameters = new object[] { 111 };
script.IsExecutionInSandbox = false;
var result = scriptEngineProvider.Execute<int>(script);
Assert.True(result.IsSuccess);
Assert.Equal(111, result.Data);
}
[Trait("desc", "执行不受信任的脚本 execute untrasted code")]
[Fact]
public void ExecuteUntrastedCode()
{
IScriptEngine scriptEngineProvider = new CSharpScriptEngine();
DynamicScript script = new DynamicScript();
script.Language = DynamicScriptLanguage.CSharp;
script.Script =
@"
using System;
public class Test
{
public int GetC(int a)
{
int c = 0;
for(; ; )
{
c += 1;
}
return c;
}
}
";
script.ClassFullName = "Test";
script.FunctionName = "GetC";
script.Parameters = new object[] { 1 };
script.IsExecutionInSandbox = true; //沙箱环境执行
script.ExecutionInSandboxMillisecondsTimeout = 100; //沙箱环境执行超时时间
var result = scriptEngineProvider.Execute<int>(script);
Assert.False(result.IsSuccess);
Assert.Equal("execution timed out!", result.Message);
}
}
}
| 28.886076 | 80 | 0.495618 | [
"Apache-2.0"
] | sevenTiny/Chameleon.FaaS | src/dotnet/Tests/Test.Bamboo.ScriptEngine.CSharp/Demo.cs | 2,350 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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.CostAndUsageReport")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Cost and Usage Report Service. The AWS Cost and Usage Report Service API allows you to enable and disable the Cost and Usage report, as well as modify the report name, the data granularity, and the delivery preferences.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Cost and Usage Report Service. The AWS Cost and Usage Report Service API allows you to enable and disable the Cost and Usage report, as well as modify the report name, the data granularity, and the delivery preferences.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS Cost and Usage Report Service. The AWS Cost and Usage Report Service API allows you to enable and disable the Cost and Usage report, as well as modify the report name, the data granularity, and the delivery preferences.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS Cost and Usage Report Service. The AWS Cost and Usage Report Service API allows you to enable and disable the Cost and Usage report, as well as modify the report name, the data granularity, and the delivery preferences.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS Cost and Usage Report Service. The AWS Cost and Usage Report Service API allows you to enable and disable the Cost and Usage report, as well as modify the report name, the data granularity, and the delivery preferences.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS Cost and Usage Report Service. The AWS Cost and Usage Report Service API allows you to enable and disable the Cost and Usage report, as well as modify the report name, the data granularity, and the delivery preferences.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 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.100.7")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 60.186441 | 314 | 0.773303 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/CostAndUsageReport/Properties/AssemblyInfo.cs | 3,551 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Cdn.Models;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Cdn
{
/// <summary> A class representing collection of AfdOrigin and their operations over its parent. </summary>
public partial class AfdOriginCollection : ArmCollection, IEnumerable<AfdOrigin>, IAsyncEnumerable<AfdOrigin>
{
private readonly ClientDiagnostics _afdOriginClientDiagnostics;
private readonly AfdOriginsRestOperations _afdOriginRestClient;
/// <summary> Initializes a new instance of the <see cref="AfdOriginCollection"/> class for mocking. </summary>
protected AfdOriginCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="AfdOriginCollection"/> class. </summary>
/// <param name="parent"> The resource representing the parent resource. </param>
internal AfdOriginCollection(ArmResource parent) : base(parent)
{
_afdOriginClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Cdn", AfdOrigin.ResourceType.Namespace, DiagnosticOptions);
ArmClient.TryGetApiVersion(AfdOrigin.ResourceType, out string afdOriginApiVersion);
_afdOriginRestClient = new AfdOriginsRestOperations(_afdOriginClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, afdOriginApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != AfdOriginGroup.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, AfdOriginGroup.ResourceType), nameof(id));
}
// Collection level operations.
/// <summary> Creates a new origin within the specified origin group. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="originName"> Name of the origin that is unique within the profile. </param>
/// <param name="origin"> Origin properties. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> or <paramref name="origin"/> is null. </exception>
public virtual AfdOriginCreateOrUpdateOperation CreateOrUpdate(bool waitForCompletion, string originName, AfdOriginData origin, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(originName, nameof(originName));
if (origin == null)
{
throw new ArgumentNullException(nameof(origin));
}
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _afdOriginRestClient.Create(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, originName, origin, cancellationToken);
var operation = new AfdOriginCreateOrUpdateOperation(ArmClient, _afdOriginClientDiagnostics, Pipeline, _afdOriginRestClient.CreateCreateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, originName, origin).Request, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates a new origin within the specified origin group. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="originName"> Name of the origin that is unique within the profile. </param>
/// <param name="origin"> Origin properties. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> or <paramref name="origin"/> is null. </exception>
public async virtual Task<AfdOriginCreateOrUpdateOperation> CreateOrUpdateAsync(bool waitForCompletion, string originName, AfdOriginData origin, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(originName, nameof(originName));
if (origin == null)
{
throw new ArgumentNullException(nameof(origin));
}
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _afdOriginRestClient.CreateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, originName, origin, cancellationToken).ConfigureAwait(false);
var operation = new AfdOriginCreateOrUpdateOperation(ArmClient, _afdOriginClientDiagnostics, Pipeline, _afdOriginRestClient.CreateCreateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, originName, origin).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets an existing origin within an origin group. </summary>
/// <param name="originName"> Name of the origin which is unique within the profile. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> is null. </exception>
public virtual Response<AfdOrigin> Get(string originName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(originName, nameof(originName));
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.Get");
scope.Start();
try
{
var response = _afdOriginRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, originName, cancellationToken);
if (response.Value == null)
throw _afdOriginClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new AfdOrigin(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets an existing origin within an origin group. </summary>
/// <param name="originName"> Name of the origin which is unique within the profile. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> is null. </exception>
public async virtual Task<Response<AfdOrigin>> GetAsync(string originName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(originName, nameof(originName));
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.Get");
scope.Start();
try
{
var response = await _afdOriginRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, originName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _afdOriginClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new AfdOrigin(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="originName"> Name of the origin which is unique within the profile. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> is null. </exception>
public virtual Response<AfdOrigin> GetIfExists(string originName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(originName, nameof(originName));
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.GetIfExists");
scope.Start();
try
{
var response = _afdOriginRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, originName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<AfdOrigin>(null, response.GetRawResponse());
return Response.FromValue(new AfdOrigin(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="originName"> Name of the origin which is unique within the profile. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> is null. </exception>
public async virtual Task<Response<AfdOrigin>> GetIfExistsAsync(string originName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(originName, nameof(originName));
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.GetIfExists");
scope.Start();
try
{
var response = await _afdOriginRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, originName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<AfdOrigin>(null, response.GetRawResponse());
return Response.FromValue(new AfdOrigin(ArmClient, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="originName"> Name of the origin which is unique within the profile. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> is null. </exception>
public virtual Response<bool> Exists(string originName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(originName, nameof(originName));
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(originName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="originName"> Name of the origin which is unique within the profile. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="originName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="originName"/> is null. </exception>
public async virtual Task<Response<bool>> ExistsAsync(string originName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(originName, nameof(originName));
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(originName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists all of the existing origins within an origin group. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="AfdOrigin" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<AfdOrigin> GetAll(CancellationToken cancellationToken = default)
{
Page<AfdOrigin> FirstPageFunc(int? pageSizeHint)
{
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.GetAll");
scope.Start();
try
{
var response = _afdOriginRestClient.ListByOriginGroup(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new AfdOrigin(ArmClient, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<AfdOrigin> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.GetAll");
scope.Start();
try
{
var response = _afdOriginRestClient.ListByOriginGroupNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new AfdOrigin(ArmClient, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists all of the existing origins within an origin group. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="AfdOrigin" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<AfdOrigin> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<AfdOrigin>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.GetAll");
scope.Start();
try
{
var response = await _afdOriginRestClient.ListByOriginGroupAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new AfdOrigin(ArmClient, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<AfdOrigin>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _afdOriginClientDiagnostics.CreateScope("AfdOriginCollection.GetAll");
scope.Start();
try
{
var response = await _afdOriginRestClient.ListByOriginGroupNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new AfdOrigin(ArmClient, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
IEnumerator<AfdOrigin> IEnumerable<AfdOrigin>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<AfdOrigin> IAsyncEnumerable<AfdOrigin>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 53.516854 | 265 | 0.637256 | [
"MIT"
] | git-thomasdolan/azure-sdk-for-net | sdk/cdn/Azure.ResourceManager.Cdn/src/Generated/AfdOriginCollection.cs | 19,052 | C# |
using FluentValidation;
using ReadItLater.Infrastructure.Queries.User;
namespace ReadItLater.Infrastructure.DataValidators.Queries.User
{
public class GetUserByCredentialsQueryValidator : AbstractValidator<GetUserByCredentialsQuery>
{
public GetUserByCredentialsQueryValidator()
{
RuleFor(p => p.Username)
.NotEmpty()
.MinimumLength(3)
.MaximumLength(100);
RuleFor(p => p.Password)
.NotEmpty()
.MinimumLength(3)
.MaximumLength(100);
}
}
}
| 28.428571 | 98 | 0.599665 | [
"MIT"
] | Grigorenko/ReadItLater | ReadItLater.Infrastructure/DataValidators/Queries/User/GetUserByCredentialsQueryValidator.cs | 599 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneChanger : MonoBehaviour {
public void ChangeScene()
{
SceneManager.LoadScene("RaceArea");
}
}
| 17.857143 | 43 | 0.736 | [
"MIT"
] | smcguire56/GestureBasedUIProject | GestureProject/Assets/Scripts/SceneChanger.cs | 252 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Bindings;
using Microsoft.Azure.WebJobs.Host.Protocols;
using Microsoft.WindowsAzure.Storage.Blob;
namespace Microsoft.Azure.WebJobs.Host.Blobs.Bindings
{
internal class WatchableCloudBlobStream : DelegatingCloudBlobStream, IWatcher
{
private readonly IBlobCommitedAction _committedAction;
private bool _committed;
private bool _completed;
private long _countWritten;
private bool _flushed;
public WatchableCloudBlobStream(CloudBlobStream inner, IBlobCommitedAction committedAction)
: base(inner)
{
_committedAction = committedAction;
}
public override bool CanWrite
{
get
{
// Be nicer than the SDK. Return false when calling Write would throw.
return base.CanWrite && !_committed;
}
}
public bool HasCommitted
{
get { return _committed; }
}
public override Task CommitAsync() => CommitAsync(CancellationToken.None);
public async Task CommitAsync(CancellationToken cancellationToken)
{
_committed = true;
await base.CommitAsync();
if (_committedAction != null)
{
await _committedAction.ExecuteAsync(cancellationToken);
}
}
public override void Close()
{
if (!_committed)
{
Task.Run(async () => await CommitAsync()).GetAwaiter().GetResult();
}
base.Close();
}
public override void Flush()
{
base.Flush();
_flushed = true;
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
Task baskTask = base.FlushAsync(cancellationToken);
return FlushAsyncCore(baskTask);
}
private async Task FlushAsyncCore(Task task)
{
await task;
_flushed = true;
}
public override void Write(byte[] buffer, int offset, int count)
{
base.Write(buffer, offset, count);
_countWritten += count;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
Task baseTask = base.WriteAsync(buffer, offset, count, cancellationToken);
return WriteAsyncCore(baseTask, count);
}
private async Task WriteAsyncCore(Task task, int count)
{
await task;
_countWritten += count;
}
public override void WriteByte(byte value)
{
base.WriteByte(value);
_countWritten++;
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
Task baseTask = new TaskFactory().FromAsync(base.BeginWrite, base.EndWrite, buffer, offset, count, state: null);
return new TaskAsyncResult(WriteAsyncCore(baseTask, count), callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
TaskAsyncResult result = (TaskAsyncResult)asyncResult;
result.End();
}
/// <summary>Commits the stream as appropriate (when written to or flushed) and finalizes status.</summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>
/// A <see cref="Task"/> that commits the stream as appropriate and finalizes status. The result of the task is
/// <see langword="true"/> when the stream was committed (either by this method or previously); otherwise,
/// <see langword="false"/>
/// </returns>
public async Task<bool> CompleteAsync(CancellationToken cancellationToken)
{
if (!_committed && (_countWritten > 0 || _flushed))
{
await CommitAsync(cancellationToken);
}
_completed = true;
return _committed;
}
public ParameterLog GetStatus()
{
if (_committed || _countWritten > 0 || _flushed)
{
return new WriteBlobParameterLog { WasWritten = true, BytesWritten = _countWritten };
}
else if (_completed)
{
return new WriteBlobParameterLog { WasWritten = false, BytesWritten = 0 };
}
else
{
return null;
}
}
}
}
| 31.85443 | 124 | 0.589708 | [
"MIT"
] | Nasicus/azure-webjobs-sdk | src/Microsoft.Azure.WebJobs.Extensions.Storage/Blobs/Bindings/WatchableCloudBlobStream.cs | 5,035 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace AlertLambdas.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 38.387387 | 99 | 0.626848 | [
"Apache-2.0"
] | aliozgur/xamarin-forms-book-samples | Chapter20/AlertLambdas/AlertLambdas/AlertLambdas.UWP/App.xaml.cs | 4,261 | C# |
using System.Drawing;
namespace iSukces.DrawingPanel
{
internal struct IntVector
{
private readonly int _x;
private readonly int _y;
public IntVector(int x, int y)
{
_x = x;
_y = y;
}
public static IntVector operator +(IntVector a, IntVector b) { return new IntVector(a._x + b._x, a._y + b._y); }
public static Point operator +(Point a, IntVector b) { return new Point(a.X + b._x, a.Y + b._y); }
public static Point operator -(Point a, IntVector b) { return new Point(a.X - b._x, a.Y - b._y); }
}
}
| 26.304348 | 120 | 0.573554 | [
"MIT"
] | isukces/iSukces.DrawingPanel | app/iSukces.DrawingPanel/IntVector.cs | 607 | C# |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V6.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V6.Resources
{
/// <summary>Resource name for the <c>MobileDeviceConstant</c> resource.</summary>
public sealed partial class MobileDeviceConstantName : gax::IResourceName, sys::IEquatable<MobileDeviceConstantName>
{
/// <summary>The possible contents of <see cref="MobileDeviceConstantName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>mobileDeviceConstants/{criterion_id}</c>.</summary>
Criterion = 1,
}
private static gax::PathTemplate s_criterion = new gax::PathTemplate("mobileDeviceConstants/{criterion_id}");
/// <summary>Creates a <see cref="MobileDeviceConstantName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="MobileDeviceConstantName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static MobileDeviceConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new MobileDeviceConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="MobileDeviceConstantName"/> with the pattern <c>mobileDeviceConstants/{criterion_id}</c>
/// .
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="MobileDeviceConstantName"/> constructed from the provided ids.
/// </returns>
public static MobileDeviceConstantName FromCriterion(string criterionId) =>
new MobileDeviceConstantName(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="MobileDeviceConstantName"/> with pattern
/// <c>mobileDeviceConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="MobileDeviceConstantName"/> with pattern
/// <c>mobileDeviceConstants/{criterion_id}</c>.
/// </returns>
public static string Format(string criterionId) => FormatCriterion(criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="MobileDeviceConstantName"/> with pattern
/// <c>mobileDeviceConstants/{criterion_id}</c>.
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="MobileDeviceConstantName"/> with pattern
/// <c>mobileDeviceConstants/{criterion_id}</c>.
/// </returns>
public static string FormatCriterion(string criterionId) =>
s_criterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="MobileDeviceConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>mobileDeviceConstants/{criterion_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="mobileDeviceConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="MobileDeviceConstantName"/> if successful.</returns>
public static MobileDeviceConstantName Parse(string mobileDeviceConstantName) =>
Parse(mobileDeviceConstantName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="MobileDeviceConstantName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>mobileDeviceConstants/{criterion_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="mobileDeviceConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="MobileDeviceConstantName"/> if successful.</returns>
public static MobileDeviceConstantName Parse(string mobileDeviceConstantName, bool allowUnparsed) =>
TryParse(mobileDeviceConstantName, allowUnparsed, out MobileDeviceConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="MobileDeviceConstantName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>mobileDeviceConstants/{criterion_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="mobileDeviceConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="MobileDeviceConstantName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string mobileDeviceConstantName, out MobileDeviceConstantName result) =>
TryParse(mobileDeviceConstantName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="MobileDeviceConstantName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>mobileDeviceConstants/{criterion_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="mobileDeviceConstantName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="MobileDeviceConstantName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string mobileDeviceConstantName, bool allowUnparsed, out MobileDeviceConstantName result)
{
gax::GaxPreconditions.CheckNotNull(mobileDeviceConstantName, nameof(mobileDeviceConstantName));
gax::TemplatedResourceName resourceName;
if (s_criterion.TryParseName(mobileDeviceConstantName, out resourceName))
{
result = FromCriterion(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(mobileDeviceConstantName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private MobileDeviceConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CriterionId = criterionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="MobileDeviceConstantName"/> class from the component parts of
/// pattern <c>mobileDeviceConstants/{criterion_id}</c>
/// </summary>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public MobileDeviceConstantName(string criterionId) : this(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Criterion: return s_criterion.Expand(CriterionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as MobileDeviceConstantName);
/// <inheritdoc/>
public bool Equals(MobileDeviceConstantName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(MobileDeviceConstantName a, MobileDeviceConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(MobileDeviceConstantName a, MobileDeviceConstantName b) => !(a == b);
}
public partial class MobileDeviceConstant
{
/// <summary>
/// <see cref="gagvr::MobileDeviceConstantName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal MobileDeviceConstantName ResourceNameAsMobileDeviceConstantName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::MobileDeviceConstantName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::MobileDeviceConstantName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal MobileDeviceConstantName MobileDeviceConstantName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::MobileDeviceConstantName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| 51.919231 | 190 | 0.642418 | [
"Apache-2.0"
] | PierrickVoulet/google-ads-dotnet | src/V6/Resources/MobileDeviceConstantResourceNames.g.cs | 13,499 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TCM_AgenciaViagem.Models
{
public class Pacote
{
public ushort IdPacote { get; set; }
public byte QuantidadeDiarias { get; set; }
public byte QuantidadeQuartos { get; set; }
public DateTime DataCheckin { get; set; }
public DateTime DataCheckout { get; set; }
public string Origem { get; set; }
public string Destino { get; set; }
public byte NumeroAdultos { get; set; }
public byte NumeroCriancas { get; set; }
public string TipoTransporte { get; set; }
public decimal ValorUnitario { get; set; }
public string DescricaoPacote { get; set; }
public string ResumoPacote { get; set; }
public string RoteiroViagem { get; set; }
/*
* Pacote
IdPacote: ushort
QuantidadeDiarias: ushort
QuantidadeQuartos: ushort
DataCheckin: DateTime
DataCheckout: DateTime
Origem: string
Destino: string
NumeroAdultos: byte
NumeroCriancas: byte
TipoTransporte: string
ValorUnitario: double(10)
DescricaoPacote: string
ResumoPacote: string
RoteiroViagem: string
*/
}
} | 28.357143 | 51 | 0.674223 | [
"MIT"
] | mikhailsb/TCM_AgenciaViagem | TCM_AgenciaViagem/TCM_AgenciaViagem/Models/Pacote.cs | 1,193 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.