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 |
|---|---|---|---|---|---|---|---|---|
namespace Game.Util
{
using Game.Util.Commands;
using McMaster.Extensions.CommandLineUtils;
using System;
using System.Threading.Tasks;
public class Program
{
public async static Task<int> Main(string[] args)
{
try
{
return await CommandLineApplication.ExecuteAsync<RootCommand>(args);
}
catch (Exception e)
{
while (e.InnerException != null)
e = e.InnerException;
Console.Error.WriteLine($"ERROR: {e}");
return 1;
}
}
}
}
| 23.481481 | 84 | 0.506309 | [
"MIT"
] | daud-io/daud | Game.Util/Program.cs | 636 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorldGenerator : MonoBehaviour
{
public Transform world;
public Transform player;
public GameObject obstaclePrefab;
public Material worldMaterial;
Vector2Int dimensions;
Vector2 size;
Dictionary<Vector2Int, GameObject> chunks;
int chunkRadius = 5;
Vector2Int lastChunkPos;
void Awake()
{
dimensions = new Vector2Int(25, 25);
size = new Vector2(50, 50);
lastChunkPos = getChunkPos();
chunks = new Dictionary<Vector2Int, GameObject>();
createChunks(getChunkPos());
}
void Update()
{
Vector2Int currentChunkPos = getChunkPos();
if(currentChunkPos != lastChunkPos)
{
createChunks(currentChunkPos);
}
lastChunkPos = currentChunkPos;
}
Vector2Int getChunkPos()
{
return new Vector2Int(Mathf.FloorToInt(player.transform.position.x / size.x), Mathf.FloorToInt(player.transform.position.z / size.y));
}
void createChunks(Vector2Int currentChunkPos)
{
HashSet<Vector2Int> chunksToRemove = new HashSet<Vector2Int>(chunks.Keys);
for (int x = currentChunkPos.x - chunkRadius; x < currentChunkPos.x + chunkRadius; x++)
{
for (int z = currentChunkPos.y - chunkRadius; z < currentChunkPos.y + chunkRadius; z++)
{
Vector2Int chunkPos = new Vector2Int(x, z);
chunksToRemove.Remove(chunkPos);
if (!chunks.ContainsKey(chunkPos))
chunks.Add(chunkPos, createChunkObject(new Vector3(x * size.x, 0, z * size.y)));
}
}
foreach(var chunkPos in chunksToRemove)
{
Destroy(chunks[chunkPos]);
chunks.Remove(chunkPos);
}
}
GameObject createChunkObject(Vector3 position)
{
GameObject worldChunk = new GameObject();
worldChunk.name = "WorldChunk";
worldChunk.transform.position = position;
worldChunk.transform.parent = world;
GameObject bottom = createChunkMeshObject(position, false);
bottom.transform.parent = worldChunk.transform;
GameObject top = createChunkMeshObject(position + new Vector3(0, 10f, 0), true);
top.transform.parent = worldChunk.transform;
//place obstacles
for (int i = 0; i < 20; i++)
{
Vector2 perlinPos = new Vector2(position.x + Random.value * size.x, position.z + Random.value * size.y);
Vector3 obPos = new Vector3(perlinPos.x, getPerlinHeight(perlinPos), perlinPos.y);
GameObject obstacle = Instantiate(obstaclePrefab, obPos, Quaternion.identity, worldChunk.transform);
//obstacle.transform.eulerAngles = new Vector3(Random.value * 90f - 45f, Random.value * 360f, Random.value * 90f - 45f);
obstacle.name = "obstacle";
RaycastHit hit;
if (Physics.Raycast(obstacle.transform.position + new Vector3(0, 5, 0), Vector3.down, out hit, Mathf.Infinity))
{
obstacle.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
obstacle.transform.eulerAngles += new Vector3(Random.value * 60 - 30f, 0, Random.value * 60f - 30f);
}
}
return worldChunk;
}
GameObject createChunkMeshObject(Vector3 position, bool flip)
{
GameObject chunkMeshObject = new GameObject();
chunkMeshObject.name = "WorldChunk";
chunkMeshObject.transform.position = position;
MeshCollider collider = chunkMeshObject.AddComponent<MeshCollider>();
MeshRenderer renderer = chunkMeshObject.AddComponent<MeshRenderer>();
renderer.sharedMaterial = worldMaterial;
MeshFilter filter = chunkMeshObject.AddComponent<MeshFilter>();
Mesh mesh = createChunkMesh(position, flip);
filter.sharedMesh = mesh;
collider.sharedMesh = mesh;
return chunkMeshObject;
}
float getPerlinHeight(Vector2 position)
{
return getPerlinHeight(position, 0.035f, 5f) + getPerlinHeight(position, 0.005f, 75f);
}
float getPerlinHeight(Vector2 position, float perlinScale, float heightScale)
{
float x = position.x;
float z = position.y;
Vector2 perlinOffset = new Vector2(10000, 10000);
x += perlinOffset.x;
z += perlinOffset.y;
x *= perlinScale;
z *= perlinScale;
float height = Mathf.PerlinNoise(x, z);
height *= heightScale;
return height;
}
Mesh createChunkMesh(Vector3 position, bool flip)
{
Mesh mesh = new Mesh();
Vector3[] verticies = new Vector3[(dimensions.x + 1) * (dimensions.y + 1)];
int[] triangles = new int[dimensions.x * dimensions.y * 6];
Vector2[] uv = new Vector2[verticies.Length];
//verticies
for (int i = 0, x = 0; x < dimensions.x + 1; x++)
{
for (int z = 0; z < dimensions.y + 1; z++)
{
float xpos = position.x + (float)x / dimensions.x * size.x;
float zpos = position.z + (float)z / dimensions.y * size.y;
float height = getPerlinHeight(new Vector2(xpos, zpos));
verticies[i] = new Vector3((float)x / dimensions.x * size.x, height, (float)z / dimensions.y * size.y);
uv[i] = new Vector2((float)x / dimensions.x, (float)z / dimensions.y);
i++;
}
}
//triangles
for (int i = 0, x = 0; x < dimensions.x; x++)
{
for (int z = 0; z < dimensions.y; z++)
{
//create square:
int zRowLength = dimensions.y + 1;
int selectZRowIndex = x * zRowLength;
int selectPositionInZRow = selectZRowIndex + z;
//create triangle 1 of square
int squareIndex = i * 6;
triangles[squareIndex] = selectPositionInZRow;
triangles[squareIndex + 1 + (!flip ? 0 : 1)] = selectPositionInZRow + 1;
triangles[squareIndex + 2 - (!flip ? 0 : 1)] = selectPositionInZRow + zRowLength + 1;
//create triangle 2 of square
triangles[squareIndex + 3] = selectPositionInZRow;
triangles[squareIndex + 4 + (!flip ? 0 : 1)] = selectPositionInZRow + zRowLength + 1;
triangles[squareIndex + 5 - (!flip ? 0 : 1)] = selectPositionInZRow + zRowLength;
i++;
}
}
mesh.vertices = verticies;
mesh.triangles = triangles;
mesh.uv = uv;
mesh.RecalculateNormals();
return mesh;
}
} | 34.771144 | 143 | 0.574188 | [
"MIT"
] | CallumFerguson/CS4610FinalProject | Assets/Scripts/WorldGenerator.cs | 6,991 | C# |
using System;
using System.ComponentModel;
using System.Windows.Data;
using AVM.DDP;
namespace PETBrowser
{
public class TBManifestViewModel
{
public MetaTBManifest Manifest { get; set; }
public ICollectionView Dependencies { get; set; }
public ICollectionView Artifacts { get; set; }
public ICollectionView VisualizationArtifacts { get; set; }
public ICollectionView Metrics { get; set; }
public ICollectionView Parameters { get; set; }
public ICollectionView Steps { get; set; }
public string CreatedTime
{
get
{
var parsedTime = DateTime.Parse(Manifest.Created);
return parsedTime.ToString("G");
}
}
public TBManifestViewModel(string manifestPath)
{
Manifest = MetaTBManifest.Deserialize(manifestPath);
Dependencies = new ListCollectionView(Manifest.Dependencies);
Artifacts = new ListCollectionView(Manifest.Artifacts);
Artifacts.SortDescriptions.Add(new SortDescription("Tag", ListSortDirection.Ascending));
VisualizationArtifacts = new ListCollectionView(Manifest.VisualizationArtifacts);
VisualizationArtifacts.SortDescriptions.Add(new SortDescription("Tag", ListSortDirection.Ascending));
Metrics = new ListCollectionView(Manifest.Metrics);
Metrics.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
Parameters = new ListCollectionView(Manifest.Parameters);
Parameters.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
Steps = new ListCollectionView(Manifest.Steps);
}
}
} | 36.040816 | 113 | 0.666478 | [
"MIT"
] | lefevre-fraser/openmeta-mms | src/PETBrowser/TBManifestViewModel.cs | 1,768 | 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 gamelift-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GameLift.Model
{
/// <summary>
/// Container for the parameters to the UpdateFleetPortSettings operation.
/// Updates port settings for a fleet. To update settings, specify the fleet ID to be
/// updated and list the permissions you want to update. List the permissions you want
/// to add in <code>InboundPermissionAuthorizations</code>, and permissions you want to
/// remove in <code>InboundPermissionRevocations</code>. Permissions to be removed must
/// match existing fleet permissions. If successful, the fleet ID for the updated fleet
/// is returned.
///
///
/// <para>
/// Fleet-related operations include:
/// </para>
/// <ul> <li>
/// <para>
/// <a>CreateFleet</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>ListFleets</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DeleteFleet</a>
/// </para>
/// </li> <li>
/// <para>
/// Describe fleets:
/// </para>
/// <ul> <li>
/// <para>
/// <a>DescribeFleetAttributes</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeFleetCapacity</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeFleetPortSettings</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeFleetUtilization</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeRuntimeConfiguration</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeEC2InstanceLimits</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>DescribeFleetEvents</a>
/// </para>
/// </li> </ul> </li> <li>
/// <para>
/// Update fleets:
/// </para>
/// <ul> <li>
/// <para>
/// <a>UpdateFleetAttributes</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>UpdateFleetCapacity</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>UpdateFleetPortSettings</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>UpdateRuntimeConfiguration</a>
/// </para>
/// </li> </ul> </li> <li>
/// <para>
/// Manage fleet actions:
/// </para>
/// <ul> <li>
/// <para>
/// <a>StartFleetActions</a>
/// </para>
/// </li> <li>
/// <para>
/// <a>StopFleetActions</a>
/// </para>
/// </li> </ul> </li> </ul>
/// </summary>
public partial class UpdateFleetPortSettingsRequest : AmazonGameLiftRequest
{
private string _fleetId;
private List<IpPermission> _inboundPermissionAuthorizations = new List<IpPermission>();
private List<IpPermission> _inboundPermissionRevocations = new List<IpPermission>();
/// <summary>
/// Gets and sets the property FleetId.
/// <para>
/// Unique identifier for a fleet to update port settings for.
/// </para>
/// </summary>
public string FleetId
{
get { return this._fleetId; }
set { this._fleetId = value; }
}
// Check to see if FleetId property is set
internal bool IsSetFleetId()
{
return this._fleetId != null;
}
/// <summary>
/// Gets and sets the property InboundPermissionAuthorizations.
/// <para>
/// Collection of port settings to be added to the fleet record.
/// </para>
/// </summary>
public List<IpPermission> InboundPermissionAuthorizations
{
get { return this._inboundPermissionAuthorizations; }
set { this._inboundPermissionAuthorizations = value; }
}
// Check to see if InboundPermissionAuthorizations property is set
internal bool IsSetInboundPermissionAuthorizations()
{
return this._inboundPermissionAuthorizations != null && this._inboundPermissionAuthorizations.Count > 0;
}
/// <summary>
/// Gets and sets the property InboundPermissionRevocations.
/// <para>
/// Collection of port settings to be removed from the fleet record.
/// </para>
/// </summary>
public List<IpPermission> InboundPermissionRevocations
{
get { return this._inboundPermissionRevocations; }
set { this._inboundPermissionRevocations = value; }
}
// Check to see if InboundPermissionRevocations property is set
internal bool IsSetInboundPermissionRevocations()
{
return this._inboundPermissionRevocations != null && this._inboundPermissionRevocations.Count > 0;
}
}
} | 30.532967 | 117 | 0.566853 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/GameLift/Generated/Model/UpdateFleetPortSettingsRequest.cs | 5,557 | C# |
using GraphQL.Net;
namespace Tests
{
public class StarWarsTests
{
public static void BasicQueryHero<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery("query HeroNameQuery { hero { name } }");
Test.DeepEquals(results, "{ hero: { name: 'R2-D2' } }");
}
public static void BasicQueryHeroWithIdAndFriends<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery("query HeroNameQuery { hero { id, name, friends { name } } }");
Test.DeepEquals(results,
"{ hero: { id: '2001', name: 'R2-D2', friends: [ { name: 'Luke Skywalker' },{ name: 'Han Solo' }, { name: 'Leia Organa'} ] } }");
}
public static void BasicQueryHeroWithFriendsOfFriends<TContext>(GraphQL<TContext> gql)
{
var results =
gql.ExecuteQuery(
"query HeroNameQuery { hero { name, friends { name, appearsIn, friends { name } } } }");
Test.DeepEquals(results,
@"{hero: {
name: 'R2-D2',
friends: [
{
name: 'Luke Skywalker',
appearsIn: [ 'NEWHOPE', 'EMPIRE', 'JEDI' ],
friends: [
{
name: 'Han Solo',
},
{
name: 'Leia Organa',
},
{
name: 'C-3PO',
},
{
name: 'R2-D2',
}
]
},
{
name: 'Han Solo',
appearsIn: [ 'NEWHOPE', 'EMPIRE', 'JEDI' ],
friends: [
{
name: 'Luke Skywalker',
},
{
name: 'Leia Organa',
},
{
name: 'R2-D2',
}
]
},
{
name: 'Leia Organa',
appearsIn: [ 'NEWHOPE', 'EMPIRE', 'JEDI' ],
friends: [
{
name: 'Luke Skywalker',
},
{
name: 'Han Solo',
},
{
name: 'C-3PO',
},
{
name: 'R2-D2',
}
]
}
]
}
}");
}
public static void BasicQueryFetchLuke<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery("query FetchLukeQuery { human(id: \"1000\") { name } }");
Test.DeepEquals(results,
"{ human: { name: 'Luke Skywalker' } }");
}
public static void FragmentsDuplicatedContent<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"
query DuplicateFields {
luke: human(id: ""1000"") {
name
homePlanet
}
leia: human(id: ""1003"") {
name
homePlanet
}
}
"
);
Test.DeepEquals(results,
@"
{
luke: {
name: 'Luke Skywalker',
homePlanet: 'Tatooine'
},
leia: {
name: 'Leia Organa',
homePlanet: 'Alderaan'
}
}
");
}
public static void FragmentsAvoidDuplicatedContent<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"query UseFragment {
luke: human(id: ""1000"") {
...HumanFragment
}
leia: human(id: ""1003"") {
...HumanFragment
}
}
fragment HumanFragment on Human {
name
homePlanet
}
"
);
Test.DeepEquals(results,
@"
{
luke: {
name: 'Luke Skywalker',
homePlanet: 'Tatooine'
},
leia: {
name: 'Leia Organa',
homePlanet: 'Alderaan'
}
}
");
}
public static void FragmentsInlineFragments<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"query UseInlineFragments {
luke: hero(episode: EMPIRE) {
...HumanFragment,
...DroidFragment
}
r2d2: hero {
...HumanFragment,
...DroidFragment
}
}
fragment HumanFragment on Human {
name
homePlanet
}
fragment DroidFragment on Droid {
name
primaryFunction
}
"
);
Test.DeepEquals(results,
@"
{
luke: {
name: 'Luke Skywalker',
homePlanet: 'Tatooine'
},
r2d2: {
name: 'R2-D2',
primaryFunction: 'Astromech'
}
}
");
}
public static void TypenameR2Droid<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery("query CheckTypeOfR2 { hero { __typename, name } }");
Test.DeepEquals(results,
"{ hero: { __typename: 'Droid', name: 'R2-D2' } }");
}
public static void TypenameLukeHuman<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery("query CheckTypeOfLuke { hero(episode: EMPIRE) { __typename, name } }");
Test.DeepEquals(results,
"{ hero: { __typename: 'Human', name: 'Luke Skywalker' } }");
}
public static void IntrospectionDroidType<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"query IntrospectionDroidTypeQuery {
__type(name: ""Droid"") {
name
}
}");
Test.DeepEquals(results,
"{ __type: { name: 'Droid' } }");
}
public static void IntrospectionDroidTypeKind<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"query IntrospectionDroidKindQuery {
__type(name: ""Droid"") {
name
kind
}
}");
Test.DeepEquals(results,
"{ __type: { name: 'Droid', kind: 'OBJECT' } }");
}
public static void IntrospectionCharacterInterface<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"query IntrospectionCharacterKindQuery {
__type(name: ""ICharacter"") {
name
kind
}
}");
Test.DeepEquals(results,
"{ __type: { name: 'ICharacter', kind: 'INTERFACE' } }");
}
public static void UnionTypeStarship<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"query UnionTypeStarshipQuery {
search(text: ""starship"") {
__typename
}
}");
Test.DeepEquals(results,
"{ search: { __typename: 'Starship'} }");
}
public static void UnionTypeHuman<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"query UnionTypeStarshipQuery {
search(text: ""human"") {
__typename
}
}");
Test.DeepEquals(results,
"{ search: { __typename: 'Human'} }");
}
public static void UnionTypeDroid<TContext>(GraphQL<TContext> gql)
{
var results = gql.ExecuteQuery(
@"query UnionTypeStarshipQuery {
search(text: ""droid"") {
__typename
}
}");
Test.DeepEquals(results,
"{ search: { __typename: 'Droid'} }");
}
}
} | 33.021352 | 145 | 0.374609 | [
"MIT"
] | nexussays/graphql-net | Tests/StarWarsTests.cs | 9,281 | C# |
using BrightIdeasSoftware;
using EAAddinFramework.Mapping;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using MP = MappingFramework;
using UML = TSF.UmlToolingFramework.UML;
namespace EAMapping
{
/// <summary>
/// Description of MappingControlGUI.
/// </summary>
public partial class MappingControlGUI : UserControl
{
private List<MP.Mapping> selectedMappings => this.selectedNode != null ?
this.selectedNode?.mappings.ToList() :
new List<MP.Mapping>();
private MP.MappingSet mappingSet { get; set; }
private List<MappingDetailsControl> mappingDetailControls { get; } = new List<MappingDetailsControl>();
public MappingControlGUI()
{
// The InitializeComponent() call is required for Windows Forms designer
// support.
this.InitializeComponent();
this.setDelegates();
}
private void addMappingDetailControl(int i)
{
var detailsControl = new MappingDetailsControl();
detailsControl.mappingDeleted += this.mappingDeleted;
detailsControl.mapping_Enter += this.mappingEnter;
detailsControl.AutoSizeMode = AutoSizeMode.GrowAndShrink;
detailsControl.BorderStyle = BorderStyle.FixedSingle;
detailsControl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
detailsControl.TabIndex = i;
detailsControl.Hide();
this.mappingDetailControls.Add(detailsControl);
this.mappingPanel.Controls.Add(detailsControl,0,i );
}
private void mappingEnter(object sender, EventArgs e)
{
var detailsControl = sender as MappingDetailsControl;
var mapping = detailsControl.mapping;
this.sourceTreeView.Reveal(mapping.source, false);
this.targetTreeView.Reveal(mapping.target, false);
}
private void mappingDeleted(object sender, EventArgs e)
{
var detailsControl = sender as MappingDetailsControl;
var mapping = detailsControl.mapping;
//get source and target
var source = mapping?.source;
var target = mapping?.target;
//delete the mapping
detailsControl.mapping?.delete();
//clear the GUI
this.clearMappingDetails();
//show the mappings again
this.showMappings(this.selectedMappings);
//refresh to show the updated data
this.sourceTreeView.RefreshObject(this.sourceTreeView.Objects.Cast<MappingNode>().FirstOrDefault());
this.targetTreeView.RefreshObject(this.sourceTreeView.Objects.Cast<MappingNode>().FirstOrDefault());
}
private void clearMappingDetails()
{
foreach (var detailsControl in this.mappingDetailControls)
{
detailsControl.mapping = null;
detailsControl.Hide();
}
}
private void showMappings(List<MP.Mapping> mappings)
{
for (int i = 0; i < mappings.Count(); i++)
{
//make sure there are enough mappingDetailControls
while (i >= this.mappingDetailControls.Count)
{
this.addMappingDetailControl(i);
}
//set details and show
this.mappingDetailControls[i].mapping = mappings[i];
this.mappingDetailControls[i].Show();
}
}
private void setDelegates()
{
//tell the control who can expand
TreeListView.CanExpandGetterDelegate canExpandGetter = delegate (object x)
{
var mappingNode = (MappingNode)x;
return mappingNode.childNodes.Any();
};
this.sourceTreeView.CanExpandGetter = canExpandGetter;
this.targetTreeView.CanExpandGetter = canExpandGetter;
//tell the control how to expand
TreeListView.ChildrenGetterDelegate childrenGetter = delegate (object x)
{
var mappingNode = (MappingNode)x;
return mappingNode.childNodes;
};
this.sourceTreeView.ChildrenGetter = childrenGetter;
this.targetTreeView.ChildrenGetter = childrenGetter;
//parentgetter to be able to reveal deeply nested nodes
TreeListView.ParentGetterDelegate parentGetter = delegate (object x)
{
var mappingNode = (MappingNode)x;
return mappingNode.parent;
};
this.sourceTreeView.ParentGetter = parentGetter;
this.targetTreeView.ParentGetter = parentGetter;
//tell the control which image to show
ImageGetterDelegate imageGetter = delegate (object rowObject)
{
if (rowObject is ElementMappingNode)
{
if (((ElementMappingNode)rowObject).source is UML.Classes.Kernel.Package)
{
return "packageNode";
}
else
{
return "classifierNode";
}
}
if (rowObject is AttributeMappingNode)
{
return "attributeNode";
}
if (rowObject is AssociationMappingNode)
{
return "associationNode";
}
else
{
return string.Empty;
}
};
this.sourceColumn.ImageGetter = imageGetter;
this.targetColumn.ImageGetter = imageGetter;
}
public Mapping SelectedMapping =>
//LinkedTreeNodes link = this.trees.SelectedLink;
//if(link == null) { return null; }
//return link.Mapping;
null;
private MP.MappingNode selectedSourceNode => this.sourceTreeView.SelectedObject as MP.MappingNode;
private MP.MappingNode selectedTargetNode => this.targetTreeView.SelectedObject as MP.MappingNode;
private MP.MappingNode selectedNode { get; set; }
public void loadMappingSet(MP.MappingSet mappingSet)
{
//first clear the existing mappings
this.clear();
//then add the new mappingSet
this.mappingSet = mappingSet;
this.sourceTreeView.Objects = new List<MP.MappingNode>() { mappingSet.source };
this.targetTreeView.Objects = new List<MP.MappingNode>() { mappingSet.target };
//expand the treeviews
this.sourceTreeView.ExpandAll();
this.targetTreeView.ExpandAll();
}
private void clear()
{
this.sourceExpandColumn.HeaderCheckState = CheckState.Unchecked;
this.targetExpandedColumn.HeaderCheckState = CheckState.Unchecked;
this.clearMappingDetails();
}
// export
public event EventHandler exportMappingSet;
void ExportButtonClick(object sender, EventArgs e)
{
this.exportMappingSet?.Invoke(this.mappingSet, e);
}
private void sourceTreeView_SelectedIndexChanged(object sender, EventArgs e)
{
//set the selected node
this.selectedNode = this.selectedSourceNode;
//show the mappings
this.showSourceMappings();
}
private void showSourceMappings()
{
// remove any mappings currently showing
this.clearMappingDetails();
if (this.selectedSourceNode != null)
{
this.showMappings(this.selectedMappings);
foreach (var mapping in this.selectedMappings)
{
this.targetTreeView.Reveal(mapping.target, false);
}
}
}
private void targetTreeView_SelectedIndexChanged(object sender, EventArgs e)
{
//set the selected node
this.selectedNode = this.selectedTargetNode;
//show the mappings
showTargetMappings();
}
private void showTargetMappings()
{
// remove any mappings currently showing
this.clearMappingDetails(); ;
if (this.selectedTargetNode != null)
{
this.showMappings(this.selectedMappings);
foreach (var mapping in this.selectedMappings)
{
this.sourceTreeView.Reveal(mapping.source, false);
}
}
}
private void targetTreeView_CellRightClick(object sender, CellRightClickEventArgs e)
{
//TODO: enableDisable context menu options
}
private void MappingContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
//disable option new empty mapping if node is readonly
var parent = ((ContextMenuStrip)sender).SourceControl;
if (parent == this.sourceTreeView)
{
this.newEmptyMappingToolStripMenuItem.Enabled = !this.selectedSourceNode.isReadOnly;
}
else
{
this.newEmptyMappingToolStripMenuItem.Enabled = !this.selectedTargetNode.isReadOnly;
}
}
private void selectInProjectBrowserToolStripMenuItem_Click(object sender, EventArgs e)
{
var parent = ((ContextMenuStrip)((ToolStripMenuItem)sender).Owner).SourceControl;
if (parent == this.sourceTreeView)
{
this.selectMappingNode(this.selectedSourceNode);
}
else
{
this.selectMappingNode(this.selectedTargetNode);
}
}
private void selectMappingNode(MP.MappingNode node)
{
if (node?.source != null)
{
node.source.select();
}
}
private void openPropertiesToolStripMenuItem_Click(object sender, EventArgs e)
{
var parent = ((ContextMenuStrip)((ToolStripMenuItem)sender).Owner).SourceControl;
if (parent == this.sourceTreeView)
{
this.openMappingNodeProperties(this.selectedSourceNode);
}
else
{
this.openMappingNodeProperties(this.selectedTargetNode);
}
}
private void openMappingNodeProperties(MP.MappingNode node)
{
if (node?.source != null)
{
node.source.openProperties();
}
}
public event EventHandler selectNewMappingTarget;
public event EventHandler selectNewMappingSource;
private void selectNewMappingRootToolStripMenuItem_Click(object sender, EventArgs e)
{
var parent = ((ContextMenuStrip)((ToolStripMenuItem)sender).Owner).SourceControl;
if (parent == this.targetTreeView)
{
selectNewMappingTarget?.Invoke(this.mappingSet, e);
//reload the target view
this.targetTreeView.Objects = new List<MP.MappingNode>() { this.mappingSet.target };
this.targetTreeView.RefreshObject(this.mappingSet.target);
this.targetTreeView.ExpandAll();
}
else
{
selectNewMappingSource?.Invoke(this.mappingSet, e);
}
}
private void newEmptyMappingToolStripMenuItem_Click(object sender, EventArgs e)
{
var parent = ((ContextMenuStrip)((ToolStripMenuItem)sender).Owner).SourceControl;
if (parent == this.sourceTreeView)
{
this.selectedSourceNode.createEmptyMapping(false);
}
if (parent == this.targetTreeView)
{
this.selectedTargetNode.createEmptyMapping(true);
//select the target node again in the view to force showing the mapping details
showTargetMappings();
}
}
private void sourceTreeView_ItemActivate(object sender, EventArgs e)
{
this.selectMappingNode(this.selectedSourceNode);
}
private void targetTreeView_ItemActivate(object sender, EventArgs e)
{
this.selectMappingNode(this.selectedTargetNode);
}
private void targetTreeView_ModelCanDrop(object sender, ModelDropEventArgs e)
{
this.canDrop(e, targetTreeView);
}
public event EventHandler<BrightIdeasSoftware.ModelDropEventArgs> sourceToTargetDropped;
private void targetTreeView_ModelDropped(object sender, ModelDropEventArgs e)
{
sourceToTargetDropped?.Invoke(sender, e);
this.showSourceMappings();
}
private void sourceTreeView_ModelCanDrop(object sender, ModelDropEventArgs e)
{
this.canDrop(e, sourceTreeView);
}
private void canDrop(ModelDropEventArgs e, TreeListView treeListView)
{
var targetNode = e.TargetModel as MP.MappingNode;
var sourceNode = e.SourceModels.Cast<MP.MappingNode>().FirstOrDefault();
var topNode = treeListView.Objects.Cast<MP.MappingNode>().FirstOrDefault();
//
if (targetNode != null && sourceNode != null
//do not allow mapping to self
&& targetNode != sourceNode
//make sure the nodes are not empty
&& targetNode.source != null && sourceNode.source != null
//do not allow to drop on same treeView
&& sourceNode != topNode
&& !sourceNode.isChildOf(topNode))
{
if (sourceNode.isReadOnly)
{
e.Effect = DragDropEffects.None;
e.InfoMessage = "Source item is read-only!";
}
//make sure that they are not already mapped
else if( sourceNode.mappings.Any (x => x.target == targetNode && x.source == sourceNode
|| x.target == sourceNode && x.source == targetNode))
{
e.Effect = DragDropEffects.None;
e.InfoMessage = "Items are already mapped!";
}
else
{
//OK we can create the mapping
e.Effect = DragDropEffects.Link;
e.InfoMessage = "Create new Mapping";
}
}
else
{
e.Effect = DragDropEffects.None;
}
}
public event EventHandler<BrightIdeasSoftware.ModelDropEventArgs> targetToSourceDropped;
private void sourceTreeView_ModelDropped(object sender, ModelDropEventArgs e)
{
targetToSourceDropped?.Invoke(sender, e);
this.showTargetMappings();
}
private void targetTreeView_FormatRow(object sender, FormatRowEventArgs e)
{
if (this.selectedMappings.Any(x => x.target == e.Model))
{
e.Item.BackColor = Color.LightYellow;
//e.Item.Font = new Font(e.Item.Font, FontStyle.Bold);
}
}
private void sourceTreeView_FormatRow(object sender, FormatRowEventArgs e)
{
if (this.selectedMappings.Any(x => x.source == e.Model))
{
e.Item.BackColor = Color.LightYellow;
//e.Item.Font = new Font(e.Item.Font, FontStyle.Bold);
}
}
private void sourceTreeView_HeaderCheckBoxChanging(object sender, HeaderCheckBoxChangingEventArgs e)
{
setAllExpanded(this.sourceTreeView, e.NewCheckState == CheckState.Checked, false);
}
private void targetTreeView_HeaderCheckBoxChanging(object sender, HeaderCheckBoxChangingEventArgs e)
{
setAllExpanded(this.targetTreeView, e.NewCheckState == CheckState.Checked, true);
}
private void setAllExpanded(TreeListView treeView, bool expand, bool isTarget)
{
//set expanded property on all nodes
var root = treeView.Objects.Cast<MappingNode>().FirstOrDefault();
setExpanded(root,expand, isTarget);
treeView.RefreshObject(root);
//expand all
treeView.ExpandAll();
}
private void setExpanded(MappingNode node, bool expand, bool isTarget)
{
//don't do anything if null
if (node == null) return;
//set expanded property
if (!node.showAll)
{
node.setChildNodes();
if (! isTarget)
{
node.getMyMappings();
}
}
node.showAll = expand;
//do the same for the childnodes
foreach (MappingNode subNode in node.childNodes)
{
setExpanded(subNode, expand, isTarget);
}
}
private void sourceTreeView_FormatCell(object sender, FormatCellEventArgs e)
{
if (e.ColumnIndex == this.sourceColumn.Index)
{
setAbstractItalic(e);
}
}
private static void setAbstractItalic(FormatCellEventArgs e)
{
var node = e.Model as ElementMappingNode;
if (node != null)
{
var sourceElement = node.source as UML.Classes.Kernel.Classifier;
if (sourceElement != null && sourceElement.isAbstract)
{
e.SubItem.Font = new Font(e.SubItem.Font, FontStyle.Italic);
}
}
}
private void targetTreeView_FormatCell(object sender, FormatCellEventArgs e)
{
if (e.ColumnIndex == this.targetColumn.Index)
{
setAbstractItalic(e);
}
}
private void targetTreeView_SubItemChecking(object sender, SubItemCheckingEventArgs e)
{
var node = e.RowObject as MappingNode;
//make sure the childeNodes are set on target nodes as they don't automatically get all child nodes
if (node != null && e.NewValue == CheckState.Checked)
{
//make sure to set showAll property to allow the GUI to expand
node.showAll = true;
node.setChildNodes();
this.targetTreeView.Expand(node);
}
}
private void sourceTreeView_SubItemChecking(object sender, SubItemCheckingEventArgs e)
{
var node = e.RowObject as MappingNode;
//make sure the childeNodes are set as they don't automatically get all child nodes
if (node != null && e.NewValue == CheckState.Checked)
{
//make sure to set showAll property to allow the GUI to expand
node.showAll = true;
//get child nodes
node.setChildNodes();
//make sure we get the mappings
node.getMyMappings();
foreach (var subNode in node.allChildNodes)
{
//and the mappings of the childNodes
subNode.getMyMappings();
}
//then expand
this.sourceTreeView.Expand(node);
//reload the target to make sure all target nodes for the mappings are there
this.targetTreeView.RefreshObject(node.mappingSet.target);
}
}
}
}
| 38.130435 | 112 | 0.560954 | [
"BSD-2-Clause"
] | CuchulainX/Enterprise-Architect-Toolpack | EAMapping/MappingControlGUI.cs | 20,173 | C# |
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace OldStylePlatformingGame
{
#if WINDOWS || LINUX
/// <summary>
/// The main class.
/// </summary>
public static class Program
{
private static Game1 game;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
game = new Game1();
game.Run();
}
public static Game1 Instance { get { return game; } }
}
#endif
}
| 19.258065 | 61 | 0.562814 | [
"MIT"
] | adamuso/OldStylePlatformingGame | OldStylePlatformingGame/Program.cs | 599 | C# |
//--------------------------------------------------------
// This code is generated by AutoFastGenerator.
// You should not modify the code.
//--------------------------------------------------------
namespace FlowScriptEngineBasicExtension.FlowSourceObjects.Hashtable
{
public partial class ParseFloatValueFlowSourceObject
{
public override object GetPropertyValue(string propertyName)
{
switch (propertyName)
{
case "Value":
return Value;
default:
return null;
}
}
protected override void SetPropertyValue(string propertyName, object value)
{
switch (propertyName)
{
case "Default":
Default = (System.Single)value;
break;
case "Hashtable":
Hashtable = (System.Collections.Generic.Dictionary<System.Object, System.Object>)value;
break;
case "Key":
Key = (System.String)value;
break;
}
}
public override void ConnectEvent(string eventName, FlowScriptEngine.FlowEventHandler eventHandler)
{
switch (eventName)
{
case "ParseFailed":
ParseFailed += new FlowScriptEngine.FlowEventHandler(eventHandler);
break;
}
}
}
}
| 31.395833 | 107 | 0.473789 | [
"Apache-2.0"
] | KHCmaster/PPD | Win/FlowScriptEngineBasicExtension/FlowSourceObjects/Hashtable/ParseFloatValueFlowSourceObject.AutoFast.cs | 1,509 | C# |
// /*
// * Copyright (c) 2014, Furore (info@furore.com) and contributors
// * See the file CONTRIBUTORS for details.
// *
// * This file is licensed under the BSD 3-Clause license
// * available at https://raw.github.com/furore-fhir/spark/master/LICENSE
// */
namespace Spark.Engine.Service.FhirServiceExtensions
{
using System.Collections.Generic;
using Core;
public interface ISnapshotPaginationCalculator
{
IEnumerable<IKey> GetKeysForPage(Snapshot snapshot, int? start = null);
int GetIndexForLastPage(Snapshot snapshot);
int? GetIndexForNextPage(Snapshot snapshot, int? start = null);
int? GetIndexForPreviousPage(Snapshot snapshot, int? start = null);
}
} | 34.333333 | 79 | 0.704577 | [
"BSD-3-Clause"
] | jjrdk/spark | src/Spark.Engine/Service/FhirServiceExtensions/ISnapshotPaginationCalculator.cs | 721 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Lyu
{
public class GenBezierCoordObjs : MonoBehaviour {
public BezierCurve _BCurve;
public float _AlongStart = 0.0f, _AlongStep = 0.05f;
public float _ShiftStart = 0.5f, _ShiftStep = 0.0f;
public float _DepthStart = 0.0f, _DepthStep = 0.0f;
public int _count = 20;
public List<BezierCurveCoord> _BCoords = new List<BezierCurveCoord> ();
public GameObject _Prefab;
public UnityEvent _Generated;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void SetCount(int cnt)
{
_count = cnt;
}
public void SetAlongStep(float astep)
{
_AlongStep = astep;
}
[ContextMenu("GenerateObjs")]
public void GenerateObjs()
{
//_AlongStep = 1.0f / (float)_count;
for (int i = 0; i < _count; i++) {
GameObject newObj = Instantiate (_Prefab,Vector3.zero,Quaternion.identity) as GameObject;
newObj.transform.SetParent (transform);
BezierCurveCoord bcd = newObj.AddComponent<BezierCurveCoord> ();
bcd._bCurve = _BCurve;
bcd._Along = _AlongStart + _AlongStep * i;
bcd._Shift = _ShiftStart + _ShiftStep * i;
bcd._Depth = _DepthStart + _DepthStep * i;
_BCoords.Add (bcd);
}
_Generated.Invoke ();
}
[ContextMenu("ClearObjs")]
private void ClearObjsImmediate()
{
foreach (BezierCurveCoord bcd in _BCoords) {
DestroyImmediate (bcd.gameObject);
}
_BCoords.Clear ();
}
public void DisableBezierCoordsUpdating()
{
foreach (BezierCurveCoord bcc in _BCoords) {
bcc._UpdatingPos = false;
}
}
public void ClearObjs()
{
foreach (BezierCurveCoord bcd in _BCoords) {
Destroy (bcd.gameObject);
}
_BCoords.Clear ();
}
}
}
| 21.647059 | 93 | 0.678261 | [
"MIT"
] | iniwap/LianQiClient | Assets/MiroChessBord/Utils/SpecialCoordSystem/GenBezierCoordObjs.cs | 1,842 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OfficeDevPnP.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Enums;
namespace OfficeDevPnP.Core.Tests.AppModelExtensions
{
[TestClass()]
public class StructuralNavigationExtensionsTests
{
static string CurrentDynamicChildLimit = "__CurrentDynamicChildLimit";
static string GlobalDynamicChildLimit = "__GlobalDynamicChildLimit";
#region Test initialize and cleanup
static bool deactivateSiteFeatureOnTeardown = false;
static bool deactivateWebFeatureOnTeardown = false;
[ClassInitialize()]
public static void ClassInit(TestContext context)
{
using (var ctx = TestCommon.CreateClientContext())
{
Web web;
Site site;
site = ctx.Site;
web = ctx.Site.RootWeb;
if (!site.IsFeatureActive(Constants.FeatureId_Site_Publishing))
{
site.ActivateFeature(Constants.FeatureId_Site_Publishing);
deactivateSiteFeatureOnTeardown = true;
}
if (!web.IsFeatureActive(Constants.FeatureId_Web_Publishing))
{
site.RootWeb.ActivateFeature(Constants.FeatureId_Web_Publishing);
deactivateWebFeatureOnTeardown = true;
}
}
}
[ClassCleanup()]
public static void ClassCleanup()
{
using (var ctx = TestCommon.CreateClientContext())
{
if (deactivateSiteFeatureOnTeardown)
{
ctx.Site.DeactivateFeature(Constants.FeatureId_Site_Publishing);
}
if (deactivateWebFeatureOnTeardown)
{
ctx.Web.DeactivateFeature(Constants.FeatureId_Web_Publishing);
}
}
}
#endregion
#region Area navigation settings tests (AreaNavigationSettings.aspx) / only applies to publishing sites
[TestMethod]
public void GetNavigationSettingsTest()
{
using (var clientContext = TestCommon.CreateClientContext())
{
//Set MaxDynamicItems upfront to the default value
clientContext.Load(clientContext.Web, w => w.AllProperties);
clientContext.ExecuteQueryRetry();
clientContext.Web.AllProperties[CurrentDynamicChildLimit] = 18;
clientContext.Web.AllProperties[GlobalDynamicChildLimit] = 22;
clientContext.Web.Update();
clientContext.ExecuteQueryRetry();
var web = clientContext.Web;
AreaNavigationEntity nav = web.GetNavigationSettings();
Assert.AreEqual(18, (int)nav.CurrentNavigation.MaxDynamicItems);
Assert.AreEqual(22, (int)nav.GlobalNavigation.MaxDynamicItems);
}
}
[TestMethod]
public void UpdateNavigationSettingsTest()
{
using (var clientContext = TestCommon.CreateClientContext())
{
//Set MaxDynamicItems upfront to the default value
clientContext.Load(clientContext.Web, w => w.AllProperties);
clientContext.ExecuteQueryRetry();
clientContext.Web.AllProperties[CurrentDynamicChildLimit] = 20;
clientContext.Web.AllProperties[GlobalDynamicChildLimit] = 20;
clientContext.Web.Update();
clientContext.ExecuteQueryRetry();
AreaNavigationEntity nav = new AreaNavigationEntity();
nav.GlobalNavigation.ManagedNavigation = false;
nav.GlobalNavigation.MaxDynamicItems = 13;
nav.GlobalNavigation.ShowSubsites = true;
nav.GlobalNavigation.ShowPages = true;
nav.CurrentNavigation.ManagedNavigation = false;
nav.CurrentNavigation.MaxDynamicItems = 15;
nav.CurrentNavigation.ShowSubsites = true;
nav.CurrentNavigation.ShowPages = true;
nav.Sorting = StructuralNavigationSorting.Automatically;
nav.SortBy = StructuralNavigationSortBy.Title ;
nav.SortAscending = true;
clientContext.Web.UpdateNavigationSettings(nav);
clientContext.Load(clientContext.Web, w => w.AllProperties);
clientContext.ExecuteQueryRetry();
int currentDynamicChildLimit = -1;
int.TryParse(clientContext.Web.AllProperties[CurrentDynamicChildLimit].ToString(), out currentDynamicChildLimit);
int globalDynamicChildLimit = -1;
int.TryParse(clientContext.Web.AllProperties[GlobalDynamicChildLimit].ToString(), out globalDynamicChildLimit);
Assert.AreEqual(13, globalDynamicChildLimit);
Assert.AreEqual(15, currentDynamicChildLimit);
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Sorting was set to ManuallyButPagesAutomatically without pages being shown in structural navigation")]
public void UpdateNavigationSettings2Test()
{
using (var clientContext = TestCommon.CreateClientContext())
{
var web = clientContext.Web;
AreaNavigationEntity nav = new AreaNavigationEntity();
nav.GlobalNavigation.MaxDynamicItems = 12;
nav.GlobalNavigation.ShowSubsites = true;
nav.GlobalNavigation.ShowPages = false;
nav.CurrentNavigation.MaxDynamicItems = 14;
nav.CurrentNavigation.ShowSubsites = false;
nav.CurrentNavigation.ShowPages = false;
// setting this throws an exception
nav.Sorting = StructuralNavigationSorting.ManuallyButPagesAutomatically;
nav.SortBy = StructuralNavigationSortBy.LastModifiedDate;
nav.SortAscending = false;
web.UpdateNavigationSettings(nav);
}
}
#endregion
}
}
| 41.291139 | 158 | 0.597486 | [
"MIT"
] | phrueegsegger/PnP-Sites-Core | Core/OfficeDevPnP.Core.Tests/Extensions/StructuralNavigationExtensionsTests.cs | 6,526 | C# |
// /*
// * Copyright (c) 2014, Furore (info@furore.com) and contributors
// * See the file CONTRIBUTORS for details.
// *
// * This file is licensed under the BSD 3-Clause license
// * available at https://raw.github.com/furore-fhir/spark/master/LICENSE
// */
namespace Spark.Postgres
{
using Marten;
public class FhirRegistry : MartenRegistry
{
public FhirRegistry()
{
For<EntryEnvelope>()
.Index(x => x.Id)
.Duplicate(x => x.ResourceType)
.Duplicate(x => x.Resource.Id)
.Duplicate(x => x.Resource.VersionId)
.Duplicate(x => x.ResourceKey)
.Duplicate(x => x.Deleted)
.Duplicate(x => x.IsPresent)
.Index(x => x.When)
.GinIndexJsonData();
For<IndexEntry>()
.Identity(x => x.Id)
.Index(x => x.Id)
.Duplicate(x => x.ResourceType)
.GinIndexJsonData();
}
}
}
| 29.571429 | 74 | 0.50628 | [
"BSD-3-Clause"
] | jjrdk/spark | src/Spark.Postgres/FhirRegistry.cs | 1,037 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2015-2020 Rasmus Mikkelsen
// Copyright (c) 2015-2020 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Threading;
using System.Threading.Tasks;
using EventFlow.Aggregates;
using EventFlow.ReadStores;
using EventFlow.TestHelpers.Aggregates;
using EventFlow.TestHelpers.Aggregates.Events;
namespace EventFlow.Tests.UnitTests.ReadStores
{
public class TestAsyncReadModel : IReadModel, IAmAsyncReadModelFor<ThingyAggregate, ThingyId, ThingyPingEvent>
{
public Task ApplyAsync(
IReadModelContext context,
IDomainEvent<ThingyAggregate, ThingyId, ThingyPingEvent> domainEvent,
CancellationToken cancellationToken )
{
return Task.Delay( 0, cancellationToken );
}
}
}
| 43.181818 | 114 | 0.751053 | [
"MIT"
] | AhLay/EventFlow | Source/EventFlow.Tests/UnitTests/ReadStores/TestAsyncReadModel.cs | 1,900 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Shared.AI;
using Robust.Client.Graphics;
using Robust.Client.Player;
using Robust.Shared.Enums;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Timing;
namespace Content.Client.GameObjects.EntitySystems.AI
{
#if DEBUG
public class ClientPathfindingDebugSystem : EntitySystem
{
private PathfindingDebugMode _modes = PathfindingDebugMode.None;
private float _routeDuration = 4.0f; // How long before we remove a route from the overlay
private DebugPathfindingOverlay? _overlay;
public override void Initialize()
{
base.Initialize();
SubscribeNetworkEvent<SharedAiDebug.AStarRouteMessage>(HandleAStarRouteMessage);
SubscribeNetworkEvent<SharedAiDebug.JpsRouteMessage>(HandleJpsRouteMessage);
SubscribeNetworkEvent<SharedAiDebug.PathfindingGraphMessage>(HandleGraphMessage);
SubscribeNetworkEvent<SharedAiDebug.ReachableChunkRegionsDebugMessage>(HandleRegionsMessage);
SubscribeNetworkEvent<SharedAiDebug.ReachableCacheDebugMessage>(HandleCachedRegionsMessage);
// I'm lazy
EnableOverlay();
}
public override void Shutdown()
{
base.Shutdown();
DisableOverlay();
}
private void HandleAStarRouteMessage(SharedAiDebug.AStarRouteMessage message)
{
if ((_modes & PathfindingDebugMode.Nodes) != 0 ||
(_modes & PathfindingDebugMode.Route) != 0)
{
_overlay?.AStarRoutes.Add(message);
Timer.Spawn(TimeSpan.FromSeconds(_routeDuration), () =>
{
if (_overlay == null) return;
_overlay.AStarRoutes.Remove(message);
});
}
}
private void HandleJpsRouteMessage(SharedAiDebug.JpsRouteMessage message)
{
if ((_modes & PathfindingDebugMode.Nodes) != 0 ||
(_modes & PathfindingDebugMode.Route) != 0)
{
_overlay?.JpsRoutes.Add(message);
Timer.Spawn(TimeSpan.FromSeconds(_routeDuration), () =>
{
if (_overlay == null) return;
_overlay.JpsRoutes.Remove(message);
});
}
}
private void HandleGraphMessage(SharedAiDebug.PathfindingGraphMessage message)
{
EnableOverlay().UpdateGraph(message.Graph);
}
private void HandleRegionsMessage(SharedAiDebug.ReachableChunkRegionsDebugMessage message)
{
EnableOverlay().UpdateRegions(message.GridId, message.Regions);
}
private void HandleCachedRegionsMessage(SharedAiDebug.ReachableCacheDebugMessage message)
{
EnableOverlay().UpdateCachedRegions(message.GridId, message.Regions, message.Cached);
}
private DebugPathfindingOverlay EnableOverlay()
{
if (_overlay != null)
{
return _overlay;
}
var overlayManager = IoCManager.Resolve<IOverlayManager>();
_overlay = new DebugPathfindingOverlay {Modes = _modes};
overlayManager.AddOverlay(_overlay);
return _overlay;
}
private void DisableOverlay()
{
if (_overlay == null)
{
return;
}
_overlay.Modes = 0;
var overlayManager = IoCManager.Resolve<IOverlayManager>();
overlayManager.RemoveOverlay(_overlay);
_overlay = null;
}
public void Disable()
{
_modes = PathfindingDebugMode.None;
DisableOverlay();
}
private void EnableMode(PathfindingDebugMode tooltip)
{
_modes |= tooltip;
if (_modes != 0)
{
EnableOverlay();
}
if (_overlay != null)
{
_overlay.Modes = _modes;
}
if (tooltip == PathfindingDebugMode.Graph)
{
RaiseNetworkEvent(new SharedAiDebug.RequestPathfindingGraphMessage());
}
if (tooltip == PathfindingDebugMode.Regions)
{
RaiseNetworkEvent(new SharedAiDebug.SubscribeReachableMessage());
}
// TODO: Request region graph, although the client system messages didn't seem to be going through anymore
// So need further investigation.
}
private void DisableMode(PathfindingDebugMode mode)
{
if (mode == PathfindingDebugMode.Regions && (_modes & PathfindingDebugMode.Regions) != 0)
{
RaiseNetworkEvent(new SharedAiDebug.UnsubscribeReachableMessage());
}
_modes &= ~mode;
if (_modes == 0)
{
DisableOverlay();
}
else if (_overlay != null)
{
_overlay.Modes = _modes;
}
}
public void ToggleTooltip(PathfindingDebugMode mode)
{
if ((_modes & mode) != 0)
{
DisableMode(mode);
}
else
{
EnableMode(mode);
}
}
}
internal sealed class DebugPathfindingOverlay : Overlay
{
private readonly IEyeManager _eyeManager;
private readonly IPlayerManager _playerManager;
// TODO: Add a box like the debug one and show the most recent path stuff
public override OverlaySpace Space => OverlaySpace.ScreenSpace;
private readonly ShaderInstance _shader;
public PathfindingDebugMode Modes { get; set; } = PathfindingDebugMode.None;
// Graph debugging
public readonly Dictionary<int, List<Vector2>> Graph = new();
private readonly Dictionary<int, Color> _graphColors = new();
// Cached regions
public readonly Dictionary<GridId, Dictionary<int, List<Vector2>>> CachedRegions =
new();
private readonly Dictionary<GridId, Dictionary<int, Color>> _cachedRegionColors =
new();
// Regions
public readonly Dictionary<GridId, Dictionary<int, Dictionary<int, List<Vector2>>>> Regions =
new();
private readonly Dictionary<GridId, Dictionary<int, Dictionary<int, Color>>> _regionColors =
new();
// Route debugging
// As each pathfinder is very different you'll likely want to draw them completely different
public readonly List<SharedAiDebug.AStarRouteMessage> AStarRoutes = new();
public readonly List<SharedAiDebug.JpsRouteMessage> JpsRoutes = new();
public DebugPathfindingOverlay()
{
_shader = IoCManager.Resolve<IPrototypeManager>().Index<ShaderPrototype>("unshaded").Instance();
_eyeManager = IoCManager.Resolve<IEyeManager>();
_playerManager = IoCManager.Resolve<IPlayerManager>();
}
#region Graph
public void UpdateGraph(Dictionary<int, List<Vector2>> graph)
{
Graph.Clear();
_graphColors.Clear();
var robustRandom = IoCManager.Resolve<IRobustRandom>();
foreach (var (chunk, nodes) in graph)
{
Graph[chunk] = nodes;
_graphColors[chunk] = new Color(robustRandom.NextFloat(), robustRandom.NextFloat(),
robustRandom.NextFloat(), 0.3f);
}
}
private void DrawGraph(DrawingHandleScreen screenHandle, Box2 viewport)
{
foreach (var (chunk, nodes) in Graph)
{
foreach (var tile in nodes)
{
if (!viewport.Contains(tile)) continue;
var screenTile = _eyeManager.WorldToScreen(tile);
var box = new UIBox2(
screenTile.X - 15.0f,
screenTile.Y - 15.0f,
screenTile.X + 15.0f,
screenTile.Y + 15.0f);
screenHandle.DrawRect(box, _graphColors[chunk]);
}
}
}
#endregion
#region Regions
//Server side debugger should increment every region
public void UpdateCachedRegions(GridId gridId, Dictionary<int, List<Vector2>> messageRegions, bool cached)
{
if (!CachedRegions.ContainsKey(gridId))
{
CachedRegions.Add(gridId, new Dictionary<int, List<Vector2>>());
_cachedRegionColors.Add(gridId, new Dictionary<int, Color>());
}
foreach (var (region, nodes) in messageRegions)
{
CachedRegions[gridId][region] = nodes;
if (cached)
{
_cachedRegionColors[gridId][region] = Color.Blue.WithAlpha(0.3f);
}
else
{
_cachedRegionColors[gridId][region] = Color.Green.WithAlpha(0.3f);
}
Timer.Spawn(3000, () =>
{
if (CachedRegions[gridId].ContainsKey(region))
{
CachedRegions[gridId].Remove(region);
_cachedRegionColors[gridId].Remove(region);
}
});
}
}
private void DrawCachedRegions(DrawingHandleScreen screenHandle, Box2 viewport)
{
var attachedEntity = _playerManager.LocalPlayer?.ControlledEntity;
if (attachedEntity == null || !CachedRegions.TryGetValue(attachedEntity.Transform.GridID, out var entityRegions))
{
return;
}
foreach (var (region, nodes) in entityRegions)
{
foreach (var tile in nodes)
{
if (!viewport.Contains(tile)) continue;
var screenTile = _eyeManager.WorldToScreen(tile);
var box = new UIBox2(
screenTile.X - 15.0f,
screenTile.Y - 15.0f,
screenTile.X + 15.0f,
screenTile.Y + 15.0f);
screenHandle.DrawRect(box, _cachedRegionColors[attachedEntity.Transform.GridID][region]);
}
}
}
public void UpdateRegions(GridId gridId, Dictionary<int, Dictionary<int, List<Vector2>>> messageRegions)
{
if (!Regions.ContainsKey(gridId))
{
Regions.Add(gridId, new Dictionary<int, Dictionary<int, List<Vector2>>>());
_regionColors.Add(gridId, new Dictionary<int, Dictionary<int, Color>>());
}
var robustRandom = IoCManager.Resolve<IRobustRandom>();
foreach (var (chunk, regions) in messageRegions)
{
Regions[gridId][chunk] = new Dictionary<int, List<Vector2>>();
_regionColors[gridId][chunk] = new Dictionary<int, Color>();
foreach (var (region, nodes) in regions)
{
Regions[gridId][chunk].Add(region, nodes);
_regionColors[gridId][chunk][region] = new Color(robustRandom.NextFloat(), robustRandom.NextFloat(),
robustRandom.NextFloat(), 0.3f);
}
}
}
private void DrawRegions(DrawingHandleScreen screenHandle, Box2 viewport)
{
var attachedEntity = _playerManager.LocalPlayer?.ControlledEntity;
if (attachedEntity == null || !Regions.TryGetValue(attachedEntity.Transform.GridID, out var entityRegions))
{
return;
}
foreach (var (chunk, regions) in entityRegions)
{
foreach (var (region, nodes) in regions)
{
foreach (var tile in nodes)
{
if (!viewport.Contains(tile)) continue;
var screenTile = _eyeManager.WorldToScreen(tile);
var box = new UIBox2(
screenTile.X - 15.0f,
screenTile.Y - 15.0f,
screenTile.X + 15.0f,
screenTile.Y + 15.0f);
screenHandle.DrawRect(box, _regionColors[attachedEntity.Transform.GridID][chunk][region]);
}
}
}
}
#endregion
#region Pathfinder
private void DrawAStarRoutes(DrawingHandleScreen screenHandle, Box2 viewport)
{
foreach (var route in AStarRoutes)
{
// Draw box on each tile of route
foreach (var position in route.Route)
{
if (!viewport.Contains(position)) continue;
var screenTile = _eyeManager.WorldToScreen(position);
// worldHandle.DrawLine(position, nextWorld.Value, Color.Blue);
var box = new UIBox2(
screenTile.X - 15.0f,
screenTile.Y - 15.0f,
screenTile.X + 15.0f,
screenTile.Y + 15.0f);
screenHandle.DrawRect(box, Color.Orange.WithAlpha(0.25f));
}
}
}
private void DrawAStarNodes(DrawingHandleScreen screenHandle, Box2 viewport)
{
foreach (var route in AStarRoutes)
{
var highestGScore = route.GScores.Values.Max();
foreach (var (tile, score) in route.GScores)
{
if ((route.Route.Contains(tile) && (Modes & PathfindingDebugMode.Route) != 0) ||
!viewport.Contains(tile))
{
continue;
}
var screenTile = _eyeManager.WorldToScreen(tile);
var box = new UIBox2(
screenTile.X - 15.0f,
screenTile.Y - 15.0f,
screenTile.X + 15.0f,
screenTile.Y + 15.0f);
screenHandle.DrawRect(box, new Color(
0.0f,
score / highestGScore,
1.0f - (score / highestGScore),
0.1f));
}
}
}
private void DrawJpsRoutes(DrawingHandleScreen screenHandle, Box2 viewport)
{
foreach (var route in JpsRoutes)
{
// Draw box on each tile of route
foreach (var position in route.Route)
{
if (!viewport.Contains(position)) continue;
var screenTile = _eyeManager.WorldToScreen(position);
// worldHandle.DrawLine(position, nextWorld.Value, Color.Blue);
var box = new UIBox2(
screenTile.X - 15.0f,
screenTile.Y - 15.0f,
screenTile.X + 15.0f,
screenTile.Y + 15.0f);
screenHandle.DrawRect(box, Color.Orange.WithAlpha(0.25f));
}
}
}
private void DrawJpsNodes(DrawingHandleScreen screenHandle, Box2 viewport)
{
foreach (var route in JpsRoutes)
{
foreach (var tile in route.JumpNodes)
{
if ((route.Route.Contains(tile) && (Modes & PathfindingDebugMode.Route) != 0) ||
!viewport.Contains(tile))
{
continue;
}
var screenTile = _eyeManager.WorldToScreen(tile);
var box = new UIBox2(
screenTile.X - 15.0f,
screenTile.Y - 15.0f,
screenTile.X + 15.0f,
screenTile.Y + 15.0f);
screenHandle.DrawRect(box, new Color(
0.0f,
1.0f,
0.0f,
0.2f));
}
}
}
#endregion
protected override void Draw(in OverlayDrawArgs args)
{
if (Modes == 0)
{
return;
}
var screenHandle = args.ScreenHandle;
screenHandle.UseShader(_shader);
var viewport = _eyeManager.GetWorldViewport();
if ((Modes & PathfindingDebugMode.Route) != 0)
{
DrawAStarRoutes(screenHandle, viewport);
DrawJpsRoutes(screenHandle, viewport);
}
if ((Modes & PathfindingDebugMode.Nodes) != 0)
{
DrawAStarNodes(screenHandle, viewport);
DrawJpsNodes(screenHandle, viewport);
}
if ((Modes & PathfindingDebugMode.Graph) != 0)
{
DrawGraph(screenHandle, viewport);
}
if ((Modes & PathfindingDebugMode.CachedRegions) != 0)
{
DrawCachedRegions(screenHandle, viewport);
}
if ((Modes & PathfindingDebugMode.Regions) != 0)
{
DrawRegions(screenHandle, viewport);
}
}
}
[Flags]
public enum PathfindingDebugMode : byte
{
None = 0,
Route = 1 << 0,
Graph = 1 << 1,
Nodes = 1 << 2,
CachedRegions = 1 << 3,
Regions = 1 << 4,
}
#endif
}
| 34.992293 | 125 | 0.516491 | [
"MIT"
] | BingoJohnson/space-station-14 | Content.Client/GameObjects/EntitySystems/AI/ClientPathfindingDebugSystem.cs | 18,163 | C# |
using System.Windows.Forms;
namespace ScannerProject
{
partial class f_AddOrRemoveStudentForm
{
/// <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 Windows Form 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.components = new System.ComponentModel.Container();
this.listBox_StudentsInClass = new System.Windows.Forms.ListBox();
this.b_Save = new System.Windows.Forms.Button();
this.l_Help = new System.Windows.Forms.Label();
this.timer_Scanner = new System.Windows.Forms.Timer(this.components);
this.textBox_AddStudent = new System.Windows.Forms.TextBox();
this.button_AddStudent = new System.Windows.Forms.Button();
this.SuspendLayout();
//this.Form1_FormClosed += new FormClosedEventHandler(Form1_FormClosed);
//
// listBox_StudentsInClass
//
this.listBox_StudentsInClass.FormattingEnabled = true;
this.listBox_StudentsInClass.Location = new System.Drawing.Point(292, 11);
this.listBox_StudentsInClass.Name = "listBox_StudentsInClass";
this.listBox_StudentsInClass.Size = new System.Drawing.Size(204, 316);
this.listBox_StudentsInClass.TabIndex = 0;
this.listBox_StudentsInClass.SelectedIndexChanged += new System.EventHandler(this.listBox_StudentsInClass_SelectedIndexChanged);
//
// b_Save
//
this.b_Save.Location = new System.Drawing.Point(52, 263);
this.b_Save.Name = "b_Save";
this.b_Save.Size = new System.Drawing.Size(186, 64);
this.b_Save.TabIndex = 1;
this.b_Save.Text = "Save";
this.b_Save.UseVisualStyleBackColor = true;
this.b_Save.Click += new System.EventHandler(this.b_Save_Click);
//
// l_Help
//
this.l_Help.AutoSize = true;
this.l_Help.Location = new System.Drawing.Point(13, 12);
this.l_Help.Name = "l_Help";
this.l_Help.Size = new System.Drawing.Size(37, 13);
this.l_Help.TabIndex = 2;
this.l_Help.Text = "l_Help";
//
// textBox_AddStudent
//
this.textBox_AddStudent.Location = new System.Drawing.Point(52, 187);
this.textBox_AddStudent.Name = "textBox_AddStudent";
this.textBox_AddStudent.Size = new System.Drawing.Size(186, 20);
this.textBox_AddStudent.TabIndex = 3;
//
// button_AddStudent
//
this.button_AddStudent.Location = new System.Drawing.Point(105, 213);
this.button_AddStudent.Name = "button_AddStudent";
this.button_AddStudent.Size = new System.Drawing.Size(75, 23);
this.button_AddStudent.TabIndex = 4;
this.button_AddStudent.Text = "+ Student";
this.button_AddStudent.UseVisualStyleBackColor = true;
this.button_AddStudent.Click += new System.EventHandler(this.button_AddStudent_Click);
//
// f_AddOrRemoveStudentForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Snow;
this.ClientSize = new System.Drawing.Size(508, 339);
this.Controls.Add(this.button_AddStudent);
this.Controls.Add(this.textBox_AddStudent);
this.Controls.Add(this.l_Help);
this.Controls.Add(this.b_Save);
this.Controls.Add(this.listBox_StudentsInClass);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "f_AddOrRemoveStudentForm";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox listBox_StudentsInClass;
private System.Windows.Forms.Button b_Save;
private System.Windows.Forms.Label l_Help;
private System.Windows.Forms.Timer timer_Scanner;
private System.Windows.Forms.TextBox textBox_AddStudent;
private System.Windows.Forms.Button button_AddStudent;
public object Form1_FormClosed { get; private set; }
}
} | 43.381356 | 140 | 0.610666 | [
"MIT"
] | rohitrtk/ScannerProject | f_AddOrRemoveStudentForm.Designer.cs | 5,121 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Tests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.CosmosElements;
using Microsoft.Azure.Cosmos.Diagnostics;
using Microsoft.Azure.Cosmos.Query;
using Microsoft.Azure.Cosmos.Query.Core;
using Microsoft.Azure.Cosmos.Query.Core.ContinuationTokens;
using Microsoft.Azure.Cosmos.Query.Core.ExecutionComponent;
using Microsoft.Azure.Cosmos.Query.Core.ExecutionComponent.Aggregate;
using Microsoft.Azure.Cosmos.Query.Core.ExecutionComponent.Distinct;
using Microsoft.Azure.Cosmos.Query.Core.ExecutionComponent.SkipTake;
using Microsoft.Azure.Cosmos.Query.Core.ExecutionContext;
using Microsoft.Azure.Cosmos.Query.Core.Metrics;
using Microsoft.Azure.Cosmos.Query.Core.Monads;
using Microsoft.Azure.Cosmos.Query.Core.QueryClient;
using Microsoft.Azure.Cosmos.Query.Core.QueryPlan;
using Microsoft.Azure.Cosmos.Resource.CosmosExceptions;
using Microsoft.Azure.Documents;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class CosmosQueryUnitTests
{
[TestMethod]
public void VerifyNegativeCosmosQueryResponseStream()
{
string contianerRid = "mockContainerRid";
string errorMessage = "TestErrorMessage";
string activityId = "TestActivityId";
double requestCharge = 42.42;
CosmosDiagnosticsContext diagnostics = new CosmosDiagnosticsContextCore();
CosmosException cosmosException = CosmosExceptionFactory.CreateBadRequestException(errorMessage, diagnosticsContext: diagnostics);
diagnostics.GetOverallScope().Dispose();
QueryResponse queryResponse = QueryResponse.CreateFailure(
statusCode: HttpStatusCode.NotFound,
cosmosException: cosmosException,
requestMessage: null,
responseHeaders: new CosmosQueryResponseMessageHeaders(
null,
null,
ResourceType.Document,
contianerRid)
{
RequestCharge = requestCharge,
ActivityId = activityId
},
diagnostics: diagnostics);
Assert.AreEqual(HttpStatusCode.NotFound, queryResponse.StatusCode);
Assert.AreEqual(cosmosException.Message, queryResponse.ErrorMessage);
Assert.AreEqual(requestCharge, queryResponse.Headers.RequestCharge);
Assert.AreEqual(activityId, queryResponse.Headers.ActivityId);
Assert.AreEqual(diagnostics, queryResponse.DiagnosticsContext);
Assert.IsNull(queryResponse.Content);
}
[TestMethod]
public void VerifyCosmosQueryResponseStream()
{
string contianerRid = "mockContainerRid";
(QueryResponseCore response, IList<ToDoItem> items) = QueryResponseMessageFactory.Create(
itemIdPrefix: $"TestPage",
continuationToken: "SomeContinuationToken",
collectionRid: contianerRid,
itemCount: 100);
QueryResponseCore responseCore = response;
QueryResponse queryResponse = QueryResponse.CreateSuccess(
result: responseCore.CosmosElements,
count: responseCore.CosmosElements.Count,
responseLengthBytes: responseCore.ResponseLengthBytes,
serializationOptions: null,
responseHeaders: new CosmosQueryResponseMessageHeaders(
responseCore.ContinuationToken,
responseCore.DisallowContinuationTokenMessage,
ResourceType.Document,
contianerRid)
{
RequestCharge = responseCore.RequestCharge,
ActivityId = responseCore.ActivityId
},
diagnostics: new CosmosDiagnosticsContextCore());
using (Stream stream = queryResponse.Content)
{
using (Stream innerStream = queryResponse.Content)
{
Assert.IsTrue(object.ReferenceEquals(stream, innerStream), "Content should return the same stream");
}
}
}
[TestMethod]
public void VerifyItemQueryResponseResult()
{
string contianerRid = "mockContainerRid";
(QueryResponseCore response, IList<ToDoItem> items) factoryResponse = QueryResponseMessageFactory.Create(
itemIdPrefix: $"TestPage",
continuationToken: "SomeContinuationToken",
collectionRid: contianerRid,
itemCount: 100);
QueryResponseCore responseCore = factoryResponse.response;
List<CosmosElement> cosmosElements = new List<CosmosElement>(responseCore.CosmosElements);
QueryResponse queryResponse = QueryResponse.CreateSuccess(
result: cosmosElements,
count: cosmosElements.Count,
responseLengthBytes: responseCore.ResponseLengthBytes,
serializationOptions: null,
responseHeaders: new CosmosQueryResponseMessageHeaders(
responseCore.ContinuationToken,
responseCore.DisallowContinuationTokenMessage,
ResourceType.Document,
contianerRid)
{
RequestCharge = responseCore.RequestCharge,
ActivityId = responseCore.ActivityId
},
diagnostics: new CosmosDiagnosticsContextCore());
QueryResponse<ToDoItem> itemQueryResponse = QueryResponseMessageFactory.CreateQueryResponse<ToDoItem>(queryResponse);
List<ToDoItem> resultItems = new List<ToDoItem>(itemQueryResponse.Resource);
ToDoItemComparer comparer = new ToDoItemComparer();
Assert.AreEqual(factoryResponse.items.Count, resultItems.Count);
for (int i = 0; i < factoryResponse.items.Count; i++)
{
Assert.AreNotSame(factoryResponse.items[i], resultItems[i]);
Assert.AreEqual(0, comparer.Compare(factoryResponse.items[i], resultItems[i]));
}
}
[TestMethod]
public void VerifyItemQueryResponseCosmosElements()
{
string containerRid = "mockContainerRid";
(QueryResponseCore response, IList<ToDoItem> items) factoryResponse = QueryResponseMessageFactory.Create(
itemIdPrefix: $"TestPage",
continuationToken: "SomeContinuationToken",
collectionRid: containerRid,
itemCount: 100);
QueryResponseCore responseCore = factoryResponse.response;
List<CosmosElement> cosmosElements = new List<CosmosElement>(responseCore.CosmosElements);
QueryResponse queryResponse = QueryResponse.CreateSuccess(
result: cosmosElements,
count: cosmosElements.Count,
responseLengthBytes: responseCore.ResponseLengthBytes,
serializationOptions: null,
responseHeaders: new CosmosQueryResponseMessageHeaders(
responseCore.ContinuationToken,
responseCore.DisallowContinuationTokenMessage,
ResourceType.Document,
containerRid)
{
RequestCharge = responseCore.RequestCharge,
ActivityId = responseCore.ActivityId
},
diagnostics: new CosmosDiagnosticsContextCore());
QueryResponse<CosmosElement> itemQueryResponse = QueryResponseMessageFactory.CreateQueryResponse<CosmosElement>(queryResponse);
List<CosmosElement> resultItems = new List<CosmosElement>(itemQueryResponse.Resource);
Assert.AreEqual(cosmosElements.Count, resultItems.Count);
for (int i = 0; i < cosmosElements.Count; i++)
{
Assert.AreSame(cosmosElements[i], resultItems[i]);
}
}
[TestMethod]
public async Task TestCosmosQueryExecutionComponentOnFailure()
{
(IList<IDocumentQueryExecutionComponent> components, QueryResponseCore response) setupContext = await this.GetAllExecutionComponents();
foreach (DocumentQueryExecutionComponentBase component in setupContext.components)
{
QueryResponseCore response = await component.DrainAsync(1, default(CancellationToken));
Assert.AreEqual(setupContext.response, response);
}
}
[TestMethod]
public async Task TestCosmosQueryExecutionComponentCancellation()
{
(IList<IDocumentQueryExecutionComponent> components, QueryResponseCore response) setupContext = await this.GetAllExecutionComponents();
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
foreach (DocumentQueryExecutionComponentBase component in setupContext.components)
{
try
{
QueryResponseCore response = await component.DrainAsync(1, cancellationTokenSource.Token);
Assert.Fail("cancellation token should have thrown an exception");
}
catch (OperationCanceledException e)
{
Assert.IsNotNull(e.Message);
}
}
}
[TestMethod]
public async Task TestCosmosQueryPartitionKeyDefinition()
{
PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition();
QueryRequestOptions queryRequestOptions = new QueryRequestOptions
{
Properties = new Dictionary<string, object>()
{
{"x-ms-query-partitionkey-definition", partitionKeyDefinition }
}
};
SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(@"select * from t where t.something = 42 ");
bool allowNonValueAggregateQuery = true;
bool isContinuationExpected = true;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationtoken = cancellationTokenSource.Token;
Mock<CosmosQueryClient> client = new Mock<CosmosQueryClient>();
string exceptionMessage = "Verified that the PartitionKeyDefinition was correctly set. Cancel the rest of the query";
client
.Setup(x => x.GetCachedContainerQueryPropertiesAsync(It.IsAny<Uri>(), It.IsAny<Cosmos.PartitionKey?>(), cancellationtoken))
.ReturnsAsync(new ContainerQueryProperties("mockContainer", null, partitionKeyDefinition));
client
.Setup(x => x.ByPassQueryParsing())
.Returns(false);
client
.Setup(x => x.TryGetPartitionedQueryExecutionInfoAsync(
It.IsAny<SqlQuerySpec>(),
It.IsAny<PartitionKeyDefinition>(),
It.IsAny<bool>(),
It.IsAny<bool>(),
It.IsAny<bool>(),
It.IsAny<bool>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(TryCatch<PartitionedQueryExecutionInfo>.FromException(
new InvalidOperationException(
exceptionMessage)));
CosmosQueryExecutionContextFactory.InputParameters inputParameters = new CosmosQueryExecutionContextFactory.InputParameters(
sqlQuerySpec: sqlQuerySpec,
initialUserContinuationToken: null,
initialFeedRange: null,
maxConcurrency: queryRequestOptions?.MaxConcurrency,
maxItemCount: queryRequestOptions?.MaxItemCount,
maxBufferedItemCount: queryRequestOptions?.MaxBufferedItemCount,
partitionKey: queryRequestOptions?.PartitionKey,
properties: queryRequestOptions?.Properties,
partitionedQueryExecutionInfo: null,
executionEnvironment: queryRequestOptions?.ExecutionEnvironment,
returnResultsInDeterministicOrder: true,
forcePassthrough: false,
testInjections: queryRequestOptions?.TestSettings);
CosmosQueryContext cosmosQueryContext = new CosmosQueryContextCore(
client: client.Object,
queryRequestOptions: queryRequestOptions,
resourceTypeEnum: ResourceType.Document,
operationType: OperationType.Query,
resourceType: typeof(QueryResponse),
resourceLink: new Uri("dbs/mockdb/colls/mockColl", UriKind.Relative),
isContinuationExpected: isContinuationExpected,
allowNonValueAggregateQuery: allowNonValueAggregateQuery,
diagnosticsContext: new CosmosDiagnosticsContextCore(),
correlatedActivityId: new Guid("221FC86C-1825-4284-B10E-A6029652CCA6"));
CosmosQueryExecutionContext context = CosmosQueryExecutionContextFactory.Create(
cosmosQueryContext,
inputParameters);
QueryResponseCore queryResponse = await context.ExecuteNextAsync(cancellationtoken);
Assert.AreEqual(HttpStatusCode.BadRequest, queryResponse.StatusCode);
Assert.IsTrue(queryResponse.CosmosException.ToString().Contains(exceptionMessage), "response error message did not contain the proper substring.");
}
private async Task<(IList<IDocumentQueryExecutionComponent> components, QueryResponseCore response)> GetAllExecutionComponents()
{
(Func<CosmosElement, Task<TryCatch<IDocumentQueryExecutionComponent>>> func, QueryResponseCore response) = this.SetupBaseContextToVerifyFailureScenario();
List<IDocumentQueryExecutionComponent> components = new List<IDocumentQueryExecutionComponent>();
List<AggregateOperator> operators = new List<AggregateOperator>()
{
AggregateOperator.Average,
AggregateOperator.Count,
AggregateOperator.Max,
AggregateOperator.Min,
AggregateOperator.Sum
};
components.Add((await AggregateDocumentQueryExecutionComponent.TryCreateAsync(
ExecutionEnvironment.Client,
operators.ToArray(),
new Dictionary<string, AggregateOperator?>()
{
{ "test", AggregateOperator.Count }
},
new List<string>() { "test" },
false,
null,
func)).Result);
components.Add((await DistinctDocumentQueryExecutionComponent.TryCreateAsync(
ExecutionEnvironment.Client,
null,
func,
DistinctQueryType.Ordered)).Result);
components.Add((await SkipDocumentQueryExecutionComponent.TryCreateAsync(
ExecutionEnvironment.Client,
5,
null,
func)).Result);
components.Add((await TakeDocumentQueryExecutionComponent.TryCreateLimitDocumentQueryExecutionComponentAsync(
ExecutionEnvironment.Client,
5,
null,
func)).Result);
components.Add((await TakeDocumentQueryExecutionComponent.TryCreateTopDocumentQueryExecutionComponentAsync(
ExecutionEnvironment.Client,
5,
null,
func)).Result);
return (components, response);
}
private (Func<CosmosElement, Task<TryCatch<IDocumentQueryExecutionComponent>>>, QueryResponseCore) SetupBaseContextToVerifyFailureScenario()
{
CosmosDiagnosticsContext diagnosticsContext = new CosmosDiagnosticsContextCore();
diagnosticsContext.AddDiagnosticsInternal( new PointOperationStatistics(
Guid.NewGuid().ToString(),
System.Net.HttpStatusCode.Unauthorized,
subStatusCode: SubStatusCodes.PartitionKeyMismatch,
responseTimeUtc: DateTime.UtcNow,
requestCharge: 4,
errorMessage: null,
method: HttpMethod.Post,
requestUri: new Uri("http://localhost.com"),
requestSessionToken: null,
responseSessionToken: null));
IReadOnlyCollection<QueryPageDiagnostics> diagnostics = new List<QueryPageDiagnostics>()
{
new QueryPageDiagnostics(
Guid.NewGuid(),
"0",
"SomeQueryMetricText",
"SomeIndexUtilText",
diagnosticsContext)
};
QueryResponseCore failure = QueryResponseCore.CreateFailure(
System.Net.HttpStatusCode.Unauthorized,
SubStatusCodes.PartitionKeyMismatch,
new CosmosException(
statusCodes: HttpStatusCode.Unauthorized,
message: "Random error message",
subStatusCode: default,
stackTrace: default,
activityId: "TestActivityId",
requestCharge: 42.89,
retryAfter: default,
headers: default,
diagnosticsContext: default,
error: default,
innerException: default),
42.89,
"TestActivityId");
Mock<IDocumentQueryExecutionComponent> baseContext = new Mock<IDocumentQueryExecutionComponent>();
baseContext.Setup(x => x.DrainAsync(It.IsAny<int>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<QueryResponseCore>(failure));
Task<TryCatch<IDocumentQueryExecutionComponent>> callBack(CosmosElement x) => Task.FromResult<TryCatch<IDocumentQueryExecutionComponent>>(TryCatch<IDocumentQueryExecutionComponent>.FromResult(baseContext.Object));
return (callBack, failure);
}
}
} | 48.977273 | 225 | 0.601444 | [
"MIT"
] | Camios/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/CosmosQueryUnitTests.cs | 19,397 | C# |
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia
namespace EtAlii.xTechnology.Hosting.Tests.Infrastructure.Grpc
{
public class AuthenticationServiceFactory : IServiceFactory
{
public IService Create(ServiceConfiguration configuration, Status status, IHost host) => new AuthenticationService(configuration, status);
}
}
| 40.5 | 146 | 0.775309 | [
"MIT"
] | vrenken/EtAlii.Ubigia | Source/Frameworks/EtAlii.xTechnology.Hosting/Tests/EtAlii.xTechnology.Hosting.Tests.TestSystem1.Grpc/Authentication/AuthenticationServiceFactory.cs | 407 | C# |
namespace Globe30Chk
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl();
this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.delLayerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.attriTabShowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.gLCDataSToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.nullValueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.commonEdgeDiffToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.verticalGLCNoiseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.horizontalGLCNoiseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.existingRulesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.spatialExistingRulesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.neighborhoodRelationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.containRelationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.disjointRelationDRToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.temporalExistingRulesToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.qualityCheckingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.quantityCheckingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.vorAdjacentRulesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.rSFeaturePointsFPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.deleteNoisePointsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.createVorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.vorZonalRangeStatisToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.constrainedVorAdjacentRuleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.crowdSourcingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addNetReferenceMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.yypeCompatibleJudgementToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.rulesDiscoveryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.numberToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.adjRelationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.conRelationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.disjRelationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.numberOfTemproalRelationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.axLicenseControl2 = new ESRI.ArcGIS.Controls.AxLicenseControl();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl2)).BeginInit();
this.SuspendLayout();
//
// axToolbarControl1
//
this.axToolbarControl1.Dock = System.Windows.Forms.DockStyle.Top;
this.axToolbarControl1.Location = new System.Drawing.Point(0, 35);
this.axToolbarControl1.Name = "axToolbarControl1";
this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState")));
this.axToolbarControl1.Size = new System.Drawing.Size(1261, 28);
this.axToolbarControl1.TabIndex = 2;
//
// axTOCControl1
//
this.axTOCControl1.Dock = System.Windows.Forms.DockStyle.Left;
this.axTOCControl1.Location = new System.Drawing.Point(0, 63);
this.axTOCControl1.Name = "axTOCControl1";
this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState")));
this.axTOCControl1.Size = new System.Drawing.Size(307, 785);
this.axTOCControl1.TabIndex = 1;
//
// axMapControl1
//
this.axMapControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axMapControl1.Location = new System.Drawing.Point(307, 63);
this.axMapControl1.Name = "axMapControl1";
this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState")));
this.axMapControl1.Size = new System.Drawing.Size(954, 785);
this.axMapControl1.TabIndex = 0;
//
// menuStrip1
//
this.menuStrip1.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.menuStrip1.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.menuStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible;
this.menuStrip1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.gLCDataSToolStripMenuItem,
this.existingRulesToolStripMenuItem,
this.vorAdjacentRulesToolStripMenuItem,
this.crowdSourcingToolStripMenuItem,
this.rulesDiscoveryToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Padding = new System.Windows.Forms.Padding(4, 3, 0, 3);
this.menuStrip1.Size = new System.Drawing.Size(1261, 35);
this.menuStrip1.TabIndex = 4;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem,
this.delLayerToolStripMenuItem,
this.attriTabShowToolStripMenuItem});
this.fileToolStripMenuItem.Font = new System.Drawing.Font("Georgia", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.fileToolStripMenuItem.ForeColor = System.Drawing.Color.Black;
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(93, 29);
this.fileToolStripMenuItem.Text = "File (F)";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(213, 30);
this.openToolStripMenuItem.Text = "Open (O)";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(210, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("exitToolStripMenuItem.Image")));
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(213, 30);
this.exitToolStripMenuItem.Text = "Exit (E)";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// delLayerToolStripMenuItem
//
this.delLayerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("delLayerToolStripMenuItem.Image")));
this.delLayerToolStripMenuItem.Name = "delLayerToolStripMenuItem";
this.delLayerToolStripMenuItem.Size = new System.Drawing.Size(213, 30);
this.delLayerToolStripMenuItem.Text = "DelLayer";
this.delLayerToolStripMenuItem.Click += new System.EventHandler(this.delLayerToolStripMenuItem_Click);
//
// attriTabShowToolStripMenuItem
//
this.attriTabShowToolStripMenuItem.Name = "attriTabShowToolStripMenuItem";
this.attriTabShowToolStripMenuItem.Size = new System.Drawing.Size(213, 30);
this.attriTabShowToolStripMenuItem.Text = "AttriTabShow";
this.attriTabShowToolStripMenuItem.Click += new System.EventHandler(this.attriTabShowToolStripMenuItem_Click);
//
// gLCDataSToolStripMenuItem
//
this.gLCDataSToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.nullValueToolStripMenuItem,
this.commonEdgeDiffToolStripMenuItem,
this.toolStripSeparator3,
this.verticalGLCNoiseToolStripMenuItem,
this.horizontalGLCNoiseToolStripMenuItem});
this.gLCDataSToolStripMenuItem.Font = new System.Drawing.Font("Georgia", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.gLCDataSToolStripMenuItem.ForeColor = System.Drawing.Color.Black;
this.gLCDataSToolStripMenuItem.Name = "gLCDataSToolStripMenuItem";
this.gLCDataSToolStripMenuItem.Size = new System.Drawing.Size(211, 29);
this.gLCDataSToolStripMenuItem.Text = "Data Structure (DS)";
//
// nullValueToolStripMenuItem
//
this.nullValueToolStripMenuItem.Image = global::Globe30Chk.Properties.Resources._null;
this.nullValueToolStripMenuItem.Name = "nullValueToolStripMenuItem";
this.nullValueToolStripMenuItem.Size = new System.Drawing.Size(329, 30);
this.nullValueToolStripMenuItem.Text = "Null Value (NV)";
this.nullValueToolStripMenuItem.Click += new System.EventHandler(this.nullValueToolStripMenuItem_Click);
//
// commonEdgeDiffToolStripMenuItem
//
this.commonEdgeDiffToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("commonEdgeDiffToolStripMenuItem.Image")));
this.commonEdgeDiffToolStripMenuItem.Name = "commonEdgeDiffToolStripMenuItem";
this.commonEdgeDiffToolStripMenuItem.Size = new System.Drawing.Size(329, 30);
this.commonEdgeDiffToolStripMenuItem.Text = "Common Edge Diff (DED)";
this.commonEdgeDiffToolStripMenuItem.Click += new System.EventHandler(this.commonEdgeDiffToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(326, 6);
//
// verticalGLCNoiseToolStripMenuItem
//
this.verticalGLCNoiseToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("verticalGLCNoiseToolStripMenuItem.Image")));
this.verticalGLCNoiseToolStripMenuItem.Name = "verticalGLCNoiseToolStripMenuItem";
this.verticalGLCNoiseToolStripMenuItem.Size = new System.Drawing.Size(329, 30);
this.verticalGLCNoiseToolStripMenuItem.Text = "Vertical Noise (VN)";
this.verticalGLCNoiseToolStripMenuItem.Click += new System.EventHandler(this.verticalGLCNoiseToolStripMenuItem_Click);
//
// horizontalGLCNoiseToolStripMenuItem
//
this.horizontalGLCNoiseToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("horizontalGLCNoiseToolStripMenuItem.Image")));
this.horizontalGLCNoiseToolStripMenuItem.Name = "horizontalGLCNoiseToolStripMenuItem";
this.horizontalGLCNoiseToolStripMenuItem.Size = new System.Drawing.Size(329, 30);
this.horizontalGLCNoiseToolStripMenuItem.Text = "Horizontal Noise (HN)";
this.horizontalGLCNoiseToolStripMenuItem.Click += new System.EventHandler(this.horizontalGLCNoiseToolStripMenuItem_Click);
//
// existingRulesToolStripMenuItem
//
this.existingRulesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.spatialExistingRulesToolStripMenuItem,
this.toolStripSeparator1,
this.temporalExistingRulesToolStripMenuItem1});
this.existingRulesToolStripMenuItem.Font = new System.Drawing.Font("Georgia", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.existingRulesToolStripMenuItem.ForeColor = System.Drawing.Color.Black;
this.existingRulesToolStripMenuItem.Name = "existingRulesToolStripMenuItem";
this.existingRulesToolStripMenuItem.Size = new System.Drawing.Size(207, 29);
this.existingRulesToolStripMenuItem.Text = "Existing Rules (ER)";
//
// spatialExistingRulesToolStripMenuItem
//
this.spatialExistingRulesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.neighborhoodRelationToolStripMenuItem,
this.containRelationToolStripMenuItem,
this.disjointRelationDRToolStripMenuItem});
this.spatialExistingRulesToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("spatialExistingRulesToolStripMenuItem.Image")));
this.spatialExistingRulesToolStripMenuItem.Name = "spatialExistingRulesToolStripMenuItem";
this.spatialExistingRulesToolStripMenuItem.Size = new System.Drawing.Size(376, 30);
this.spatialExistingRulesToolStripMenuItem.Text = "Spatial Existing Rules (SER)";
//
// neighborhoodRelationToolStripMenuItem
//
this.neighborhoodRelationToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("neighborhoodRelationToolStripMenuItem.Image")));
this.neighborhoodRelationToolStripMenuItem.Name = "neighborhoodRelationToolStripMenuItem";
this.neighborhoodRelationToolStripMenuItem.Size = new System.Drawing.Size(289, 30);
this.neighborhoodRelationToolStripMenuItem.Text = "con_wRelation (CNR)";
this.neighborhoodRelationToolStripMenuItem.Click += new System.EventHandler(this.neighborhoodRelationToolStripMenuItem_Click);
//
// containRelationToolStripMenuItem
//
this.containRelationToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("containRelationToolStripMenuItem.Image")));
this.containRelationToolStripMenuItem.Name = "containRelationToolStripMenuItem";
this.containRelationToolStripMenuItem.Size = new System.Drawing.Size(289, 30);
this.containRelationToolStripMenuItem.Text = "sur_dRelation (SR)";
this.containRelationToolStripMenuItem.Click += new System.EventHandler(this.containRelationToolStripMenuItem_Click);
//
// disjointRelationDRToolStripMenuItem
//
this.disjointRelationDRToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("disjointRelationDRToolStripMenuItem.Image")));
this.disjointRelationDRToolStripMenuItem.Name = "disjointRelationDRToolStripMenuItem";
this.disjointRelationDRToolStripMenuItem.Size = new System.Drawing.Size(360, 30);
this.disjointRelationDRToolStripMenuItem.Text = "Disjoint Relation(DR)";
this.disjointRelationDRToolStripMenuItem.Click += new System.EventHandler(this.disjointRelationDRToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(373, 6);
//
// temporalExistingRulesToolStripMenuItem1
//
this.temporalExistingRulesToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.qualityCheckingToolStripMenuItem,
this.toolStripSeparator5,
this.quantityCheckingToolStripMenuItem});
this.temporalExistingRulesToolStripMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("temporalExistingRulesToolStripMenuItem1.Image")));
this.temporalExistingRulesToolStripMenuItem1.Name = "temporalExistingRulesToolStripMenuItem1";
this.temporalExistingRulesToolStripMenuItem1.Size = new System.Drawing.Size(376, 30);
this.temporalExistingRulesToolStripMenuItem1.Text = "Temporal Existing Rules (TER)";
this.temporalExistingRulesToolStripMenuItem1.Click += new System.EventHandler(this.temporalExistingRulesToolStripMenuItem1_Click);
//
// qualityCheckingToolStripMenuItem
//
this.qualityCheckingToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("qualityCheckingToolStripMenuItem.Image")));
this.qualityCheckingToolStripMenuItem.Name = "qualityCheckingToolStripMenuItem";
this.qualityCheckingToolStripMenuItem.Size = new System.Drawing.Size(340, 30);
this.qualityCheckingToolStripMenuItem.Text = "Quality Checking (QualC)";
this.qualityCheckingToolStripMenuItem.Click += new System.EventHandler(this.qualityCheckingToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(337, 6);
//
// quantityCheckingToolStripMenuItem
//
this.quantityCheckingToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("quantityCheckingToolStripMenuItem.Image")));
this.quantityCheckingToolStripMenuItem.Name = "quantityCheckingToolStripMenuItem";
this.quantityCheckingToolStripMenuItem.Size = new System.Drawing.Size(340, 30);
this.quantityCheckingToolStripMenuItem.Text = "Quantity Checking (QuanC)";
this.quantityCheckingToolStripMenuItem.Click += new System.EventHandler(this.quantityCheckingToolStripMenuItem_Click);
//
// vorAdjacentRulesToolStripMenuItem
//
this.vorAdjacentRulesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.rSFeaturePointsFPToolStripMenuItem,
this.toolStripSeparator4,
this.deleteNoisePointsToolStripMenuItem,
this.toolStripSeparator10,
this.createVorToolStripMenuItem,
this.toolStripSeparator9,
this.vorZonalRangeStatisToolStripMenuItem,
this.toolStripSeparator7,
this.constrainedVorAdjacentRuleToolStripMenuItem});
this.vorAdjacentRulesToolStripMenuItem.Font = new System.Drawing.Font("Georgia", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.vorAdjacentRulesToolStripMenuItem.ForeColor = System.Drawing.Color.Black;
this.vorAdjacentRulesToolStripMenuItem.Name = "vorAdjacentRulesToolStripMenuItem";
this.vorAdjacentRulesToolStripMenuItem.Size = new System.Drawing.Size(261, 29);
this.vorAdjacentRulesToolStripMenuItem.Text = "VorAdjacent Rules (VAR)";
//
// rSFeaturePointsFPToolStripMenuItem
//
this.rSFeaturePointsFPToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("rSFeaturePointsFPToolStripMenuItem.Image")));
this.rSFeaturePointsFPToolStripMenuItem.Name = "rSFeaturePointsFPToolStripMenuItem";
this.rSFeaturePointsFPToolStripMenuItem.Size = new System.Drawing.Size(362, 30);
this.rSFeaturePointsFPToolStripMenuItem.Text = "RS Feature Points (FP)";
this.rSFeaturePointsFPToolStripMenuItem.Click += new System.EventHandler(this.rSFeaturePointsFPToolStripMenuItem_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(359, 6);
//
// deleteNoisePointsToolStripMenuItem
//
this.deleteNoisePointsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("deleteNoisePointsToolStripMenuItem.Image")));
this.deleteNoisePointsToolStripMenuItem.Name = "deleteNoisePointsToolStripMenuItem";
this.deleteNoisePointsToolStripMenuItem.Size = new System.Drawing.Size(362, 30);
this.deleteNoisePointsToolStripMenuItem.Text = "Delete Noise Points (DNP)";
this.deleteNoisePointsToolStripMenuItem.Click += new System.EventHandler(this.deleteNoisePointsToolStripMenuItem_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
this.toolStripSeparator10.Size = new System.Drawing.Size(359, 6);
//
// createVorToolStripMenuItem
//
this.createVorToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("createVorToolStripMenuItem.Image")));
this.createVorToolStripMenuItem.Name = "createVorToolStripMenuItem";
this.createVorToolStripMenuItem.Size = new System.Drawing.Size(362, 30);
this.createVorToolStripMenuItem.Text = "CreateVor (CV)";
this.createVorToolStripMenuItem.Click += new System.EventHandler(this.createVorToolStripMenuItem_Click);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
this.toolStripSeparator9.Size = new System.Drawing.Size(359, 6);
//
// vorZonalRangeStatisToolStripMenuItem
//
this.vorZonalRangeStatisToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("vorZonalRangeStatisToolStripMenuItem.Image")));
this.vorZonalRangeStatisToolStripMenuItem.Name = "vorZonalRangeStatisToolStripMenuItem";
this.vorZonalRangeStatisToolStripMenuItem.Size = new System.Drawing.Size(362, 30);
this.vorZonalRangeStatisToolStripMenuItem.Text = "VorZonalRange Statis (VZRS)";
this.vorZonalRangeStatisToolStripMenuItem.Click += new System.EventHandler(this.vorZonalRangeStatisToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(359, 6);
//
// constrainedVorAdjacentRuleToolStripMenuItem
//
this.constrainedVorAdjacentRuleToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("constrainedVorAdjacentRuleToolStripMenuItem.Image")));
this.constrainedVorAdjacentRuleToolStripMenuItem.Name = "constrainedVorAdjacentRuleToolStripMenuItem";
this.constrainedVorAdjacentRuleToolStripMenuItem.Size = new System.Drawing.Size(362, 30);
this.constrainedVorAdjacentRuleToolStripMenuItem.Text = "VorAdjacent Checking (VAC)";
this.constrainedVorAdjacentRuleToolStripMenuItem.Click += new System.EventHandler(this.constrainedVorAdjacentRuleToolStripMenuItem_Click);
//
// crowdSourcingToolStripMenuItem
//
this.crowdSourcingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addNetReferenceMapToolStripMenuItem,
this.toolStripSeparator6,
this.yypeCompatibleJudgementToolStripMenuItem});
this.crowdSourcingToolStripMenuItem.Font = new System.Drawing.Font("Georgia", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.crowdSourcingToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText;
this.crowdSourcingToolStripMenuItem.ImageTransparentColor = System.Drawing.SystemColors.ControlLightLight;
this.crowdSourcingToolStripMenuItem.Name = "crowdSourcingToolStripMenuItem";
this.crowdSourcingToolStripMenuItem.Size = new System.Drawing.Size(213, 29);
this.crowdSourcingToolStripMenuItem.Text = "CrowdSourcing (CS)";
//
// addNetReferenceMapToolStripMenuItem
//
this.addNetReferenceMapToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("addNetReferenceMapToolStripMenuItem.Image")));
this.addNetReferenceMapToolStripMenuItem.Name = "addNetReferenceMapToolStripMenuItem";
this.addNetReferenceMapToolStripMenuItem.Size = new System.Drawing.Size(370, 30);
this.addNetReferenceMapToolStripMenuItem.Text = "Add NetReference Map (ANM)";
this.addNetReferenceMapToolStripMenuItem.Click += new System.EventHandler(this.addNetReferenceMapToolStripMenuItem_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(367, 6);
//
// yypeCompatibleJudgementToolStripMenuItem
//
this.yypeCompatibleJudgementToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("yypeCompatibleJudgementToolStripMenuItem.Image")));
this.yypeCompatibleJudgementToolStripMenuItem.Name = "yypeCompatibleJudgementToolStripMenuItem";
this.yypeCompatibleJudgementToolStripMenuItem.Size = new System.Drawing.Size(370, 30);
this.yypeCompatibleJudgementToolStripMenuItem.Text = "Toponym Detecting";
this.yypeCompatibleJudgementToolStripMenuItem.Click += new System.EventHandler(this.yypeCompatibleJudgementToolStripMenuItem_Click);
//
// rulesDiscoveryToolStripMenuItem
//
this.rulesDiscoveryToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.numberToolStripMenuItem,
this.numberOfTemproalRelationToolStripMenuItem});
this.rulesDiscoveryToolStripMenuItem.Font = new System.Drawing.Font("Georgia", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.rulesDiscoveryToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText;
this.rulesDiscoveryToolStripMenuItem.Name = "rulesDiscoveryToolStripMenuItem";
this.rulesDiscoveryToolStripMenuItem.Size = new System.Drawing.Size(210, 29);
this.rulesDiscoveryToolStripMenuItem.Text = "Rule Discovery(RD)";
//
// numberToolStripMenuItem
//
this.numberToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.adjRelationToolStripMenuItem,
this.toolStripSeparator8,
this.conRelationToolStripMenuItem,
this.toolStripSeparator11,
this.disjRelationToolStripMenuItem});
this.numberToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("numberToolStripMenuItem.Image")));
this.numberToolStripMenuItem.Name = "numberToolStripMenuItem";
this.numberToolStripMenuItem.Size = new System.Drawing.Size(364, 30);
this.numberToolStripMenuItem.Text = "Number of Spatial Relation";
this.numberToolStripMenuItem.Click += new System.EventHandler(this.numberToolStripMenuItem_Click);
//
// adjRelationToolStripMenuItem
//
this.adjRelationToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("adjRelationToolStripMenuItem.Image")));
this.adjRelationToolStripMenuItem.Name = "adjRelationToolStripMenuItem";
this.adjRelationToolStripMenuItem.Size = new System.Drawing.Size(224, 30);
this.adjRelationToolStripMenuItem.Text = "con_wRelation";
this.adjRelationToolStripMenuItem.Click += new System.EventHandler(this.adjRelationToolStripMenuItem_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(221, 6);
//
// conRelationToolStripMenuItem
//
this.conRelationToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("conRelationToolStripMenuItem.Image")));
this.conRelationToolStripMenuItem.Name = "conRelationToolStripMenuItem";
this.conRelationToolStripMenuItem.Size = new System.Drawing.Size(224, 30);
this.conRelationToolStripMenuItem.Text = "sur_dRelation";
this.conRelationToolStripMenuItem.Click += new System.EventHandler(this.conRelationToolStripMenuItem_Click);
//
// toolStripSeparator11
//
this.toolStripSeparator11.Name = "toolStripSeparator11";
this.toolStripSeparator11.Size = new System.Drawing.Size(221, 6);
//
// disjRelationToolStripMenuItem
//
this.disjRelationToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("disjRelationToolStripMenuItem.Image")));
this.disjRelationToolStripMenuItem.Name = "disjRelationToolStripMenuItem";
this.disjRelationToolStripMenuItem.Size = new System.Drawing.Size(224, 30);
this.disjRelationToolStripMenuItem.Text = "disjRelation";
this.disjRelationToolStripMenuItem.Click += new System.EventHandler(this.disjRelationToolStripMenuItem_Click);
//
// numberOfTemproalRelationToolStripMenuItem
//
this.numberOfTemproalRelationToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("numberOfTemproalRelationToolStripMenuItem.Image")));
this.numberOfTemproalRelationToolStripMenuItem.Name = "numberOfTemproalRelationToolStripMenuItem";
this.numberOfTemproalRelationToolStripMenuItem.Size = new System.Drawing.Size(364, 30);
this.numberOfTemproalRelationToolStripMenuItem.Text = "Number of Temproal Relation";
this.numberOfTemproalRelationToolStripMenuItem.Click += new System.EventHandler(this.numberOfTemproalRelationToolStripMenuItem_Click);
//
// axLicenseControl2
//
this.axLicenseControl2.Enabled = true;
this.axLicenseControl2.Location = new System.Drawing.Point(644, 471);
this.axLicenseControl2.Name = "axLicenseControl2";
this.axLicenseControl2.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl2.OcxState")));
this.axLicenseControl2.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl2.TabIndex = 5;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1261, 848);
this.Controls.Add(this.axLicenseControl2);
this.Controls.Add(this.axMapControl1);
this.Controls.Add(this.axTOCControl1);
this.Controls.Add(this.axToolbarControl1);
this.Controls.Add(this.menuStrip1);
this.ForeColor = System.Drawing.SystemColors.Window;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "Form1";
this.Text = "GlobeLand30 DID";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1;
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1;
private ESRI.ArcGIS.Controls.AxMapControl axMapControl1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem gLCDataSToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem existingRulesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem vorAdjacentRulesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem nullValueToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem createVorToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem crowdSourcingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem spatialExistingRulesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem temporalExistingRulesToolStripMenuItem1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem addNetReferenceMapToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem verticalGLCNoiseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem horizontalGLCNoiseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem qualityCheckingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem quantityCheckingToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem constrainedVorAdjacentRuleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem neighborhoodRelationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem containRelationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem commonEdgeDiffToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem rSFeaturePointsFPToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem vorZonalRangeStatisToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteNoisePointsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private System.Windows.Forms.ToolStripMenuItem yypeCompatibleJudgementToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem attriTabShowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem delLayerToolStripMenuItem;
//private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private System.Windows.Forms.ToolStripMenuItem rulesDiscoveryToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem numberToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem numberOfTemproalRelationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem disjointRelationDRToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem adjRelationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem conRelationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem disjRelationToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl2;
}
}
| 68.821248 | 183 | 0.691137 | [
"MIT"
] | KangErLong/land-cover-data-checking | Form1.Designer.cs | 40,971 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpSquigglesDesktop : CSharpSquigglesCommon
{
public CSharpSquigglesDesktop(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, WellKnownProjectTemplates.ClassLibrary)
{
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/19091"), Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public override void VerifySyntaxErrorSquiggles()
{
base.VerifySyntaxErrorSquiggles();
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/19091"), Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public override void VerifySemanticErrorSquiggles()
{
base.VerifySemanticErrorSquiggles();
}
}
}
| 38.354839 | 161 | 0.723297 | [
"Apache-2.0"
] | Suchiman/roslyn | src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSquigglesDesktop.cs | 1,191 | C# |
/**
* Name:Train.Models-aers_tbl_hospdep
* Author: banshine
* Description: aers_tbl_hospdep 实体层
* Date: 2015-6-8 10:57:02
* */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace Aersysm.Domain
{
[DataContract]
public partial class aers_tbl_hospdep
{
#region HospdepId
[DataMember]
public String HospdepId { get;set; }
#endregion
#region BasedepId
[DataMember]
public String BasedepId { get;set; }
#endregion
#region HospId
[DataMember]
public String HospId { get;set; }
#endregion
#region HospdepName
[DataMember]
public String HospdepName { get;set; }
#endregion
#region SpellNo
[DataMember]
public String SpellNo { get;set; }
#endregion
#region HospdepLogo
[DataMember]
public String HospdepLogo { get;set; }
#endregion
#region DisplayOrder
[DataMember]
public Int32 DisplayOrder { get;set; }
#endregion
#region IsFlag
[DataMember]
public Int32 IsFlag { get;set; }
#endregion
#region Remarks
[DataMember]
public String Remarks { get;set; }
#endregion
#region OperatorId
[DataMember]
public String OperatorId { get;set; }
#endregion
#region OperatorDate
[DataMember]
public DateTime OperatorDate { get;set; }
#endregion
[DataMember]
public String HospName { get; set; }
[DataMember]
public String Grade { get; set; }
[DataMember]
public int EveCount { get; set; }
}
}
| 18.7 | 53 | 0.425751 | [
"Apache-2.0"
] | TanHaoran/NurseService1.0 | Aersysm.Domain/aers_tbl_hospdep.cs | 2,439 | C# |
/*
* Mail Baby API
*
* This is an API defintion for accesssing the Mail.Baby mail service.
*
* The version of the OpenAPI document: 1.0.0
* Contact: detain@interserver.net
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Net;
namespace Org.OpenAPITools.Client
{
/// <summary>
/// Provides a non-generic contract for the ApiResponse wrapper.
/// </summary>
public interface IApiResponse
{
/// <summary>
/// The data type of <see cref="Content"/>
/// </summary>
Type ResponseType { get; }
/// <summary>
/// The content of this response
/// </summary>
Object Content { get; }
/// <summary>
/// Gets or sets the status code (HTTP status code)
/// </summary>
/// <value>The status code.</value>
HttpStatusCode StatusCode { get; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
Multimap<string, string> Headers { get; }
/// <summary>
/// Gets or sets any error text defined by the calling client.
/// </summary>
String ErrorText { get; set; }
/// <summary>
/// Gets or sets any cookies passed along on the response.
/// </summary>
List<Cookie> Cookies { get; set; }
/// <summary>
/// The raw content of this response
/// </summary>
string RawContent { get; }
}
/// <summary>
/// API Response
/// </summary>
public class ApiResponse<T> : IApiResponse
{
#region Properties
/// <summary>
/// Gets or sets the status code (HTTP status code)
/// </summary>
/// <value>The status code.</value>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Gets or sets the HTTP headers
/// </summary>
/// <value>HTTP headers</value>
public Multimap<string, string> Headers { get; }
/// <summary>
/// Gets or sets the data (parsed HTTP body)
/// </summary>
/// <value>The data.</value>
public T Data { get; }
/// <summary>
/// Gets or sets any error text defined by the calling client.
/// </summary>
public String ErrorText { get; set; }
/// <summary>
/// Gets or sets any cookies passed along on the response.
/// </summary>
public List<Cookie> Cookies { get; set; }
/// <summary>
/// The content of this response
/// </summary>
public Type ResponseType
{
get { return typeof(T); }
}
/// <summary>
/// The data type of <see cref="Content"/>
/// </summary>
public object Content
{
get { return Data; }
}
/// <summary>
/// The raw content
/// </summary>
public string RawContent { get; }
#endregion Properties
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="headers">HTTP headers.</param>
/// <param name="data">Data (parsed HTTP body)</param>
/// <param name="rawContent">Raw content.</param>
public ApiResponse(HttpStatusCode statusCode, Multimap<string, string> headers, T data, string rawContent)
{
StatusCode = statusCode;
Headers = headers;
Data = data;
RawContent = rawContent;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="headers">HTTP headers.</param>
/// <param name="data">Data (parsed HTTP body)</param>
public ApiResponse(HttpStatusCode statusCode, Multimap<string, string> headers, T data) : this(statusCode, headers, data, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="data">Data (parsed HTTP body)</param>
/// <param name="rawContent">Raw content.</param>
public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
/// </summary>
/// <param name="statusCode">HTTP status code.</param>
/// <param name="data">Data (parsed HTTP body)</param>
public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null)
{
}
#endregion Constructors
}
}
| 30.285714 | 135 | 0.546384 | [
"MIT"
] | interserver/mailbaby-api-samples | openapi-client/csharp-netcore/src/Org.OpenAPITools/Client/ApiResponse.cs | 5,088 | C# |
using Engine.Mongo.Entity;
using Engine.Mongo.Operation;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
namespace Engine.Mongo.Template
{
/// 提供 push-pull-sync-transaction 操作的分布式库
/// 支持:
/// 同步-数据拉取-写入
/// @modify yellow date 2016.11.21
/// </summary>
public class MemoryCacheTemplate
{
/// <summary>
/// 返回当前最新时间
/// </summary>
protected string Now
{
get
{
return DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
}
}
/// <summary>
/// 操作数据库名
/// </summary>
protected string _dataBaseName = null;
/// <summary>
/// 标识是否初始化,默认false
/// </summary>
protected bool _hasInilized = false;
/// <summary>
/// 持久化操作
/// </summary>
protected PushToMongoOperation _push = null;
/// <summary>
/// 缓存化操作
/// </summary>
protected PullToMemoryOperation _pull = null;
/// <summary>
/// 数据修复
/// </summary>
public virtual void RepairData() { }
/// <summary>
/// 内存对象初始化
/// </summary>
public virtual void Inilization(string connectString)
{
_hasInilized = true;
_pull = new PullToMemoryOperation(_dataBaseName, connectString);
_push = new PushToMongoOperation(_dataBaseName, connectString);
}
/// <summary>
/// 数据更新,可重写,虚函数
/// </summary>
public virtual void Persistence() { }
/// <summary>
/// 检查数据增量,并同步内存和数据库
/// </summary>
protected void SyncMemoryDataBase() { }
/// <summary>
/// 虚函数,导入数据库
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="list">数据集合</param>
/// <param name="tableName">表名</param>
/// <param name="dataName">数据表名,默认为 _dataBaseName 编译常量 </param>
protected async Task<bool> ImportToDataBase<T>(List<T> list, string tableName) where T : MongoEntity, new()
{
var task = await _push.PushData<T>(tableName, list);
return task;
}
/// <summary>
/// 根据dictionary构造查询器
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="filterDictionary"></param>
/// <returns></returns>
protected BsonDocumentFilterDefinition<T> BuildFilter<T>(Dictionary<string, string> filterDictionary)
{
var simpleQuery = new BsonDocument();
foreach (var element in filterDictionary)
simpleQuery.Add(new BsonElement(element.Key, BsonValue.Create(element.Value)));
return new BsonDocumentFilterDefinition<T>(simpleQuery);
}
/// <summary>
/// 导出数据
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="dataBaseName">数据集名</param>
/// <param name="tableName">表名</param>
/// <param name="pullAction">回调函数</param>
protected void ExportFromDataBase<T>(string tableName, Action<List<T>> pullAction = null, Dictionary<string, string> filterDictionary = null) where T : MongoEntity
{
BsonDocumentFilterDefinition<T> filter = null;
if (filterDictionary != null)
filter = BuildFilter<T>(filterDictionary);
_pull.PullData<T>(tableName, pullAction, filter);
}
/// <summary>
/// 修改对象
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="targetObjectId">待修改对象id</param>
/// <param name="targetObject">新的对象值</param>
/// <param name="collection">数据集(内存副本)</param>
/// <param name="tableName">表名</param>
protected async Task<bool> Modify<T>(string targetObjectId, T targetObject, List<T> collection, string tableName, List<string> forbidden = null) where T : MongoEntity
{
try
{
bool isUpdate = false;
T omf = collection.Find(p => p.objectId.Equals(targetObjectId));
if (omf == null || !omf.Verify()) return false;
Type type = targetObject.GetType();
foreach (PropertyInfo element in type.GetProperties())
{
//筛选派生类属性,基础类属性予以修改
if (element.DeclaringType.Equals(type))
{
var newValue = element.GetValue(targetObject);
if (newValue == null) continue;
var sourceValue = element.GetValue(omf);
//新值与原值不等
if (!newValue.Equals(sourceValue))
{
if (forbidden != null && forbidden.Contains(element.Name))
return false;
//string型
if (newValue.GetType().Equals(typeof(string)))
{
if (newValue != null && !newValue.Equals(""))
{
element.SetValue(omf, newValue);
isUpdate = true;
}
}
//int型
else if (newValue.GetType().Equals(typeof(int)))
{
element.SetValue(omf, newValue);
isUpdate = true;
}
//double型
else if (newValue.GetType().Equals(typeof(double)))
{
if (!newValue.Equals(0.000000))
{
element.SetValue(omf, newValue);
isUpdate = true;
}
}
//bool型
else if (newValue.GetType().Equals(typeof(bool)))
{
element.SetValue(omf, newValue);
isUpdate = true;
}
//list类型
else if (typeof(IList).IsAssignableFrom(element.PropertyType))
{
if (newValue != null)
{
element.SetValue(omf, newValue);
isUpdate = true;
}
}
}
}
}
bool isSuccess = false;
if (isUpdate)
isSuccess = await _push.Update(omf, tableName);
return isSuccess;
}
catch
{
return false;
}
}
/// <summary>
/// 删除数据
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="targetObjectId">被删除数据objectId</param>
/// <param name="collection">数据集(内存副本)</param>
/// <param name="tableName">表名</param>
protected async Task<bool> Close<T>(string targetObjectId, List<T> collection, string tableName) where T : MongoEntity
{
T omf = collection.Find(p => p.objectId.Equals(targetObjectId));
if (omf == null) return false;
omf.closed = true;
var flag = await _push.Update<T>(omf, tableName);
if (flag)
collection.Remove(omf);
return flag;
}
}
}
| 38.815534 | 174 | 0.461856 | [
"MIT"
] | KIWI-ST/kiwi.server | Laboratory/Engine.Mongo/Template/MemoryCacheTemplate.cs | 8,458 | C# |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Microsoft.Tools.ServiceModel.ComSvcConfig
{
using System;
using System.ServiceModel.Channels;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.ServiceModel;
using System.EnterpriseServices;
using Microsoft.Tools.ServiceModel;
using Microsoft.Tools.ServiceModel.SvcUtil;
using Microsoft.Win32;
using System.Security.Permissions;
static internal partial class HR
{
public static readonly int COMADMIN_E_OBJECT_DOES_NOT_EXIST = unchecked((int)0x80110809);
}
enum RuntimeVersions
{
V20,
V40
}
static internal class ComAdminWrapper
{
static readonly string ListenerApplicationName = SR.GetString(SR.WebServiceAppName);
static Assembly ListenerAssembly = typeof(Message).Assembly;
static string ListenerComponentDescription = SR.GetString(SR.ListenerCompDescription);
const string ListenerWSUName = "ServiceModelInitializer";
internal const string Wcf30RegistryKey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0\Setup\Windows Communication Foundation";
internal const string Runtime30InstallPathName = "RuntimeInstallPath";
const string fileName = @"ServiceMonikerSupport.dll";
static bool FindApplication(string appidOrName, out ICatalogObject targetAppObj, out ICatalogCollection appColl)
{
targetAppObj = null;
appColl = null;
bool found = false;
ICatalog2 catalog = GetCatalog();
string partitionId = null;
partitionId = GetPartitionIdForApplication(catalog, appidOrName, true);
if (!string.IsNullOrEmpty(partitionId))
{
SetCurrentPartition(catalog, partitionId);
}
appColl = (ICatalogCollection)(catalog.GetCollection(CollectionName.Applications));
appColl.Populate();
for (int i = 0; i < appColl.Count(); i++)
{
ICatalogObject appObj = (ICatalogObject)(appColl.Item(i));
string id = ((string)appObj.Key()).ToLowerInvariant();
string name = ((string)appObj.Name()).ToLowerInvariant();
appidOrName = appidOrName.ToLowerInvariant();
if (!found)
{
if ((appidOrName == id) || (appidOrName == name))
{
found = true;
targetAppObj = appObj;
}
}
else
{
if ((appidOrName == id) || (appidOrName == name))
{
throw Tool.CreateException(SR.GetString(SR.AmbiguousApplicationName, appidOrName), null);
}
}
}
return found;
}
static bool FindListener(Guid appid, out Guid clsid, out string progid)
{
clsid = Guid.Empty;
progid = null;
ICatalogObject appObj = null;
ICatalogCollection appColl = null;
if (!FindApplication(appid.ToString("B"), out appObj, out appColl))
{
throw Tool.CreateException(SR.GetString(SR.ApplicationNotFound, appid.ToString("B")), null);
}
ICatalogCollection comps = (ICatalogCollection)appColl.GetCollection(CollectionName.Components, appObj.Key());
comps.Populate();
for (int i = 0; i < comps.Count(); i++)
{
ICatalogObject compObj = (ICatalogObject)comps.Item(i);
if (IsListenerComponent(compObj))
{
clsid = new Guid((string)compObj.Key());
progid = (string)compObj.Name();
return true;
}
}
return false;
}
static bool SetComponentProperty(string appIdOrName, string compIdOrName, string property, object value)
{
ICatalogObject appObj = null;
ICatalogCollection appColl = null;
if (!FindApplication(appIdOrName, out appObj, out appColl))
{
throw Tool.CreateException(SR.GetString(SR.ApplicationNotFound, appIdOrName), null);
}
ICatalogCollection comps = (ICatalogCollection)appColl.GetCollection(CollectionName.Components, appObj.Key());
comps.Populate();
compIdOrName = compIdOrName.ToLowerInvariant(); //make compName lowercase
for (int i = 0; i < comps.Count(); i++)
{
ICatalogObject compObj = (ICatalogObject)comps.Item(i);
string name = ((string)compObj.Name()).ToLowerInvariant(); //make name lowercase
string id = ((string)compObj.Key()).ToLowerInvariant(); //make key lowercase
if (name == compIdOrName || id == compIdOrName)
{
compObj.SetValue(property, value);
comps.SaveChanges();
return true;
}
}
return false;
}
public static ComAdminAppInfo GetAppInfo(string appidOrName)
{
ICatalogObject appObj = null;
ICatalogCollection appColl = null;
if (!FindApplication(appidOrName, out appObj, out appColl))
{
return null;
}
ComAdminAppInfo appInfo = null;
try
{
appInfo = new ComAdminAppInfo(appObj, appColl);
}
catch (COMException ex)
{
ToolConsole.WriteWarning(SR.GetString(SR.FailedToFetchApplicationInformationFromCatalog, appidOrName, ex.ErrorCode, ex.Message));
}
return appInfo;
}
public static Guid[] GetApplicationIds()
{
ICatalog2 catalog = GetCatalog();
List<Guid> appIds = new List<Guid>();
ICatalogCollection partitions = (ICatalogCollection)(catalog.GetCollection(CollectionName.Partitions));
partitions.Populate();
for (int i = 0; i < partitions.Count(); i++)
{
ICatalogObject partition = (ICatalogObject)(partitions.Item(i));
ICatalogCollection applications = (ICatalogCollection)(partitions.GetCollection(CollectionName.Applications, partition.Key()));
applications.Populate();
for (int j = 0; j < applications.Count(); j++)
{
ICatalogObject obj = (ICatalogObject)(applications.Item(j));
appIds.Add(new Guid((string)obj.Key()));
}
}
return appIds.ToArray();
}
static ICatalog2 GetCatalog()
{
return (ICatalog2)(new xCatalog());
}
public static string GetPartitionIdForApplication(Guid appId)
{
ICatalog2 catalog = GetCatalog();
return GetPartitionIdForApplication(catalog, appId.ToString("B"), true);
}
public static string GetGlobalPartitionID()
{
ICatalog2 catalog = GetCatalog();
return catalog.GlobalPartitionID();
}
static string GetPartitionIdForApplication(ICatalog2 catalog, string appId, bool notThrow)
{
string partitionId = null;
try
{
partitionId = catalog.GetPartitionID(appId);
}
catch (COMException e)
{
if (!notThrow)
throw Tool.CreateException(SR.GetString(SR.CouldNotGetPartition), e);
else if (e.ErrorCode == HR.COMADMIN_E_OBJECT_DOES_NOT_EXIST)
ToolConsole.WriteWarning(SR.GetString(SR.ApplicationNotFound, appId));
else
ToolConsole.WriteWarning(SR.GetString(SR.CouldnotGetPartitionForApplication, appId, e.ErrorCode, e.Message));
return null;
}
return partitionId;
}
public static bool GetApplicationBitness(ICatalog2 catalog, string partitionID, string applicationID)
{
ICatalogCollection partitions = (ICatalogCollection)(catalog.GetCollection(CollectionName.Partitions));
ICatalogCollection applications = (ICatalogCollection)(partitions.GetCollection(CollectionName.Applications, partitionID));
applications.Populate();
ICatalogCollection components = (ICatalogCollection)applications.GetCollection(CollectionName.Components, applicationID);
try
{
components.Populate();
}
catch (Exception ex)
{
if (ex is NullReferenceException || ex is SEHException)
{
throw ex;
}
throw Tool.CreateException(SR.GetString(SR.FailedToDetermineTheBitnessOfApplication, applicationID), ex);
}
ICatalogObject component = (ICatalogObject)(components.Item(0));
return IsBitness64bit(component);
}
public static string GetAppropriateBitnessModuleModulePath(bool is64bit, RuntimeVersions runtimeVersion)
{
if (RuntimeVersions.V40 == runtimeVersion)
{
// Retrieve the regkey with Read permission. Note that on Windows 8 and later, only Trusted installer has write access to this key.
using (RegistryHandle regKey = RegistryHandle.GetCorrectBitnessHKLMSubkey(is64bit, ServiceModelInstallStrings.WinFXRegistryKey, false))
{
return (regKey.GetStringValue(ServiceModelInstallStrings.RuntimeInstallPathName).TrimEnd('\0') + "\\" + fileName);
}
}
else
{
// Try to find the 3.0 version
RegistryHandle regkey = null;
try
{
if (SafeNativeMethods.ERROR_SUCCESS == RegistryHandle.TryGetCorrectBitnessHKLMSubkey(is64bit, Wcf30RegistryKey, out regkey))
{
return (regkey.GetStringValue(Runtime30InstallPathName).TrimEnd('\0') + "\\" + fileName);
}
else
{
//We don't want to automatically roll forward to 4.0, so we throw an exception if we can't find the 3.0 reg key
throw Tool.CreateException(SR.GetString(SR.FailedToGetRegistryKey, Wcf30RegistryKey, "3.0"), null);
}
}
finally
{
if (regkey != null)
{
regkey.Dispose();
}
}
}
}
public static void CreateTypeLib(String fileName, Guid clsid)
{
try
{
ICreateTypeLib typelib = SafeNativeMethods.CreateTypeLib(fileName);
typelib.SetGuid(Guid.NewGuid());
typelib.SetName(ListenerWSUName);
typelib.SetDocString(ListenerWSUName);
ICreateTypeInfo typeInfo = typelib.CreateTypeInfo(ListenerWSUName, System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_COCLASS);
typeInfo.SetGuid(clsid);
typeInfo.SetDocString(ListenerWSUName);
ICreateTypeInfo2 typeInfo2 = (ICreateTypeInfo2)typeInfo;
typeInfo2.SetName(ListenerWSUName + "Component");
typeInfo2.SetTypeFlags(2);
typeInfo.LayOut();
typelib.SaveAllChanges();
}
catch (Exception ex)
{
if (ex is NullReferenceException || ex is SEHException)
{
throw ex;
}
throw Tool.CreateException(SR.GetString(SR.FailedToCreateTypeLibrary), ex);
}
}
public static void CreateRegistryKey(bool is64bit, Guid clsid, string module)
{
using (RegistryHandle regKey = RegistryHandle.GetBitnessHKCR(is64bit))
{
using (RegistryHandle clsidKey = regKey.CreateSubKey(@"clsid\" + clsid.ToString("B")))
{
clsidKey.SetValue("", ListenerWSUName);
using (RegistryHandle inprocServer32Key = clsidKey.CreateSubKey("InprocServer32"))
{
inprocServer32Key.SetValue("", module);
inprocServer32Key.SetValue("ThreadingModel", "Both");
}
using (RegistryHandle progID = clsidKey.CreateSubKey("ProgID"))
{
progID.SetValue("", ListenerWSUName);
}
}
}
}
public static bool IsApplicationWow(Guid appid)
{
if (IntPtr.Size == 8)
{
string application = appid.ToString("B");
string partitionId = null;
ICatalog2 catalog = GetCatalog();
partitionId = GetPartitionIdForApplication(catalog, application, false);
// Search for the listener in this partition..
bool is64bit = GetApplicationBitness(catalog, partitionId, application);
return !is64bit;
}
else
return false;
}
public static void InstallListener(Guid appid, string path, RuntimeVersions runtimeVersion)
{
string application = appid.ToString("B");
string partitionId = null;
ICatalog2 catalog = GetCatalog();
partitionId = GetPartitionIdForApplication(catalog, application, false);
// Search for the listener in this partition..
bool is64bit = GetApplicationBitness(catalog, partitionId, application);
Guid clsidVal = Guid.NewGuid();
string clsid = clsidVal.ToString("B");
string tlb = Path.Combine(path, application + "." + clsid + ".tlb");
try
{
// No other listener in this partition, we're the first - install using RegistrationHelper
AtomicFile.SafeDeleteFile(tlb);
string modulePath = GetAppropriateBitnessModuleModulePath(is64bit, runtimeVersion);
if (string.IsNullOrEmpty(modulePath))
throw Tool.CreateException(SR.GetString(SR.CannotFindServiceInitializerModuleInRegistry), null);
CreateTypeLib(tlb, clsidVal);
CreateRegistryKey(is64bit, clsidVal, modulePath);
catalog.InstallComponent(application, modulePath, tlb, null);
MarkComponentAsPrivate(catalog, partitionId, application, ListenerWSUName);
if (!SetComponentProperty(application, ListenerWSUName, PropertyName.Description, ListenerComponentDescription))
ToolConsole.WriteWarning(SR.GetString(SR.CannotSetComponentDescription, clsid, appid.ToString("B")));
if (!SetComponentProperty(application, ListenerWSUName, PropertyName.InitializesServerApplication, "1"))
ToolConsole.WriteWarning(SR.GetString(SR.CannotSetComponentInitializerProperty, ListenerWSUName, appid.ToString("B")));
if (!SetComponentProperty(application, ListenerWSUName, PropertyName.ComponentAccessChecksEnabled, "0"))
ToolConsole.WriteWarning(SR.GetString(SR.CannotDisableAccessChecksOnInitializer, ListenerWSUName, appid.ToString("B")));
}
catch (Exception ex)
{
if (ex is NullReferenceException || ex is SEHException)
{
throw ex;
}
throw Tool.CreateException(SR.GetString(SR.CouldNotInstallListener), ex);
}
finally
{
AtomicFile.SafeDeleteFile(tlb);
}
}
static void MarkComponentAsPrivate(ICatalog2 catalog, string partitionID, string applicationID, string progid)
{
ICatalogCollection partitions = (ICatalogCollection)(catalog.GetCollection(CollectionName.Partitions));
ICatalogCollection applications = (ICatalogCollection)(partitions.GetCollection(CollectionName.Applications, partitionID));
applications.Populate();
ICatalogCollection components = (ICatalogCollection)applications.GetCollection(CollectionName.Components, applicationID);
try
{
components.Populate();
for (int j = 0; j < components.Count(); j++)
{
ICatalogObject component = (ICatalogObject)(components.Item(j));
if ((string)component.Name() == progid)
{
component.SetValue(PropertyName.IsPrivateComponent, true);
components.SaveChanges();
break;
}
}
}
catch (Exception ex)
{
if (ex is NullReferenceException || ex is SEHException)
{
throw ex;
}
ToolConsole.WriteWarning(SR.GetString(SR.FailedToMarkListenerComponentAsPrivateForApplication, progid, applicationID));
}
}
static bool IsBitness64bit(ICatalogObject component)
{
int bitness = (int)component.GetValue(PropertyName.Bitness);
if (bitness == 1)
{
return false;
}
else
{
return true;
}
}
internal static bool IsListenerComponent(ICatalogObject compObj)
{
string compName = (string)compObj.Name();
if (compName.ToUpperInvariant() == ListenerWSUName.ToUpperInvariant())
return true;
return false;
}
static void RemoveClsidFromRegistry(bool is64bit, string clsid)
{
RegistryHandle regKey = RegistryHandle.GetBitnessHKCR(is64bit);
string baseKey = "Clsid\\" + clsid;
regKey.DeleteKey(baseKey + "\\InprocServer32");
regKey.DeleteKey(baseKey + "\\ProgID");
regKey.DeleteKey(baseKey);
}
// returns true if deleted
static bool RemoveComponent(ICatalog2 catalog, string partitionId, string applicationId, string progid)
{
int deleteIndex = -1;
ICatalogCollection partitions = (ICatalogCollection)catalog.GetCollection(CollectionName.Partitions);
partitions.Populate();
ICatalogCollection applications = (ICatalogCollection)(partitions.GetCollection(CollectionName.Applications, partitionId));
applications.Populate();
ICatalogCollection components = (ICatalogCollection)(applications.GetCollection(CollectionName.Components, applicationId));
try
{
components.Populate();
bool is64bit = false;
string clsid = null;
for (int i = 0; i < components.Count(); i++)
{
ICatalogObject comp = (ICatalogObject)components.Item(i);
if (((string)comp.Name()).ToLowerInvariant() == progid.ToLowerInvariant())
{
clsid = ((string)comp.Key()).ToLowerInvariant();
is64bit = IsBitness64bit(comp);
deleteIndex = i;
break;
}
}
if (deleteIndex == -1)
{
return false;
}
components.Remove(deleteIndex);
components.SaveChanges();
RemoveClsidFromRegistry(is64bit, clsid);
}
catch (Exception e)
{
if (e is NullReferenceException || e is SEHException)
{
throw e;
}
ToolConsole.WriteWarning(SR.GetString(SR.FailedToRemoveListenerComponentFromApplication, applicationId, progid));
}
return true;
}
public static bool RemoveListener(Guid appid)
{
string application = appid.ToString("B");
string partitionId = null;
Guid listenerClsid;
string listenerProgid;
ICatalog2 catalog = GetCatalog();
partitionId = GetPartitionIdForApplication(catalog, application, false);
bool is64bit = GetApplicationBitness(catalog, partitionId, application);
if (FindListener(appid, out listenerClsid, out listenerProgid))
return RemoveComponent(catalog, partitionId, application, listenerProgid);
return false;
}
public static bool ResolveApplicationId(string appidOrName, out Guid appId)
{
ICatalogObject appObj = null;
ICatalogCollection appColl = null;
appId = Guid.Empty;
if (!FindApplication(appidOrName, out appObj, out appColl))
{
return false;
}
appId = new Guid((string)appObj.Key());
return true;
}
static void SetCurrentPartition(ICatalog2 catalog, string partitionId)
{
try
{
catalog.CurrentPartition(partitionId);
}
catch (Exception e)
{
if (e is NullReferenceException || e is SEHException)
{
throw e;
}
throw Tool.CreateException(SR.GetString(SR.CouldNotSetPartition), e);
}
}
public static void SetAppDir(string appidOrName, string path)
{
ICatalogObject appObj = null;
ICatalogCollection appColl = null;
if (!FindApplication(appidOrName, out appObj, out appColl))
{
throw Tool.CreateException(SR.GetString(SR.ApplicationNotFound, appidOrName), null);
}
appObj.SetValue(PropertyName.ApplicationDirectory, path);
appColl.SaveChanges();
}
}
class ComAdminAppInfo
{
string appdir;
Guid appid;
string appname;
bool serverActivated;
bool systemApplication;
bool processPooled;
bool automaticRecycling;
bool listenerExists;
List<ComAdminClassInfo> classes;
RuntimeVersions runtimeVersion;
static Guid CLSID_CLRMetaHost = new Guid("{9280188d-0e8e-4867-b30c-7fa83884e8de}");
static Guid CLSID_ServiceInitializer = new Guid("{59856830-3ECB-4D29-9CFE-DDD0F74B96A2}");
static List<Version> CLRVersions = new List<Version>(2) { new Version("2.0"), new Version("4.0") };
public string ApplicationDirectory { get { return this.appdir; } }
public Guid ID { get { return this.appid; } }
public string Name { get { return this.appname; } }
public List<ComAdminClassInfo> Classes { get { return this.classes; } }
public bool IsServerActivated { get { return this.serverActivated; } }
public bool IsSystemApplication { get { return this.systemApplication; } }
public bool IsProcessPooled { get { return this.processPooled; } }
public bool IsAutomaticRecycling { get { return this.automaticRecycling; } }
public bool ListenerExists { get { return this.listenerExists; } }
public RuntimeVersions RuntimeVersion { get { return this.runtimeVersion; } }
public ComAdminAppInfo(ICatalogObject appObj, ICatalogCollection appColl)
{
this.appid = new Guid((string)appObj.Key());
this.appname = (string)appObj.Name();
this.appdir = (string)appObj.GetValue(PropertyName.ApplicationDirectory);
// Note that casting to long would throw an InvalidCastException
this.serverActivated = ((int)appObj.GetValue(PropertyName.Activation)) == 1;
this.systemApplication = (bool)appObj.GetValue(PropertyName.IsSystem);
this.processPooled = ((int)appObj.GetValue(PropertyName.ConcurrentApps)) > 1;
this.automaticRecycling = (((int)appObj.GetValue(PropertyName.RecycleActivationLimit) > 0) ||
((int)appObj.GetValue(PropertyName.RecycleCallLimit) > 0) ||
((int)appObj.GetValue(PropertyName.RecycleLifetimeLimit) > 0) ||
((int)appObj.GetValue(PropertyName.RecycleMemoryLimit) > 0));
this.BuildClasses(appObj, appColl);
}
bool TryGetVersionFromString(StringBuilder versionStr, out Version version)
{
string versionString;
bool isSuccessful = false;
version = null;
if (versionStr[0] == 'v' || versionStr[0] == 'V')
{
int strLen = versionStr.Length - 1;
versionString = versionStr.ToString(1, strLen);
}
else
{
versionString = versionStr.ToString();
}
try
{
version = new Version(versionString);
isSuccessful = true;
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
return isSuccessful;
}
bool IsCLRVersionInstalled(Version clrVersion)
{
object pCLRMetaHost;
bool isRuntimeVersionDetermined = false;
if (SafeNativeMethods.ERROR_SUCCESS == SafeNativeMethods.CLRCreateInstance(CLSID_CLRMetaHost, typeof(IClrMetaHost).GUID, out pCLRMetaHost))
{
IClrMetaHost metaHost = (IClrMetaHost)pCLRMetaHost;
IEnumUnknown enumUnknownPtr;
enumUnknownPtr = metaHost.EnumerateInstalledRuntimes();
object[] pUnk = new object[1];
int pceltFetched;
while (SafeNativeMethods.ERROR_SUCCESS == enumUnknownPtr.Next(1, pUnk, out pceltFetched) && !isRuntimeVersionDetermined)
{
int bufferSize = 256;
StringBuilder builder = new StringBuilder(256);
IClrRuntimeInfo runtimeInfo = (IClrRuntimeInfo)pUnk[0];
runtimeInfo.GetVersionString(builder, ref bufferSize);
Version installedClrVersion;
if (TryGetVersionFromString(builder, out installedClrVersion))
{
if (clrVersion.Major == installedClrVersion.Major && clrVersion.Minor == installedClrVersion.Minor)
{
isRuntimeVersionDetermined = true;
}
}
}
}
return isRuntimeVersionDetermined;
}
bool ValidateCLRVersion(Version clrVersion)
{
foreach (Version releasedCLRVersion in CLRVersions)
{
if (clrVersion.Major == releasedCLRVersion.Major && clrVersion.Minor == releasedCLRVersion.Minor)
{
return true;
}
}
return false;
}
void BuildClasses(ICatalogObject appObj, ICatalogCollection appColl)
{
int versionStrSize = 256;
StringBuilder version = new StringBuilder(256);
bool isFrameworkVersionSet = false;
bool isRuntimeVersionSet = false;
bool isRuntimeVersionInstalled = true;
int length = 0;
Version appClrVersion = null;
this.classes = new List<ComAdminClassInfo>();
ICatalogCollection comps = (ICatalogCollection)appColl.GetCollection(CollectionName.Components, appObj.Key());
comps.Populate();
for (int i = 0; i < comps.Count(); i++)
{
ICatalogObject comp = (ICatalogObject)comps.Item(i);
ComAdminClassInfo classInfo = new ComAdminClassInfo(comp, comps);
isFrameworkVersionSet = false;
if (!isRuntimeVersionSet)
{
isFrameworkVersionSet = (SafeNativeMethods.ERROR_SUCCESS == SafeNativeMethods.GetRequestedRuntimeVersionForCLSID(classInfo.Clsid, version, versionStrSize, ref length, 0));
if (isFrameworkVersionSet && TryGetVersionFromString(version, out appClrVersion))
{
if (IsCLRVersionInstalled(appClrVersion))
{
isRuntimeVersionSet = true;
}
else if (ValidateCLRVersion(appClrVersion))
{
// We've found an valid CLR version in the app but that runtime version is not installed
isRuntimeVersionSet = true;
isRuntimeVersionInstalled = false;
}
}
}
if (ComAdminWrapper.IsListenerComponent(comp))
{
this.listenerExists = true;
}
else
{
this.classes.Add(classInfo);
}
}
//Parse the version number we get
// If the version is V4.0* we are going to register the 4.0 version of ServiceMonikerSupport.dll
// Anything else we are going to register the 3.0 version of ServiceMonikerSupport.dll
if (isRuntimeVersionSet && isRuntimeVersionInstalled)
{
if (appClrVersion.Major == 4 && appClrVersion.Minor == 0)
{
this.runtimeVersion = RuntimeVersions.V40;
}
else if (appClrVersion.Major == 2 && appClrVersion.Minor == 0)
{
this.runtimeVersion = RuntimeVersions.V20;
}
else
{
// It is non of the CLR version this tool recognize
throw Tool.CreateException(SR.GetString(SR.FailedToGetRuntime, appClrVersion.ToString()), null);
}
}
else if (!isRuntimeVersionInstalled)
{
// When we can't find the matching runtime for the user application, throw an application exception
throw Tool.CreateException(SR.GetString(SR.FailedToGetRuntime, appClrVersion.ToString()), null);
}
else
{
this.runtimeVersion = RuntimeVersions.V40;
}
}
public ComAdminClassInfo FindClass(string classNameOrGuid)
{
ComAdminClassInfo resolvedClassInfo = null;
classNameOrGuid = classNameOrGuid.ToLowerInvariant();
foreach (ComAdminClassInfo classInfo in this.classes)
{
if ((classInfo.Clsid.ToString("B").ToLowerInvariant() == classNameOrGuid)
|| classInfo.Name.ToLowerInvariant() == classNameOrGuid)
{
if (resolvedClassInfo == null)
{
resolvedClassInfo = classInfo;
}
else
{
throw Tool.CreateException(SR.GetString(SR.AmbiguousComponentName, classNameOrGuid), null);
}
}
}
return resolvedClassInfo;
}
}
class ComAdminClassInfo
{
Guid clsid;
List<ComAdminInterfaceInfo> interfaces;
bool isPrivate;
string progid;
TransactionOption transactionOption;
public Guid Clsid { get { return this.clsid; } }
public bool IsPrivate { get { return this.isPrivate; } }
public string Name { get { return this.progid; } }
public List<ComAdminInterfaceInfo> Interfaces { get { return this.interfaces; } }
public bool SupportsTransactionFlow
{
get
{
if ((transactionOption == TransactionOption.Required) ||
(transactionOption == TransactionOption.Supported))
return true;
else
return false;
}
}
public ComAdminClassInfo(ICatalogObject compObj, ICatalogCollection compColl)
{
this.clsid = new Guid((string)compObj.Key());
this.progid = (string)compObj.Name();
this.isPrivate = (bool)compObj.GetValue(PropertyName.IsPrivateComponent);
this.transactionOption = (TransactionOption)compObj.GetValue(PropertyName.TransactionOption);
this.BuildInterfaces(compObj, compColl);
}
void BuildInterfaces(ICatalogObject compObj, ICatalogCollection compColl)
{
this.interfaces = new List<ComAdminInterfaceInfo>();
ICatalogCollection interfaceColl = (ICatalogCollection)compColl.GetCollection(CollectionName.InterfacesForComponent, compObj.Key());
interfaceColl.Populate();
for (int i = 0; i < interfaceColl.Count(); i++)
{
ICatalogObject itf = (ICatalogObject)interfaceColl.Item(i);
Guid interfaceID = new Guid((string)itf.Key());
ComAdminInterfaceInfo interfaceInfo = new ComAdminInterfaceInfo(interfaceID, (string)itf.Name());
this.interfaces.Add(interfaceInfo);
}
}
public ComAdminInterfaceInfo FindInterface(string interfaceNameOrGuid)
{
ComAdminInterfaceInfo resolvedInterfaceInfo = null;
interfaceNameOrGuid = interfaceNameOrGuid.ToLowerInvariant();
foreach (ComAdminInterfaceInfo interfaceInfo in this.interfaces)
{
if ((interfaceInfo.Iid.ToString("B").ToLowerInvariant() == interfaceNameOrGuid.ToLowerInvariant())
|| interfaceInfo.Name.ToLowerInvariant() == interfaceNameOrGuid)
{
if (resolvedInterfaceInfo == null)
{
resolvedInterfaceInfo = interfaceInfo;
}
else
{
throw Tool.CreateException(SR.GetString(SR.AmbiguousInterfaceName, interfaceNameOrGuid), null);
}
}
}
return resolvedInterfaceInfo;
}
}
class ComAdminInterfaceInfo
{
Guid iid;
string name;
public Guid Iid { get { return this.iid; } }
public string Name { get { return this.name; } }
public ComAdminInterfaceInfo(Guid iid, string name)
{
this.iid = iid;
this.name = name;
}
}
}
| 39.429825 | 191 | 0.556396 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/cdf/src/WCF/Tools/comsvcutil/ComAdminWrapper.cs | 35,960 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using ICSharpCode.Reporting.Interfaces.Export;
using ICSharpCode.Reporting.PageBuilder.ExportColumns;
namespace ICSharpCode.Reporting.Items
{
/// <summary>
/// Description of BaseRowItem.
/// </summary>
public class BaseRowItem:ReportContainer
{
public BaseRowItem()
{
}
public override IExportColumn CreateExportColumn()
{
var er = new ExportRow();
er.ToExportItem(this);
// var er = new ExportRow(){
// Name = this.Name,
// Size = this.Size,
// Location = this.Location,
// CanGrow = this.CanGrow,
// BackColor = this.BackColor,
// DesiredSize = this.Size
// };
return er;
}
}
}
| 36.895833 | 93 | 0.734613 | [
"MIT"
] | TetradogOther/SharpDevelop | src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Items/BaseRowItem.cs | 1,773 | C# |
using System;
using System.IO;
using Conjuntos.Entities;
using System.Collections.Generic;
namespace Conjuntos
{
class Program
{
static void Main(string[] args)
{
HashSet<LogRecords> set = new HashSet<LogRecords>();
Console.WriteLine("Enter file full path: ");
string path = Console.ReadLine();
try
{
using (StreamReader sr = File.OpenText(path))
while (!sr.EndOfStream)
{
string[] line = sr.ReadLine().Split(' ');
string name = line[0];
DateTime instant = DateTime.Parse(line[1]);
set.Add(new LogRecords { Username = name, Instant = instant });
}
Console.WriteLine("Total Users: " + set.Count);
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
}
}
}
| 26.684211 | 87 | 0.469428 | [
"MIT"
] | AllisonSBahls/csharp | Conjuntos/Conjuntos/Program.cs | 1,016 | C# |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
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("HookProCommands")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Acme")]
[assembly: AssemblyProduct("HookProCommands")]
[assembly: AssemblyCopyright("Copyright © Acme 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("588e8517-6081-4373-aba7-f346ea531bed")]
// 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")]
| 36.254545 | 84 | 0.746239 | [
"Apache-2.0"
] | Dithn/arcgis-pro-sdk-community-samples | Framework/HookProCommands/Properties/AssemblyInfo.cs | 1,995 | C# |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
using com.spacepuppy;
namespace com.spacepuppyeditor
{
public class ComponentHeaderDrawer : GUIDrawer
{
#region Fields
private ComponentHeaderAttribute _attribute;
private System.Type _componentType;
#endregion
#region CONSTRUCTOR
internal void Init(ComponentHeaderAttribute attrib, System.Type compType)
{
_attribute = attrib;
_componentType = compType;
}
#endregion
#region Properties
public ComponentHeaderAttribute Attribute { get { return _attribute; } }
public System.Type ComponentType { get { return _componentType; } }
#endregion
#region Methods
public virtual float GetHeight(SerializedObject serializedObject)
{
return 0f;
}
public virtual void OnGUI(Rect position, SerializedObject serializedObject)
{
}
#endregion
}
}
| 19.574074 | 83 | 0.637654 | [
"Unlicense"
] | dipique/spacepuppy-unity-framework-3.0 | SpacepuppyUnityFrameworkEditor/ComponentHeaderDrawer.cs | 1,059 | C# |
using System.Collections.Generic;
public class Item
{
public List<MotionPathData> motionPathData;
public int recordDay;
}
| 17.2 | 55 | 0.581395 | [
"MIT"
] | s-albert/GtToGpx | model/Item.cs | 172 | 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 Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Extensions;
/// <summary>Schedule resource properties used for updates.</summary>
public partial class ScheduleUpdateProperties :
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IScheduleUpdateProperties,
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IScheduleUpdatePropertiesInternal
{
/// <summary>Internal Acessors for RecurrencePattern</summary>
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePattern Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IScheduleUpdatePropertiesInternal.RecurrencePattern { get => (this._recurrencePattern = this._recurrencePattern ?? new Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.RecurrencePattern()); set { {_recurrencePattern = value;} } }
/// <summary>Backing field for <see cref="Note" /> property.</summary>
private string _note;
/// <summary>Notes for this schedule.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Owned)]
public string Note { get => this._note; set => this._note = value; }
/// <summary>Backing field for <see cref="RecurrencePattern" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePattern _recurrencePattern;
/// <summary>The recurrence pattern of the scheduled actions.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Owned)]
internal Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePattern RecurrencePattern { get => (this._recurrencePattern = this._recurrencePattern ?? new Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.RecurrencePattern()); set => this._recurrencePattern = value; }
/// <summary>When the recurrence will expire. This date is inclusive.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Inlined)]
public global::System.DateTime? RecurrencePatternExpirationDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePatternInternal)RecurrencePattern).ExpirationDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePatternInternal)RecurrencePattern).ExpirationDate = value ?? default(global::System.DateTime); }
/// <summary>The frequency of the recurrence.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.RecurrenceFrequency? RecurrencePatternFrequency { get => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePatternInternal)RecurrencePattern).Frequency; set => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePatternInternal)RecurrencePattern).Frequency = value ?? ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.RecurrenceFrequency)""); }
/// <summary>
/// The interval to invoke the schedule on. For example, interval = 2 and RecurrenceFrequency.Daily will run every 2 days.
/// When no interval is supplied, an interval of 1 is used.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Inlined)]
public int? RecurrencePatternInterval { get => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePatternInternal)RecurrencePattern).Interval; set => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePatternInternal)RecurrencePattern).Interval = value ?? default(int); }
/// <summary>The week days the schedule runs. Used for when the Frequency is set to Weekly.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Inlined)]
public Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.WeekDay[] RecurrencePatternWeekDay { get => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePatternInternal)RecurrencePattern).WeekDay; set => ((Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePatternInternal)RecurrencePattern).WeekDay = value ?? null /* arrayOf */; }
/// <summary>Backing field for <see cref="StartAt" /> property.</summary>
private global::System.DateTime? _startAt;
/// <summary>
/// When lab user virtual machines will be started. Timestamp offsets will be ignored and timeZoneId is used instead.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Owned)]
public global::System.DateTime? StartAt { get => this._startAt; set => this._startAt = value; }
/// <summary>Backing field for <see cref="StopAt" /> property.</summary>
private global::System.DateTime? _stopAt;
/// <summary>
/// When lab user virtual machines will be stopped. Timestamp offsets will be ignored and timeZoneId is used instead.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Owned)]
public global::System.DateTime? StopAt { get => this._stopAt; set => this._stopAt = value; }
/// <summary>Backing field for <see cref="TimeZoneId" /> property.</summary>
private string _timeZoneId;
/// <summary>The IANA timezone id for the schedule.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.LabServices.PropertyOrigin.Owned)]
public string TimeZoneId { get => this._timeZoneId; set => this._timeZoneId = value; }
/// <summary>Creates an new <see cref="ScheduleUpdateProperties" /> instance.</summary>
public ScheduleUpdateProperties()
{
}
}
/// Schedule resource properties used for updates.
public partial interface IScheduleUpdateProperties :
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.IJsonSerializable
{
/// <summary>Notes for this schedule.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Notes for this schedule.",
SerializedName = @"notes",
PossibleTypes = new [] { typeof(string) })]
string Note { get; set; }
/// <summary>When the recurrence will expire. This date is inclusive.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"When the recurrence will expire. This date is inclusive.",
SerializedName = @"expirationDate",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? RecurrencePatternExpirationDate { get; set; }
/// <summary>The frequency of the recurrence.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The frequency of the recurrence.",
SerializedName = @"frequency",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.RecurrenceFrequency) })]
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.RecurrenceFrequency? RecurrencePatternFrequency { get; set; }
/// <summary>
/// The interval to invoke the schedule on. For example, interval = 2 and RecurrenceFrequency.Daily will run every 2 days.
/// When no interval is supplied, an interval of 1 is used.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The interval to invoke the schedule on. For example, interval = 2 and RecurrenceFrequency.Daily will run every 2 days. When no interval is supplied, an interval of 1 is used.",
SerializedName = @"interval",
PossibleTypes = new [] { typeof(int) })]
int? RecurrencePatternInterval { get; set; }
/// <summary>The week days the schedule runs. Used for when the Frequency is set to Weekly.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The week days the schedule runs. Used for when the Frequency is set to Weekly.",
SerializedName = @"weekDays",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.WeekDay) })]
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.WeekDay[] RecurrencePatternWeekDay { get; set; }
/// <summary>
/// When lab user virtual machines will be started. Timestamp offsets will be ignored and timeZoneId is used instead.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"When lab user virtual machines will be started. Timestamp offsets will be ignored and timeZoneId is used instead.",
SerializedName = @"startAt",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? StartAt { get; set; }
/// <summary>
/// When lab user virtual machines will be stopped. Timestamp offsets will be ignored and timeZoneId is used instead.
/// </summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"When lab user virtual machines will be stopped. Timestamp offsets will be ignored and timeZoneId is used instead.",
SerializedName = @"stopAt",
PossibleTypes = new [] { typeof(global::System.DateTime) })]
global::System.DateTime? StopAt { get; set; }
/// <summary>The IANA timezone id for the schedule.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The IANA timezone id for the schedule.",
SerializedName = @"timeZoneId",
PossibleTypes = new [] { typeof(string) })]
string TimeZoneId { get; set; }
}
/// Schedule resource properties used for updates.
internal partial interface IScheduleUpdatePropertiesInternal
{
/// <summary>Notes for this schedule.</summary>
string Note { get; set; }
/// <summary>The recurrence pattern of the scheduled actions.</summary>
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.IRecurrencePattern RecurrencePattern { get; set; }
/// <summary>When the recurrence will expire. This date is inclusive.</summary>
global::System.DateTime? RecurrencePatternExpirationDate { get; set; }
/// <summary>The frequency of the recurrence.</summary>
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.RecurrenceFrequency? RecurrencePatternFrequency { get; set; }
/// <summary>
/// The interval to invoke the schedule on. For example, interval = 2 and RecurrenceFrequency.Daily will run every 2 days.
/// When no interval is supplied, an interval of 1 is used.
/// </summary>
int? RecurrencePatternInterval { get; set; }
/// <summary>The week days the schedule runs. Used for when the Frequency is set to Weekly.</summary>
Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.WeekDay[] RecurrencePatternWeekDay { get; set; }
/// <summary>
/// When lab user virtual machines will be started. Timestamp offsets will be ignored and timeZoneId is used instead.
/// </summary>
global::System.DateTime? StartAt { get; set; }
/// <summary>
/// When lab user virtual machines will be stopped. Timestamp offsets will be ignored and timeZoneId is used instead.
/// </summary>
global::System.DateTime? StopAt { get; set; }
/// <summary>The IANA timezone id for the schedule.</summary>
string TimeZoneId { get; set; }
}
} | 69.95288 | 492 | 0.705561 | [
"MIT"
] | Agazoth/azure-powershell | src/LabServices/generated/api/Models/Api20211001Preview/ScheduleUpdateProperties.cs | 13,171 | C# |
using System;
using System.Collections.Generic;
namespace MicroFeel.YonYou.EntityFrameworkCore.Data
{
public partial class OmMomaterials
{
public int MomaterialsId { get; set; }
public int MoDetailsId { get; set; }
public int Moid { get; set; }
public string CInvCode { get; set; }
public decimal? IQuantity { get; set; }
public DateTime? DRequiredDate { get; set; }
public decimal? ISendQty { get; set; }
public string CFree1 { get; set; }
public string CFree2 { get; set; }
public string CFree3 { get; set; }
public string CFree4 { get; set; }
public string CFree5 { get; set; }
public string CFree6 { get; set; }
public string CFree7 { get; set; }
public string CFree8 { get; set; }
public string CFree9 { get; set; }
public string CFree10 { get; set; }
public decimal? FBaseQtyN { get; set; }
public decimal? FBaseQtyD { get; set; }
public decimal? FCompScrp { get; set; }
public byte? BFvqty { get; set; }
public byte? IWiptype { get; set; }
public string CWhCode { get; set; }
public decimal? IUnitQuantity { get; set; }
public string CBatch { get; set; }
public int? OpComponentId { get; set; }
public byte? SubFlag { get; set; }
public string CDefine22 { get; set; }
public string CDefine23 { get; set; }
public string CDefine24 { get; set; }
public string CDefine25 { get; set; }
public float? CDefine26 { get; set; }
public float? CDefine27 { get; set; }
public string CDefine28 { get; set; }
public string CDefine29 { get; set; }
public string CDefine30 { get; set; }
public string CDefine31 { get; set; }
public string CDefine32 { get; set; }
public string CDefine33 { get; set; }
public int? CDefine34 { get; set; }
public int? CDefine35 { get; set; }
public DateTime? CDefine36 { get; set; }
public DateTime? CDefine37 { get; set; }
public decimal? Fbasenumn { get; set; }
public decimal? IUnitNum { get; set; }
public decimal? INum { get; set; }
public decimal? ISendNum { get; set; }
public string CUnitId { get; set; }
public decimal? IComplementQty { get; set; }
public decimal? IComplementNum { get; set; }
public decimal? FTransQty { get; set; }
public byte[] DUfts { get; set; }
public decimal? CBatchProperty1 { get; set; }
public decimal? CBatchProperty2 { get; set; }
public decimal? CBatchProperty3 { get; set; }
public decimal? CBatchProperty4 { get; set; }
public decimal? CBatchProperty5 { get; set; }
public string CBatchProperty6 { get; set; }
public string CBatchProperty7 { get; set; }
public string CBatchProperty8 { get; set; }
public string CBatchProperty9 { get; set; }
public DateTime? CBatchProperty10 { get; set; }
public short? Sotype { get; set; }
public string Sodid { get; set; }
public string Csocode { get; set; }
public int? Irowno { get; set; }
public string Cdemandmemo { get; set; }
public string Cdetailsdemandcode { get; set; }
public string Cdetailsdemandmemo { get; set; }
public string Csendtype { get; set; }
public decimal? Fsendapplyqty { get; set; }
public decimal? Fsendapplynum { get; set; }
public decimal? Fapplyqty { get; set; }
public decimal? Fapplynum { get; set; }
public string CbMemo { get; set; }
public string Csubsysbarcode { get; set; }
public decimal? IPickQty { get; set; }
public decimal? IPickNum { get; set; }
public byte? IProductType { get; set; }
public string CFactoryCode { get; set; }
public virtual OmMomain Mo { get; set; }
public virtual OmModetails MoDetails { get; set; }
}
}
| 43.397849 | 58 | 0.593409 | [
"Apache-2.0"
] | microfeel/Yonyou | MicroFeel.YonYou.EntityFrameworkCore/Data/OmMomaterials.cs | 4,038 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OneStoryProjectEditor
{
public partial class TopForm : Form
{
public TopForm()
{
InitializeComponent();
}
private void TopForm_Load(object sender, EventArgs e)
{
Top = 0;
StoryEditor.SuspendSaveDialog++;
}
private void TopForm_FormClosed(object sender, FormClosedEventArgs e)
{
StoryEditor.SuspendSaveDialog--;
}
}
}
| 21.83871 | 78 | 0.602659 | [
"MIT"
] | bobeaton/OneStoryEditor | StoryEditor/TopForm.cs | 679 | C# |
using Research.Web.Framework.Models;
using System.ComponentModel.DataAnnotations;
namespace Research.Web.Models.Messages
{
/// <summary>
/// Represents an email account model
/// </summary>
// [Validator(typeof(EmailAccountValidator))]
public partial class EmailAccountModel : BaseEntityModel
{
#region Properties
[DataType(DataType.EmailAddress)]
// [NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.Email")]
public string Email { get; set; }
//[NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.DisplayName")]
public string DisplayName { get; set; }
//[NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.Host")]
public string Host { get; set; }
//[NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.Port")]
public int Port { get; set; }
//[NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.Username")]
public string Username { get; set; }
//[NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.Password")]
[DataType(DataType.Password)]
//[NoTrim]
public string Password { get; set; }
//[NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.EnableSsl")]
public bool EnableSsl { get; set; }
//[NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.UseDefaultCredentials")]
public bool UseDefaultCredentials { get; set; }
//[NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.IsDefaultEmailAccount")]
public bool IsDefaultEmailAccount { get; set; }
// [NopResourceDisplayName("Admin.Configuration.EmailAccounts.Fields.SendTestEmailTo")]
public string SendTestEmailTo { get; set; }
#endregion
}
} | 37.877551 | 100 | 0.695043 | [
"MIT"
] | Sakchai/ResearchProject | Research.Web.Framework/Models/Messages/EmailAccountModel.cs | 1,858 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using CrmSystem.Domain.Models;
using CrmSystem.Domain.Repositories;
namespace CrmSystem.EntityFramework.Repositories
{
public class ContactNoteRepository : Repository<ContactNote>, IContactNoteRepository
{
public CrmSystemContext CrmSystemContext => Context as CrmSystemContext;
public ContactNoteRepository(DbContext context) : base(context)
{
}
public override IEnumerable<ContactNote> Find(Expression<Func<ContactNote, bool>> predicate)
{
return CrmSystemContext.Set<ContactNote>().Include(cn => cn.Contact)
.Include(cn => cn.Contact.Company).Where(predicate)
.Include(cn => cn.CreatedBy)
.Include(cn => cn.ModifiedBy);
}
}
} | 33.961538 | 100 | 0.689694 | [
"MIT"
] | eabasquliyev/CRMSystem | CrmSystem.EntityFramework/Repositories/ContactNoteRepository.cs | 885 | 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 guardduty-2017-11-28.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.GuardDuty.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.GuardDuty.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribePublishingDestination operation
/// </summary>
public class DescribePublishingDestinationResponseUnmarshaller : 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)
{
DescribePublishingDestinationResponse response = new DescribePublishingDestinationResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("destinationId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.DestinationId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("destinationProperties", targetDepth))
{
var unmarshaller = DestinationPropertiesUnmarshaller.Instance;
response.DestinationProperties = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("destinationType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.DestinationType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("publishingFailureStartTimestamp", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
response.PublishingFailureStartTimestamp = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Status = 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)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException"))
{
return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonGuardDutyException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DescribePublishingDestinationResponseUnmarshaller _instance = new DescribePublishingDestinationResponseUnmarshaller();
internal static DescribePublishingDestinationResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribePublishingDestinationResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.666667 | 192 | 0.630791 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/GuardDuty/Generated/Model/Internal/MarshallTransformations/DescribePublishingDestinationResponseUnmarshaller.cs | 5,612 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.ComponentModel;
namespace Azure.ResourceManager.ConnectedVmware.Models
{
/// <summary> The type of managed service identity. </summary>
public readonly partial struct IdentityType : IEquatable<IdentityType>
{
private readonly string _value;
/// <summary> Initializes a new instance of <see cref="IdentityType"/>. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public IdentityType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string NoneValue = "None";
private const string SystemAssignedValue = "SystemAssigned";
/// <summary> None. </summary>
public static IdentityType None { get; } = new IdentityType(NoneValue);
/// <summary> SystemAssigned. </summary>
public static IdentityType SystemAssigned { get; } = new IdentityType(SystemAssignedValue);
/// <summary> Determines if two <see cref="IdentityType"/> values are the same. </summary>
public static bool operator ==(IdentityType left, IdentityType right) => left.Equals(right);
/// <summary> Determines if two <see cref="IdentityType"/> values are not the same. </summary>
public static bool operator !=(IdentityType left, IdentityType right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="IdentityType"/>. </summary>
public static implicit operator IdentityType(string value) => new IdentityType(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is IdentityType other && Equals(other);
/// <inheritdoc />
public bool Equals(IdentityType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
| 44.423077 | 131 | 0.670563 | [
"MIT"
] | RecencyBias/azure-sdk-for-net | sdk/connectedvmware/Azure.ResourceManager.ConnectedVmware/src/Generated/Models/IdentityType.cs | 2,310 | C# |
// Copyright (c) 2021 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/
// Licensed under MIT license. See License.txt in the project root for license information.
namespace AuthPermissions.SetupCode
{
/// <summary>
/// The different database types that AuthPermissions supports
/// </summary>
public enum AuthPDatabaseTypes
{
/// <summary>
/// This is the default - AuthPermissions will throw an exception to say you must define the database type
/// </summary>
NotSet,
/// <summary>
/// This is a in-memory database - useful for unit testing
/// </summary>
SqliteInMemory,
/// <summary>
/// SQL Server database is used
/// </summary>
SqlServer
}
} | 33.166667 | 114 | 0.619347 | [
"MIT"
] | JonPSmith/AuthPermissions.AspNetCore | AuthPermissions/SetupCode/DatabaseTypes.cs | 798 | C# |
using o2g.Types.RoutingNS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace o2g.Internal.Types.Routing
{
internal class O2GRoutingState
{
public List<PresentationRoute> PresentationRoutes { get; set; }
public List<ForwardRoute> ForwardRoutes { get; set; }
public List<OverflowRoute> OverflowRoutes { get; set; }
public DndState DndState { get; set; }
private bool? GetRemoteExtensionActivation()
{
if ((PresentationRoutes == null) || (PresentationRoutes.Count == 0))
{
return null;
}
for (int i = 0; i < PresentationRoutes.Count; i++)
{
PresentationRoute presentationRoute = PresentationRoutes[i];
for (int j = 0; j < PresentationRoutes[i].Destinations.Count; j++)
{
O2GDestination destination = PresentationRoutes[i].Destinations[j];
if (destination.Type == "MOBILE")
{
if (destination.Selected.HasValue)
{
return destination.Selected.Value;
}
}
}
}
return null;
}
public RoutingState ToRoutingState()
{
RoutingState routingState = new();
routingState.DndState = DndState;
if ((ForwardRoutes != null) && (ForwardRoutes.Count > 0))
{
routingState.Forward = ForwardRoutes[0].ToForward();
}
else
{
routingState.Forward = new()
{
Destination = Destination.None
};
}
if ((OverflowRoutes != null) && (OverflowRoutes.Count > 0))
{
routingState.Overflow = OverflowRoutes[0].ToOverflow();
}
else
{
routingState.Overflow = new()
{
Destination = Destination.None
};
}
routingState.RemoteExtensionActivated = GetRemoteExtensionActivation();
return routingState;
}
}
}
| 30 | 87 | 0.494444 | [
"MIT"
] | ALE-OPENNESS/CSharp-SDK | Internal/Types/Routing/O2GRoutingState.cs | 2,342 | C# |
/*
* Copyright (c) Contributors, http://vision-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
* For an explanation of the license of each contributor and the content it
* covers please see the Licenses directory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Vision-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using Vision.Framework.SceneInfo;
namespace Vision.Framework.Modules
{
public interface ITerrainChannel
{
int Height { get; }
float this[int x, int y] { get; set; }
int Width { get; }
IScene Scene { get; set; }
/// <summary>
/// Squash the entire heightmap into a single dimensioned array
/// </summary>
/// <returns></returns>
short[] GetSerialized();
bool Tainted(int x, int y);
ITerrainChannel MakeCopy();
/// <summary>
/// Gets the average height of the area +2 in both the X and Y directions from the given position
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
float GetNormalizedGroundHeight(int x, int y);
/// <summary>
/// Gets the average height of land above the waterline at the specified point.
/// </summary>
/// <returns>The normalized land height.</returns>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
float GetNormalizedLandHeight (int x, int y);
/// <summary>
/// Generates new terrain based upon supplied parameters.
/// </summary>
/// <param name="landType">Land type.</param>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
/// <param name="smoothing">Smoothing.</param>
/// <param name="scene">Scene.</param>
void GenerateTerrain(string terrainType, float min, float max, int smoothing, IScene scene);
/// <summary>
/// Recalculates land area.
/// </summary>
void ReCalcLandArea ();
}
} | 43.337349 | 110 | 0.641646 | [
"MIT"
] | VisionSim/Vision-Sim | Vision/Framework/Modules/ITerrainChannel.cs | 3,597 | 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("13. LinkedQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("13. LinkedQueue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("487afb05-8cb7-446c-be6a-78cf1cce57fa")]
// 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.918919 | 84 | 0.743407 | [
"MIT"
] | mirkatabga/TelerikAcademyHomeworks | Data-Structures-and-Algorithms/LinearDataStructuresHomework/13. LinkedQueue/Properties/AssemblyInfo.cs | 1,406 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace SoftJail.DataProcessor.ExportDto
{
[XmlType("Message")]
public class ExportMessageDto
{
public string Description { get; set; }
}
}
| 19.071429 | 47 | 0.715356 | [
"Apache-2.0"
] | KostadinovK/CSharp-DB | 02-Entity Framework Core/13-Past Exams/Exam 12.08.2018/SoftJail/DataProcessor/ExportDto/ExportMessageDto.cs | 269 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class UIController : MonoBehaviour {
[SerializeField] private Slider racistSlider;
[SerializeField] private Toggle invertControlsToggle;
[SerializeField] private InputField field;
[SerializeField] private GameObject pausePanel;
private void Start() {
//PlayerPrefs.DeleteAll();
if (field) {
field.onEndEdit.AddListener(ChangeName);
field.text = PlayerPrefs.GetString("player_name", "Lil Dicky");
}
}
private void Update () {
if (Input.GetKey("escape")) {
if(SceneManager.GetActiveScene().name == "MainUIScene") {
ExitGame();
}
else if(GameManager.Instance.playerController.dickMoving) {
Time.timeScale = 0.0f;
pausePanel.SetActive(true);
}
}
}
private void ChangeName(string name) {
PlayerPrefs.SetString("player_name", name);
}
public void Restart () {
Time.timeScale = 1f;
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void ExitGame () {
Application.Quit();
}
public void GoToMainMenu () {
Time.timeScale = 1f;
SceneManager.LoadScene("MainUIScene");
}
public void GoToHighScore () {
Time.timeScale = 1f;
SceneManager.LoadScene("Highscore");
}
public void GoToCredits () {
Time.timeScale = 1f;
SceneManager.LoadScene("Credits");
}
public void OnPlayGame () {
int newValue = (int)racistSlider.value;
Debug.Log("Racist Difficulty changed from: "+ PlayerPrefs.GetInt("racistDifficulty", -1).ToString() + " to: " + newValue.ToString());
PlayerPrefs.SetInt("racistDifficulty", (int)newValue);
int invert = invertControlsToggle.isOn ? 1 : 0;
Debug.Log("Invert Controlls changed from: " + PlayerPrefs.GetInt("invertControls", -1).ToString() + " to: " + invert.ToString());
PlayerPrefs.SetInt("invertControls", invert);
SceneManager.LoadSceneAsync("SpawningScene");
}
public void Resume() {
Time.timeScale = 1f;
pausePanel.SetActive(false);
}
}
| 26.780488 | 135 | 0.658925 | [
"MIT"
] | RokKos/keep-it-in-the-pants | keep-it-in-the-pants/Assets/Scripts/UIController.cs | 2,198 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ExtensionBlocks;
namespace RegistryPlugin.OpenSavePidlMRU.ShellItems
{
public class ShellBag0X1F : ShellBag
{
private readonly List<PropertySheet> _sheets;
public ShellBag0X1F(byte[] rawBytes)
{
ExtensionBlocks = new List<IExtensionBlock>();
PropertyStore = new PropertyStore();
_sheets = new List<PropertySheet>();
var index = 0;
var dataSig = BitConverter.ToUInt32(rawBytes, 6);
if (dataSig == 0xbeebee00)
{
ProcessPropertyViewDefault(rawBytes);
return;
}
if (dataSig == 0xF5A6B710)
{
// this is a strange one. it contains a drive letter and other unknown items
index = 13;
var dl = CodePagesEncodingProvider.Instance.GetEncoding(1252).GetString(rawBytes, index, 3);
FriendlyName = "Users property view?: Drive letter";
Value = dl;
return;
}
if (rawBytes[0] == 0x14) //This is a GUID only
{
ProcessGuid(rawBytes);
return;
}
if (rawBytes[0] == 50 || rawBytes[0] == 58) //This is a GUID and a beefXX, usually 25
{
ProcessGuid(rawBytes);
index += 20;
var extsize = BitConverter.ToInt16(rawBytes, index);
if (extsize > 0)
{
var signature = BitConverter.ToUInt32(rawBytes, index + 4);
var block = Utils.GetExtensionBlockFromBytes(signature, rawBytes.Skip(index).ToArray());
ExtensionBlocks.Add(block);
}
index += extsize;
if (index != rawBytes[0])
{
Debug.WriteLine("remaining data!!!");
}
return;
}
FriendlyName = "Users property view";
var bin = new BinaryReader(new MemoryStream(rawBytes));
bin.ReadBytes(2); // skip size
bin.ReadByte(); //skip indicator (0x1F)
var sortIndicator = bin.ReadByte();
var dataSize = bin.ReadUInt16(); // BitConverter.ToUInt16(rawBytes, index);
var dataSignature = bin.ReadUInt32(); // BitConverter.ToUInt32(rawBytes, index);
var propertyStoreSize = bin.ReadUInt16(); //BitConverter.ToUInt16(rawBytes, index);
var identifierSize = bin.ReadUInt16(); //BitConverter.ToUInt16(rawBytes, index);
if (identifierSize > 0)
{
bin.ReadBytes(identifierSize);
//index += identifierSize; // whats here?
}
if (propertyStoreSize > 0)
{
var propertysheetBytes = bin.ReadBytes(propertyStoreSize);
var propStore = new PropertyStore(propertysheetBytes);
var p = propStore.Sheets.Where(t => t.PropertyNames.ContainsKey("AutoList"));
if (p.Any())
{
//we can now look thry prop bytes for extension blocks
//TODO this is a hack until we can process vectors natively
var extOffsets = new List<int>();
try
{
var regexObj = new Regex("([0-9A-F]{2})-00-EF-BE", RegexOptions.IgnoreCase);
var matchResult = regexObj.Match(BitConverter.ToString(propertysheetBytes));
while (matchResult.Success)
{
extOffsets.Add(matchResult.Index);
matchResult = matchResult.NextMatch();
}
foreach (var extOffset in extOffsets)
{
var binaryOffset = extOffset / 3 - 4;
var exSize = BitConverter.ToInt16(propertysheetBytes, binaryOffset);
var exBytes = propertysheetBytes.Skip(binaryOffset).Take(exSize).ToArray();
var signature1 = BitConverter.ToUInt32(exBytes, 4);
var block1 = Utils.GetExtensionBlockFromBytes(signature1, exBytes);
ExtensionBlocks.Add(block1);
}
}
catch (ArgumentException)
{
throw;
// Syntax error in the regular expression
}
}
PropertyStore = propStore;
}
bin.ReadBytes(2); //skip end of property sheet marker
var rawguid = Utils.ExtractGuidFromShellItem(bin.ReadBytes(16));
// index += 16;
rawguid = Utils.ExtractGuidFromShellItem(bin.ReadBytes(16));
// index += 16;
var name = Utils.GetFolderNameFromGuid(rawguid);
var extsize1 = bin.ReadUInt16(); // BitConverter.ToUInt16(rawBytes, index);
if (extsize1 > 0)
{
//TODO is it ever bigger than one block? if so loop it
//move position back 2 so we get the entire block of data below
bin.BaseStream.Position -= 2;
while (bin.BaseStream.Position != bin.BaseStream.Length)
{
extsize1 = bin.ReadUInt16();
if (extsize1 == 0)
{
break;
}
bin.BaseStream.Position -= 2;
var extBytes = bin.ReadBytes(extsize1);
var signature1 = BitConverter.ToUInt32(extBytes, 4);
//Debug.WriteLine(" 0x1f bag sig: " + signature1.ToString("X8"));
var block1 = Utils.GetExtensionBlockFromBytes(signature1, extBytes);
ExtensionBlocks.Add(block1);
}
//Trace.Assert(bin.BaseStream.Position == bin.BaseStream.Length);
}
Value = name;
}
public PropertyStore PropertyStore { get; private set; }
/// <summary>
/// Last access time of BagPath
/// </summary>
public DateTimeOffset? LastAccessTime { get; set; }
private void ProcessGuid(byte[] rawBytes)
{
FriendlyName = "Root folder: GUID";
var index = 2;
index += 2; // move past index and a single unknown value
var rawguid1 = new byte[16];
Array.Copy(rawBytes, index, rawguid1, 0, 16);
var rawguid = Utils.ExtractGuidFromShellItem(rawguid1);
var foldername = Utils.GetFolderNameFromGuid(rawguid);
index += 16;
Value = foldername;
if (rawBytes.Length == index)
{
}
// var size = BitConverter.ToInt16(rawBytes, index);
// if (size == 0)
// {
// index += 2;
// }
}
private void ProcessPropertyViewDefault(byte[] rawBytes)
{
FriendlyName = "Variable: Users property view";
var index = 10;
var shellPropertySheetListSize = BitConverter.ToInt16(rawBytes, index);
index += 2;
var identifiersize = BitConverter.ToInt16(rawBytes, index);
index += 2;
var identifierData = new byte[identifiersize];
Array.Copy(rawBytes, index, identifierData, 0, identifiersize);
index += identifiersize;
if (shellPropertySheetListSize > 0)
{
var propBytes = rawBytes.Skip(index).Take(shellPropertySheetListSize).ToArray();
var propStore = new PropertyStore(propBytes);
PropertyStore = propStore;
var p = propStore.Sheets.Where(t => t.PropertyNames.ContainsKey("32"));
if (p.Any())
{
//we can now look thry prop bytes for extension blocks
//TODO this is a hack until we can process vectors natively
var extOffsets = new List<int>();
try
{
var regexObj = new Regex("([0-9A-F]{2})-00-EF-BE", RegexOptions.IgnoreCase);
var matchResult = regexObj.Match(BitConverter.ToString(propBytes));
while (matchResult.Success)
{
extOffsets.Add(matchResult.Index);
matchResult = matchResult.NextMatch();
}
foreach (var extOffset in extOffsets)
{
var binaryOffset = extOffset / 3 - 4;
var exSize = BitConverter.ToInt16(propBytes, binaryOffset);
var exBytes = propBytes.Skip(binaryOffset).Take(exSize).ToArray();
var signature1 = BitConverter.ToUInt32(exBytes, 4);
var block1 = Utils.GetExtensionBlockFromBytes(signature1, exBytes);
ExtensionBlocks.Add(block1);
}
}
catch (ArgumentException)
{
throw;
// Syntax error in the regular expression
}
}
}
else
{
if (rawBytes[0x28] == 0x2f ||
rawBytes[0x24] == 0x4e && rawBytes[0x26] == 0x2f && rawBytes[0x28] == 0x41)
{
//we have a good date
var zip = new ShellBagZipContents(rawBytes);
FriendlyName = zip.FriendlyName;
LastAccessTime = zip.LastAccessTime;
Value = zip.Value;
return;
}
Debug.Write("Oh no! No property sheets!");
Value = "!!! Unable to determine Value !!!";
}
index += shellPropertySheetListSize;
index += 2; //move past end of property sheet terminator
var extBlockSize = BitConverter.ToInt16(rawBytes, index);
if (extBlockSize > 0)
{
//process extension blocks
while (extBlockSize > 0)
{
var extBytes = rawBytes.Skip(index).Take(extBlockSize).ToArray();
index += extBlockSize;
var signature1 = BitConverter.ToUInt32(extBytes, 4);
var block1 = Utils.GetExtensionBlockFromBytes(signature1, extBytes);
ExtensionBlocks.Add(block1);
extBlockSize = BitConverter.ToInt16(rawBytes, index);
}
}
int terminator = BitConverter.ToInt16(rawBytes, index);
if (terminator > 0)
{
throw new Exception($"Expected terminator of 0, but got {terminator}");
}
var valuestring = (from propertySheet in PropertyStore.Sheets
from propertyName in propertySheet.PropertyNames
where propertyName.Key == "10"
select propertyName.Value).FirstOrDefault();
if (valuestring == null)
{
var namesList =
(from propertySheet in PropertyStore.Sheets
from propertyName in propertySheet.PropertyNames
select propertyName.Value)
.ToList();
valuestring = string.Join("::", namesList.ToArray());
}
if (valuestring == "")
{
valuestring = "No Property sheet value found";
}
Value = valuestring;
}
public override string ToString()
{
var sb = new StringBuilder();
if (LastAccessTime.HasValue)
{
sb.AppendLine(
$"Accessed On: {LastAccessTime.Value.ToString(Utils.GetDateTimeFormatWithMilliseconds())}");
sb.AppendLine();
}
if (PropertyStore.Sheets.Count > 0)
{
sb.AppendLine("Property Sheets");
sb.AppendLine(PropertyStore.ToString());
}
sb.AppendLine(base.ToString());
return sb.ToString();
}
}
} | 31.181159 | 112 | 0.489891 | [
"MIT"
] | AndrewRathbun/RegistryPlugins | RegistryPlugin.OpenSavePidlMRU/ShellItems/ShellBag0x1f.cs | 12,911 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Attractor : MonoBehaviour
{
public float rotationPull = 1.0f;
public float mass = 1.0f;
private const float gravitationalPull = 667.4f;
private void Start()
{
}
void FixedUpdate()
{
}
private void OnTriggerStay2D(Collider2D collision)
{
Attract(collision.gameObject);
}
void Attract(GameObject objToAttract)
{
//Debug.Log(gameObject.name + " is attracting " + objToAttract.name);
Rigidbody2D rbToAttract = objToAttract.GetComponent<Rigidbody2D>();
Vector2 direction = new Vector2(transform.position.x, transform.position.y) - rbToAttract.position;
float distance = direction.magnitude;
// Position
float forceMagnitude = gravitationalPull * (mass * rbToAttract.mass) / Mathf.Pow(distance, 3);
Vector2 force = direction.normalized * forceMagnitude;
rbToAttract.AddForce(force);
// Rotation
float angle = Vector3.Angle(Vector3.up, objToAttract.transform.position - transform.position);
float currentAngle = objToAttract.transform.eulerAngles.z;
if (objToAttract.transform.position.x > transform.position.x)
{
angle = -angle;
}
float finalAngle = Mathf.LerpAngle(currentAngle, angle, Time.deltaTime);
objToAttract.transform.eulerAngles = new Vector3(0, 0, finalAngle);
}
}
| 30.204082 | 107 | 0.671622 | [
"MIT"
] | cortexarts/Otter-Space-Prototype | Prototype/Assets/Scripts/Controllers/Attractor.cs | 1,482 | C# |
using System.Collections.Generic;
using SecureByDesign.Host.Domain.Model;
namespace SecureByDesign.Host.Domain.Services
{
public class ProductResult
{
public ProductResult(ServiceResult result, Product product)
{
Result = result;
Value = product;
}
public ServiceResult Result { get; }
public Product Value { get; }
}
public class ProductListResult
{
public ProductListResult(ServiceResult result, IEnumerable<Product> products)
{
Result = result;
Value = products;
}
public ServiceResult Result { get; }
public IEnumerable<Product> Value { get; }
}
} | 22.3125 | 85 | 0.607843 | [
"MIT"
] | Omegapoint/rest-sec | labs/6-secdesign/Host/Domain/Services/ProductResult.cs | 714 | C# |
// Copyright 2018-2020 Finbuckle LLC, Andrew White, and Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
namespace Finbuckle.MultiTenant
{
public class MultiTenantOptions
{
public IList<string> IgnoredIdentifiers = new List<string>();
public MultiTenantEvents Events { get; set; } = new MultiTenantEvents();
}
} | 37.5 | 80 | 0.734444 | [
"Apache-2.0"
] | 861191244/Finbuckle.MultiTenant | src/Finbuckle.MultiTenant/MultiTenantOptions.cs | 900 | C# |
// *************************************************************
// project: graphql-aspnet
// --
// repo: https://github.com/graphql-aspnet
// docs: https://graphql-aspnet.github.io
// --
// License: MIT
// *************************************************************
namespace GraphQL.AspNet.Schemas.TypeSystem
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using GraphQL.AspNet.Common;
using GraphQL.AspNet.Common.Extensions;
using GraphQL.AspNet.Interfaces.TypeSystem;
/// <summary>
/// A representation of any given enumeration (fixed set of values) in the type system.
/// </summary>
/// <seealso cref="IEnumGraphType" />
[DebuggerDisplay("ENUM {Name}")]
public class EnumGraphType : IEnumGraphType
{
private readonly Dictionary<string, IEnumOption> _options;
/// <summary>
/// Initializes a new instance of the <see cref="EnumGraphType" /> class.
/// </summary>
/// <param name="name">The name to assign to this enumeration in the graph.</param>
/// <param name="enumType">Type of the enum.</param>
public EnumGraphType(string name, Type enumType)
{
this.Name = Validation.ThrowIfNullEmptyOrReturn(name, nameof(name));
this.ObjectType = Validation.ThrowIfNullOrReturn(enumType, nameof(enumType));
this.InternalName = this.ObjectType.FriendlyName();
this.Publish = true;
_options = new Dictionary<string, IEnumOption>();
}
/// <summary>
/// Adds the option.
/// </summary>
/// <param name="option">The option.</param>
public void AddOption(IEnumOption option)
{
Validation.ThrowIfNull(option, nameof(option));
_options.Add(option.Name, option);
}
/// <summary>
/// Determines whether the provided item is of a concrete type represented by this graph type.
/// </summary>
/// <param name="item">The item to check.</param>
/// <returns><c>true</c> if the item is of the correct type; otherwise, <c>false</c>.</returns>
public bool ValidateObject(object item)
{
if (item == null)
return true;
if (!(item is Enum))
return false;
return Enum.IsDefined(this.ObjectType, item);
}
/// <summary>
/// Gets the values that can be handled by this enumeration.
/// </summary>
/// <value>The values.</value>
public IReadOnlyDictionary<string, IEnumOption> Values => _options;
/// <summary>
/// Gets the formal name of this item as it exists in the object graph.
/// </summary>
/// <value>The publically referenced name of this field in the graph.</value>
public string Name { get; }
/// <summary>
/// Gets or sets the human-readable description distributed with this field
/// when requested. The description should accurately describe the contents of this field
/// to consumers.
/// </summary>
/// <value>The publically referenced description of this field in the type system.</value>
public string Description { get; set; }
/// <summary>
/// Gets the value indicating what type of graph type this instance is in the type system. (object, scalar etc.)
/// </summary>
/// <value>The kind.</value>
public TypeKind Kind => TypeKind.ENUM;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="IGraphType" /> is published on an introspection request.
/// </summary>
/// <value><c>true</c> if publish; otherwise, <c>false</c>.</value>
public virtual bool Publish { get; set; }
/// <summary>
/// Gets the type of the object this graph type was made from.
/// </summary>
/// <value>The type of the object.</value>
public Type ObjectType { get; }
/// <summary>
/// Gets a fully qualified name of the type as it exists on the server (i.e. Namespace.ClassName). This name
/// is used in many exceptions and internal error messages.
/// </summary>
/// <value>The name of the internal.</value>
public string InternalName { get; }
/// <summary>
/// Gets a value indicating whether this instance is virtual and added by the runtime to facilitate
/// a user defined graph structure. When false, this graph types points to a concrete type
/// defined by a developer.
/// </summary>
/// <value><c>true</c> if this instance is virtual; otherwise, <c>false</c>.</value>
public virtual bool IsVirtual => false;
}
} | 39.801653 | 124 | 0.58451 | [
"MIT"
] | NET1211/aspnet-archive-tools | src/graphql-aspnet/Schemas/TypeSystem/EnumGraphType.cs | 4,818 | C# |
using Bucket.Rpc.Messages;
using Newtonsoft.Json;
using System.Text;
namespace Bucket.Rpc.Transport.Codec.Implementation
{
public sealed class JsonTransportMessageEncoder : ITransportMessageEncoder
{
#region Implementation of ITransportMessageEncoder
public byte[] Encode(TransportMessage message)
{
var content = JsonConvert.SerializeObject(message);
return Encoding.UTF8.GetBytes(content);
}
#endregion Implementation of ITransportMessageEncoder
}
}
| 26.6 | 78 | 0.714286 | [
"MIT"
] | q315523275/.net-core- | src/Rpc/DotNetty/Bucket.Rpc/Transport/Codec/Implementation/JsonTransportMessageEncoder.cs | 534 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DrawniteCore.Networking
{
public static class Constants
{
public static readonly string SERVER_IP = "127.0.0.1";
public static readonly int AUTH_PORT = 20000;
}
}
| 20.769231 | 62 | 0.703704 | [
"MIT"
] | Stijnn/DrawniteIO | DrawniteIO/DrawniteCore/Networking/Constants.cs | 272 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using MvvmCross.Core.ViewModels;
using MvvmCrossBackstack.Core.PresentationHints;
namespace MvvmCrossBackstack.Core.ViewModels
{
public class UserDashboardViewModel : MvxViewModel
{
private ICommand _goHomeCommand = null;
private ICommand _showMoreCommand = null;
private int _pageOrder = 0;
public ICommand GoHomeCommand => _goHomeCommand ?? (_goHomeCommand = new MvxCommand(GoHome));
public ICommand ShowMoreCommand => _showMoreCommand ?? (_showMoreCommand = new MvxCommand(ShowMore));
public int PageOrder
{
get { return _pageOrder; }
private set { SetProperty(ref _pageOrder, value); }
}
public void Init(int pageOrder = 0)
{
PageOrder = pageOrder;
}
private void GoHome()
{
//navigate to main page
ShowViewModel<MainViewModel>();
//clear the whole back stack
ChangePresentation(new ClearBackstackHint());
}
private void ShowMore()
{
ShowViewModel<UserDashboardViewModel>(new
{
pageOrder = PageOrder + 1
});
}
}
}
| 27.32 | 109 | 0.614934 | [
"MIT"
] | MartinZikmund/blog-2017 | MvvmCrossBackstack/MvvmCrossBackstack.Core/ViewModels/UserDashboardViewModel.cs | 1,368 | C# |
namespace HaberPortal.Formlar
{
partial class FormRegister
{
/// <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 Windows Form 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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormRegister));
this.panel1 = new System.Windows.Forms.Panel();
this.label5 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.pictureBox_Logo = new System.Windows.Forms.PictureBox();
this.button_Cikis = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.label_Message = new System.Windows.Forms.Label();
this.panel3 = new System.Windows.Forms.Panel();
this.linkLabel_GirisYap = new System.Windows.Forms.LinkLabel();
this.btn_Cikis = new System.Windows.Forms.Button();
this.lbl_Parola = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.lbl_Isim = new System.Windows.Forms.Label();
this.btn_KayitYap = new System.Windows.Forms.Button();
this.txt_Parola = new System.Windows.Forms.TextBox();
this.txt_Isim = new System.Windows.Forms.TextBox();
this.lbl_Soyad = new System.Windows.Forms.Label();
this.txt_Soyad = new System.Windows.Forms.TextBox();
this.lbl_Eposta = new System.Windows.Forms.Label();
this.txt_Eposta = new System.Windows.Forms.TextBox();
this.lbl_DogumTarihi = new System.Windows.Forms.Label();
this.dateTimePicker_DogumTarihi = new System.Windows.Forms.DateTimePicker();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox_Logo)).BeginInit();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(41)))), ((int)(((byte)(128)))), ((int)(((byte)(185)))));
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label7);
this.panel1.Controls.Add(this.label6);
this.panel1.Controls.Add(this.pictureBox_Logo);
this.panel1.Controls.Add(this.button_Cikis);
this.panel1.Dock = System.Windows.Forms.DockStyle.Left;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(300, 530);
this.panel1.TabIndex = 0;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Century Gothic", 13.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.label5.ForeColor = System.Drawing.Color.White;
this.label5.Location = new System.Drawing.Point(88, 201);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(158, 30);
this.label5.TabIndex = 9;
this.label5.Text = "Haber Portal";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Century Gothic", 13.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.label7.ForeColor = System.Drawing.Color.White;
this.label7.Location = new System.Drawing.Point(64, 245);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(182, 30);
this.label7.TabIndex = 10;
this.label7.Text = "Uygulamasına";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Century Gothic", 13.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.label6.ForeColor = System.Drawing.Color.White;
this.label6.Location = new System.Drawing.Point(88, 291);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(158, 30);
this.label6.TabIndex = 9;
this.label6.Text = "Hoş Geldiniz";
//
// pictureBox_Logo
//
this.pictureBox_Logo.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox_Logo.Image")));
this.pictureBox_Logo.Location = new System.Drawing.Point(68, 38);
this.pictureBox_Logo.Name = "pictureBox_Logo";
this.pictureBox_Logo.Size = new System.Drawing.Size(165, 145);
this.pictureBox_Logo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.pictureBox_Logo.TabIndex = 8;
this.pictureBox_Logo.TabStop = false;
//
// button_Cikis
//
this.button_Cikis.FlatAppearance.BorderSize = 0;
this.button_Cikis.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Red;
this.button_Cikis.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button_Cikis.Font = new System.Drawing.Font("Century Gothic", 19.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.button_Cikis.Location = new System.Drawing.Point(0, 611);
this.button_Cikis.Name = "button_Cikis";
this.button_Cikis.Size = new System.Drawing.Size(287, 150);
this.button_Cikis.TabIndex = 0;
this.button_Cikis.UseVisualStyleBackColor = true;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Century Gothic", 13.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.label4.ForeColor = System.Drawing.Color.Black;
this.label4.Location = new System.Drawing.Point(11, 39);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(310, 30);
this.label4.TabIndex = 8;
this.label4.Text = "Haber Portal Kayıt Sayfası";
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.White;
this.panel2.Controls.Add(this.label_Message);
this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel2.Location = new System.Drawing.Point(300, 472);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(450, 58);
this.panel2.TabIndex = 1;
//
// label_Message
//
this.label_Message.AutoSize = true;
this.label_Message.Font = new System.Drawing.Font("Century Gothic", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.label_Message.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.label_Message.Location = new System.Drawing.Point(12, 21);
this.label_Message.Name = "label_Message";
this.label_Message.Size = new System.Drawing.Size(134, 19);
this.label_Message.TabIndex = 0;
this.label_Message.Text = "label_Message";
//
// panel3
//
this.panel3.BackColor = System.Drawing.Color.White;
this.panel3.Controls.Add(this.dateTimePicker_DogumTarihi);
this.panel3.Controls.Add(this.lbl_DogumTarihi);
this.panel3.Controls.Add(this.txt_Eposta);
this.panel3.Controls.Add(this.lbl_Eposta);
this.panel3.Controls.Add(this.txt_Soyad);
this.panel3.Controls.Add(this.lbl_Soyad);
this.panel3.Controls.Add(this.linkLabel_GirisYap);
this.panel3.Controls.Add(this.btn_Cikis);
this.panel3.Controls.Add(this.lbl_Parola);
this.panel3.Controls.Add(this.label3);
this.panel3.Controls.Add(this.lbl_Isim);
this.panel3.Controls.Add(this.label4);
this.panel3.Controls.Add(this.btn_KayitYap);
this.panel3.Controls.Add(this.txt_Parola);
this.panel3.Controls.Add(this.txt_Isim);
this.panel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel3.Location = new System.Drawing.Point(300, 0);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(450, 472);
this.panel3.TabIndex = 2;
//
// linkLabel_GirisYap
//
this.linkLabel_GirisYap.Anchor = System.Windows.Forms.AnchorStyles.None;
this.linkLabel_GirisYap.AutoSize = true;
this.linkLabel_GirisYap.Cursor = System.Windows.Forms.Cursors.PanNE;
this.linkLabel_GirisYap.Font = new System.Drawing.Font("Century Gothic", 10.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.linkLabel_GirisYap.ForeColor = System.Drawing.Color.Black;
this.linkLabel_GirisYap.LinkColor = System.Drawing.Color.Black;
this.linkLabel_GirisYap.Location = new System.Drawing.Point(277, 419);
this.linkLabel_GirisYap.Name = "linkLabel_GirisYap";
this.linkLabel_GirisYap.Size = new System.Drawing.Size(82, 19);
this.linkLabel_GirisYap.TabIndex = 10;
this.linkLabel_GirisYap.TabStop = true;
this.linkLabel_GirisYap.Text = "Giriş Yap";
this.linkLabel_GirisYap.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel_GirisYap_LinkClicked);
//
// btn_Cikis
//
this.btn_Cikis.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.btn_Cikis.Cursor = System.Windows.Forms.Cursors.Hand;
this.btn_Cikis.FlatAppearance.BorderSize = 0;
this.btn_Cikis.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btn_Cikis.Font = new System.Drawing.Font("Century Gothic", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.btn_Cikis.ForeColor = System.Drawing.Color.Red;
this.btn_Cikis.Location = new System.Drawing.Point(395, 0);
this.btn_Cikis.Name = "btn_Cikis";
this.btn_Cikis.Size = new System.Drawing.Size(55, 55);
this.btn_Cikis.TabIndex = 9;
this.btn_Cikis.Text = "X";
this.btn_Cikis.UseVisualStyleBackColor = true;
this.btn_Cikis.Click += new System.EventHandler(this.btn_Cikis_Click);
//
// lbl_Parola
//
this.lbl_Parola.Anchor = System.Windows.Forms.AnchorStyles.None;
this.lbl_Parola.AutoSize = true;
this.lbl_Parola.ForeColor = System.Drawing.Color.Black;
this.lbl_Parola.Location = new System.Drawing.Point(108, 315);
this.lbl_Parola.Name = "lbl_Parola";
this.lbl_Parola.Size = new System.Drawing.Size(63, 21);
this.lbl_Parola.TabIndex = 6;
this.lbl_Parola.Text = "Parola";
//
// label3
//
this.label3.Anchor = System.Windows.Forms.AnchorStyles.None;
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Century Gothic", 16.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.label3.ForeColor = System.Drawing.Color.Blue;
this.label3.Location = new System.Drawing.Point(-224, -6);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(176, 34);
this.label3.TabIndex = 6;
this.label3.Text = "Giriş Sayfası";
//
// lbl_Isim
//
this.lbl_Isim.Anchor = System.Windows.Forms.AnchorStyles.None;
this.lbl_Isim.AutoSize = true;
this.lbl_Isim.ForeColor = System.Drawing.Color.Black;
this.lbl_Isim.Location = new System.Drawing.Point(108, 95);
this.lbl_Isim.Name = "lbl_Isim";
this.lbl_Isim.Size = new System.Drawing.Size(40, 21);
this.lbl_Isim.TabIndex = 6;
this.lbl_Isim.Text = "İsim";
//
// btn_KayitYap
//
this.btn_KayitYap.Anchor = System.Windows.Forms.AnchorStyles.None;
this.btn_KayitYap.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(41)))), ((int)(((byte)(128)))), ((int)(((byte)(185)))));
this.btn_KayitYap.FlatAppearance.BorderSize = 0;
this.btn_KayitYap.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btn_KayitYap.Font = new System.Drawing.Font("Century Gothic", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.btn_KayitYap.ForeColor = System.Drawing.Color.White;
this.btn_KayitYap.Location = new System.Drawing.Point(107, 373);
this.btn_KayitYap.Name = "btn_KayitYap";
this.btn_KayitYap.Size = new System.Drawing.Size(252, 43);
this.btn_KayitYap.TabIndex = 5;
this.btn_KayitYap.Text = "Kayıt Ol";
this.btn_KayitYap.UseVisualStyleBackColor = false;
this.btn_KayitYap.Click += new System.EventHandler(this.btn_KayitYap_Click);
//
// txt_Parola
//
this.txt_Parola.Anchor = System.Windows.Forms.AnchorStyles.None;
this.txt_Parola.Location = new System.Drawing.Point(107, 339);
this.txt_Parola.Name = "txt_Parola";
this.txt_Parola.PasswordChar = '*';
this.txt_Parola.Size = new System.Drawing.Size(252, 28);
this.txt_Parola.TabIndex = 2;
this.txt_Parola.Text = "Şifre";
//
// txt_Isim
//
this.txt_Isim.Anchor = System.Windows.Forms.AnchorStyles.None;
this.txt_Isim.Location = new System.Drawing.Point(107, 119);
this.txt_Isim.Name = "txt_Isim";
this.txt_Isim.Size = new System.Drawing.Size(252, 28);
this.txt_Isim.TabIndex = 2;
this.txt_Isim.Tag = "";
this.txt_Isim.Text = "İsim Giriniz";
//
// lbl_Soyad
//
this.lbl_Soyad.Anchor = System.Windows.Forms.AnchorStyles.None;
this.lbl_Soyad.AutoSize = true;
this.lbl_Soyad.ForeColor = System.Drawing.Color.Black;
this.lbl_Soyad.Location = new System.Drawing.Point(108, 150);
this.lbl_Soyad.Name = "lbl_Soyad";
this.lbl_Soyad.Size = new System.Drawing.Size(61, 21);
this.lbl_Soyad.TabIndex = 11;
this.lbl_Soyad.Text = "Soyad";
//
// txt_Soyad
//
this.txt_Soyad.Anchor = System.Windows.Forms.AnchorStyles.None;
this.txt_Soyad.Location = new System.Drawing.Point(107, 174);
this.txt_Soyad.Name = "txt_Soyad";
this.txt_Soyad.Size = new System.Drawing.Size(252, 28);
this.txt_Soyad.TabIndex = 12;
this.txt_Soyad.Tag = "";
this.txt_Soyad.Text = "Soyad Giriniz";
//
// lbl_Eposta
//
this.lbl_Eposta.Anchor = System.Windows.Forms.AnchorStyles.None;
this.lbl_Eposta.AutoSize = true;
this.lbl_Eposta.ForeColor = System.Drawing.Color.Black;
this.lbl_Eposta.Location = new System.Drawing.Point(108, 205);
this.lbl_Eposta.Name = "lbl_Eposta";
this.lbl_Eposta.Size = new System.Drawing.Size(72, 21);
this.lbl_Eposta.TabIndex = 13;
this.lbl_Eposta.Text = "E-Posta";
//
// txt_Eposta
//
this.txt_Eposta.Anchor = System.Windows.Forms.AnchorStyles.None;
this.txt_Eposta.Location = new System.Drawing.Point(107, 229);
this.txt_Eposta.Name = "txt_Eposta";
this.txt_Eposta.Size = new System.Drawing.Size(252, 28);
this.txt_Eposta.TabIndex = 14;
this.txt_Eposta.Tag = "";
this.txt_Eposta.Text = "E-Posta Adresinizi Giriniz";
//
// lbl_DogumTarihi
//
this.lbl_DogumTarihi.Anchor = System.Windows.Forms.AnchorStyles.None;
this.lbl_DogumTarihi.AutoSize = true;
this.lbl_DogumTarihi.ForeColor = System.Drawing.Color.Black;
this.lbl_DogumTarihi.Location = new System.Drawing.Point(108, 260);
this.lbl_DogumTarihi.Name = "lbl_DogumTarihi";
this.lbl_DogumTarihi.Size = new System.Drawing.Size(116, 21);
this.lbl_DogumTarihi.TabIndex = 15;
this.lbl_DogumTarihi.Text = "Doğum Tarihi";
//
// dateTimePicker_DogumTarihi
//
this.dateTimePicker_DogumTarihi.Location = new System.Drawing.Point(107, 284);
this.dateTimePicker_DogumTarihi.Name = "dateTimePicker_DogumTarihi";
this.dateTimePicker_DogumTarihi.Size = new System.Drawing.Size(252, 28);
this.dateTimePicker_DogumTarihi.TabIndex = 17;
//
// FormRegister
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 21F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Honeydew;
this.ClientSize = new System.Drawing.Size(750, 530);
this.Controls.Add(this.panel3);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Font = new System.Drawing.Font("Century Gothic", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162)));
this.ForeColor = System.Drawing.Color.ForestGreen;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Margin = new System.Windows.Forms.Padding(4);
this.Name = "FormRegister";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Giriş Sayfasi";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox_Logo)).EndInit();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button button_Cikis;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label_Message;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Button btn_KayitYap;
private System.Windows.Forms.TextBox txt_Parola;
private System.Windows.Forms.TextBox txt_Isim;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label lbl_Parola;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label lbl_Isim;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.PictureBox pictureBox_Logo;
private System.Windows.Forms.Button btn_Cikis;
private System.Windows.Forms.LinkLabel linkLabel_GirisYap;
private System.Windows.Forms.TextBox txt_Soyad;
private System.Windows.Forms.Label lbl_Soyad;
private System.Windows.Forms.DateTimePicker dateTimePicker_DogumTarihi;
private System.Windows.Forms.Label lbl_DogumTarihi;
private System.Windows.Forms.TextBox txt_Eposta;
private System.Windows.Forms.Label lbl_Eposta;
}
} | 52.822222 | 173 | 0.609498 | [
"MIT"
] | SalimUlusoy/HaberPortal | HaberPortal/HaberPortal/Formlar/FormRegister.Designer.cs | 21,408 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Newtonsoft.Json;
using NBitcoin.JsonConverters;
namespace BTCPayServer.JsonConverters
{
class DateTimeMilliJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(DateTime).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()) ||
typeof(DateTimeOffset).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()) ||
typeof(DateTimeOffset?).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
static DateTimeOffset unixRef = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return null;
if (reader.TokenType == JsonToken.Null)
return null;
var result = UnixTimeToDateTime((ulong)(long)reader.Value);
if (objectType == typeof(DateTime))
return result.UtcDateTime;
return result;
}
private DateTimeOffset UnixTimeToDateTime(ulong value)
{
var v = (long)value;
if(v < 0)
throw new FormatException("Invalid datetime (less than 1/1/1970)");
return unixRef + TimeSpan.FromMilliseconds((long)v);
}
private long DateTimeToUnixTime(in DateTime time)
{
var date = ((DateTimeOffset)time).ToUniversalTime();
long v = (long)(date - unixRef).TotalMilliseconds;
if(v < 0)
throw new FormatException("Invalid datetime (less than 1/1/1970)");
return v;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DateTime time;
if (value is DateTime)
time = (DateTime)value;
else
time = ((DateTimeOffset)value).UtcDateTime;
if (time < UnixTimeToDateTime(0))
time = UnixTimeToDateTime(0).UtcDateTime;
writer.WriteValue(DateTimeToUnixTime(time));
}
}
}
| 36.015385 | 124 | 0.604443 | [
"MIT"
] | Argoneum/btcpayserver | BTCPayServer/JsonConverters/DateTimeMilliJsonConverter.cs | 2,343 | C# |
using System;
namespace Supertext.Base.Http
{
public interface IUriBuilder
{
Uri CreateAbsoluteUri(string relativeUrl);
/// <summary>
/// To use ResolveUrl, the URL template should contain the place holder {domain}
/// </summary>
/// <param name="urlTemplate"></param>
/// <returns></returns>
Uri ResolveUrl(string urlTemplate);
}
} | 25.1875 | 88 | 0.60794 | [
"MIT"
] | Supertext/Supertext.Base | Supertext.Base/Http/IUriBuilder.cs | 405 | C# |
namespace com.spacepuppy
{
/// <summary>
/// Just a name for contract purposes. You should probably inherit from RadicalYieldInstruciton, or composite it, unless
/// you know what you're doing.
/// </summary>
public interface IRadicalYieldInstruction
{
/// <summary>
/// The instruction completed, but not necessarily successfully.
/// </summary>
bool IsComplete { get; }
/// <summary>
/// Process the tick of the coroutine, returning true if the instruction should continue blocking, false if it should stop blocking.
/// </summary>
/// <param name="yieldObject">An object to treat as the yield object between now and the next call to Tick.</param>
/// <returns>True to continue blocking, false to stop blocking.</returns>
bool Tick(out object yieldObject);
}
/// <summary>
/// Base abstract class that implements IRadicalYieldInstruction. It implements IRadicalYieldInstruction in the most
/// commonly used setup. You should only ever implement IRadicalYieldInstruction directly if you can't inherit from this
/// in your inheritance chain, or you want none standard behaviour.
/// </summary>
public abstract class RadicalYieldInstruction : IRadicalYieldInstruction
{
#region Fields
private bool _complete;
#endregion
#region Properties
public bool IsComplete { get { return _complete; } }
#endregion
#region Methods
protected virtual void SetSignal()
{
_complete = true;
}
protected void ResetSignal()
{
_complete = false;
}
protected virtual bool Tick(out object yieldObject)
{
yieldObject = null;
return !_complete;
}
#endregion
#region IRadicalYieldInstruction Interface
bool IRadicalYieldInstruction.Tick(out object yieldObject)
{
if (_complete)
{
yieldObject = null;
return false;
}
return this.Tick(out yieldObject);
}
#endregion
#region Static Interface
public static IProgressingYieldInstruction Null
{
get
{
return NullYieldInstruction.Null;
}
}
#endregion
}
}
| 24.918367 | 140 | 0.593366 | [
"MIT"
] | ronaldgameking/spacepuppy-unity-framework-4.0 | Framework/com.spacepuppy.radicalcoroutine/Runtime/src/IRadicalYieldInstruction.cs | 2,444 | C# |
using System;
using System.Collections.Generic;
#nullable disable
namespace Lab3.Models
{
public partial class Track
{
public int TrackId { get; set; }
public string Name { get; set; }
public int? AlbumId { get; set; }
public int MediaTypeId { get; set; }
public int? GenreId { get; set; }
public string Composer { get; set; }
public int Milliseconds { get; set; }
public int? Bytes { get; set; }
public double UnitPrice { get; set; }
public virtual Album Album { get; set; }
public virtual Genre Genre { get; set; }
public virtual MediaType MediaType { get; set; }
}
}
| 27.28 | 56 | 0.595308 | [
"MIT"
] | Alanomari/ITHSDATABASLab3 | Lab3/Models/Track.cs | 684 | C# |
using System;
using System.Collections.Generic;
using InputHelper;
using Microsoft.Xna.Framework;
namespace MenuBuddy
{
/// <summary>
/// This is a button thhat contains a relaitve layout
/// </summary>
public class StackLayoutButton : LayoutButton<StackLayout>, IStackLayout
{
#region Properties
public StackAlignment Alignment
{
get
{
return (Layout as StackLayout).Alignment;
}
set
{
(Layout as StackLayout).Alignment = value;
}
}
public List<IScreenItem> Items
{
get
{
return (Layout as StackLayout).Items;
}
}
#endregion //Properties
#region Initialization
/// <summary>
/// Constructs a new menu entry with the specified text.
/// </summary>
public StackLayoutButton()
{
Layout = new StackLayout();
}
public StackLayoutButton(StackLayoutButton inst) : base(inst)
{
Layout = new StackLayout(inst.Layout as StackLayout);
}
public event EventHandler<DragEventArgs> OnDrag;
public event EventHandler<DropEventArgs> OnDrop;
/// <summary>
/// Get a deep copy of this item
/// </summary>
/// <returns></returns>
public override IScreenItem DeepCopy()
{
return new StackLayoutButton(this);
}
#endregion //Initialization
#region Methods
protected override void CalculateRect()
{
//get the size of the rect
var size = Size * Scale;
//set the x component
Vector2 pos = Position.ToVector2();
switch (Horizontal)
{
case HorizontalAlignment.Center: { pos.X -= size.X / 2f; } break;
case HorizontalAlignment.Right: { pos.X -= size.X; } break;
}
//set the y component
switch (Vertical)
{
case VerticalAlignment.Center: { pos.Y -= size.Y / 2f; } break;
case VerticalAlignment.Bottom: { pos.Y -= size.Y; } break;
}
_rect = new Rectangle((int)pos.X, (int)pos.Y, (int)size.X, (int)size.Y);
//Set the position of the internal layout
var relLayout = Layout as StackLayout;
if (null != relLayout)
{
relLayout.Scale = Scale;
relLayout.Vertical = VerticalAlignment.Top;
relLayout.Horizontal = HorizontalAlignment.Left;
relLayout.Position = pos.ToPoint();
}
_rect = relLayout.Rect;
}
public void InsertItem(IScreenItem item, IScreenItem prevItem)
{
(Layout as StackLayout).InsertItem(item, prevItem);
}
public void InsertItemBefore(IScreenItem item, IScreenItem nextItem)
{
(Layout as StackLayout).InsertItemBefore(item, nextItem);
}
public bool RemoveItems<T>() where T : IScreenItem
{
return (Layout as StackLayout).RemoveItems<T>();
}
public bool CheckDrag(DragEventArgs drag)
{
return (Layout as StackLayout).CheckDrag(drag);
}
public bool CheckDrop(DropEventArgs drop)
{
return (Layout as StackLayout).CheckDrop(drop);
}
#endregion
}
} | 21.492308 | 75 | 0.678239 | [
"MIT"
] | dmanning23/MenuBuddy | MenuBuddy/MenuBuddy.SharedProject/Widgets/Buttons/StackLayoutButton.cs | 2,794 | C# |
using System.Threading.Tasks;
public static class AsyncTestHelper
{
private const int Timeout = 50;
public static T Resolve<T>(Task<T> task)
{
task.Wait(Timeout);
return task.Result;
}
} | 18.333333 | 44 | 0.645455 | [
"MIT"
] | smbc-digital/iag-contentapi | test/StockportContentApiTests/Unit/Repositories/AsyncTestHelper.cs | 220 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace I_Got_Next_2.Controller
{
[Route("api/[controller]")]
[ApiController]
public class GamesController : ControllerBase
{
}
} | 21 | 49 | 0.752381 | [
"MIT"
] | rtate2/i-got-next-2 | I-Got-Next-2/Controller/GamesController.cs | 317 | C# |
using System;
using System.Text;
namespace kbinxmlcs
{
internal class NodeBuffer : BigEndianBinaryBuffer
{
private readonly Encoding _encoding;
private readonly bool _compressed;
internal NodeBuffer(bool compressed, Encoding encoding)
{
_compressed = compressed;
_encoding = encoding;
}
internal NodeBuffer(byte[] buffer, bool compressed, Encoding encoding)
: base(buffer)
{
_compressed = compressed;
_encoding = encoding;
}
internal void WriteString(string value)
{
if (_compressed)
{
WriteU8((byte)value.Length);
WriteBytes(Sixbit.Encode(value));
}
else
{
WriteU8((byte)((value.Length - 1) | (1 << 6)));
WriteBytes(_encoding.GetBytes(value));
}
}
internal string ReadString()
{
int length = ReadU8();
if (_compressed)
return Sixbit.Decode(ReadBytes((int)Math.Ceiling(length * 6 / 8.0)), length);
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
return _encoding.GetString(ReadBytes((length & 0xBF) + 1));
#elif NETSTANDARD2_0
return _encoding.GetString(ReadBytes((length & 0xBF) + 1).ToArray());
#endif
}
}
}
| 26.301887 | 93 | 0.543759 | [
"MIT"
] | NKZsmos/kbinxmlcs | kbinxmlcs/NodeBuffer.cs | 1,396 | C# |
using UnityEngine;
using Fragsurf.TraceUtil;
namespace Fragsurf.Movement
{
public class SurfPhysics
{
///// Fields /////
/// <summary>
/// Change this if your ground is on a different layer
/// </summary>
public static int groundLayerMask = LayerMask.GetMask("Default", "Interactable", "Collide"); //(1 << 0);
private static Collider[] _colliders = new Collider [maxCollisions];
private static Vector3[] _planes = new Vector3 [maxClipPlanes];
public const float HU2M = 52.4934383202f;
private const int maxCollisions = 128;
private const int maxClipPlanes = 5;
private const int numBumps = 1;
public const float SurfSlope = 0.7f;
///// Methods /////
// http://www.00jknight.com/blog/unity-character-controller
public static void ResolveCollisions(Collider collider, ref Vector3 origin, ref Vector3 velocity,
float rigidbodyPushForce, float velocityMultiplier = 1f, float stepOffset = 0f,
ISurfControllable surfer = null)
{
// manual collision resolving
int numOverlaps = 0;
if (collider is CapsuleCollider)
{
var capc = collider as CapsuleCollider;
Vector3 point1, point2;
GetCapsulePoints(capc, origin, out point1, out point2);
numOverlaps = Physics.OverlapCapsuleNonAlloc(point1, point2, capc.radius,
_colliders, groundLayerMask, QueryTriggerInteraction.Ignore);
}
else if (collider is BoxCollider)
{
numOverlaps = Physics.OverlapBoxNonAlloc(origin, collider.bounds.extents, _colliders,
Quaternion.identity, groundLayerMask, QueryTriggerInteraction.Ignore);
}
Vector3 forwardVelocity = Vector3.Scale(velocity, new Vector3(1f, 0f, 1f));
for (int i = 0; i < numOverlaps; i++)
{
Vector3 direction;
float distance;
if (Physics.ComputePenetration(collider, origin,
Quaternion.identity, _colliders[i], _colliders[i].transform.position,
_colliders[i].transform.rotation, out direction, out distance))
{
// Step offset
if (stepOffset > 0f && surfer != null && surfer.moveData.useStepOffset)
if (StepOffset(collider, _colliders[i], ref origin, ref velocity, rigidbodyPushForce,
velocityMultiplier, stepOffset, direction, distance, forwardVelocity, surfer))
return;
// Handle collision
direction.Normalize();
Vector3 penetrationVector = direction * distance;
Vector3 velocityProjected = Vector3.Project(velocity, -direction);
velocityProjected.y = 0; // don't touch y velocity, we need it to calculate fall damage elsewhere
origin += penetrationVector;
velocity -= velocityProjected * velocityMultiplier;
Rigidbody rb = _colliders[i].GetComponentInParent<Rigidbody>();
if (rb != null && !rb.isKinematic)
rb.AddForceAtPosition(velocityProjected * velocityMultiplier * rigidbodyPushForce, origin,
ForceMode.Impulse);
}
}
}
public static bool StepOffset(Collider collider, Collider otherCollider, ref Vector3 origin,
ref Vector3 velocity, float rigidbodyPushForce, float velocityMultiplier, float stepOffset,
Vector3 direction, float distance, Vector3 forwardVelocity, ISurfControllable surfer)
{
// Return if step offset is 0
if (stepOffset <= 0f)
return false;
// Get forward direction (return if we aren't moving/are only moving vertically)
Vector3 forwardDirection = forwardVelocity.normalized;
if (forwardDirection.sqrMagnitude == 0f)
return false;
// Trace ground
Trace groundTrace = Tracer.TraceCollider(collider, origin, origin + Vector3.down * 0.1f, groundLayerMask);
if (groundTrace.hitCollider == null ||
Vector3.Angle(Vector3.up, groundTrace.planeNormal) > surfer.moveData.slopeLimit)
return false;
// Trace wall
Trace wallTrace = Tracer.TraceCollider(collider, origin, origin + velocity, groundLayerMask, 0.9f);
if (wallTrace.hitCollider == null ||
Vector3.Angle(Vector3.up, wallTrace.planeNormal) <= surfer.moveData.slopeLimit)
return false;
// Trace upwards (check for roof etc)
float upDistance = stepOffset;
Trace upTrace = Tracer.TraceCollider(collider, origin, origin + Vector3.up * stepOffset, groundLayerMask);
if (upTrace.hitCollider != null)
upDistance = upTrace.distance;
// Don't bother doing the rest if we can't move up at all anyway
if (upDistance <= 0f)
return false;
Vector3 upOrigin = origin + Vector3.up * upDistance;
// Trace forwards (check for walls etc)
float forwardMagnitude = stepOffset;
float forwardDistance = forwardMagnitude;
Trace forwardTrace = Tracer.TraceCollider(collider, upOrigin,
upOrigin + forwardDirection * Mathf.Max(0.2f, forwardMagnitude), groundLayerMask);
if (forwardTrace.hitCollider != null)
forwardDistance = forwardTrace.distance;
// Don't bother doing the rest if we can't move forward anyway
if (forwardDistance <= 0f)
return false;
Vector3 upForwardOrigin = upOrigin + forwardDirection * forwardDistance;
// Trace down (find ground)
float downDistance = upDistance;
Trace downTrace = Tracer.TraceCollider(collider, upForwardOrigin,
upForwardOrigin + Vector3.down * upDistance, groundLayerMask);
if (downTrace.hitCollider != null)
downDistance = downTrace.distance;
// Check step size/angle
float verticalStep = Mathf.Clamp(upDistance - downDistance, 0f, stepOffset);
float horizontalStep = forwardDistance;
float stepAngle = Vector3.Angle(Vector3.forward, new Vector3(0f, verticalStep, horizontalStep));
if (stepAngle > surfer.moveData.slopeLimit)
return false;
// Get new position
Vector3 endOrigin = origin + Vector3.up * verticalStep;
// Actually move
if (origin != endOrigin && forwardDistance > 0f)
{
Debug.Log("Moved up step!");
origin = endOrigin + forwardDirection * forwardDistance * Time.deltaTime;
return true;
}
else
return false;
}
/// <summary>
///
/// </summary>
public static void Friction(ref Vector3 velocity, float stopSpeed, float friction, float deltaTime)
{
var speed = velocity.magnitude;
if (speed < 0.0001905f)
return;
var drop = 0f;
// apply ground friction
var control = (speed < stopSpeed) ? stopSpeed : speed;
drop += control * friction * deltaTime;
// scale the velocity
var newspeed = speed - drop;
if (newspeed < 0)
newspeed = 0;
if (newspeed != speed)
{
newspeed /= speed;
velocity *= newspeed;
}
}
/// <summary>
///
/// </summary>
/// <param name="velocity"></param>
/// <param name="wishdir"></param>
/// <param name="wishspeed"></param>
/// <param name="accel"></param>
/// <param name="airCap"></param>
/// <param name="deltaTime"></param>
/// <returns></returns>
public static Vector3 AirAccelerate(Vector3 velocity, Vector3 wishdir, float wishspeed, float accel,
float airCap, float deltaTime)
{
var wishspd = wishspeed;
// Cap speed
wishspd = Mathf.Min(wishspd, airCap);
// Determine veer amount
var currentspeed = Vector3.Dot(velocity, wishdir);
// See how much to add
var addspeed = wishspd - currentspeed;
// If not adding any, done.
if (addspeed <= 0)
return Vector3.zero;
// Determine acceleration speed after acceleration
var accelspeed = accel * wishspeed * deltaTime;
// Cap it
accelspeed = Mathf.Min(accelspeed, addspeed);
var result = Vector3.zero;
// Adjust pmove vel.
for (int i = 0; i < 3; i++)
result[i] += accelspeed * wishdir[i];
return result;
}
/// <summary>
///
/// </summary>
/// <param name="wishdir"></param>
/// <param name="wishspeed"></param>
/// <param name="accel"></param>
/// <returns></returns>
public static Vector3 Accelerate(Vector3 currentVelocity, Vector3 wishdir, float wishspeed, float accel,
float deltaTime, float surfaceFriction)
{
// See if we are changing direction a bit
var currentspeed = Vector3.Dot(currentVelocity, wishdir);
// Reduce wishspeed by the amount of veer.
var addspeed = wishspeed - currentspeed;
// If not going to add any speed, done.
if (addspeed <= 0)
return Vector3.zero;
// Determine amount of accleration.
var accelspeed = accel * deltaTime * wishspeed * surfaceFriction;
// Cap at addspeed
if (accelspeed > addspeed)
accelspeed = addspeed;
var result = Vector3.zero;
// Adjust velocity.
for (int i = 0; i < 3; i++)
result[i] += accelspeed * wishdir[i];
return result;
}
/// <summary>
///
/// </summary>
/// <param name="velocity"></param>
/// <param name="origin"></param>
/// <param name="firstDestination"></param>
/// <param name="firstTrace"></param>
/// <returns></returns>
public static int Reflect(ref Vector3 velocity, Collider collider, Vector3 origin, float deltaTime)
{
float d;
var newVelocity = Vector3.zero;
var blocked = 0; // Assume not blocked
var numplanes = 0; // and not sliding along any planes
var originalVelocity = velocity; // Store original velocity
var primalVelocity = velocity;
var allFraction = 0f;
var timeLeft = deltaTime; // Total time for this movement operation.
for (int bumpcount = 0; bumpcount < numBumps; bumpcount++)
{
if (velocity.magnitude == 0f)
break;
// Assume we can move all the way from the current origin to the
// end point.
var end = VectorExtensions.VectorMa(origin, timeLeft, velocity);
var trace = Tracer.TraceCollider(collider, origin, end, groundLayerMask);
allFraction += trace.fraction;
if (trace.fraction > 0)
{
// actually covered some distance
originalVelocity = velocity;
numplanes = 0;
}
// If we covered the entire distance, we are done
// and can return.
if (trace.fraction == 1)
break; // moved the entire distance
// If the plane we hit has a high z component in the normal, then
// it's probably a floor
if (trace.planeNormal.y > SurfSlope)
blocked |= 1; // floor
// If the plane has a zero z component in the normal, then it's a
// step or wall
if (trace.planeNormal.y == 0)
blocked |= 2; // step / wall
// Reduce amount of m_flFrameTime left by total time left * fraction
// that we covered.
timeLeft -= timeLeft * trace.fraction;
// Did we run out of planes to clip against?
if (numplanes >= maxClipPlanes)
{
// this shouldn't really happen
// Stop our movement if so.
velocity = Vector3.zero;
//Con_DPrintf("Too many planes 4\n");
break;
}
// Set up next clipping plane
_planes[numplanes] = trace.planeNormal;
numplanes++;
// modify original_velocity so it parallels all of the clip planes
//
// reflect player velocity
// Only give this a try for first impact plane because you can get yourself stuck in an acute corner by jumping in place
// and pressing forward and nobody was really using this bounce/reflection feature anyway...
if (numplanes == 1)
{
for (int i = 0; i < numplanes; i++)
{
if (_planes[i][1] > SurfSlope)
{
// floor or slope
return blocked;
//ClipVelocity(originalVelocity, _planes[i], ref newVelocity, 1f);
//originalVelocity = newVelocity;
}
else
ClipVelocity(originalVelocity, _planes[i], ref newVelocity, 1f);
}
velocity = newVelocity;
originalVelocity = newVelocity;
}
else
{
int i = 0;
for (i = 0; i < numplanes; i++)
{
ClipVelocity(originalVelocity, _planes[i], ref velocity, 1);
int j = 0;
for (j = 0; j < numplanes; j++)
{
if (j != i)
{
// Are we now moving against this plane?
if (Vector3.Dot(velocity, _planes[j]) < 0)
break;
}
}
if (j == numplanes) // Didn't have to clip, so we're ok
break;
}
// Did we go all the way through plane set
if (i != numplanes)
{
// go along this plane
// pmove.velocity is set in clipping call, no need to set again.
;
}
else
{
// go along the crease
if (numplanes != 2)
{
velocity = Vector3.zero;
break;
}
var dir = Vector3.Cross(_planes[0], _planes[1]).normalized;
d = Vector3.Dot(dir, velocity);
velocity = dir * d;
}
//
// if original velocity is against the original velocity, stop dead
// to avoid tiny occilations in sloping corners
//
d = Vector3.Dot(velocity, primalVelocity);
if (d <= 0f)
{
//Con_DPrintf("Back\n");
velocity = Vector3.zero;
break;
}
}
}
if (allFraction == 0f)
velocity = Vector3.zero;
// Check if they slammed into a wall
//float fSlamVol = 0.0f;
//var primal2dLen = new Vector2(primal_velocity.x, primal_velocity.z).magnitude;
//var vel2dLen = new Vector2(_moveData.Velocity.x, _moveData.Velocity.z).magnitude;
//float fLateralStoppingAmount = primal2dLen - vel2dLen;
//if (fLateralStoppingAmount > PLAYER_MAX_SAFE_FALL_SPEED * 2.0f)
//{
// fSlamVol = 1.0f;
//}
//else if (fLateralStoppingAmount > PLAYER_MAX_SAFE_FALL_SPEED)
//{
// fSlamVol = 0.85f;
//}
//PlayerRoughLandingEffects(fSlamVol);
return blocked;
}
/// <summary>
///
/// </summary>
/// <param name="input"></param>
/// <param name="normal"></param>
/// <param name="output"></param>
/// <param name="overbounce"></param>
/// <returns></returns>
public static int ClipVelocity(Vector3 input, Vector3 normal, ref Vector3 output, float overbounce)
{
var angle = normal[1];
var blocked = 0x00; // Assume unblocked.
if (angle > 0) // If the plane that is blocking us has a positive z component, then assume it's a floor.
blocked |= 0x01; //
if (angle == 0) // If the plane has no Z, it is vertical (wall/step)
blocked |= 0x02; //
// Determine how far along plane to slide based on incoming direction.
var backoff = Vector3.Dot(input, normal) * overbounce;
for (int i = 0; i < 3; i++)
{
var change = normal[i] * backoff;
output[i] = input[i] - change;
}
// iterate once to make sure we aren't still moving through the plane
float adjust = Vector3.Dot(output, normal);
if (adjust < 0.0f)
{
output -= (normal * adjust);
// Msg( "Adjustment = %lf\n", adjust );
}
// Return blocking flags.
return blocked;
}
/// <summary>
///
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
public static void GetCapsulePoints(CapsuleCollider capc, Vector3 origin, out Vector3 p1, out Vector3 p2)
{
var distanceToPoints = capc.height / 2f /*- capc.radius*/;
p1 = origin + capc.center + Vector3.up * distanceToPoints;
p2 = origin + capc.center - Vector3.up * distanceToPoints;
}
}
} | 38.732394 | 136 | 0.50613 | [
"MIT"
] | Enovale/SpookyDemo | Assets/Modified fragsurf/Movement/SurfPhysics.cs | 19,252 | C# |
using loon.geom;
using loon.utils;
using loon.utils.reply;
namespace loon.opengl
{
public abstract class Painter : TextureSource
{
public object Tag;
public const int TOP_LEFT = 0;
public const int TOP_RIGHT = 1;
public const int BOTTOM_RIGHT = 2;
public const int BOTTOM_LEFT = 3;
public abstract LTexture Texture();
public abstract float Width();
public abstract float Height();
public abstract float GetDisplayWidth();
public abstract float GetDisplayHeight();
public abstract float Sx();
public abstract float Sy();
public abstract float Tx();
public abstract float Ty();
public abstract void AddToBatch(BaseBatch batch, uint tint, Affine2f tx, float x, float y, float width, float height);
public abstract void AddToBatch(BaseBatch batch, uint tint, Affine2f tx, float dx, float dy, float dw, float dh, float sx, float sy, float sw, float sh);
public override bool IsLoaded()
{
return _isLoaded;
}
public override Painter Draw()
{
return this;
}
public override GoFuture<Painter> TileAsync()
{
return GoFuture<Painter>.Success(this);
}
public override string ToString()
{
StringKeyValue builder = new StringKeyValue("Painter");
builder.Kv("size", Width() + "x" + Height()).Comma().Kv("xOff", Sx()).Comma().Kv("yOff", Sy()).Comma().Kv("widthRatio", Tx()).Comma().Kv("heightRatio", Ty());
return builder.ToString() + " <- " + Texture();
}
}
}
| 21.716418 | 161 | 0.684536 | [
"Apache-2.0"
] | TheMadTitanSkid/LGame | C#/Loon2MonoGame/LoonMonoGame-Lib/loon/opengl/Painter.cs | 1,457 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Dtos.Grant;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Services.Interfaces;
using Skoruba.IdentityServer4.Admin.Api.ExceptionHandling;
using Skoruba.IdentityServer4.Admin.Api.Helpers;
using Skoruba.IdentityServer4.Admin.Api.Configuration.Constants;
using Skoruba.IdentityServer4.Admin.EntityFramework.DbContexts;
using Skoruba.IdentityServer4.Admin.EntityFramework.Identity.Entities.Identity;
namespace Skoruba.IdentityServer4.Admin.Api.Controllers
{
[Authorize(Policy = AuthorizationConsts.AdministrationPolicy)]
public class GrantController : BaseController
{
private readonly IPersistedGrantAspNetIdentityService<AdminDbContext, UserIdentity, UserIdentityRole, string, UserIdentityUserClaim, UserIdentityUserRole, UserIdentityUserLogin, UserIdentityRoleClaim, UserIdentityUserToken> _persistedGrantService;
private readonly IStringLocalizer<GrantController> _localizer;
public GrantController(IPersistedGrantAspNetIdentityService<AdminDbContext, UserIdentity, UserIdentityRole, string, UserIdentityUserClaim, UserIdentityUserRole, UserIdentityUserLogin, UserIdentityRoleClaim, UserIdentityUserToken> persistedGrantService,
ILogger<ConfigurationController> logger,
IStringLocalizer<GrantController> localizer) : base(logger)
{
_persistedGrantService = persistedGrantService;
_localizer = localizer;
}
[HttpGet]
public async Task<IActionResult> PersistedGrants(int? page, string search)
{
var persistedGrants = await _persistedGrantService.GetPersitedGrantsByUsers(search, page ?? 1);
return Success(persistedGrants);
}
[HttpGet]
public async Task<IActionResult> PersistedGrantDelete(string id)
{
if (string.IsNullOrEmpty(id)) return NotFound();
var grant = await _persistedGrantService.GetPersitedGrantAsync(UrlHelpers.QueryStringUnSafeHash(id));
if (grant == null) return NotFound();
return Success(grant);
}
[HttpPost]
public async Task<IActionResult> PersistedGrantDelete(PersistedGrantDto grant)
{
await _persistedGrantService.DeletePersistedGrantAsync(grant.Key);
return Success();
}
[HttpPost]
public async Task<IActionResult> PersistedGrantsDelete(PersistedGrantsDto grants)
{
await _persistedGrantService.DeletePersistedGrantsAsync(grants.SubjectId);
return Success();
}
[HttpGet]
public async Task<IActionResult> PersistedGrant(string id, int? page)
{
var persistedGrants = await _persistedGrantService.GetPersitedGrantsByUser(id, page ?? 1);
persistedGrants.SubjectId = id;
return Success(persistedGrants);
}
}
} | 39.3 | 260 | 0.727099 | [
"MIT"
] | DORAdreamless/IdentityServer4.Admin | src/Skoruba.IdentityServer4.Admin.Api/Controllers/GrantController.cs | 3,146 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace FMODUnity
{
[CustomEditor(typeof(StudioBankLoader))]
[CanEditMultipleObjects]
public class StudioBankLoaderEditor : Editor
{
public override void OnInspectorGUI()
{
var load = serializedObject.FindProperty("LoadEvent");
var unload = serializedObject.FindProperty("UnloadEvent");
var tag = serializedObject.FindProperty("CollisionTag");
var banks = serializedObject.FindProperty("Banks");
var preload = serializedObject.FindProperty("PreloadSamples");
EditorGUILayout.PropertyField(load, new GUIContent("Load"));
EditorGUILayout.PropertyField(unload, new GUIContent("Unload"));
if ((load.enumValueIndex >= 3 && load.enumValueIndex <= 6) ||
(unload.enumValueIndex >= 3 && unload.enumValueIndex <= 6))
{
tag.stringValue = EditorGUILayout.TagField("Collision Tag", tag.stringValue);
}
EditorGUILayout.PropertyField(preload, new GUIContent("Preload Sample Data"));
//EditorGUILayout.PropertyField(banks);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Banks");
EditorGUILayout.BeginVertical();
if (GUILayout.Button("Add Bank", GUILayout.ExpandWidth(false)))
{
banks.InsertArrayElementAtIndex(banks.arraySize);
SerializedProperty newBank = banks.GetArrayElementAtIndex(banks.arraySize - 1);
newBank.stringValue = "";
var browser = EventBrowser.CreateInstance<EventBrowser>();
#if UNITY_5_0 || UNITY_5_1
browser.title = "Select FMOD Bank";
#else
browser.titleContent = new GUIContent("Select FMOD Bank");
#endif
browser.SelectBank(newBank);
browser.ShowUtility();
}
Texture deleteTexture = EditorGUIUtility.Load("FMOD/Delete.png") as Texture;
GUIContent deleteContent = new GUIContent(deleteTexture, "Delete Bank");
var buttonStyle = new GUIStyle(GUI.skin.button);
buttonStyle.padding.top = buttonStyle.padding.bottom = 1;
buttonStyle.margin.top = 2;
buttonStyle.padding.left = buttonStyle.padding.right = 4;
buttonStyle.fixedHeight = GUI.skin.textField.CalcSize(new GUIContent()).y;
for (int i = 0; i < banks.arraySize; i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(banks.GetArrayElementAtIndex(i), GUIContent.none);
if (GUILayout.Button(deleteContent, buttonStyle, GUILayout.ExpandWidth(false)))
{
banks.DeleteArrayElementAtIndex(i);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
Event e = Event.current;
if (e.type == EventType.dragPerform)
{
if (DragAndDrop.objectReferences.Length > 0 &&
DragAndDrop.objectReferences[0] != null &&
DragAndDrop.objectReferences[0].GetType() == typeof(EditorBankRef))
{
int pos = banks.arraySize;
banks.InsertArrayElementAtIndex(pos);
var pathProperty = banks.GetArrayElementAtIndex(pos);
pathProperty.stringValue = ((EditorBankRef)DragAndDrop.objectReferences[0]).Name;
e.Use();
}
}
if (e.type == EventType.DragUpdated)
{
if (DragAndDrop.objectReferences.Length > 0 &&
DragAndDrop.objectReferences[0] != null &&
DragAndDrop.objectReferences[0].GetType() == typeof(EditorBankRef))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Move;
DragAndDrop.AcceptDrag();
e.Use();
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
| 39.089286 | 101 | 0.573778 | [
"BSD-2-Clause"
] | SashaZHdK/WormTamagotchi | AR-Sandbox-master/Assets/Plugins/Editor/FMOD/StudioBankLoaderEditor.cs | 4,380 | C# |
#region Copyright and License
// Copyright 2010..2016 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ARSoft.Tools.Net.Dns
{
/// <summary>
/// <para>Name server ID option</para>
/// <para>
/// Defined in
/// <see cref="!:http://tools.ietf.org/html/rfc5001">RFC 5001</see>
/// </para>
/// </summary>
public class NsIdOption : EDnsOptionBase
{
/// <summary>
/// Binary data of the payload
/// </summary>
public byte[] Payload { get; private set; }
internal NsIdOption()
: base(EDnsOptionType.NsId) {}
/// <summary>
/// Creates a new instance of the NsIdOption class
/// </summary>
public NsIdOption(byte[] payload)
: this()
{
Payload = payload;
}
internal override void ParseData(byte[] resultData, int startPosition, int length)
{
Payload = DnsMessageBase.ParseByteData(resultData, ref startPosition, length);
}
internal override ushort DataLength => (ushort) (Payload?.Length ?? 0);
internal override void EncodeData(byte[] messageData, ref int currentPosition)
{
DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, Payload);
}
}
} | 29.578125 | 121 | 0.701004 | [
"Apache-2.0"
] | TomWeps/ARSoft.Tools.Net-Modified | ARSoft.Tools.Net/Dns/EDns/NsIdOption.cs | 1,895 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Identity
{
/// <summary>
/// Specifies the results for password verification.
/// </summary>
public enum PasswordVerificationResult
{
/// <summary>
/// Indicates password verification failed.
/// </summary>
Failed = 0,
/// <summary>
/// Indicates password verification was successful.
/// </summary>
Success = 1,
/// <summary>
/// Indicates password verification was successful however the password was encoded using a deprecated algorithm
/// and should be rehashed and updated.
/// </summary>
SuccessRehashNeeded = 2
}
} | 31.518519 | 120 | 0.627497 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Identity/Extensions.Core/src/PasswordVerificationResult.cs | 851 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Researcher.Bot.Integration.ElasticSearch.Interfaces
{
public interface IElasticSearchConfig
{
string Uri { get; set; }
string DefaultIndex { get; set; }
string[] AllIndices { get; set; }
int MaxDocuments { get; set; }
int MaxCallIDsSize { get; set; }
}
}
| 24.125 | 61 | 0.650259 | [
"Apache-2.0"
] | esterkaufman/Elastic-Slack-NetCore-SmartBot | Researcher.Bot.Integration.ElasticSearch/Interfaces/IElasticSearchConfig.cs | 388 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Mvc;
namespace RazorWebSite.Controllers
{
public class BackSlashController : Controller
{
public IActionResult Index() => View(@"Views\BackSlash\BackSlashView.cshtml");
}
} | 29.833333 | 86 | 0.740223 | [
"MIT"
] | 48355746/AspNetCore | src/Mvc/test/WebSites/RazorWebSite/Controllers/BackSlashController.cs | 358 | C# |
using System;
using System.Collections.Generic;
using FizzWare.NBuilder;
using NTestDataBuilder;
using TestFixtureDataPresentation.Implementation.Models;
using TestFixtureDataPresentation.Tests._05_TestDataBuilderAndObjectMother.Builders;
namespace TestFixtureDataPresentation.Tests._05_TestDataBuilderAndObjectMother.BuildersWithNBuilder
{
static class ProductBuilderExtensions
{
public static IList<Product> BuildList(this IOperable<ProductBuilder> list)
{
return list.BuildList<Product, ProductBuilder>();
}
}
class ProductBuilder : TestDataBuilder<Product, ProductBuilder>
{
List<Tuple<DateTime, Campaign>> _campaigns = new List<Tuple<DateTime, Campaign>>();
public ProductBuilder()
{
Set(x => x.Name, "A product");
}
public ProductBuilder WithName(string name)
{
Set(x => x.Name, name);
return this;
}
public ProductBuilder WithNoCampaigns()
{
_campaigns = new List<Tuple<DateTime, Campaign>>();
return this;
}
public ProductBuilder WithCampaign(DateTime now, CampaignBuilder campaign)
{
_campaigns.Add(Tuple.Create(now, campaign.Build()));
return this;
}
protected override Product BuildObject()
{
var product = new Product(Get(x => x.Name));
foreach (var campaign in _campaigns)
product.CreateCampaign(
campaign.Item1,
campaign.Item2.Demographic,
campaign.Item2.StartDate,
campaign.Item2.EndDate
);
return product;
}
}
}
| 29.803279 | 100 | 0.588009 | [
"MIT"
] | robdmoore/TestFixtureDataGenerationPresentation | TestFixtureDataPresentation/Tests/05_TestDataBuilderAndObjectMother/Builders/ProductBuilder.cs | 1,760 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.COSEM.COSEMObjects;
namespace TTC2017.SmartGrids.COSEM
{
/// <summary>
/// The public interface for ManagementLogicalDevice
/// </summary>
[DefaultImplementationTypeAttribute(typeof(ManagementLogicalDevice))]
[XmlDefaultImplementationTypeAttribute(typeof(ManagementLogicalDevice))]
public interface IManagementLogicalDevice : IModelElement, ILogicalDevice
{
}
}
| 29.844444 | 96 | 0.680566 | [
"MIT"
] | georghinkel/ttc2017smartGrids | generator/COSEM/IManagementLogicalDevice.cs | 1,345 | C# |
// Copyright © 2018 Dmitry Sikorsky. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ComponentModel.DataAnnotations;
using Platformus.Barebone.Backend.ViewModels;
namespace Platformus.Security.Backend.ViewModels.Account
{
public class ResetPasswordViewModel : ViewModelBase
{
[Display(Name = "Email")]
[Required]
[StringLength(64)]
public string Email { get; set; }
}
} | 30.75 | 111 | 0.752033 | [
"Apache-2.0"
] | 5118234/Platformus | src/Platformus.Security.Backend/Areas/Backend/ViewModels/Account/ResetPassword/ResetPasswordViewModel.cs | 495 | C# |
using BlazorBoilerplate.Infrastructure.Storage.DataModels;
using BlazorBoilerplate.Shared.Localizer;
using Breeze.Persistence;
using Finbuckle.MultiTenant;
using FluentValidation;
using IdentityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorBoilerplate.Storage
{
/// <summary>
/// Breezeのやつ。
/// ApplicationControllerで使用する
/// </summary>
public class ApplicationPersistenceManager : BasePersistenceManager<ApplicationDbContext>
{
public ApplicationPersistenceManager(ApplicationDbContext dbContext,
IHttpContextAccessor accessor,
IValidatorFactory factory,
IStringLocalizer<Global> l) : base(dbContext, accessor, factory, l)
{ }
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
if (entityInfo.Entity is UserProfile userProfile)
userProfile.LastUpdatedDate = DateTime.Now;
else if (entityInfo.Entity is ApplicationUser applicationUser && entityInfo.EntityState == Breeze.Persistence.EntityState.Modified)
{
var props = DbContext.Entry(applicationUser).GetDatabaseValues();
applicationUser.PasswordHash = props.GetValue<string>("PasswordHash");
applicationUser.SecurityStamp = props.GetValue<string>("SecurityStamp");
}
return true;
}
/// <summary>
/// HTTPコンテキストのユーザー情報に一致するユーザをDBから取得
/// 無かったら作成
/// </summary>
/// <returns></returns>
public async Task<UserProfile> GetUserProfile()
{
var user = httpContextAccessor.HttpContext.User;
var userProfile = await Context.UserProfiles.SingleOrDefaultAsync(i => i.ApplicationUser.NormalizedUserName == user.Identity.Name.ToUpper());
if (userProfile == null)
{
userProfile = new UserProfile
{
TenantId = httpContextAccessor.HttpContext.GetMultiTenantContext<TenantInfo>().TenantInfo.Id, // マルチテナント用ライブラリ(Finbuckle.MultiTenant)の機能を使用する
UserId = new Guid(user.Claims.Single(c => c.Type == JwtClaimTypes.Subject).Value),
LastUpdatedDate = DateTime.Now
};
// データベースへのエンティティの挿入、または既に存在するエンティティの更新を試みる。
await Context.UserProfiles.Upsert(userProfile).On(u => new { u.TenantId, u.UserId }).RunAsync();
//see https://github.com/artiomchi/FlexLabs.Upsert/issues/29
userProfile = await Context.UserProfiles.SingleAsync(i => i.UserId == userProfile.UserId);
}
return userProfile;
}
}
}
| 39.305556 | 163 | 0.651943 | [
"MIT"
] | genkokudo/BlizzardHaunt | src/Server/BlazorBoilerplate.Storage/ApplicationPersistenceManager.cs | 3,040 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Globalization;
namespace ASC.Data.Storage
{
public class TenantPath
{
public static string CreatePath(string tenant)
{
if (tenant == null)
{
throw new ArgumentNullException("tenant");
}
long tenantId;
if (long.TryParse(tenant, NumberStyles.Integer, CultureInfo.InvariantCulture, out tenantId))
{
var culture = CultureInfo.InvariantCulture;
return tenantId == 0 ? tenantId.ToString(culture) : tenantId.ToString("00/00/00", culture);
}
return tenant;
}
public static bool TryGetTenant(string tenantPath, out int tenant)
{
tenantPath = tenantPath.Replace("/", "");
return int.TryParse(tenantPath, out tenant);
}
}
} | 32.553191 | 108 | 0.617647 | [
"Apache-2.0"
] | jeanluctritsch/CommunityServer | common/ASC.Data.Storage/TenantPath.cs | 1,530 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Scrumptious.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace Scrumptious.Service
{
public class Startup
{
public IConfiguration Configuration;
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
Configuration = new ConfigurationBuilder()
.AddJsonFile("appSettings.Dev.json", optional: true)
.Build();
services.AddDbContext<scrumptiousdbContext>(o => o.UseSqlServer(Configuration["connectionString"]));
services.AddMvc();
services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(o => o.AllowAnyOrigin().AllowAnyMethod());
app.UseMvc();
}
}
}
| 34.636364 | 122 | 0.677822 | [
"MIT"
] | kurtispe/Scrumptious | src/Scrumptious.Service/Startup.cs | 1,526 | C# |
namespace JustOrderIt.Web.Areas.Public.ViewModels.Products
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Properties;
using JustOrderIt.Data.Models;
public class ProductInfoPartialViewModel
{
private ICollection<PropertyForProductFullViewModel> descriptionProperties;
private ICollection<string> tags;
public ProductInfoPartialViewModel()
{
this.descriptionProperties = new HashSet<PropertyForProductFullViewModel>();
this.tags = new HashSet<string>();
}
[DataType(DataType.MultilineText)]
public string DescriptionContent { get; set; }
[UIHint("DescriptionProperties")]
public ICollection<PropertyForProductFullViewModel> DescriptionProperties
{
get { return this.descriptionProperties; }
set { this.descriptionProperties = value; }
}
[UIHint("ProductTags")]
public ICollection<string> Tags
{
get { return this.tags; }
set { this.tags = value; }
}
}
} | 31.25641 | 89 | 0.628384 | [
"MIT"
] | mpenchev86/ASP.NET-MVC-FinalProject | Source/Web/JustOrderIt.Web/Areas/Public/ViewModels/Products/ProductInfoPartialViewModel.cs | 1,221 | C# |
namespace qweqwe
{
partial class almayanlar
{
/// <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 Windows Form 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.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.label13 = new System.Windows.Forms.Label();
this.tbalan = new System.Windows.Forms.TextBox();
this.label12 = new System.Windows.Forms.Label();
this.tbdurum = new System.Windows.Forms.TextBox();
this.label11 = new System.Windows.Forms.Label();
this.tbtel = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label();
this.tbadres = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.tbmahalle = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.tbilce = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.tbsoy = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.tbad = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.tbnot = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.No = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Tcno = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Ad = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Soyad = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.oturduguilce = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.mahalle = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Adres = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.telefon = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.DURUM = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.alankısı = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Not = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.label14 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.Red;
this.label3.Cursor = System.Windows.Forms.Cursors.Hand;
this.label3.Font = new System.Drawing.Font("Tahoma", 15F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.White;
this.label3.Location = new System.Drawing.Point(1011, 16);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(30, 24);
this.label3.TabIndex = 57;
this.label3.Text = "X ";
this.label3.Click += new System.EventHandler(this.label3_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.BackColor = System.Drawing.Color.DarkSlateGray;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label4.ForeColor = System.Drawing.Color.White;
this.label4.Location = new System.Drawing.Point(12, 16);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(184, 15);
this.label4.TabIndex = 58;
this.label4.Text = "SADECE KIYAFET ALMAMIŞ";
this.label4.MouseDown += new System.Windows.Forms.MouseEventHandler(this.label5_MouseDown);
this.label4.MouseMove += new System.Windows.Forms.MouseEventHandler(this.label5_MouseMove);
this.label4.MouseUp += new System.Windows.Forms.MouseEventHandler(this.label5_MouseUp);
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.DarkSlateGray;
this.label2.Cursor = System.Windows.Forms.Cursors.Hand;
this.label2.Font = new System.Drawing.Font("Tahoma", 15F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.Color.White;
this.label2.Location = new System.Drawing.Point(969, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(36, 24);
this.label2.TabIndex = 56;
this.label2.Text = "__";
this.label2.Click += new System.EventHandler(this.label2_Click);
//
// label1
//
this.label1.BackColor = System.Drawing.Color.DarkSlateGray;
this.label1.Location = new System.Drawing.Point(-24, -3);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(1090, 47);
this.label1.TabIndex = 55;
this.label1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.label5_MouseDown);
this.label1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.label5_MouseMove);
this.label1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.label5_MouseUp);
//
// button2
//
this.button2.BackColor = System.Drawing.Color.CadetBlue;
this.button2.Cursor = System.Windows.Forms.Cursors.Hand;
this.button2.FlatAppearance.BorderSize = 0;
this.button2.FlatAppearance.MouseDownBackColor = System.Drawing.Color.DarkCyan;
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.button2.ForeColor = System.Drawing.Color.White;
this.button2.Location = new System.Drawing.Point(955, 356);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(85, 36);
this.button2.TabIndex = 129;
this.button2.Text = "TEMİZLE";
this.button2.UseVisualStyleBackColor = false;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// label13
//
this.label13.AutoSize = true;
this.label13.BackColor = System.Drawing.SystemColors.ControlDark;
this.label13.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label13.ForeColor = System.Drawing.Color.Black;
this.label13.Location = new System.Drawing.Point(807, 346);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(68, 16);
this.label13.TabIndex = 128;
this.label13.Text = "Alan Kişi";
//
// tbalan
//
this.tbalan.Location = new System.Drawing.Point(810, 365);
this.tbalan.Name = "tbalan";
this.tbalan.ReadOnly = true;
this.tbalan.Size = new System.Drawing.Size(124, 20);
this.tbalan.TabIndex = 127;
//
// label12
//
this.label12.AutoSize = true;
this.label12.BackColor = System.Drawing.SystemColors.ControlDark;
this.label12.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label12.ForeColor = System.Drawing.Color.Black;
this.label12.Location = new System.Drawing.Point(849, 53);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(52, 16);
this.label12.TabIndex = 126;
this.label12.Text = "Durum";
//
// tbdurum
//
this.tbdurum.Location = new System.Drawing.Point(916, 52);
this.tbdurum.Name = "tbdurum";
this.tbdurum.ReadOnly = true;
this.tbdurum.Size = new System.Drawing.Size(124, 20);
this.tbdurum.TabIndex = 125;
//
// label11
//
this.label11.AutoSize = true;
this.label11.BackColor = System.Drawing.SystemColors.ControlDark;
this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label11.ForeColor = System.Drawing.Color.Black;
this.label11.Location = new System.Drawing.Point(649, 53);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(61, 16);
this.label11.TabIndex = 124;
this.label11.Text = "Telefon";
//
// tbtel
//
this.tbtel.Location = new System.Drawing.Point(716, 52);
this.tbtel.Name = "tbtel";
this.tbtel.ReadOnly = true;
this.tbtel.Size = new System.Drawing.Size(124, 20);
this.tbtel.TabIndex = 123;
//
// label10
//
this.label10.AutoSize = true;
this.label10.BackColor = System.Drawing.SystemColors.ControlDark;
this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label10.ForeColor = System.Drawing.Color.Black;
this.label10.Location = new System.Drawing.Point(212, 342);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(49, 16);
this.label10.TabIndex = 122;
this.label10.Text = "Adres";
//
// tbadres
//
this.tbadres.Location = new System.Drawing.Point(267, 344);
this.tbadres.Multiline = true;
this.tbadres.Name = "tbadres";
this.tbadres.ReadOnly = true;
this.tbadres.Size = new System.Drawing.Size(209, 119);
this.tbadres.TabIndex = 121;
//
// label9
//
this.label9.AutoSize = true;
this.label9.BackColor = System.Drawing.SystemColors.ControlDark;
this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label9.ForeColor = System.Drawing.Color.Black;
this.label9.Location = new System.Drawing.Point(10, 371);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(63, 16);
this.label9.TabIndex = 120;
this.label9.Text = "Mahalle";
//
// tbmahalle
//
this.tbmahalle.Location = new System.Drawing.Point(79, 370);
this.tbmahalle.Name = "tbmahalle";
this.tbmahalle.ReadOnly = true;
this.tbmahalle.Size = new System.Drawing.Size(124, 20);
this.tbmahalle.TabIndex = 119;
//
// label8
//
this.label8.AutoSize = true;
this.label8.BackColor = System.Drawing.SystemColors.ControlDark;
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label8.ForeColor = System.Drawing.Color.Black;
this.label8.Location = new System.Drawing.Point(10, 345);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(33, 16);
this.label8.TabIndex = 118;
this.label8.Text = "İlçe";
//
// tbilce
//
this.tbilce.Location = new System.Drawing.Point(79, 344);
this.tbilce.Name = "tbilce";
this.tbilce.ReadOnly = true;
this.tbilce.Size = new System.Drawing.Size(124, 20);
this.tbilce.TabIndex = 117;
//
// label7
//
this.label7.AutoSize = true;
this.label7.BackColor = System.Drawing.SystemColors.ControlDark;
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label7.ForeColor = System.Drawing.Color.Black;
this.label7.Location = new System.Drawing.Point(440, 53);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(53, 16);
this.label7.TabIndex = 116;
this.label7.Text = "Soyad";
//
// tbsoy
//
this.tbsoy.Location = new System.Drawing.Point(499, 52);
this.tbsoy.Name = "tbsoy";
this.tbsoy.ReadOnly = true;
this.tbsoy.Size = new System.Drawing.Size(124, 20);
this.tbsoy.TabIndex = 115;
//
// label5
//
this.label5.AutoSize = true;
this.label5.BackColor = System.Drawing.SystemColors.ControlDark;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label5.ForeColor = System.Drawing.Color.Black;
this.label5.Location = new System.Drawing.Point(253, 54);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(27, 16);
this.label5.TabIndex = 114;
this.label5.Text = "Ad";
//
// tbad
//
this.tbad.Location = new System.Drawing.Point(286, 53);
this.tbad.Name = "tbad";
this.tbad.ReadOnly = true;
this.tbad.Size = new System.Drawing.Size(124, 20);
this.tbad.TabIndex = 113;
//
// label6
//
this.label6.AutoSize = true;
this.label6.BackColor = System.Drawing.SystemColors.ControlDark;
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label6.ForeColor = System.Drawing.Color.Black;
this.label6.Location = new System.Drawing.Point(486, 342);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(87, 16);
this.label6.TabIndex = 112;
this.label6.Text = "Yazılan Not";
//
// tbnot
//
this.tbnot.Location = new System.Drawing.Point(579, 342);
this.tbnot.Multiline = true;
this.tbnot.Name = "tbnot";
this.tbnot.ReadOnly = true;
this.tbnot.Size = new System.Drawing.Size(204, 119);
this.tbnot.TabIndex = 111;
//
// button1
//
this.button1.BackColor = System.Drawing.Color.CadetBlue;
this.button1.FlatAppearance.BorderSize = 0;
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.button1.ForeColor = System.Drawing.Color.White;
this.button1.Location = new System.Drawing.Point(174, 52);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(52, 24);
this.button1.TabIndex = 110;
this.button1.Text = "ARA";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.ForeColor = System.Drawing.Color.Gray;
this.textBox1.Location = new System.Drawing.Point(13, 52);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(148, 20);
this.textBox1.TabIndex = 109;
this.textBox1.Text = "TC KİMLİK NUMARASI GİR";
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToOrderColumns = true;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.No,
this.Tcno,
this.Ad,
this.Soyad,
this.oturduguilce,
this.mahalle,
this.Adres,
this.telefon,
this.DURUM,
this.alankısı,
this.Not});
this.dataGridView1.Location = new System.Drawing.Point(-43, 78);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.Size = new System.Drawing.Size(1093, 257);
this.dataGridView1.TabIndex = 108;
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
//
// No
//
this.No.DataPropertyName = "sirano";
this.No.Frozen = true;
this.No.HeaderText = "No";
this.No.Name = "No";
this.No.ReadOnly = true;
this.No.Width = 50;
//
// Tcno
//
this.Tcno.DataPropertyName = "Tcno";
this.Tcno.Frozen = true;
this.Tcno.HeaderText = "Tcno";
this.Tcno.Name = "Tcno";
this.Tcno.ReadOnly = true;
//
// Ad
//
this.Ad.DataPropertyName = "ad";
this.Ad.Frozen = true;
this.Ad.HeaderText = "Ad";
this.Ad.Name = "Ad";
this.Ad.ReadOnly = true;
//
// Soyad
//
this.Soyad.DataPropertyName = "Soyad";
this.Soyad.Frozen = true;
this.Soyad.HeaderText = "Soyad";
this.Soyad.Name = "Soyad";
this.Soyad.ReadOnly = true;
//
// oturduguilce
//
this.oturduguilce.DataPropertyName = "İlce";
this.oturduguilce.Frozen = true;
this.oturduguilce.HeaderText = "İlçe";
this.oturduguilce.Name = "oturduguilce";
this.oturduguilce.ReadOnly = true;
//
// mahalle
//
this.mahalle.DataPropertyName = "Mahalle";
this.mahalle.Frozen = true;
this.mahalle.HeaderText = "Mahalle";
this.mahalle.Name = "mahalle";
this.mahalle.ReadOnly = true;
//
// Adres
//
this.Adres.DataPropertyName = "Adres";
this.Adres.Frozen = true;
this.Adres.HeaderText = "Adres";
this.Adres.Name = "Adres";
this.Adres.ReadOnly = true;
//
// telefon
//
this.telefon.DataPropertyName = "Telefon";
this.telefon.Frozen = true;
this.telefon.HeaderText = "Telefon";
this.telefon.Name = "telefon";
this.telefon.ReadOnly = true;
//
// DURUM
//
this.DURUM.DataPropertyName = "Durum";
this.DURUM.Frozen = true;
this.DURUM.HeaderText = "Durum";
this.DURUM.Name = "DURUM";
this.DURUM.ReadOnly = true;
//
// alankısı
//
this.alankısı.DataPropertyName = "AlanKisi";
this.alankısı.Frozen = true;
this.alankısı.HeaderText = "Alan Kişi";
this.alankısı.Name = "alankısı";
this.alankısı.ReadOnly = true;
//
// Not
//
this.Not.DataPropertyName = "Notl";
this.Not.Frozen = true;
this.Not.HeaderText = "Not";
this.Not.Name = "Not";
this.Not.ReadOnly = true;
//
// label14
//
this.label14.AutoSize = true;
this.label14.BackColor = System.Drawing.Color.Red;
this.label14.Enabled = false;
this.label14.Font = new System.Drawing.Font("Microsoft Sans Serif", 50F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.label14.ForeColor = System.Drawing.Color.White;
this.label14.Location = new System.Drawing.Point(187, 180);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(428, 58);
this.label14.TabIndex = 130;
this.label14.Text = "Kayıt Bulunamadı.";
//
// almayanlar
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ControlDark;
this.ClientSize = new System.Drawing.Size(1053, 471);
this.Controls.Add(this.label14);
this.Controls.Add(this.button2);
this.Controls.Add(this.label13);
this.Controls.Add(this.tbalan);
this.Controls.Add(this.label12);
this.Controls.Add(this.tbdurum);
this.Controls.Add(this.label11);
this.Controls.Add(this.tbtel);
this.Controls.Add(this.label10);
this.Controls.Add(this.tbadres);
this.Controls.Add(this.label9);
this.Controls.Add(this.tbmahalle);
this.Controls.Add(this.label8);
this.Controls.Add(this.tbilce);
this.Controls.Add(this.label7);
this.Controls.Add(this.tbsoy);
this.Controls.Add(this.label5);
this.Controls.Add(this.tbad);
this.Controls.Add(this.label6);
this.Controls.Add(this.tbnot);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label4);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(162)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "almayanlar";
this.Text = "Sadece Kıyafet Almamış";
this.Load += new System.EventHandler(this.almayanlar_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label2;
public System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.TextBox tbalan;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox tbdurum;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox tbtel;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox tbadres;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox tbmahalle;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox tbilce;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox tbsoy;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox tbad;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox tbnot;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.DataGridViewTextBoxColumn No;
private System.Windows.Forms.DataGridViewTextBoxColumn Tcno;
private System.Windows.Forms.DataGridViewTextBoxColumn Ad;
private System.Windows.Forms.DataGridViewTextBoxColumn Soyad;
private System.Windows.Forms.DataGridViewTextBoxColumn oturduguilce;
private System.Windows.Forms.DataGridViewTextBoxColumn mahalle;
private System.Windows.Forms.DataGridViewTextBoxColumn Adres;
private System.Windows.Forms.DataGridViewTextBoxColumn telefon;
private System.Windows.Forms.DataGridViewTextBoxColumn DURUM;
private System.Windows.Forms.DataGridViewTextBoxColumn alankısı;
private System.Windows.Forms.DataGridViewTextBoxColumn Not;
private System.Windows.Forms.Label label14;
}
} | 48.744643 | 215 | 0.585229 | [
"MIT"
] | Meeyzt/Sunnet-kiyafeti-dagitim-uygulamasi | almayanlar.Designer.cs | 27,337 | C# |
namespace ArmyOfCreatures.Extended.Specialties
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic.Battles;
using Logic.Specialties;
public class DoubleAttackWhenAttacking : Specialty
{
private int roundsWithDoubleAttack;
public DoubleAttackWhenAttacking(int rounds)
{
if (rounds <= 0)
{
throw new ArgumentOutOfRangeException("rounds", "The number of rounds should be greater than 0.");
}
this.roundsWithDoubleAttack = rounds;
}
public override void ApplyWhenAttacking(ICreaturesInBattle attackerWithSpecialty, ICreaturesInBattle defender)
{
if (attackerWithSpecialty == null)
{
throw new ArgumentNullException("attackerWithSpecialty");
}
if (defender == null)
{
throw new ArgumentNullException("defender");
}
if (this.roundsWithDoubleAttack <= 0)
{
// Effect expires after fixed number of rounds
return;
}
attackerWithSpecialty.CurrentAttack *= 2;
this.roundsWithDoubleAttack--;
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}({1})"
, base.ToString()
, this.roundsWithDoubleAttack);
}
}
}
| 28.280702 | 118 | 0.565136 | [
"MIT"
] | VVoev/Telerik-Academy | 05.C#ObjectOrientedProgramming/ExamPreparation/OOP6April2015/ArmyOfCreatures/Source/ArmyOfCreatures/Extended/Specialties/DoubleAttackWhenAttacking.cs | 1,614 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
namespace System.Windows.Forms
{
public abstract partial class AxHost
{
[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
public sealed class TypeLibraryTimeStampAttribute : Attribute
{
private readonly DateTime val;
public TypeLibraryTimeStampAttribute(string timestamp)
{
val = DateTime.Parse(timestamp, CultureInfo.InvariantCulture);
}
public DateTime Value
{
get
{
return val;
}
}
}
}
}
| 27.451613 | 78 | 0.59342 | [
"MIT"
] | AArnott/winforms | src/System.Windows.Forms/src/System/Windows/Forms/AxHost.TypeLibraryTimeStampAttribute.cs | 851 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3040
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MVCNestedMasterPagesDynamicContent.Views.Account
{
public partial class ChangePassword
{
}
}
| 27.052632 | 81 | 0.470817 | [
"MIT"
] | Code-Inside/Samples | 2009/MVCNestedMasterPagesDynamicContent/MVCNestedMasterPagesDynamicContent/Views/Account/ChangePassword.aspx.designer.cs | 516 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Threading.Tasks;
using Microsoft.Coyote.Specifications;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Coyote.SystematicTesting.Tests.Tasks
{
public class TaskInterfaceTests : BaseSystematicTest
{
public TaskInterfaceTests(ITestOutputHelper output)
: base(output)
{
}
private interface IAsyncSender
{
Task<bool> SendEventAsync();
}
private class AsyncSender : IAsyncSender
{
public async Task<bool> SendEventAsync()
{
// Model sending some event.
await Task.Delay(1);
return true;
}
}
[Fact(Timeout = 5000)]
public void TestAsyncInterfaceMethodCall()
{
this.Test(async () =>
{
IAsyncSender sender = new AsyncSender();
bool result = await sender.SendEventAsync();
Specification.Assert(result, "Unexpected result.");
},
configuration: GetConfiguration());
}
}
}
| 25.782609 | 67 | 0.564081 | [
"MIT"
] | arunt1204/coyote | Tests/Tests.SystematicTesting/Tasks/TaskInterfaceTests.cs | 1,188 | 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;
namespace NuGet.Services.Validation
{
/// <summary>
/// The details requires for requesting the status of an asynchronous validation or requesting that an
/// asynchronous validation be started.
/// </summary>
public interface IValidationRequest
{
/// <summary>
/// The identifier for a single validation execution.
/// </summary>
Guid ValidationId { get; }
/// <summary>
/// The package key in the NuGet gallery database. If a package is hard deleted and created, the package key
/// will be different but the <see cref="PackageId"/> and <see cref="PackageVersion"/> will be the same.
/// </summary>
int PackageKey { get; }
/// <summary>
/// The package ID. The casing of this ID need not match the author-intended casing of the ID.
/// </summary>
string PackageId { get; }
/// <summary>
/// The package version. The casing of this version need not match the author-intended casing of the version.
/// This value is not necessarily a normalized version.
/// </summary>
string PackageVersion { get; }
/// <summary>
/// The URL to the NuGet package content. This URL should be accessible without special authentication headers.
/// However, authentication information could be included in the URL (e.g. Azure Blob Storage SAS URL). This URL
/// need not have a single value for a specific <see cref="ValidationId"/>.
/// </summary>
string NupkgUrl { get; }
}
}
| 40.181818 | 120 | 0.636878 | [
"Apache-2.0"
] | DalavanCloud/ServerCommon | src/NuGet.Services.Contracts/Validation/IValidationRequest.cs | 1,770 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由T4模板自动生成
// 生成时间 2020-12-17 09:34:52
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失
// 作者:Harbour CTS
// </auto-generated>
//------------------------------------------------------------------------------
using GMS.Model;
using GMS.DAL;
namespace GMS.BLL
{
public partial class HealthExamBLL:BaseServiceDapperContrib<Model.HealthExam>
{
}
}
| 20.48 | 81 | 0.416016 | [
"MIT"
] | Cythsic/ManagementSys_Api | GMS.BLL/T4.DapperExt/HealthExamBLL.cs | 622 | C# |
using System;
namespace NumberDuplexes
{
public class Program
{
public static void Main(string[] args)
{
string[] parts = Console.ReadLine().Split(' ');
int[] numbers = new int[parts.Length];
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = int.Parse(parts[i]);
}
int dublicatedNumber = int.Parse(Console.ReadLine());
int result = 0;
for (int i = 0; i < numbers.Length; i++)
{
if(numbers[i] == dublicatedNumber)
{
result++;
}
}
Console.WriteLine(result);
}
}
}
| 22.030303 | 65 | 0.431912 | [
"MIT"
] | SpleefDinamix/SoftuniCSFundamentalsExtended | ArraysExercises/NumberDuplexes/Program.cs | 729 | C# |
using Newtonsoft.Json;
namespace Frau.Models
{
public class ExpandedShare : Share
{
[JsonProperty("user")]
public User User { get; set; }
}
} | 17.1 | 38 | 0.602339 | [
"MIT"
] | mika-sandbox/dotnet-mixier-api-wrapper | Sources/Frau/Models/ExpandedShare.cs | 173 | C# |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MMRMS.Windows.Models
{
/// <summary>
/// The model for the mcmod.info
/// </summary>
public class McModInfo
{
[JsonProperty("modid")]
public string Modid { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("mcversion")]
public string Mcversion { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("updateUrl")]
public string UpdateUrl { get; set; }
[JsonProperty("authorList")]
public IList<string> AuthorList { get; set; }
[JsonProperty("credits")]
public string Credits { get; set; }
[JsonProperty("logoFile")]
public string LogoFile { get; set; }
[JsonProperty("screenshots")]
public IList<string> Screenshots { get; set; }
[JsonProperty("dependencies")]
public IList<string> Dependencies { get; set; }
}
}
| 24.979167 | 55 | 0.582986 | [
"MIT"
] | Haveachin/MMRMS | MMRMS/MMRMS.Windows/Models/McModInfo.cs | 1,201 | C# |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
namespace ILRuntime.Mono.Cecil {
public interface IMarshalInfoProvider : IMetadataTokenProvider {
bool HasMarshalInfo { get; }
MarshalInfo MarshalInfo { get; set; }
}
static partial class Mixin {
public static bool GetHasMarshalInfo (
this IMarshalInfoProvider self,
ModuleDefinition module)
{
return module.HasImage () && module.Read (self, (provider, reader) => reader.HasMarshalInfo (provider));
}
public static MarshalInfo GetMarshalInfo (
this IMarshalInfoProvider self,
ref MarshalInfo variable,
ModuleDefinition module)
{
return module.HasImage ()
? module.Read (ref variable, self, (provider, reader) => reader.ReadMarshalInfo (provider))
: null;
}
}
}
| 22.871795 | 107 | 0.700673 | [
"MIT"
] | 172672672/Confused_ILRuntime | Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs | 892 | C# |
using CommunicationProtocol.Serialization;
using System;
using System.Numerics;
namespace CommunicationProtocol
{
public interface IActor : IBinarySerializable, IEquatable<IActor>
{
Vector2 Position { get; }
}
}
| 19.5 | 69 | 0.739316 | [
"Apache-2.0"
] | Nono02P/Communication-Protocol | CommunicationProtocol/GameObjects/IActor.cs | 236 | C# |
namespace Horizon.Payment.Alipay.Response
{
/// <summary>
/// AlipayOpenAppOpenbizmockMessageSendResponse.
/// </summary>
public class AlipayOpenAppOpenbizmockMessageSendResponse : AlipayResponse
{
}
}
| 22.7 | 77 | 0.713656 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Response/AlipayOpenAppOpenbizmockMessageSendResponse.cs | 229 | C# |
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
namespace UnityExtensions.Editor
{
public class BasePropertyDrawer : PropertyDrawer
{
/// <summary>
/// BasePropertyDrawer
/// </summary>
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
using (WideModeScope.New(true))
return EditorGUI.GetPropertyHeight(property, label, true);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
using (WideModeScope.New(true))
EditorGUI.PropertyField(position, property, label, true);
}
} // BasePropertyDrawer
/// <summary>
/// BasePropertyDrawer<T>
/// </summary>
public class BasePropertyDrawer<T> : BasePropertyDrawer where T : PropertyAttribute
{
protected new T attribute => (T)base.attribute;
} // class BasePropertyDrawer<T>
} // namespace UnityExtensions.Editor
#endif // UNITY_EDITOR | 27.5 | 96 | 0.649761 | [
"MIT"
] | darktable/UnityExtensionsCommon | Runtime/Editor/Types/BasePropertyDrawer.cs | 1,047 | C# |
namespace AbstractFactory.Conceptual
{
// Concrete Products are created by corresponding Concrete Factories.
class ConcreteProductA1 : IAbstractProductA
{
public string UsefulFunctionA()
{
return "The result of the product A1.";
}
}
}
| 24 | 73 | 0.649306 | [
"MIT"
] | BaiGanio/Design-Patterns | project/src/Creational/AbstractFactory/AbstractFactory.Conceptual/Products (Family)/ConcreteProductA1.cs | 290 | C# |
namespace Framework.WebApi.Areas.HelpPage.ModelDescriptions
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | 22.545455 | 59 | 0.649194 | [
"MIT"
] | fhnaseer/CSharping | CSharp/Framework.WebApi/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs | 248 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace vtCore
{
public class MRU
{
public MRU(uint maxProject)
{
this.maxProjects = maxProject;
}
public void load(string mruString)
{
projects = mruString.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
while (projects.Count > maxProjects)
{
projects.RemoveAt(0);
}
}
override public string ToString()
{
if (projects.Count == 0) return "";
StringBuilder mruString = new StringBuilder(projects[0]);
foreach (var project in projects.Skip(1))
{
mruString.Append($"|{project}");
}
return mruString.ToString();
}
public void AddProject(string project)
{
projects.Add(project);
while (projects.Count > maxProjects)
{
projects.RemoveAt(0);
}
}
public void RemoveFolder(string folder)
{
projects.Remove(folder);
}
private uint maxProjects;
private List<string> projects = new List<string>();
}
}
| 23.267857 | 107 | 0.520338 | [
"MIT"
] | luni64/VisualTeensy | vtCore/Implementation/MRU.cs | 1,305 | C# |
using System.Collections.Generic;
using Assets.Scripts;
using Assets.Scripts.Models;
using Assets.Scripts.Turret;
using Assets.Scripts.Utils;
using UnityEngine;
public class PrefabManager : MonoBehaviour
{
[SerializeField] private GameObject _projectilePrefab;
[SerializeField] private GameObject _turretUiPrefab;
[SerializeField] private GameObject _enemyPrefab;
[SerializeField] private GameObject _terrainTilePrefab;
[SerializeField] private GameObject _pathTilePrefab;
[SerializeField] private GameObject _turretBasePrefab;
[SerializeField] private GameObject _turretWeaponPrefab;
[SerializeField] private GameObject _basePrefab;
public GameObject BasePrefab => _basePrefab;
[SerializeField] private GameObject _lifePrefab;
public GameObject LifePrefab => _lifePrefab;
private Dictionary<string, GameObject> _projectilePrefabs = new Dictionary<string, GameObject>();
private Dictionary<string, GameObject> _turretUiPrefabs = new Dictionary<string, GameObject>();
private Dictionary<string, GameObject> _enemyPrefabs = new Dictionary<string, GameObject>();
private Dictionary<int, GameObject> _tilePrefabs = new Dictionary<int, GameObject>();
private Dictionary<string, GameObject> _turretBasePrefabs = new Dictionary<string, GameObject>();
private Dictionary<string, GameObject> _turretWeaponPrefabs = new Dictionary<string, GameObject>();
// Start is called before the first frame update
void Start()
{
}
public GameObject GetProjectilePrefab(TurretParams turretParams)
{
if (_projectilePrefabs.ContainsKey(turretParams.Name))
{
return _projectilePrefabs[turretParams.Name];
}
string prefabName = "prefab_projectile " + turretParams.Name;
GameObject prefab = CopyPrefab(_projectilePrefab, prefabName, turretParams.ProjectileTexture);
_projectilePrefabs.Add(turretParams.Name, prefab);
return prefab;
}
public GameObject GetTurretUiPrefab(TurretParams turretParams)
{
if (_turretUiPrefabs.ContainsKey(turretParams.Name))
{
return _turretUiPrefabs[turretParams.Name];
}
string prefabName = "prefab_turret_ui " + turretParams.Name;
GameObject prefab = CopyPrefab(_turretUiPrefab, prefabName, turretParams.UiTexture);
prefab.GetComponent<CreateTurret>().Params = turretParams;
_turretUiPrefabs.Add(turretParams.Name, prefab);
return prefab;
}
public GameObject GetTurretWeaponPrefab(TurretParams turretParams)
{
if (_turretWeaponPrefabs.ContainsKey(turretParams.Name))
{
return _turretWeaponPrefabs[turretParams.Name];
}
string prefabName = "prefab_turret_weapon " + turretParams.Name;
GameObject prefab = CopyPrefab(_turretWeaponPrefab, prefabName, turretParams.WeaponTexture);
_turretWeaponPrefabs.Add(turretParams.Name, prefab);
return prefab;
}
public GameObject GetTurretBasePrefab(TurretParams turretParams)
{
if (_turretBasePrefabs.ContainsKey(turretParams.Name))
{
return _turretBasePrefabs[turretParams.Name];
}
string prefabName = "prefab_turret_base " + turretParams.Name;
GameObject prefab = CopyPrefab(_turretBasePrefab, prefabName, turretParams.BaseTexture);
_turretBasePrefabs.Add(turretParams.Name, prefab);
return prefab;
}
public void SetEnemyPrefab(EnemyModel enemyModel)
{
if (_enemyPrefabs.ContainsKey(enemyModel.name))
{
return;
}
string prefabName = "prefab_enemy " + enemyModel.name;
GameObject prefab = CopyPrefab(_enemyPrefab, prefabName, enemyModel.texture);
Unit unit = prefab.GetComponent<Unit>();
unit.Hp = enemyModel.hitPoints;
unit.Speed = enemyModel.speed;
unit.MoneyReward = enemyModel.moneyReward;
unit.HitSound = ResourceUtil.LoadSound(enemyModel.sound);
_enemyPrefabs.Add(enemyModel.name, prefab);
}
public GameObject GetEnemyPrefab(string enemyName)
{
return _enemyPrefabs[enemyName];
}
public void SetTilePrefab(int tileNumber, string texturePath)
{
if (_tilePrefabs.ContainsKey(tileNumber))
{
return;
}
string prefabName = "prefab_tile " + tileNumber;
GameObject prefabSource = tileNumber != 0 ? _terrainTilePrefab : _pathTilePrefab;
GameObject prefab = CopyPrefab(prefabSource, prefabName, texturePath);
_tilePrefabs.Add(tileNumber, prefab);
}
public GameObject GetTilePrefab(int tileNumber)
{
return _tilePrefabs[tileNumber];
}
private GameObject CopyPrefab(GameObject prefab, string prefabName, string texturePath)
{
GameObject prefabCopy = Instantiate(prefab);
prefabCopy.SetActive(false);
prefabCopy.name = prefabName;
prefabCopy.transform.parent = transform;
prefabCopy.GetComponent<SpriteRenderer>().sprite =
ResourceUtil.LoadSprite(texturePath);
return prefabCopy;
}
} | 35.349315 | 103 | 0.705677 | [
"MIT"
] | zlociu/Secure-Tower-Defence | Unity_game/Assets/Scripts/Managers/PrefabManager.cs | 5,163 | C# |
using System.IO;
using Nancy;
namespace NancyCore
{
public class CustomRootPathProvider : IRootPathProvider
{
public string GetRootPath() => Directory.GetCurrentDirectory();
}
} | 19.8 | 71 | 0.717172 | [
"Unlicense"
] | 0xFireball/Template-NancyCore2 | NancyCore/RootPathProvider.cs | 198 | C# |
using Bbt.Campaign.Public.BaseResultModels;
using Bbt.Campaign.Public.Dtos;
using Bbt.Campaign.Public.Dtos.Authorization;
namespace Bbt.Campaign.Services.Services.Parameter
{
public interface IParameterService
{
public Task<BaseResponse<List<ParameterDto>>> GetActionOptionListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetBranchListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetBusinessLineListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetCampaignStartTermListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetCustomerTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetJoinTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetLanguageListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetSectorListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetViewOptionListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetProgramTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetAchievementFrequencyListAsync();
public Task<BaseResponse<List<string>>> GetCampaignChannelListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetCurrencyListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetTargetDefinitionListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetTargetOperationListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetTargetSourceListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetTargetViewTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetTriggerTimeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetVerificationTimeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetAchievementTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetParticipationTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetRoleTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetModuleTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetAuthorizationTypeListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetAllUsersRoleListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetAllUsersRoleListInProgressAsync(string cacheKey);
public Task<BaseResponse<List<ParameterDto>>> GetSingleUserRoleListAsync(string userId);
public Task<BaseResponse<List<RoleAuthorizationDto>>> GetRoleAuthorizationListAsync();
public Task<BaseResponse<List<UserRoleDto>>> GetUserRoleListAsync(string userId);
public Task<BaseResponse<List<UserRoleDto>>> SetUserRoleListAsync(string userId, List<UserRoleDto> _userRoleList);
public Task<BaseResponse<List<ParameterDto>>> GetBranchSelectDateListAsync();
public Task<BaseResponse<List<ParameterDto>>> GetChannelCodeSelectDateListAsync();
public Task<string> GetServiceData(string serviceUrl);
}
}
| 63.291667 | 122 | 0.763002 | [
"MIT"
] | hub-burgan-com-tr/bbt.loyalty | src/Bbt.Campaign.Api/Bbt.Campaign.Services/Services/Parameter/IParameterService.cs | 3,040 | C# |
namespace Data.Structures.SkillEngine
{
[ProtoBuf.ProtoContract]
public class ChargeStage
{
[ProtoBuf.ProtoMember(1)]
public float Duration { get; set; }
[ProtoBuf.ProtoMember(2)]
public float CostHpRate { get; set; }
[ProtoBuf.ProtoMember(3)]
public float CostMpRate { get; set; }
[ProtoBuf.ProtoMember(4)]
public int ShotSkillId { get; set; }
}
}
| 22.789474 | 45 | 0.605081 | [
"MIT"
] | Sheigetsu/TeraDataTools | TeraEmulatorData/Data/Structures/SkillEngine/ChargeStage.cs | 435 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
#pragma warning disable 1591
namespace PdfiumViewer
{
public class PdfException : Exception
{
public PdfError Error { get; private set; }
public PdfException()
{
}
public PdfException(PdfError error)
: this(GetMessage(error))
{
Error = error;
}
private static string GetMessage(PdfError error)
{
switch (error)
{
case PdfError.Success:
return "No error";
case PdfError.CannotOpenFile:
return "File not found or could not be opened";
case PdfError.InvalidFormat:
return "File not in PDF format or corrupted";
case PdfError.PasswordProtected:
return "Password required or incorrect password";
case PdfError.UnsupportedSecurityScheme:
return "Unsupported security scheme";
case PdfError.PageNotFound:
return "Page not found or content error";
default:
return "Unknown error";
}
}
public PdfException(string message)
: base(message)
{
}
public PdfException(string message, Exception innerException)
: base(message, innerException)
{
}
protected PdfException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 28.163934 | 81 | 0.523865 | [
"Apache-2.0"
] | Andomiel/PdfiumViewer | PdfiumViewer/PdfException.cs | 1,720 | C# |
using System;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
internal class SimpleLitShaderGUI : BaseShaderGUI
{
private const float kMinShininessValue = 0.01f;
private MaterialProperty albedoMapProp;
private MaterialProperty albedoColorProp;
private MaterialProperty specularSourceProp;
private MaterialProperty glossinessSourceProp;
private MaterialProperty specularGlossMapProp;
private MaterialProperty specularColorProp;
private MaterialProperty shininessProp;
private MaterialProperty bumpMapProp;
private MaterialProperty emissionMapProp;
private MaterialProperty emissionColorProp;
private static class Styles
{
public static GUIContent[] albedoGlosinessLabels =
{
new GUIContent("Base (RGB) Glossiness (A)", "Base Color (RGB) and Glossiness (A)"),
new GUIContent("Base (RGB)", "Base Color (RGB)")
};
public static GUIContent albedoAlphaLabel = new GUIContent("Base (RGB) Alpha (A)",
"Base Color (RGB) and Transparency (A)");
public static GUIContent[] specularGlossMapLabels =
{
new GUIContent("Specular Map (RGB)", "Specular Color (RGB)"),
new GUIContent("Specular Map (RGB) Glossiness (A)", "Specular Color (RGB) Glossiness (A)")
};
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map");
public static GUIContent emissionMapLabel = new GUIContent("Emission Map", "Emission Map");
public static readonly string[] glossinessSourceNames = Enum.GetNames(typeof(GlossinessSource));
public static string surfaceProperties = "Surface Properties";
public static string specularSourceLabel = "Specular";
public static string glossinessSourceLabel = "Glossiness Source";
public static string glossinessSource = "Glossiness Source";
public static string albedoColorLabel = "Base Color";
public static string albedoMapAlphaLabel = "Base(RGB) Alpha(A)";
public static string albedoMapGlossinessLabel = "Base(RGB) Glossiness (A)";
public static string shininessLabel = "Shininess";
public static string normalMapLabel = "Normal map";
public static string emissionColorLabel = "Emission Color";
}
public override void FindProperties(MaterialProperty[] properties)
{
base.FindProperties(properties);
albedoMapProp = FindProperty("_MainTex", properties);
albedoColorProp = FindProperty("_Color", properties);
specularSourceProp = FindProperty("_SpecSource", properties);
glossinessSourceProp = FindProperty("_GlossinessSource", properties);
specularGlossMapProp = FindProperty("_SpecGlossMap", properties);
specularColorProp = FindProperty("_SpecColor", properties);
shininessProp = FindProperty("_Shininess", properties);
bumpMapProp = FindProperty("_BumpMap", properties);
emissionMapProp = FindProperty("_EmissionMap", properties);
emissionColorProp = FindProperty("_EmissionColor", properties);
}
public override void ShaderPropertiesGUI(Material material)
{
EditorGUI.BeginChangeCheck();
{
base.ShaderPropertiesGUI(material);
GUILayout.Label(Styles.surfaceProperties, EditorStyles.boldLabel);
DoSurfaceArea();
DoSpecular();
EditorGUILayout.Space();
materialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMapProp);
EditorGUILayout.Space();
DoEmissionArea(material);
EditorGUI.BeginChangeCheck();
materialEditor.TextureScaleOffsetProperty(albedoMapProp);
if (EditorGUI.EndChangeCheck())
emissionMapProp.textureScaleAndOffset = albedoMapProp.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake
}
if (EditorGUI.EndChangeCheck())
{
foreach (var obj in blendModeProp.targets)
MaterialChanged((Material)obj);
}
DoMaterialRenderingOptions();
}
public override void MaterialChanged(Material material)
{
if (material == null)
throw new ArgumentNullException("material");
material.shaderKeywords = null;
SetupMaterialBlendMode(material);
SetMaterialKeywords(material);
}
private void SetMaterialKeywords(Material material)
{
material.shaderKeywords = null;
SetupMaterialBlendMode(material);
UpdateMaterialSpecularSource(material);
CoreUtils.SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
// A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect
// or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color.
// The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color.
MaterialEditor.FixupEmissiveFlag(material);
bool shouldEmissionBeEnabled = (material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.EmissiveIsBlack) == 0;
CoreUtils.SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled);
CoreUtils.SetKeyword(material, "_RECEIVE_SHADOWS_OFF", material.GetFloat("_ReceiveShadows") == 0.0f);
}
private void UpdateMaterialSpecularSource(Material material)
{
SpecularSource specSource = (SpecularSource)material.GetFloat("_SpecSource");
if (specSource == SpecularSource.NoSpecular)
{
CoreUtils.SetKeyword(material, "_SPECGLOSSMAP", false);
CoreUtils.SetKeyword(material, "_SPECULAR_COLOR", false);
CoreUtils.SetKeyword(material, "_GLOSSINESS_FROM_BASE_ALPHA", false);
}
else
{
GlossinessSource glossSource = (GlossinessSource)material.GetFloat("_GlossinessSource");
bool hasGlossMap = material.GetTexture("_SpecGlossMap");
CoreUtils.SetKeyword(material, "_SPECGLOSSMAP", hasGlossMap);
CoreUtils.SetKeyword(material, "_SPECULAR_COLOR", !hasGlossMap);
CoreUtils.SetKeyword(material, "_GLOSSINESS_FROM_BASE_ALPHA", glossSource == GlossinessSource.BaseAlpha);
}
}
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
{
if (material == null)
throw new ArgumentNullException("material");
if (oldShader == null)
throw new ArgumentNullException("oldShader");
base.AssignNewShaderToMaterial(material, oldShader, newShader);
// Shininess value cannot be zero since it will produce undefined values for cases where pow(0, 0).
float shininess = material.GetFloat("_Shininess");
material.SetFloat("_Shininess", Mathf.Clamp(shininess, kMinShininessValue, 1.0f));
string oldShaderName = oldShader.name;
string[] shaderStrings = oldShaderName.Split('/');
if (shaderStrings[0].Equals("Legacy Shaders") || shaderStrings[0].Equals("Mobile"))
{
ConvertFromLegacy(material, oldShaderName);
}
StandardSimpleLightingUpgrader.UpdateMaterialKeywords(material);
}
private bool RequiresAlpha()
{
SurfaceType surfaceType = (SurfaceType)surfaceTypeProp.floatValue;
return alphaClipProp.floatValue > 0.0f || surfaceType == SurfaceType.Transparent;
}
private void DoSurfaceArea()
{
EditorGUILayout.Space();
int surfaceTypeValue = (int)surfaceTypeProp.floatValue;
if ((SurfaceType)surfaceTypeValue == SurfaceType.Opaque)
{
int glossSource = (int)glossinessSourceProp.floatValue;
materialEditor.TexturePropertySingleLine(Styles.albedoGlosinessLabels[glossSource], albedoMapProp,
albedoColorProp);
}
else
{
materialEditor.TexturePropertySingleLine(Styles.albedoAlphaLabel, albedoMapProp, albedoColorProp);
}
}
private void DoSpecular()
{
EditorGUILayout.Space();
SpecularSource specularSource = (SpecularSource)specularSourceProp.floatValue;
EditorGUI.BeginChangeCheck();
bool enabled = EditorGUILayout.Toggle(Styles.specularSourceLabel, specularSource == SpecularSource.SpecularTextureAndColor);
if (EditorGUI.EndChangeCheck())
specularSourceProp.floatValue = enabled ? (float)SpecularSource.SpecularTextureAndColor : (float)SpecularSource.NoSpecular;
SpecularSource specSource = (SpecularSource)specularSourceProp.floatValue;
if (specSource != SpecularSource.NoSpecular)
{
bool hasSpecularMap = specularGlossMapProp.textureValue != null;
materialEditor.TexturePropertySingleLine(Styles.specularGlossMapLabels[(int)glossinessSourceProp.floatValue], specularGlossMapProp, hasSpecularMap ? null : specularColorProp);
EditorGUI.indentLevel += 2;
if (RequiresAlpha())
{
GUI.enabled = false;
glossinessSourceProp.floatValue = (float)EditorGUILayout.Popup(Styles.glossinessSourceLabel, (int)GlossinessSource.SpecularAlpha, Styles.glossinessSourceNames);
GUI.enabled = true;
}
else
{
int glossinessSource = (int)glossinessSourceProp.floatValue;
EditorGUI.BeginChangeCheck();
glossinessSource = EditorGUILayout.Popup(Styles.glossinessSourceLabel, glossinessSource, Styles.glossinessSourceNames);
if (EditorGUI.EndChangeCheck())
glossinessSourceProp.floatValue = glossinessSource;
GUI.enabled = true;
}
EditorGUI.BeginChangeCheck();
float shininess = EditorGUILayout.Slider(Styles.shininessLabel, shininessProp.floatValue,
kMinShininessValue, 1.0f);
if (EditorGUI.EndChangeCheck())
shininessProp.floatValue = shininess;
EditorGUI.indentLevel -= 2;
}
}
void DoEmissionArea(Material material)
{
// Emission for GI?
if (materialEditor.EmissionEnabledProperty())
{
bool hadEmissionTexture = emissionMapProp.textureValue != null;
// Texture and HDR color controls
materialEditor.TexturePropertyWithHDRColor(Styles.emissionMapLabel, emissionMapProp, emissionColorProp, false);
// If texture was assigned and color was black set color to white
float brightness = emissionColorProp.colorValue.maxColorComponent;
if (emissionMapProp.textureValue != null && !hadEmissionTexture && brightness <= 0f)
emissionColorProp.colorValue = Color.white;
// LW does not support RealtimeEmissive. We set it to bake emissive and handle the emissive is black right.
material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive;
if (brightness <= 0f)
material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack;
}
}
private void ConvertFromLegacy(Material material, string oldShaderName)
{
UpgradeParams shaderUpgradeParams = new UpgradeParams();
if (oldShaderName.Contains("Transp"))
{
shaderUpgradeParams.surfaceType = UpgradeSurfaceType.Transparent;
shaderUpgradeParams.blendMode = UpgradeBlendMode.Alpha;
shaderUpgradeParams.alphaClip = false;
shaderUpgradeParams.glosinessSource = GlossinessSource.SpecularAlpha;
}
else if (oldShaderName.Contains("Cutout"))
{
shaderUpgradeParams.surfaceType = UpgradeSurfaceType.Opaque;
shaderUpgradeParams.blendMode = UpgradeBlendMode.Alpha;
shaderUpgradeParams.alphaClip = true;
shaderUpgradeParams.glosinessSource = GlossinessSource.SpecularAlpha;
}
else
{
shaderUpgradeParams.surfaceType = UpgradeSurfaceType.Opaque;
shaderUpgradeParams.blendMode = UpgradeBlendMode.Alpha;
shaderUpgradeParams.alphaClip = false;
shaderUpgradeParams.glosinessSource = GlossinessSource.BaseAlpha;
}
if (oldShaderName.Contains("Spec"))
shaderUpgradeParams.specularSource = SpecularSource.SpecularTextureAndColor;
else
shaderUpgradeParams.specularSource = SpecularSource.NoSpecular;
material.SetFloat("_Surface", (float)shaderUpgradeParams.surfaceType);
material.SetFloat("_Blend", (float)shaderUpgradeParams.blendMode);
material.SetFloat("_SpecSource", (float)shaderUpgradeParams.specularSource);
material.SetFloat("_GlossinessSource", (float)shaderUpgradeParams.glosinessSource);
if (oldShaderName.Contains("Self-Illumin"))
{
material.SetTexture("_EmissionMap", material.GetTexture("_MainTex"));
material.SetTexture("_MainTex", null);
material.SetColor("_EmissionColor", Color.white);
}
}
}
}
| 47.561056 | 193 | 0.635348 | [
"BSD-2-Clause"
] | 1-10/VisualEffectGraphSample | GitHub/com.unity.render-pipelines.lightweight/Editor/ShaderGUI/SimpleLitShaderGUI.cs | 14,411 | C# |
// ----------------------------------------------------------------------------
// <copyright file="PhotonView.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
//
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using System;
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
using ExitGames.Client.Photon;
#if UNITY_EDITOR
using UnityEditor;
#endif
public enum ViewSynchronization { Off, ReliableDeltaCompressed, Unreliable, UnreliableOnChange }
public enum OnSerializeTransform { OnlyPosition, OnlyRotation, OnlyScale, PositionAndRotation, All }
public enum OnSerializeRigidBody { OnlyVelocity, OnlyAngularVelocity, All }
/// <summary>
/// Options to define how Ownership Transfer is handled per PhotonView.
/// </summary>
/// <remarks>
/// This setting affects how RequestOwnership and TransferOwnership work at runtime.
/// </remarks>
public enum OwnershipOption
{
/// <summary>
/// Ownership is fixed. Instantiated objects stick with their creator, scene objects always belong to the Master Client.
/// </summary>
Fixed,
/// <summary>
/// Ownership can be taken away from the current owner who can't object.
/// </summary>
Takeover,
/// <summary>
/// Ownership can be requested with PhotonView.RequestOwnership but the current owner has to agree to give up ownership.
/// </summary>
/// <remarks>The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.</remarks>
Request
}
/// <summary>
/// PUN's NetworkView replacement class for networking. Use it like a NetworkView.
/// </summary>
/// \ingroup publicApi
[AddComponentMenu("Photon Networking/Photon View &v")]
public class PhotonView : Photon.MonoBehaviour
{
#if UNITY_EDITOR
[ContextMenu("Open PUN Wizard")]
void OpenPunWizard()
{
EditorApplication.ExecuteMenuItem("Window/Photon Unity Networking");
}
#endif
public int ownerId;
public byte group = 0;
protected internal bool mixedModeIsReliable = false;
/// <summary>
/// Flag to check if ownership of this photonView was set during the lifecycle. Used for checking when joining late if event with mismatched owner and sender needs addressing.
/// </summary>
/// <value><c>true</c> if owner ship was transfered; otherwise, <c>false</c>.</value>
public bool OwnerShipWasTransfered;
// NOTE: this is now an integer because unity won't serialize short (needed for instantiation). we SEND only a short though!
// NOTE: prefabs have a prefixBackup of -1. this is replaced with any currentLevelPrefix that's used at runtime. instantiated GOs get their prefix set pre-instantiation (so those are not -1 anymore)
public int prefix
{
get
{
if (this.prefixBackup == -1 && PhotonNetwork.networkingPeer != null)
{
this.prefixBackup = PhotonNetwork.networkingPeer.currentLevelPrefix;
}
return this.prefixBackup;
}
set { this.prefixBackup = value; }
}
// this field is serialized by unity. that means it is copied when instantiating a persistent obj into the scene
public int prefixBackup = -1;
/// <summary>
/// This is the instantiationData that was passed when calling PhotonNetwork.Instantiate* (if that was used to spawn this prefab)
/// </summary>
public object[] instantiationData
{
get
{
if (!this.didAwake)
{
// even though viewID and instantiationID are setup before the GO goes live, this data can't be set. as workaround: fetch it if needed
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
return this.instantiationDataField;
}
set { this.instantiationDataField = value; }
}
internal object[] instantiationDataField;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataSent = null;
/// <summary>
/// For internal use only, don't use
/// </summary>
protected internal object[] lastOnSerializeDataReceived = null;
public ViewSynchronization synchronization;
public OnSerializeTransform onSerializeTransformOption = OnSerializeTransform.PositionAndRotation;
public OnSerializeRigidBody onSerializeRigidBodyOption = OnSerializeRigidBody.All;
/// <summary>Defines if ownership of this PhotonView is fixed, can be requested or simply taken.</summary>
/// <remarks>
/// Note that you can't edit this value at runtime.
/// The options are described in enum OwnershipOption.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public OwnershipOption ownershipTransfer = OwnershipOption.Fixed;
public List<Component> ObservedComponents;
Dictionary<Component, MethodInfo> m_OnSerializeMethodInfos = new Dictionary<Component, MethodInfo>(3);
#if UNITY_EDITOR
// Suppressing compiler warning "this variable is never used". Only used in the CustomEditor, only in Editor
#pragma warning disable 0414
[SerializeField]
bool ObservedComponentsFoldoutOpen = true;
#pragma warning restore 0414
#endif
[SerializeField]
private int viewIdField = 0;
/// <summary>
/// The ID of the PhotonView. Identifies it in a networked game (per room).
/// </summary>
/// <remarks>See: [Network Instantiation](@ref instantiateManual)</remarks>
public int viewID
{
get { return this.viewIdField; }
set
{
// if ID was 0 for an awakened PhotonView, the view should add itself into the networkingPeer.photonViewList after setup
bool viewMustRegister = this.didAwake && this.viewIdField == 0;
// TODO: decide if a viewID can be changed once it wasn't 0. most likely that is not a good idea
// check if this view is in networkingPeer.photonViewList and UPDATE said list (so we don't keep the old viewID with a reference to this object)
// PhotonNetwork.networkingPeer.RemovePhotonView(this, true);
this.ownerId = value / PhotonNetwork.MAX_VIEW_IDS;
this.viewIdField = value;
if (viewMustRegister)
{
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
}
//Debug.Log("Set viewID: " + value + " -> owner: " + this.ownerId + " subId: " + this.subId);
}
}
public int instantiationId; // if the view was instantiated with a GO, this GO has a instantiationID (first view's viewID)
/// <summary>True if the PhotonView was loaded with the scene (game object) or instantiated with InstantiateSceneObject.</summary>
/// <remarks>
/// Scene objects are not owned by a particular player but belong to the scene. Thus they don't get destroyed when their
/// creator leaves the game and the current Master Client can control them (whoever that is).
/// The ownerId is 0 (player IDs are 1 and up).
/// </remarks>
public bool isSceneView
{
get { return this.CreatorActorNr == 0; }
}
/// <summary>
/// The owner of a PhotonView is the player who created the GameObject with that view. Objects in the scene don't have an owner.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
///
/// Ownership can be transferred to another player with PhotonView.TransferOwnership or any player can request
/// ownership by calling the PhotonView's RequestOwnership method.
/// The current owner has to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
/// </remarks>
public PhotonPlayer owner
{
get
{
return PhotonPlayer.Find(this.ownerId);
}
}
public int OwnerActorNr
{
get { return this.ownerId; }
}
public bool isOwnerActive
{
get { return this.ownerId != 0 && PhotonNetwork.networkingPeer.mActors.ContainsKey(this.ownerId); }
}
public int CreatorActorNr
{
get { return this.viewIdField / PhotonNetwork.MAX_VIEW_IDS; }
}
/// <summary>
/// True if the PhotonView is "mine" and can be controlled by this client.
/// </summary>
/// <remarks>
/// PUN has an ownership concept that defines who can control and destroy each PhotonView.
/// True in case the owner matches the local PhotonPlayer.
/// True if this is a scene photonview on the Master client.
/// </remarks>
public bool isMine
{
get
{
return (this.ownerId == PhotonNetwork.player.ID) || (!this.isOwnerActive && PhotonNetwork.isMasterClient);
}
}
/// <summary>
/// The current master ID so that we can compare when we receive OnMasterClientSwitched() callback
/// It's public so that we can check it during ownerId assignments in networkPeer script
/// TODO: Maybe we can have the networkPeer always aware of the previous MasterClient?
/// </summary>
public int currentMasterID = -1;
protected internal bool didAwake;
[SerializeField]
protected internal bool isRuntimeInstantiated;
protected internal bool removedFromLocalViewList;
internal MonoBehaviour[] RpcMonoBehaviours;
private MethodInfo OnSerializeMethodInfo;
private bool failedToFindOnSerialize;
/// <summary>Called by Unity on start of the application and does a setup the PhotonView.</summary>
protected internal void Awake()
{
if (this.viewID != 0)
{
// registration might be too late when some script (on this GO) searches this view BUT GetPhotonView() can search ALL in that case
PhotonNetwork.networkingPeer.RegisterPhotonView(this);
this.instantiationDataField = PhotonNetwork.networkingPeer.FetchInstantiationData(this.instantiationId);
}
this.didAwake = true;
}
/// <summary>
/// Depending on the PhotonView's ownershipTransfer setting, any client can request to become owner of the PhotonView.
/// </summary>
/// <remarks>
/// Requesting ownership can give you control over a PhotonView, if the ownershipTransfer setting allows that.
/// The current owner might have to implement IPunCallbacks.OnOwnershipRequest to react to the ownership request.
///
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void RequestOwnership()
{
PhotonNetwork.networkingPeer.RequestOwnership(this.viewID, this.ownerId);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(PhotonPlayer newOwner)
{
this.TransferOwnership(newOwner.ID);
}
/// <summary>
/// Transfers the ownership of this PhotonView (and GameObject) to another player.
/// </summary>
/// <remarks>
/// The owner/controller of a PhotonView is also the client which sends position updates of the GameObject.
/// </remarks>
public void TransferOwnership(int newOwnerId)
{
PhotonNetwork.networkingPeer.TransferOwnership(this.viewID, newOwnerId);
this.ownerId = newOwnerId; // immediately switch ownership locally, to avoid more updates sent from this client.
}
/// <summary>
///Check ownerId assignment for sceneObjects to keep being owned by the MasterClient.
/// </summary>
/// <param name="newMasterClient">New master client.</param>
public void OnMasterClientSwitched(PhotonPlayer newMasterClient)
{
if (this.CreatorActorNr == 0 && !this.OwnerShipWasTransfered && (this.currentMasterID== -1 || this.ownerId==this.currentMasterID))
{
this.ownerId = newMasterClient.ID;
}
this.currentMasterID = newMasterClient.ID;
}
protected internal void OnDestroy()
{
if (!this.removedFromLocalViewList)
{
bool wasInList = PhotonNetwork.networkingPeer.LocalCleanPhotonView(this);
bool loading = false;
#if (!UNITY_5 || UNITY_5_0 || UNITY_5_1) && !UNITY_5_3_OR_NEWER
loading = Application.isLoadingLevel;
#endif
if (wasInList && !loading && this.instantiationId > 0 && !PhotonHandler.AppQuits && PhotonNetwork.logLevel >= PhotonLogLevel.Informational)
{
Debug.Log("PUN-instantiated '" + this.gameObject.name + "' got destroyed by engine. This is OK when loading levels. Otherwise use: PhotonNetwork.Destroy().");
}
}
}
public void SerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
SerializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
public void DeserializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (this.ObservedComponents != null && this.ObservedComponents.Count > 0)
{
for (int i = 0; i < this.ObservedComponents.Count; ++i)
{
DeserializeComponent(this.ObservedComponents[i], stream, info);
}
}
}
protected internal void DeserializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
// Use incoming data according to observed type
if (component is MonoBehaviour)
{
ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyPosition:
trans.localPosition = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyRotation:
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
case OnSerializeTransform.OnlyScale:
trans.localScale = (Vector3) stream.ReceiveNext();
break;
case OnSerializeTransform.PositionAndRotation:
trans.localPosition = (Vector3) stream.ReceiveNext();
trans.localRotation = (Quaternion) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector3) stream.ReceiveNext();
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (Vector3) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector3) stream.ReceiveNext();
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
rigidB.velocity = (Vector2) stream.ReceiveNext();
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
rigidB.angularVelocity = (float) stream.ReceiveNext();
break;
case OnSerializeRigidBody.OnlyVelocity:
rigidB.velocity = (Vector2) stream.ReceiveNext();
break;
}
}
else
{
Debug.LogError("Type of observed is unknown when receiving.");
}
}
protected internal void SerializeComponent(Component component, PhotonStream stream, PhotonMessageInfo info)
{
if (component == null)
{
return;
}
if (component is MonoBehaviour)
{
ExecuteComponentOnSerialize(component, stream, info);
}
else if (component is Transform)
{
Transform trans = (Transform) component;
switch (this.onSerializeTransformOption)
{
case OnSerializeTransform.All:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.OnlyPosition:
stream.SendNext(trans.localPosition);
break;
case OnSerializeTransform.OnlyRotation:
stream.SendNext(trans.localRotation);
break;
case OnSerializeTransform.OnlyScale:
stream.SendNext(trans.localScale);
break;
case OnSerializeTransform.PositionAndRotation:
stream.SendNext(trans.localPosition);
stream.SendNext(trans.localRotation);
break;
}
}
else if (component is Rigidbody)
{
Rigidbody rigidB = (Rigidbody) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else if (component is Rigidbody2D)
{
Rigidbody2D rigidB = (Rigidbody2D) component;
switch (this.onSerializeRigidBodyOption)
{
case OnSerializeRigidBody.All:
stream.SendNext(rigidB.velocity);
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyAngularVelocity:
stream.SendNext(rigidB.angularVelocity);
break;
case OnSerializeRigidBody.OnlyVelocity:
stream.SendNext(rigidB.velocity);
break;
}
}
else
{
Debug.LogError("Observed type is not serializable: " + component.GetType());
}
}
protected internal void ExecuteComponentOnSerialize(Component component, PhotonStream stream, PhotonMessageInfo info)
{
IPunObservable observable = component as IPunObservable;
if (observable != null)
{
observable.OnPhotonSerializeView(stream, info);
}
else if (component != null)
{
MethodInfo method = null;
bool found = this.m_OnSerializeMethodInfos.TryGetValue(component, out method);
if (!found)
{
bool foundMethod = NetworkingPeer.GetMethod(component as MonoBehaviour, PhotonNetworkingMessage.OnPhotonSerializeView.ToString(), out method);
if (foundMethod == false)
{
Debug.Log(component);
Debug.Log(PhotonNetworkingMessage.OnPhotonSerializeView.ToString());
Debug.LogError("The observed monobehaviour (" + component.name + ") of this PhotonView does not implement OnPhotonSerializeView()!");
method = null;
}
this.m_OnSerializeMethodInfos.Add(component, method);
}
if (method != null)
{
method.Invoke(component, new object[] {stream, info});
}
}
}
/// <summary>
/// Can be used to refesh the list of MonoBehaviours on this GameObject while PhotonNetwork.UseRpcMonoBehaviourCache is true.
/// </summary>
/// <remarks>
/// Set PhotonNetwork.UseRpcMonoBehaviourCache to true to enable the caching.
/// Uses this.GetComponents<MonoBehaviour>() to get a list of MonoBehaviours to call RPCs on (potentially).
///
/// While PhotonNetwork.UseRpcMonoBehaviourCache is false, this method has no effect,
/// because the list is refreshed when a RPC gets called.
/// </remarks>
public void RefreshRpcMonoBehaviourCache()
{
this.RpcMonoBehaviours = this.GetComponents<MonoBehaviour>();
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="target">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonTargets target, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// RPC calls can target "All" or the "Others".
/// Usually, the target "All" gets executed locally immediately after sending the RPC.
/// The "*ViaServer" options send the RPC to the server and execute it on this client when it's sent back.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="target">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonTargets target, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, target, encrypt, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
/// <param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
/// <param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
/// <param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RPC(string methodName, PhotonPlayer targetPlayer, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, false, parameters);
}
/// <summary>
/// Call a RPC method of this GameObject on remote clients of this room (or on all, inclunding this client).
/// </summary>
/// <remarks>
/// [Remote Procedure Calls](@ref rpcManual) are an essential tool in making multiplayer games with PUN.
/// It enables you to make every client in a room call a specific method.
///
/// This method allows you to make an RPC calls on a specific player's client.
/// Of course, calls are affected by this client's lag and that of remote clients.
///
/// Each call automatically is routed to the same PhotonView (and GameObject) that was used on the
/// originating client.
///
/// See: [Remote Procedure Calls](@ref rpcManual).
/// </remarks>
///<param name="methodName">The name of a fitting method that was has the RPC attribute.</param>
///<param name="targetPlayer">The group of targets and the way the RPC gets sent.</param>
///<param name="encrypt"> </param>
///<param name="parameters">The parameters that the RPC method has (must fit this call!).</param>
public void RpcSecure(string methodName, PhotonPlayer targetPlayer, bool encrypt, params object[] parameters)
{
PhotonNetwork.RPC(this, methodName, targetPlayer, encrypt, parameters);
}
public static PhotonView Get(Component component)
{
return component.GetComponent<PhotonView>();
}
public static PhotonView Get(GameObject gameObj)
{
return gameObj.GetComponent<PhotonView>();
}
public static PhotonView Find(int viewID)
{
return PhotonNetwork.networkingPeer.GetPhotonView(viewID);
}
public override string ToString()
{
return string.Format("View ({3}){0} on {1} {2}", this.viewID, (this.gameObject != null) ? this.gameObject.name : "GO==null", (this.isSceneView) ? "(scene)" : string.Empty, this.prefix);
}
}
| 40.106475 | 202 | 0.634713 | [
"MIT"
] | VelandelStudio/Velandel-Piracy-Hill | Assets/Photon Unity Networking/Plugins/PhotonNetwork/PhotonView.cs | 27,874 | C# |
// 日本語。
using System;
using WWUtil;
namespace WWMath {
/// <summary>
/// Stable Goertzel algorithm
/// Richard G. Lyons, Understanding Digital Signal Processing, 3 rd Ed., Pearson, 2011, pp. 840
/// </summary>
public class WWGoertzel {
int mN;
DelayT<WWComplex> mDelay;
WWQuadratureOscillatorInt mOsc;
/// <summary>
/// 時間ドメイン値xを入力すると、N点DFTの周波数ドメイン値Xのm番目の周波数binの値を戻す。
/// </summary>
/// <param name="m">周波数binの番号。0≦m<N</param>
/// <param name="N">DFTサイズN。</param>
public WWGoertzel(int m, int N) {
if (N <= 0) {
throw new ArgumentOutOfRangeException("N");
}
mN = N;
mDelay = new DelayT<WWComplex>(1);
mDelay.Fill(WWComplex.Zero());
mOsc = new WWQuadratureOscillatorInt(-m, N);
}
/// <summary>
/// 時間ドメイン値xを1サンプル入力、N点DFTの周波数ドメイン値Xのm番目の周波数成分値を出力。
/// </summary>
/// <param name="x">時間ドメイン値x</param>
/// <returns>X^m(q)</returns>
public WWComplex Filter(double x) {
var c = mOsc.Next();
var m = WWComplex.Mul(c, x);
var prev = mDelay.GetNthDelayedSampleValue(0);
var r = WWComplex.Add(m, prev);
mDelay.Filter(r);
return r;
}
}
}
| 26.096154 | 99 | 0.527634 | [
"MIT"
] | yamamoto2002/bitspersampleconv2 | WWMath/WWGoertzel.cs | 1,559 | 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.
// </auto-generated>
namespace Microsoft.Azure.Management.CosmosDB.Fluent
{
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>
/// CollectionOperations operations.
/// </summary>
internal partial class CollectionOperations : IServiceOperations<CosmosDBManagementClient>, ICollectionOperations
{
/// <summary>
/// Initializes a new instance of the CollectionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal CollectionOperations(CosmosDBManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CosmosDBManagementClient
/// </summary>
public CosmosDBManagementClient Client { get; private set; }
/// <summary>
/// Retrieves the metrics determined by the given filter for the given database
/// account and collection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of an Azure resource group.
/// </param>
/// <param name='accountName'>
/// Cosmos DB database account name.
/// </param>
/// <param name='databaseRid'>
/// Cosmos DB database rid.
/// </param>
/// <param name='collectionRid'>
/// Cosmos DB collection rid.
/// </param>
/// <param name='filter'>
/// An OData filter expression that describes a subset of metrics to return.
/// The parameters that can be filtered are name.value (name of the metric, can
/// have an or of multiple names), startTime, endTime, and timeGrain. The
/// supported operator is eq.
/// </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<IEnumerable<Metric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string accountName, string databaseRid, string collectionRid, string filter, 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 (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 50);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[a-z0-9]+(-[a-z0-9]+)*"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[a-z0-9]+(-[a-z0-9]+)*");
}
}
if (databaseRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseRid");
}
if (collectionRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "collectionRid");
}
if (filter == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "filter");
}
string apiVersion = "2019-12-12";
// 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("accountName", accountName);
tracingParameters.Add("databaseRid", databaseRid);
tracingParameters.Add("collectionRid", collectionRid);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("filter", filter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetrics", 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.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/metrics").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{databaseRid}", System.Uri.EscapeDataString(databaseRid));
_url = _url.Replace("{collectionRid}", System.Uri.EscapeDataString(collectionRid));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
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("GET");
_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;
// 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);
}
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<IEnumerable<Metric>>();
_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<Page<Metric>>(_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;
}
/// <summary>
/// Retrieves the usages (most recent storage data) for the given collection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of an Azure resource group.
/// </param>
/// <param name='accountName'>
/// Cosmos DB database account name.
/// </param>
/// <param name='databaseRid'>
/// Cosmos DB database rid.
/// </param>
/// <param name='collectionRid'>
/// Cosmos DB collection rid.
/// </param>
/// <param name='filter'>
/// An OData filter expression that describes a subset of usages to return. The
/// supported parameter is name.value (name of the metric, can have an or of
/// multiple names).
/// </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<IEnumerable<Usage>>> ListUsagesWithHttpMessagesAsync(string resourceGroupName, string accountName, string databaseRid, string collectionRid, string filter = default(string), 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 (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 50);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[a-z0-9]+(-[a-z0-9]+)*"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[a-z0-9]+(-[a-z0-9]+)*");
}
}
if (databaseRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseRid");
}
if (collectionRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "collectionRid");
}
string apiVersion = "2019-12-12";
// 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("accountName", accountName);
tracingParameters.Add("databaseRid", databaseRid);
tracingParameters.Add("collectionRid", collectionRid);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("filter", filter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListUsages", 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.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/usages").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{databaseRid}", System.Uri.EscapeDataString(databaseRid));
_url = _url.Replace("{collectionRid}", System.Uri.EscapeDataString(collectionRid));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
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("GET");
_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;
// 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);
}
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<IEnumerable<Usage>>();
_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<Page<Usage>>(_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;
}
/// <summary>
/// Retrieves metric definitions for the given collection.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of an Azure resource group.
/// </param>
/// <param name='accountName'>
/// Cosmos DB database account name.
/// </param>
/// <param name='databaseRid'>
/// Cosmos DB database rid.
/// </param>
/// <param name='collectionRid'>
/// Cosmos DB collection rid.
/// </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<IEnumerable<MetricDefinition>>> ListMetricDefinitionsWithHttpMessagesAsync(string resourceGroupName, string accountName, string databaseRid, string collectionRid, 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 (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 50);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[a-z0-9]+(-[a-z0-9]+)*"))
{
throw new ValidationException(ValidationRules.Pattern, "accountName", "^[a-z0-9]+(-[a-z0-9]+)*");
}
}
if (databaseRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseRid");
}
if (collectionRid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "collectionRid");
}
string apiVersion = "2019-12-12";
// 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("accountName", accountName);
tracingParameters.Add("databaseRid", databaseRid);
tracingParameters.Add("collectionRid", collectionRid);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetricDefinitions", 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.DocumentDB/databaseAccounts/{accountName}/databases/{databaseRid}/collections/{collectionRid}/metricDefinitions").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{databaseRid}", System.Uri.EscapeDataString(databaseRid));
_url = _url.Replace("{collectionRid}", System.Uri.EscapeDataString(collectionRid));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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("GET");
_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;
// 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);
}
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<IEnumerable<MetricDefinition>>();
_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<Page<MetricDefinition>>(_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;
}
}
}
| 46.4 | 343 | 0.556891 | [
"MIT"
] | Azure/azure-libraries-for-net | src/ResourceManagement/CosmosDB/Generated/CollectionOperations.cs | 37,352 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Shared.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Shared.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Please verify email first.
/// </summary>
public static string EmailNotVerified {
get {
return ResourceManager.GetString("EmailNotVerified", resourceCulture);
}
}
}
}
| 42.205479 | 172 | 0.603376 | [
"MIT"
] | kishanchdry/Core5.0Dapper | Shared/Properties/Resources.Designer.cs | 3,083 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.