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 NinetyNineProblems.Arithmetic
{
public class P31
{
public static bool IsPrime(int n)
{
if (n <= 1)
{
return false;
}
else if (n <= 3)
{
return true;
}
else if (n % 2 == 0 || n % 3 == 0)
{
return false;
}
for (int i = 5; i * i <= n; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0)
{
return false;
}
}
return true;
}
}
} | 20.387097 | 50 | 0.280063 | [
"MIT"
] | Frederick-S/NinetyNineProblems | NinetyNineProblems/Arithmetic/P31.cs | 632 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace BarCodeScanner.Helps
{
public class BoolToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
} | 27.95 | 103 | 0.68873 | [
"Apache-2.0"
] | eldiablo-1226/BarCode-Scanner-Controller | src/BarCodeScanner/Helps/BoolToVisibilityConverter.cs | 561 | C# |
#if !NETSTANDARD13
/*
* 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 clouddirectory-2017-01-11.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.CloudDirectory.Model
{
/// <summary>
/// Base class for ListObjectParentPaths paginators.
/// </summary>
internal sealed partial class ListObjectParentPathsPaginator : IPaginator<ListObjectParentPathsResponse>, IListObjectParentPathsPaginator
{
private readonly IAmazonCloudDirectory _client;
private readonly ListObjectParentPathsRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<ListObjectParentPathsResponse> Responses => new PaginatedResponse<ListObjectParentPathsResponse>(this);
internal ListObjectParentPathsPaginator(IAmazonCloudDirectory client, ListObjectParentPathsRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<ListObjectParentPathsResponse> IPaginator<ListObjectParentPathsResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
var nextToken = _request.NextToken;
ListObjectParentPathsResponse response;
do
{
_request.NextToken = nextToken;
response = _client.ListObjectParentPaths(_request);
nextToken = response.NextToken;
yield return response;
}
while (nextToken != null);
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<ListObjectParentPathsResponse> IPaginator<ListObjectParentPathsResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
var nextToken = _request.NextToken;
ListObjectParentPathsResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.ListObjectParentPathsAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (nextToken != null);
}
#endif
}
}
#endif | 39.318681 | 164 | 0.673002 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/_bcl45+netstandard/ListObjectParentPathsPaginator.cs | 3,578 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rekognition-2016-06-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Rekognition.Model
{
/// <summary>
/// Container for the parameters to the StartPersonTracking operation.
/// Starts the asynchronous tracking of a person's path in a stored video.
///
///
/// <para>
/// Amazon Rekognition Video can track the path of people in a video stored in an Amazon
/// S3 bucket. Use <a>Video</a> to specify the bucket name and the filename of the video.
/// <code>StartPersonTracking</code> returns a job identifier (<code>JobId</code>) which
/// you use to get the results of the operation. When label detection is finished, Amazon
/// Rekognition publishes a completion status to the Amazon Simple Notification Service
/// topic that you specify in <code>NotificationChannel</code>.
/// </para>
///
/// <para>
/// To get the results of the person detection operation, first check that the status
/// value published to the Amazon SNS topic is <code>SUCCEEDED</code>. If so, call <a>GetPersonTracking</a>
/// and pass the job identifier (<code>JobId</code>) from the initial call to <code>StartPersonTracking</code>.
/// </para>
/// </summary>
public partial class StartPersonTrackingRequest : AmazonRekognitionRequest
{
private string _clientRequestToken;
private string _jobTag;
private NotificationChannel _notificationChannel;
private Video _video;
/// <summary>
/// Gets and sets the property ClientRequestToken.
/// <para>
/// Idempotent token used to identify the start request. If you use the same token with
/// multiple <code>StartPersonTracking</code> requests, the same <code>JobId</code> is
/// returned. Use <code>ClientRequestToken</code> to prevent the same job from being accidently
/// started more than once.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=64)]
public string ClientRequestToken
{
get { return this._clientRequestToken; }
set { this._clientRequestToken = value; }
}
// Check to see if ClientRequestToken property is set
internal bool IsSetClientRequestToken()
{
return this._clientRequestToken != null;
}
/// <summary>
/// Gets and sets the property JobTag.
/// <para>
/// An identifier you specify that's returned in the completion notification that's published
/// to your Amazon Simple Notification Service topic. For example, you can use <code>JobTag</code>
/// to group related jobs and identify them in the completion notification.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string JobTag
{
get { return this._jobTag; }
set { this._jobTag = value; }
}
// Check to see if JobTag property is set
internal bool IsSetJobTag()
{
return this._jobTag != null;
}
/// <summary>
/// Gets and sets the property NotificationChannel.
/// <para>
/// The Amazon SNS topic ARN you want Amazon Rekognition Video to publish the completion
/// status of the people detection operation to.
/// </para>
/// </summary>
public NotificationChannel NotificationChannel
{
get { return this._notificationChannel; }
set { this._notificationChannel = value; }
}
// Check to see if NotificationChannel property is set
internal bool IsSetNotificationChannel()
{
return this._notificationChannel != null;
}
/// <summary>
/// Gets and sets the property Video.
/// <para>
/// The video in which you want to detect people. The video must be stored in an Amazon
/// S3 bucket.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public Video Video
{
get { return this._video; }
set { this._video = value; }
}
// Check to see if Video property is set
internal bool IsSetVideo()
{
return this._video != null;
}
}
} | 37.560284 | 116 | 0.609894 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Rekognition/Generated/Model/StartPersonTrackingRequest.cs | 5,296 | C# |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 Aurora-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 System.Collections.Generic;
using System.IO;
using Aurora.DataManager.Migration;
using Aurora.DataManager.Migration.Migrators;
using Aurora.DataManager.MySQL;
using Aurora.DataManager.SQLite;
using NUnit.Framework;
using Aurora.Framework;
namespace Aurora.DataManager.Tests
{
public class MigrationTests
{
private string dbFileName = "TestMigration.db";
public class TestMigrator : Migrator
{
public TestMigrator()
{
Version = new Version(2010, 3, 13);
CanProvideDefaults = true;
schema = new List<Rec<string, ColumnDefinition[]>>();
AddSchema("test_table", ColDefs(
ColDef("id", ColumnTypes.Integer,true),
ColDef("test_string", ColumnTypes.String),
ColDef("test_string1", ColumnTypes.String1),
ColDef("test_string2", ColumnTypes.String2),
ColDef("test_string45", ColumnTypes.String45),
ColDef("test_string50", ColumnTypes.String50),
ColDef("test_string100", ColumnTypes.String100),
ColDef("test_string512", ColumnTypes.String512),
ColDef("test_string1024", ColumnTypes.String1024),
ColDef("test_string8196", ColumnTypes.String8196),
ColDef("test_blob", ColumnTypes.Blob),
ColDef("test_text", ColumnTypes.Text),
ColDef("test_date", ColumnTypes.Date)
));
}
protected override void DoCreateDefaults(DataSessionProvider sessionProvider, IDataConnector genericData)
{
EnsureAllTablesInSchemaExist(genericData);
}
protected override bool DoValidate(DataSessionProvider sessionProvider, IDataConnector genericData)
{
return TestThatAllTablesValidate(genericData);
}
protected override void DoMigrate(DataSessionProvider sessionProvider, IDataConnector genericData)
{
DoCreateDefaults(sessionProvider, genericData);
}
protected override void DoPrepareRestorePoint(DataSessionProvider sessionProvider, IDataConnector genericData)
{
CopyAllTablesToTempVersions(genericData);
}
public override void DoRestore(DataSessionProvider sessionProvider, IDataConnector genericData)
{
RestoreTempTablesToReal(genericData);
}
}
[Test]
public void MigrationTestsTests()
{
//IMPORTANT NOTIFICATION
//Till I figure out a way, please delete the .db file or drop tables clean before running this
//Switch the comments to test one technology or another
var technology = DataManagerTechnology.SQLite;
//var technology = DataManagerTechnology.MySql;
var mysqlconnectionstring = "Data Source=localhost;Database=auroratest;User ID=auroratest;Password=test;";
var sqliteconnectionstring = string.Format("URI=file:{0},version=3", dbFileName);
string connectionString = (technology==DataManagerTechnology.SQLite)?sqliteconnectionstring:mysqlconnectionstring;
CreateEmptyDatabase();
DataSessionProvider sessionProvider = new DataSessionProvider(technology, connectionString);
IDataConnector genericData = ((technology==DataManagerTechnology.SQLite)? (IDataConnector) new SQLiteLoader():new MySQLDataLoader());
genericData.ConnectToDatabase(connectionString);
var migrators = new List<Migrator>();
var testMigrator0 = new TestMigrator();
migrators.Add(testMigrator0);
var migrationManager = new MigrationManager(sessionProvider, genericData, migrators);
Assert.AreEqual(testMigrator0.Version, migrationManager.LatestVersion, "Latest version is correct");
Assert.IsNull(migrationManager.GetDescriptionOfCurrentOperation(),"Description should be null before deciding what to do.");
migrationManager.DetermineOperation();
var operationDescription = migrationManager.GetDescriptionOfCurrentOperation();
Assert.AreEqual(MigrationOperationTypes.CreateDefaultAndUpgradeToTarget, operationDescription.OperationType, "Operation type is correct.");
Assert.AreEqual(testMigrator0.Version, operationDescription.CurrentVersion, "Current version is correct");
//There will be no migration because there is only one migrator which will provide the default
Assert.IsNull(operationDescription.StartVersion, "Start migration version is correct");
Assert.IsNull(operationDescription.EndVersion, "End migration version is correct");
try
{
migrationManager.ExecuteOperation();
Assert.AreEqual(testMigrator0.Version, genericData.GetAuroraVersion(), "Version of settings is updated");
}
catch(MigrationOperationException)
{
Assert.Fail("Something failed during execution we weren't expecting.");
}
bool valid = migrationManager.ValidateVersion(migrationManager.LatestVersion);
Assert.AreEqual(true,valid,"Database is a valid version");
migrationManager.DetermineOperation();
var operationDescription2 = migrationManager.GetDescriptionOfCurrentOperation();
Assert.AreEqual(MigrationOperationTypes.DoNothing, operationDescription2.OperationType, "Operation type is correct.");
Assert.AreEqual(testMigrator0.Version, operationDescription2.CurrentVersion, "Current version is correct");
Assert.IsNull(operationDescription2.StartVersion, "Start migration version is correct");
Assert.IsNull(operationDescription2.EndVersion, "End migration version is correct");
migrationManager.ExecuteOperation();
genericData.CloseDatabase();
}
private void CreateEmptyDatabase()
{
if( File.Exists(dbFileName))
{
File.Delete(dbFileName);
}
}
}
}
| 50.259259 | 152 | 0.657701 | [
"BSD-3-Clause"
] | BillyWarrhol/Aurora-Sim | Aurora/DataManagerTests/MigrationTests.cs | 8,142 | C# |
// THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using System.Data;
namespace Ukadc.Diagnostics.Listeners
{
/// <summary>
/// The interface exposed by all data access adaptors
/// </summary>
public interface IDataAccessAdapter
{
/// <summary>
/// Initializes the <see cref="SqlDataAccessAdapter"/>
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <param name="commandText">The text for the command</param>
/// <param name="commandType">The type of the command</param>
void Initialize(string connectionString, string commandText, CommandType commandType);
/// <summary>
/// Creates a new <see cref="IDataAccessCommand"/>.
/// </summary>
/// <returns>a new <see cref="IDataAccessCommand"/></returns>
IDataAccessCommand CreateCommand();
}
} | 39.703704 | 94 | 0.661381 | [
"MIT"
] | pakoros/Backload | Examples/Example13/Ukadc.Diagnostics/Ukadc.Diagnostics/Listeners/IDataAccessAdapter.cs | 1,072 | C# |
using System.Collections.Generic;
using AutoMapper;
using CollectionsOnline.Core.Config;
using CollectionsOnline.Core.Indexes;
using CollectionsOnline.Core.Models;
using CollectionsOnline.WebSite.Models.Api;
using Nancy;
using Nancy.Metadata.Modules;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Raven.Client;
using Serilog;
namespace CollectionsOnline.WebSite.Modules.Api
{
public class ArticlesApiMetadataModule : MetadataModule<ApiMetadata>
{
public ArticlesApiMetadataModule(IDocumentStore documentStore)
{
Log.Logger.Debug("Creating Article Api Metadata");
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
};
using (var documentSession = documentStore.OpenSession())
{
var sampleArticle = documentSession.Advanced.DocumentQuery<Article, CombinedIndex>()
.WhereEquals("RecordType", "Article")
.FirstOrDefault();
Describe["articles-api-index"] = description =>
{
return new ApiMetadata
{
Name = description.Name,
Method = description.Method,
Path = description.Path,
Description = "Returns a bunch of articles.",
StatusCodes = new Dictionary<HttpStatusCode, string>
{
{HttpStatusCode.OK, "A bunch of articles were able to be retrieved ok."}
},
SampleResponse = JsonConvert.SerializeObject(new[] { Mapper.Map<Article, ArticleApiViewModel>(sampleArticle) }, jsonSerializerSettings),
ExampleUrl = description.Path
};
};
Describe["articles-api-by-id"] = description =>
{
return new ApiMetadata
{
Name = description.Name,
Method = description.Method,
Path = description.Path,
Description = "Returns a single article by Id.",
Parameters = new[]
{
new ApiParameter
{
Parameter = "Id",
Necessity = "required",
Description = "Id of article to be retrieved."
}
},
StatusCodes = new Dictionary<HttpStatusCode, string>
{
{HttpStatusCode.OK, "The article was found and retrieved ok."},
{HttpStatusCode.NotFound, "The article could not be found and probably does not exist."}
},
SampleResponse = JsonConvert.SerializeObject(Mapper.Map<Article, ArticleApiViewModel>(sampleArticle), jsonSerializerSettings),
ExampleUrl = (sampleArticle != null) ? string.Format("{0}/{1}", Constants.ApiPathBase, sampleArticle.Id) : null,
};
};
}
}
}
} | 43.0875 | 160 | 0.51407 | [
"MIT"
] | museumsvictoria/collections-online | src/CollectionsOnline.WebSite/Modules/Api/ArticlesApiMetadataModule.cs | 3,449 | C# |
using System;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
namespace THNETII.WindowsSdk.PlaygroundTest
{
public static class TestHostHelper
{
public static IHostBuilder CreateHostBuilder(string[]? args) =>
Host.CreateDefaultBuilder(args ?? Array.Empty<string>())
.UseEnvironment("Testing")
.ConfigureLogging(logging =>
{
var consoleService = logging.Services.FirstOrDefault(desc =>
desc.ServiceType == typeof(ILoggerProvider) && desc.ImplementationType == typeof(ConsoleLoggerProvider)
);
if (consoleService is ServiceDescriptor)
logging.Services.Remove(consoleService);
})
.ConfigureAppConfiguration(config => config.AddUserSecrets(typeof(TestHostHelper).Assembly, optional: true))
.ConfigureAppConfiguration((context, config) =>
{
var fileProvider = new EmbeddedFileProvider(typeof(TestHostHelper).Assembly);
var hostingEnvironment = context.HostingEnvironment;
var sources = config.Sources;
int originalSourcesCount = sources.Count;
config.AddJsonFile(fileProvider,
$"appsettings.json",
optional: true, reloadOnChange: true);
config.AddJsonFile(fileProvider,
$"appsettings.{hostingEnvironment.EnvironmentName}.json",
optional: true, reloadOnChange: true);
const int insert_idx = 1;
for (int i_dst = insert_idx, i_src = originalSourcesCount;
i_src < sources.Count; i_dst++, i_src++)
{
var configSource = sources[i_src];
sources.RemoveAt(i_src);
sources.Insert(i_dst, configSource);
}
})
.ConfigureServices((context, services) =>
{
services.AddOptions<ConsoleLifetimeOptions>()
.Configure<IConfiguration>((opts, config) =>
config.Bind("Lifetime", opts));
});
}
}
| 43.644068 | 127 | 0.556893 | [
"MIT"
] | thnetii/windows-sdk-nuget | test/THNETII.WindowsSdk.PlaygroundTest/TestHostHelper.cs | 2,575 | C# |
using System.Linq;
using HSL;
using NUnit.Framework;
namespace GraphQLinq.Tests
{
[TestFixture]
[Category("Collection query")]
[Category("Integration tests")]
class CollectionQueryTests
{
readonly HslGraphContext hslGraphContext = new HslGraphContext("https://api.digitransit.fi/routing/v1/routers/finland/index/graphql");
[Test]
public void SelectingNamesReturnsListOfNames()
{
var query = hslGraphContext.Stations().Select(l => l.name);
var names = query.ToList();
Assert.Multiple(() =>
{
CollectionAssert.IsNotEmpty(names);
CollectionAssert.AllItemsAreNotNull(names);
});
}
[Test]
public void SelectingNamesDoesNotReturnStops()
{
var query = hslGraphContext.Stations();
var stations = query.ToList();
Assert.That(stations, Is.All.Matches<Stop>(l => l.stops == null));
}
[Test]
public void SelectingNamesAndIncludingStopsReturnsStops()
{
var query = hslGraphContext.Stations().Include(s => s.stops);
var stations = query.ToList();
Assert.That(stations, Is.All.Matches<Stop>(s => s.stops != null));
}
[Test]
public void SelectingNamesAndStopsReturnsStops()
{
var query = hslGraphContext.Stations().Select(location => new { location.name, location.stops });
var stations = query.ToList();
var stationsWithNullStops = stations.Where(s => s.stops == null).ToList();
CollectionAssert.IsEmpty(stationsWithNullStops);
}
[Test]
public void SelectingNamesWithAliasAndStopsReturnsStopsAndNames()
{
var query = hslGraphContext.Stations().Select(location => new { StationName = location.name, location.stops });
var stations = query.ToList();
var stationsWithNullStops = stations.Where(s => s.stops == null).ToList();
var stationsWithNullCity = stations.Where(s => s.StationName == null).ToList();
Assert.Multiple(() =>
{
CollectionAssert.IsEmpty(stationsWithNullStops);
CollectionAssert.IsEmpty(stationsWithNullCity);
});
}
}
} | 31.092105 | 142 | 0.589082 | [
"Apache-2.0"
] | Giorgi/GraphQLinq | src/GraphQLinq.Tests/CollectionQueryTests.cs | 2,363 | C# |
using ECMABasic.Core.Exceptions;
using ECMABasic.Core.Statements;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ECMABasic.Core
{
/// <summary>
/// A program is an executable list of program lines.
/// </summary>
public class Program : IEnumerable<ProgramLine>, IListable
{
private readonly Dictionary<int, ProgramLine> _lines;
private readonly List<ProgramLine> _sortedLines;
private readonly Dictionary<int, int> _lineNumberToIndex;
public Program()
{
_lines = new Dictionary<int, ProgramLine>();
_sortedLines = new List<ProgramLine>();
_lineNumberToIndex = new Dictionary<int, int>();
}
public ProgramLine this[int lineNumber]
{
get
{
if (_lines.ContainsKey(lineNumber))
{
return _lines[lineNumber];
}
else
{
return null;
}
}
}
public int Length
{
get
{
return _sortedLines.Count;
}
}
public void Execute(IEnvironment env)
{
if (Length == 0)
{
// Nothing to execute.
return;
}
try
{
ValidateEndLine();
// Begin executing with the first line number.
var lineIndex = 0;
if (env.CurrentLineNumber == 0)
{
env.CurrentLineNumber = _sortedLines[lineIndex].LineNumber;
}
else
{
lineIndex = _lineNumberToIndex[env.CurrentLineNumber];
}
while (true)
{
var oldLineNumber = env.CurrentLineNumber;
var line = this[env.CurrentLineNumber];
line.Statement.Execute(env);
if (oldLineNumber == env.CurrentLineNumber)
{
// The statement didn't modify the current line number, so we can simply move to the next one.
lineIndex++;
env.CurrentLineNumber = _sortedLines[lineIndex].LineNumber;
}
else
{
// The statement modified the current line number, so we need to recalculate the line index.
var nextLine = _lines[env.CurrentLineNumber];
lineIndex = _lineNumberToIndex[env.CurrentLineNumber];
}
if (lineIndex >= Length)
{
throw new ProgramEndException();
}
}
}
catch (ProgramEndException)
{
}
catch (RuntimeException ex)
{
env.ReportError(ex.Message);
}
}
public void MoveToNextLine(IEnvironment env)
{
var lineIndex = _lineNumberToIndex[env.CurrentLineNumber];
lineIndex++;
if (lineIndex < Length)
{
env.CurrentLineNumber = _sortedLines[lineIndex].LineNumber;
}
}
public void Insert(ProgramLine line)
{
_lines[line.LineNumber] = line;
_sortedLines.Clear();
_sortedLines.AddRange(_lines.OrderBy(x => x.Value.LineNumber).Select(x => x.Value));
_lineNumberToIndex[line.LineNumber] = _sortedLines.IndexOf(line);
}
public void Delete(int lineNumber)
{
if (_lines.ContainsKey(lineNumber))
{
_sortedLines.Remove(_lines[lineNumber]);
_lines.Remove(lineNumber);
_lineNumberToIndex.Remove(lineNumber);
}
}
public void Clear()
{
_lines.Clear();
_sortedLines.Clear();
}
public string ToListing()
{
return string.Join(string.Empty, _lines.Select(x => x.Value.ToListing()));
}
public IEnumerator<ProgramLine> GetEnumerator()
{
foreach (var line in _sortedLines)
{
yield return line;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private void ValidateEndLine()
{
var ENDs = this.Where(x => x.Statement is EndStatement);
if (!ENDs.Any())
{
throw new NoEndInstructionException();
}
var lastLineNumber = this.Max(x => x.LineNumber);
if (ENDs.First().LineNumber != lastLineNumber)
{
throw new SyntaxException("END IS NOT LAST", ENDs.First().LineNumber);
}
}
}
}
| 21.401163 | 100 | 0.660147 | [
"MIT"
] | p-unity-lineage/ecma_basic | src/ECMABasic.Core/Program.cs | 3,683 | 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.Test.ModuleCore;
namespace XLinqTests
{
public class XNodeReplaceOnDocument3 : XNodeReplace
{
public override void AddChildren()
{
AddChild(new TestVariation(OnXDocument) { Attribute = new VariationAttribute("(BVT)XDocument: Replace with multiple nodes") { Params = new object[] { 2, "<?xml version='1.0'?>\t<?PI?> <E><sub1/></E>\n <!--comx--> " }, Priority = 0 } });
}
}
}
| 36.0625 | 248 | 0.656846 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Private.Xml.Linq/tests/TreeManipulation/XNodeReplaceOnDocument3.cs | 577 | C# |
using System;
using System.Linq;
namespace _1._01.SortEvenNumbers
{
class Program
{
static void Main(string[] args)
{
int[] numbers = Console.ReadLine()
.Split(", ", StringSplitOptions.RemoveEmptyEntries)
.Select((number) =>
{
return int.Parse(number);
})
.Where(n => n % 2 == 0)
.OrderBy(x => x)
.ToArray();
Console.WriteLine(string.Join(", ", numbers));
}
}
}
| 23.208333 | 67 | 0.443447 | [
"MIT"
] | yovko93/CSharp-Repo | CSharp_Advanced/FunctionalProgramming - LabAndExercise/1.01.SortEvenNumbers/Program.cs | 559 | 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("ModalEnforcement.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ModalEnforcement.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 36.448276 | 84 | 0.743614 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter24/ModalEnforcement/ModalEnforcement/ModalEnforcement.UWP/Properties/AssemblyInfo.cs | 1,060 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MultiverseCommunication
{
class Program
{
//тринадесетична бройна система
static void Main(string[] args)
{
var alphabet = new List<string> { "CHU", "TEL", "OFT", "IVA", "EMY", "VNB", "POQ", "ERI", "CAD", "K-A", "IIA", "YLO", "PLA" };//имаме масив от букви в инпровизираната бройна система
//прочитаме входа и го разделяме на тройки символи
var input = Console.ReadLine();
long decimalRepresentation = 0;
for (int i = 0; i < input.Length; i += 3)//на всяка стъпка в цикъла да прескача по 3 символа
{
//променлива digit в тринадесетична бройна система
var digit13 = input.Substring(i, 3);//започва от i и взима по три сивмола
//десетичното число, на която тази цифра отговаря
//ако беше масив трябваше да е Array.IndexOf
var decimalValue = alphabet.IndexOf(digit13);//по даден елемент в съответния списък ми дава индекса, на който той се намира, в случая, ако му подам "TEL" ще ми върне 1; И това е десетичната стойност на числото
decimalRepresentation *= 13;//умножаваме по 13, защото работим с тринадесетична бройна система
decimalRepresentation += decimalValue;//прибавяме десетичната стойност
}
Console.WriteLine(decimalRepresentation);
//тестваме максималния възможен вход: 9 пъти PLAPLAPLAPLAPLAPLAPLAPLAPLA
//сменяме променливата върху, която натрупваме на long
//var input = Console.ReadLine();
//алгоритъм за преобразуване от една бройна система в друга
//var hex = "FAB1";
//var decimalRepresentation = 0;
//for (int i = 0; i < hex.Length; i++)//за всяка цифра от шестнадесетичното число
//{
// //взимам десетичното число и го умножавам по бройната система, с която работя
// decimalRepresentation *= 16;
// if (hex[i] >= '0' && hex[i] <= '9')//ако съответната цифра от шестнадесетичната бройна система е между 0 и 9
// {
// //прибавям към числото десетичното представяне на цифрата от съответната бройна система
// decimalRepresentation += hex[i] - '0';// hex[i] - '0' - ще ни го обърне в цифра за 0 - 0 за 8 - 8
// }
// else
// {
// decimalRepresentation += hex[i] + 10 - 'A';//това ще ни обърне буквите в цифри съответно 10,11,12,13,14,15
// }
//}
//Console.WriteLine(decimalRepresentation);
}
}
}
| 50.125 | 225 | 0.583541 | [
"MIT"
] | HMNikolova/Telerik_Academy | Exam/C#2/CSharpTwo/MultiverseCommunication/Program.cs | 3,708 | C# |
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>", Scope = "member", Target = "~M:SimCards.EventHandlers.BackgroundServices.EventListenerHostedService.StartAsync(System.Threading.CancellationToken)~System.Threading.Tasks.Task")]
[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>", Scope = "member", Target = "~M:SimCards.EventHandlers.BackgroundServices.CompletedOrderPollingHostedService.ExecuteAsync(System.Threading.CancellationToken)~System.Threading.Tasks.Task")]
[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>", Scope = "member", Target = "~M:SimCards.EventHandlers.Program.Main(System.String[])~System.Int32")]
[assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "<Pending>", Scope = "member", Target = "~M:SimCards.EventHandlers.Program.BuildHost(System.String[])~Microsoft.Extensions.Hosting.IHost")]
[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>", Scope = "member", Target = "~M:SimCards.EventHandlers.Handlers.ProvisionRequestedHandler.Handle(SimCards.EventHandlers.Messages.ProvisionRequestedMessage)~System.Threading.Tasks.Task{System.Boolean}")]
| 125.769231 | 314 | 0.790826 | [
"MIT"
] | JonQuxBurton/MobileMicroservicesSample | src/SimCards/SimCards.EventHandlers/GlobalSuppressions.cs | 1,637 | C# |
using System;
using Xunit;
using Shouldly;
using OhDotNetLib.Utils;
namespace OhDotNetLib.Tests
{
public class ObjectNullCheckerTest
{
#region Verify_IsNullOrEmptyOfAnyOneShouldBeWork
[Fact]
public void Verify_IsNullOrEmptyOfAnyOneShouldBeWork()
{
var str = string.Empty;
ObjectNullChecker.IsNullOrEmptyOfAnyOne(str).ShouldBe(true);
// str.ToUppper() should not raise expression , because of str == null . it will stop continue execute
ObjectNullChecker.IsNullOrEmptyOfAnyOne(str, str.ToUpper()).ShouldBe(true);
}
#endregion
}
}
| 24.692308 | 114 | 0.669782 | [
"Apache-2.0"
] | oceanho/OhDotNetLib | test/OhDotNetLib.Tests/Utils/ObjectNullCheckerTest.cs | 642 | C# |
using Xunit;
namespace TelAPI.InboundXML.Test
{
public class PlayTest : TelAPIBaseTest
{
[Fact]
public void Can_I_Generate_Play()
{
var response = new Response();
response.Play("http://www.audio-url.com");
Assert.True(IsValidInboundXML(response.CreateXml()));
}
[Fact]
public void Can_I_Generate_Play_With_Attributes()
{
var response = new Response();
response.Play("http://www.audio-url.com", 10);
Assert.True(IsValidInboundXML(response.CreateXml()));
}
}
}
| 22.892857 | 66 | 0.542902 | [
"MIT"
] | TelAPI/telapi-dotnet | library/TelAPI.InboundXML.Test/PlayTest.cs | 643 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 06:00:28 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using go;
#nullable enable
namespace go {
namespace cmd {
namespace vendor {
namespace golang.org {
namespace x {
namespace sys
{
public static partial class unix_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
public partial struct BpfProgram
{
// Constructors
public BpfProgram(NilType _)
{
this.Len = default;
this.Insns = default;
}
public BpfProgram(uint Len = default, ref ptr<BpfInsn> Insns = default)
{
this.Len = Len;
this.Insns = Insns;
}
// Enable comparisons between nil and BpfProgram struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(BpfProgram value, NilType nil) => value.Equals(default(BpfProgram));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(BpfProgram value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, BpfProgram value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, BpfProgram value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator BpfProgram(NilType nil) => default(BpfProgram);
}
[GeneratedCode("go2cs", "0.1.0.0")]
public static BpfProgram BpfProgram_cast(dynamic value)
{
return new BpfProgram(value.Len, ref value.Insns);
}
}
}}}}}} | 32.529412 | 111 | 0.58906 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/cmd/vendor/golang.org/x/sys/unix/ztypes_darwin_386_BpfProgramStruct.cs | 2,212 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Google.Protobuf;
using Knet.Kudu.Client.Connection;
using Knet.Kudu.Client.Internal;
using Knet.Kudu.Client.Protobuf;
using Knet.Kudu.Client.Tablet;
using Microsoft.Extensions.Logging;
namespace Knet.Kudu.Client.Logging;
internal static class LoggerHelperExtensions
{
public static void MisconfiguredMasterAddresses(
this ILogger logger,
IReadOnlyList<HostAndPort> clientMasters,
IReadOnlyList<HostPortPB> clusterMasters)
{
var clientMastersStr = string.Join(",", clientMasters);
var clusterMastersStr = string.Join(",", clusterMasters
.Select(m => m.ToHostAndPort()));
logger.MisconfiguredMasterAddresses(
clientMasters.Count,
clusterMasters.Count,
clientMastersStr,
clusterMastersStr);
}
public static void UnableToConnectToServer(
this ILogger logger,
Exception exception,
ServerInfo serverInfo)
{
var hostPort = serverInfo.HostPort;
var ip = serverInfo.Endpoint.Address;
var uuid = serverInfo.Uuid;
logger.UnableToConnectToServer(exception, hostPort, ip, uuid);
}
public static void ScannerExpired(
this ILogger logger,
ByteString scannerId,
string tableName,
RemoteTablet? tablet)
{
var scannerIdStr = scannerId.ToStringUtf8();
var tabletId = tablet?.TabletId;
logger.ScannerExpired(scannerIdStr, tableName, tabletId);
}
}
| 28.436364 | 70 | 0.680946 | [
"Apache-2.0"
] | xqrzd/kudu | src/Knet.Kudu.Client/Logging/LoggerHelperExtensions.cs | 1,564 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Batch.Protocol.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Additional parameters for Enable operation.
/// </summary>
public partial class JobEnableOptions
{
/// <summary>
/// Initializes a new instance of the JobEnableOptions class.
/// </summary>
public JobEnableOptions()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the JobEnableOptions class.
/// </summary>
/// <param name="timeout">The maximum time that the server can spend
/// processing the request, in seconds. The default is 30
/// seconds.</param>
/// <param name="clientRequestId">The caller-generated request
/// identity, in the form of a GUID with no decoration such as curly
/// braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.</param>
/// <param name="returnClientRequestId">Whether the server should
/// return the client-request-id in the response.</param>
/// <param name="ocpDate">The time the request was issued. Client
/// libraries typically set this to the current system clock time; set
/// it explicitly if you are calling the REST API directly.</param>
/// <param name="ifMatch">An ETag value associated with the version of
/// the resource known to the client. The operation will be performed
/// only if the resource's current ETag on the service exactly matches
/// the value specified by the client.</param>
/// <param name="ifNoneMatch">An ETag value associated with the version
/// of the resource known to the client. The operation will be
/// performed only if the resource's current ETag on the service does
/// not match the value specified by the client.</param>
/// <param name="ifModifiedSince">A timestamp indicating the last
/// modified time of the resource known to the client. The operation
/// will be performed only if the resource on the service has been
/// modified since the specified time.</param>
/// <param name="ifUnmodifiedSince">A timestamp indicating the last
/// modified time of the resource known to the client. The operation
/// will be performed only if the resource on the service has not been
/// modified since the specified time.</param>
public JobEnableOptions(int? timeout = default(int?), System.Guid? clientRequestId = default(System.Guid?), bool? returnClientRequestId = default(bool?), System.DateTime? ocpDate = default(System.DateTime?), string ifMatch = default(string), string ifNoneMatch = default(string), System.DateTime? ifModifiedSince = default(System.DateTime?), System.DateTime? ifUnmodifiedSince = default(System.DateTime?))
{
Timeout = timeout;
ClientRequestId = clientRequestId;
ReturnClientRequestId = returnClientRequestId;
OcpDate = ocpDate;
IfMatch = ifMatch;
IfNoneMatch = ifNoneMatch;
IfModifiedSince = ifModifiedSince;
IfUnmodifiedSince = ifUnmodifiedSince;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the maximum time that the server can spend processing
/// the request, in seconds. The default is 30 seconds.
/// </summary>
[Newtonsoft.Json.JsonIgnore]
public int? Timeout { get; set; }
/// <summary>
/// Gets or sets the caller-generated request identity, in the form of
/// a GUID with no decoration such as curly braces, e.g.
/// 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
/// </summary>
[Newtonsoft.Json.JsonIgnore]
public System.Guid? ClientRequestId { get; set; }
/// <summary>
/// Gets or sets whether the server should return the client-request-id
/// in the response.
/// </summary>
[Newtonsoft.Json.JsonIgnore]
public bool? ReturnClientRequestId { get; set; }
/// <summary>
/// Gets or sets the time the request was issued. Client libraries
/// typically set this to the current system clock time; set it
/// explicitly if you are calling the REST API directly.
/// </summary>
[JsonConverter(typeof(DateTimeRfc1123JsonConverter))]
[Newtonsoft.Json.JsonIgnore]
public System.DateTime? OcpDate { get; set; }
/// <summary>
/// Gets or sets an ETag value associated with the version of the
/// resource known to the client. The operation will be performed only
/// if the resource's current ETag on the service exactly matches the
/// value specified by the client.
/// </summary>
[Newtonsoft.Json.JsonIgnore]
public string IfMatch { get; set; }
/// <summary>
/// Gets or sets an ETag value associated with the version of the
/// resource known to the client. The operation will be performed only
/// if the resource's current ETag on the service does not match the
/// value specified by the client.
/// </summary>
[Newtonsoft.Json.JsonIgnore]
public string IfNoneMatch { get; set; }
/// <summary>
/// Gets or sets a timestamp indicating the last modified time of the
/// resource known to the client. The operation will be performed only
/// if the resource on the service has been modified since the
/// specified time.
/// </summary>
[JsonConverter(typeof(DateTimeRfc1123JsonConverter))]
[Newtonsoft.Json.JsonIgnore]
public System.DateTime? IfModifiedSince { get; set; }
/// <summary>
/// Gets or sets a timestamp indicating the last modified time of the
/// resource known to the client. The operation will be performed only
/// if the resource on the service has not been modified since the
/// specified time.
/// </summary>
[JsonConverter(typeof(DateTimeRfc1123JsonConverter))]
[Newtonsoft.Json.JsonIgnore]
public System.DateTime? IfUnmodifiedSince { get; set; }
}
}
| 45.72 | 413 | 0.640274 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/batch/Microsoft.Azure.Batch/src/GeneratedProtocol/Models/JobEnableOptions.cs | 6,858 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2016-11-15.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.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CapacityReservationTargetResponse Object
/// </summary>
public class CapacityReservationTargetResponseUnmarshaller : IUnmarshaller<CapacityReservationTargetResponse, XmlUnmarshallerContext>, IUnmarshaller<CapacityReservationTargetResponse, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public CapacityReservationTargetResponse Unmarshall(XmlUnmarshallerContext context)
{
CapacityReservationTargetResponse unmarshalledObject = new CapacityReservationTargetResponse();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("capacityReservationId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.CapacityReservationId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("capacityReservationResourceGroupArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.CapacityReservationResourceGroupArn = unmarshaller.Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public CapacityReservationTargetResponse Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static CapacityReservationTargetResponseUnmarshaller _instance = new CapacityReservationTargetResponseUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static CapacityReservationTargetResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.320388 | 213 | 0.610337 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/CapacityReservationTargetResponseUnmarshaller.cs | 3,947 | C# |
using System.Collections.Generic;
using System.Data;
using Dapper;
namespace Dapperer.QueryBuilders.MsSql.TableValueParams
{
public abstract class SimpleListTableValueParams<TColumnType>
{
private readonly IEnumerable<TColumnType> _records;
private readonly string _tableName;
private readonly string _columnName;
protected SimpleListTableValueParams(
IEnumerable<TColumnType> records,
string tableName,
string columnName)
{
_records = records;
_tableName = tableName;
_columnName = columnName;
}
public DataTable AsDataTable()
{
var table = new DataTable(nameof(_tableName))
{
Columns =
{
new DataColumn(_columnName, typeof(TColumnType))
}
};
foreach (var record in _records)
{
table.Rows.Add(record);
}
return table;
}
public SqlMapper.ICustomQueryParameter AsTableValuedParameter() =>
AsDataTable().AsTableValuedParameter(_tableName);
}
} | 27.090909 | 74 | 0.575503 | [
"MIT"
] | josephjeganathan/Dapperer | Dapperer/QueryBuilders/MsSql/TableValueParams/SimpleListTableValueParams.cs | 1,194 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CacheStorage.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.Caching
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Policies;
/// <summary>
/// The cache storage.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
public class CacheStorage<TKey, TValue> : ICacheStorage<TKey, TValue>
{
#region Fields
private readonly Func<ExpirationPolicy> _defaultExpirationPolicyInitCode;
/// <summary>
/// Determines whether the cache storage can store null values.
/// </summary>
private readonly bool _storeNullValues;
/// <summary>
/// The dictionary.
/// </summary>
private readonly Dictionary<TKey, CacheStorageValueInfo<TValue>> _dictionary;
/// <summary>
/// The synchronization object.
/// </summary>
private readonly object _syncObj = new object();
/// <summary>
/// The synchronization objects.
/// </summary>
private readonly Dictionary<TKey, object> _syncObjs = new Dictionary<TKey, object>();
/// <summary>
/// The timer that is being executed to invalidate the cache.
/// </summary>
private Timer _expirationTimer;
/// <summary>
/// The expiration timer interval.
/// </summary>
private TimeSpan _expirationTimerInterval;
/// <summary>
/// Determines whether the cache storage can check for expired items.
/// </summary>
private bool _checkForExpiredItems;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CacheStorage{TKey,TValue}" /> class.
/// </summary>
/// <param name="defaultExpirationPolicyInitCode">The default expiration policy initialization code.</param>
/// <param name="storeNullValues">Allow store null values on the cache.</param>
[ObsoleteEx(Message = "Use other ctor, this is kept to not introduce breaking changes",
Replacement = "ctor(Func<ExpirationPolicy>, bool, IEqualityComparer<TKey>)", TreatAsErrorFromVersion = "4.5", RemoveInVersion = "5.0")]
public CacheStorage(Func<ExpirationPolicy> defaultExpirationPolicyInitCode, bool storeNullValues)
: this(defaultExpirationPolicyInitCode, storeNullValues, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CacheStorage{TKey,TValue}" /> class.
/// </summary>
/// <param name="defaultExpirationPolicyInitCode">The default expiration policy initialization code.</param>
/// <param name="storeNullValues">Allow store null values on the cache.</param>
/// <param name="equalityComparer">The equality comparer.</param>
public CacheStorage(Func<ExpirationPolicy> defaultExpirationPolicyInitCode = null, bool storeNullValues = false,
IEqualityComparer<TKey> equalityComparer = null)
{
_dictionary = new Dictionary<TKey, CacheStorageValueInfo<TValue>>(equalityComparer);
_storeNullValues = storeNullValues;
_defaultExpirationPolicyInitCode = defaultExpirationPolicyInitCode;
_expirationTimerInterval = TimeSpan.FromSeconds(1);
}
#endregion
#region ICacheStorage<TKey,TValue> Members
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The value associated with the specified key, or default value for the type of the value if the key do not exists.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public TValue this[TKey key]
{
get { return Get(key); }
}
/// <summary>
/// Gets the keys so it is possible to enumerate the cache.
/// </summary>
/// <value>The keys.</value>
public IEnumerable<TKey> Keys
{
get
{
lock (_syncObj)
{
return _dictionary.Keys;
}
}
}
/// <summary>
/// Gets or sets the expiration timer interval.
/// <para />
/// The default value is <c>TimeSpan.FromSeconds(1)</c>.
/// </summary>
/// <value>The expiration timer interval.</value>
public TimeSpan ExpirationTimerInterval
{
get { return _expirationTimerInterval; }
set
{
_expirationTimerInterval = value;
UpdateTimer();
}
}
private void UpdateTimer()
{
lock (_syncObj)
{
if (!_checkForExpiredItems)
{
if (_expirationTimer != null)
{
_expirationTimer.Dispose();
_expirationTimer = null;
}
}
else
{
var timeSpan = _expirationTimerInterval;
if (_expirationTimer == null)
{
_expirationTimer = new Timer(OnTimerElapsed, null, timeSpan, timeSpan);
}
else
{
_expirationTimer.Change(timeSpan, timeSpan);
}
}
}
}
/// <summary>
/// Gets the value associated with the specified key
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <returns>The value associated with the specified key, or default value for the type of the value if the key do not exists.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public TValue Get(TKey key)
{
Argument.IsNotNull("key", key);
CacheStorageValueInfo<TValue> valueInfo;
lock (GetLockByKey(key))
{
_dictionary.TryGetValue(key, out valueInfo);
}
return (valueInfo != null) ? valueInfo.Value : default(TValue);
}
/// <summary>
/// Determines whether the cache contains a value associated with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns><c>true</c> if the cache contains an element with the specified key; otherwise, <c>false</c>.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public bool Contains(TKey key)
{
Argument.IsNotNull("key", key);
lock (GetLockByKey(key))
{
return _dictionary.ContainsKey(key);
}
}
/// <summary>
/// Adds a value to the cache associated with to a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="code">The deferred initialization code of the value.</param>
/// <param name="expirationPolicy">The expiration policy.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <returns>The instance initialized by the <paramref name="code" />.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception>
[SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:TabsMustNotBeUsed", Justification = "Reviewed. Suppression is OK here.")]
public TValue GetFromCacheOrFetch(TKey key, Func<TValue> code, ExpirationPolicy expirationPolicy, bool @override = false)
{
Argument.IsNotNull("key", key);
Argument.IsNotNull("code", code);
TValue value;
lock (GetLockByKey(key))
{
bool containsKey = _dictionary.ContainsKey(key);
if (!containsKey || @override)
{
value = code.Invoke();
if (!ReferenceEquals(value, null) || _storeNullValues)
{
if (expirationPolicy == null && _defaultExpirationPolicyInitCode != null)
{
expirationPolicy = _defaultExpirationPolicyInitCode.Invoke();
}
var valueInfo = new CacheStorageValueInfo<TValue>(value, expirationPolicy);
lock (_syncObj)
{
_dictionary[key] = valueInfo;
}
if (valueInfo.CanExpire)
{
_checkForExpiredItems = true;
}
if (expirationPolicy != null)
{
if (_expirationTimer == null)
{
UpdateTimer();
}
}
}
}
else
{
value = _dictionary[key].Value;
}
}
return value;
}
/// <summary>
/// Adds a value to the cache associated with to a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="code">The deferred initialization code of the value.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <param name="expiration">The timespan in which the cache item should expire when added.</param>
/// <returns>The instance initialized by the <paramref name="code" />.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception>
public TValue GetFromCacheOrFetch(TKey key, Func<TValue> code, bool @override = false, TimeSpan expiration = default(TimeSpan))
{
return GetFromCacheOrFetch(key, code, ExpirationPolicy.Duration(expiration), @override);
}
/// <summary>
/// Adds a value to the cache associated with to a key asynchronously.
/// <para />
/// Note that this is a wrapper around <see cref="GetFromCacheOrFetch(TKey,System.Func{TValue},ExpirationPolicy,bool)"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="code">The deferred initialization code of the value.</param>
/// <param name="expirationPolicy">The expiration policy.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <returns>The instance initialized by the <paramref name="code" />.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception>
public async Task<TValue> GetFromCacheOrFetchAsync(TKey key, Func<TValue> code, ExpirationPolicy expirationPolicy, bool @override = false)
{
return await Task.Factory.StartNew(() => GetFromCacheOrFetch(key, code, expirationPolicy, @override));
}
/// <summary>
/// Adds a value to the cache associated with to a key asynchronously.
/// <para />
/// Note that this is a wrapper around <see cref="GetFromCacheOrFetch(TKey,System.Func{TValue},bool,TimeSpan)"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="code">The deferred initialization code of the value.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <param name="expiration">The timespan in which the cache item should expire when added.</param>
/// <returns>The instance initialized by the <paramref name="code" />.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception>
public async Task<TValue> GetFromCacheOrFetchAsync(TKey key, Func<TValue> code, bool @override = false, TimeSpan expiration = default(TimeSpan))
{
return await Task.Factory.StartNew(() => GetFromCacheOrFetch(key, code, @override, expiration));
}
/// <summary>
/// Adds a value to the cache associated with to a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <param name="expiration">The timespan in which the cache item should expire when added.</param>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public void Add(TKey key, TValue @value, bool @override = false, TimeSpan expiration = default(TimeSpan))
{
Add(key, value, ExpirationPolicy.Duration(expiration), @override);
}
/// <summary>
/// Adds a value to the cache associated with to a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="expirationPolicy">The expiration policy.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public void Add(TKey key, TValue @value, ExpirationPolicy expirationPolicy, bool @override = false)
{
Argument.IsNotNull("key", key);
if (!_storeNullValues)
{
Argument.IsNotNull("value", value);
}
GetFromCacheOrFetch(key, () => @value, expirationPolicy, @override);
}
/// <summary>
/// Removes an item from the cache.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="action">The action that need to be executed in synchronization with the item cache removal.</param>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public void Remove(TKey key, Action action = null)
{
Argument.IsNotNull("key", key);
lock (GetLockByKey(key))
{
if (_dictionary.ContainsKey(key))
{
if (action != null)
{
action.Invoke();
}
_dictionary.Remove(key);
}
}
}
/// <summary>
/// Clears all the items currently in the cache.
/// </summary>
public void Clear()
{
var keysToRemove = new List<TKey>();
lock (_syncObj)
{
keysToRemove.AddRange(_dictionary.Keys);
foreach (var keyToRemove in keysToRemove)
{
lock (GetLockByKey(keyToRemove))
{
_dictionary.Remove(keyToRemove);
}
}
_checkForExpiredItems = false;
UpdateTimer();
}
}
/// <summary>
/// Removes the expired items from the cache.
/// </summary>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1409:RemoveUnnecessaryCode", Justification = "Reviewed. Suppression is OK here.")]
private void RemoveExpiredItems()
{
bool containsItemsThatCanExpire = false;
var keysToRemove = new List<TKey>();
lock (_syncObj)
{
foreach (var cacheItem in _dictionary)
{
var valueInfo = cacheItem.Value;
if (valueInfo.IsExpired)
{
keysToRemove.Add(cacheItem.Key);
}
else
{
if (!containsItemsThatCanExpire && valueInfo.CanExpire)
{
containsItemsThatCanExpire = true;
}
}
}
}
foreach (var keyToRemove in keysToRemove)
{
lock (GetLockByKey(keyToRemove))
{
_dictionary.Remove(keyToRemove);
}
}
lock (_syncObj)
{
if (_checkForExpiredItems != containsItemsThatCanExpire)
{
_checkForExpiredItems = containsItemsThatCanExpire;
UpdateTimer();
}
}
}
/// <summary>
/// Gets the lock by key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The lock object.</returns>
private object GetLockByKey(TKey key)
{
lock (_syncObj)
{
var containsKey = _syncObjs.ContainsKey(key);
if (!containsKey)
{
_syncObjs[key] = new object();
}
}
return _syncObjs[key];
}
/// <summary>
/// Called when the timer to clean up the cache elapsed.
/// </summary>
/// <param name="state">The timer state.</param>
private void OnTimerElapsed(object state)
{
if (!_checkForExpiredItems)
{
return;
}
RemoveExpiredItems();
}
#endregion
}
} | 40.510684 | 152 | 0.534311 | [
"MIT"
] | nix63/Catel | src/Catel.Core/Catel.Core.Shared/Caching/CacheStorage.cs | 18,959 | C# |
partial class Editor_Tiles
{
/// <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(Editor_Tiles));
this.scrlTileX = new System.Windows.Forms.HScrollBar();
this.scrlTileY = new System.Windows.Forms.VScrollBar();
this.picTile = new System.Windows.Forms.PictureBox();
this.grpAttributes = new System.Windows.Forms.GroupBox();
this.optBlock = new System.Windows.Forms.RadioButton();
this.butClear = new System.Windows.Forms.Button();
this.butCancel = new System.Windows.Forms.Button();
this.butSave = new System.Windows.Forms.Button();
this.grpTile = new System.Windows.Forms.GroupBox();
this.scrlTile = new System.Windows.Forms.HScrollBar();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.optAttributes = new System.Windows.Forms.RadioButton();
this.optDirBlock = new System.Windows.Forms.RadioButton();
((System.ComponentModel.ISupportInitialize)(this.picTile)).BeginInit();
this.grpAttributes.SuspendLayout();
this.grpTile.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// scrlTileX
//
this.scrlTileX.LargeChange = 1;
this.scrlTileX.Location = new System.Drawing.Point(14, 453);
this.scrlTileX.Name = "scrlTileX";
this.scrlTileX.Size = new System.Drawing.Size(256, 19);
this.scrlTileX.TabIndex = 69;
//
// scrlTileY
//
this.scrlTileY.Cursor = System.Windows.Forms.Cursors.Default;
this.scrlTileY.LargeChange = 1;
this.scrlTileY.Location = new System.Drawing.Point(270, 69);
this.scrlTileY.Maximum = 255;
this.scrlTileY.Name = "scrlTileY";
this.scrlTileY.Size = new System.Drawing.Size(19, 384);
this.scrlTileY.TabIndex = 70;
//
// picTile
//
this.picTile.BackColor = System.Drawing.Color.Black;
this.picTile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.picTile.Location = new System.Drawing.Point(14, 69);
this.picTile.Name = "picTile";
this.picTile.Size = new System.Drawing.Size(256, 384);
this.picTile.TabIndex = 68;
this.picTile.TabStop = false;
this.picTile.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picTile_MouseDown);
//
// grpAttributes
//
this.grpAttributes.Controls.Add(this.optBlock);
this.grpAttributes.Location = new System.Drawing.Point(297, 141);
this.grpAttributes.Name = "grpAttributes";
this.grpAttributes.Size = new System.Drawing.Size(98, 264);
this.grpAttributes.TabIndex = 71;
this.grpAttributes.TabStop = false;
this.grpAttributes.Text = "Attributes";
//
// optBlock
//
this.optBlock.AutoSize = true;
this.optBlock.Location = new System.Drawing.Point(6, 19);
this.optBlock.Name = "optBlock";
this.optBlock.Size = new System.Drawing.Size(52, 17);
this.optBlock.TabIndex = 75;
this.optBlock.TabStop = true;
this.optBlock.Text = "Block";
this.optBlock.UseVisualStyleBackColor = true;
this.optBlock.CheckedChanged += new System.EventHandler(this.optBlock_CheckedChanged);
//
// butClear
//
this.butClear.Location = new System.Drawing.Point(297, 431);
this.butClear.Name = "butClear";
this.butClear.Size = new System.Drawing.Size(97, 21);
this.butClear.TabIndex = 74;
this.butClear.Text = "Clear";
this.butClear.UseVisualStyleBackColor = true;
this.butClear.Click += new System.EventHandler(this.butClear_Click);
//
// butCancel
//
this.butCancel.Location = new System.Drawing.Point(297, 451);
this.butCancel.Name = "butCancel";
this.butCancel.Size = new System.Drawing.Size(97, 21);
this.butCancel.TabIndex = 73;
this.butCancel.Text = "Cancel";
this.butCancel.UseVisualStyleBackColor = true;
this.butCancel.Click += new System.EventHandler(this.butCancel_Click);
//
// butSave
//
this.butSave.Location = new System.Drawing.Point(297, 411);
this.butSave.Name = "butSave";
this.butSave.Size = new System.Drawing.Size(97, 21);
this.butSave.TabIndex = 72;
this.butSave.Text = "Save";
this.butSave.UseVisualStyleBackColor = true;
this.butSave.Click += new System.EventHandler(this.butSave_Click);
//
// grpTile
//
this.grpTile.Controls.Add(this.scrlTile);
this.grpTile.Location = new System.Drawing.Point(12, 12);
this.grpTile.Name = "grpTile";
this.grpTile.Size = new System.Drawing.Size(382, 49);
this.grpTile.TabIndex = 75;
this.grpTile.TabStop = false;
this.grpTile.Text = "Tile: 1";
//
// scrlTile
//
this.scrlTile.LargeChange = 1;
this.scrlTile.Location = new System.Drawing.Point(9, 18);
this.scrlTile.Minimum = 1;
this.scrlTile.Name = "scrlTile";
this.scrlTile.Size = new System.Drawing.Size(370, 19);
this.scrlTile.TabIndex = 16;
this.scrlTile.Value = 1;
this.scrlTile.ValueChanged += new System.EventHandler(this.scrlTile_ValueChanged);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.optAttributes);
this.groupBox2.Controls.Add(this.optDirBlock);
this.groupBox2.Location = new System.Drawing.Point(297, 69);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(98, 66);
this.groupBox2.TabIndex = 76;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Set";
//
// optAttributes
//
this.optAttributes.AutoSize = true;
this.optAttributes.Checked = true;
this.optAttributes.Location = new System.Drawing.Point(6, 19);
this.optAttributes.Name = "optAttributes";
this.optAttributes.Size = new System.Drawing.Size(69, 17);
this.optAttributes.TabIndex = 75;
this.optAttributes.TabStop = true;
this.optAttributes.Text = "Attributes";
this.optAttributes.UseVisualStyleBackColor = true;
this.optAttributes.CheckedChanged += new System.EventHandler(this.optAttributes_CheckedChanged);
//
// optDirBlock
//
this.optDirBlock.BackColor = System.Drawing.Color.Transparent;
this.optDirBlock.Location = new System.Drawing.Point(6, 42);
this.optDirBlock.Name = "optDirBlock";
this.optDirBlock.Size = new System.Drawing.Size(91, 17);
this.optDirBlock.TabIndex = 76;
this.optDirBlock.Text = "Dir. Block";
this.optDirBlock.UseVisualStyleBackColor = false;
this.optDirBlock.CheckedChanged += new System.EventHandler(this.optDirBlock_CheckedChanged);
//
// Editor_Tiles
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(406, 487);
this.ControlBox = false;
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.butCancel);
this.Controls.Add(this.grpTile);
this.Controls.Add(this.butClear);
this.Controls.Add(this.butSave);
this.Controls.Add(this.grpAttributes);
this.Controls.Add(this.scrlTileX);
this.Controls.Add(this.scrlTileY);
this.Controls.Add(this.picTile);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Editor_Tiles";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Tile Editor";
((System.ComponentModel.ISupportInitialize)(this.picTile)).EndInit();
this.grpAttributes.ResumeLayout(false);
this.grpAttributes.PerformLayout();
this.grpTile.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
public System.Windows.Forms.HScrollBar scrlTileX;
public System.Windows.Forms.VScrollBar scrlTileY;
public System.Windows.Forms.PictureBox picTile;
private System.Windows.Forms.GroupBox grpAttributes;
private System.Windows.Forms.Button butClear;
private System.Windows.Forms.Button butCancel;
private System.Windows.Forms.Button butSave;
private System.Windows.Forms.RadioButton optBlock;
private System.Windows.Forms.GroupBox grpTile;
public System.Windows.Forms.HScrollBar scrlTile;
private System.Windows.Forms.GroupBox groupBox2;
public System.Windows.Forms.RadioButton optDirBlock;
public System.Windows.Forms.RadioButton optAttributes;
} | 46.064935 | 144 | 0.601259 | [
"MIT"
] | ricardodalarme/CryBits | Editors/Editors/Tiles.Designer.cs | 10,643 | C# |
using System;
using Ultraviolet.Core;
namespace Ultraviolet.OpenGL.Bindings
{
public static unsafe partial class gl
{
/* NOTE: Functions which are shared with the ARB extension are defined in GL_ARB_direct_state_access.cs */
[MonoNativeFunctionWrapper]
private delegate void glTextureParameteriEXTDelegate(uint texture, uint target, uint pname, int param);
[Require(Extension = "GL_EXT_direct_state_access")]
private static glTextureParameteriEXTDelegate glTextureParameteriEXT = null;
[MonoNativeFunctionWrapper]
private delegate void glTextureImage2DEXTDelegate(uint texture, uint target, int level, int internalformat, int width, int height, int border, uint format, uint type, IntPtr pixels);
[Require(Extension = "GL_EXT_direct_state_access")]
private static glTextureImage2DEXTDelegate glTextureImage2DEXT = null;
[MonoNativeFunctionWrapper]
private delegate void glTextureImage3DEXTDelegate(uint texture, uint target, int level, int internalformat, int width, int height, int depth, int border, uint format, uint type, IntPtr pixels);
[Require(Extension = "GL_EXT_direct_state_access")]
private static glTextureImage3DEXTDelegate glTextureImage3DEXT = null;
[MonoNativeFunctionWrapper]
private delegate void glTextureSubImage2DEXTDelegate(uint texture, uint target, int level, int xoffset, int yoffset, int width, int height, uint format, uint type, IntPtr pixels);
[Require(Extension = "GL_EXT_direct_state_access")]
private static glTextureSubImage2DEXTDelegate glTextureSubImage2DEXT = null;
[MonoNativeFunctionWrapper]
private delegate void glTextureSubImage3DEXTDelegate(uint texture, uint target, int level, int xoffset, int yoffset, int zoffset, int width, int height, int depth, uint format, uint type, IntPtr pixels);
[Require(Extension = "GL_EXT_direct_state_access")]
private static glTextureSubImage3DEXTDelegate glTextureSubImage3DEXT = null;
}
}
| 57.055556 | 211 | 0.754625 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet.OpenGL.Bindings/Shared/Extensions/EXT_direct_state_access.cs | 2,056 | C# |
namespace Zaabee.SystemTextJson;
public static partial class SystemTextJsonHelper
{
/// <summary>
/// Convert the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
/// </summary>
/// <param name="value"></param>
/// <param name="stream"></param>
/// <param name="options"></param>
/// <typeparam name="TValue"></typeparam>
public static void Pack<TValue>(TValue? value, Stream? stream, JsonSerializerOptions? options = null)
{
if (stream is null) return;
JsonSerializer.Serialize(stream, value, options);
stream.TrySeek(0, SeekOrigin.Begin);
}
/// <summary>
/// Convert the provided value to UTF-8 encoded JSON text and write it to the <see cref="System.IO.Stream"/>.
/// </summary>
/// <param name="type"></param>
/// <param name="value"></param>
/// <param name="stream"></param>
/// <param name="options"></param>
public static void Pack(Type type, object? value, Stream? stream, JsonSerializerOptions? options = null)
{
if (stream is null) return;
JsonSerializer.Serialize(stream, value, type, options);
stream.TrySeek(0, SeekOrigin.Begin);
}
} | 38.1875 | 113 | 0.634206 | [
"MIT"
] | PicoHex/Zaabee.Serializers | src/Zaabee.SystemTextJson/SystemTextJson.Helper.Stream.Pack.cs | 1,222 | C# |
namespace Dit.Umb.ToolBox.Models.Enum
{
public enum EHighlightRendering
{
None, Teaser, Gallery
}
} | 17.142857 | 38 | 0.65 | [
"MIT"
] | hummelfax/MUTOBO | Dit.Umb.ToolBox.Models/Enum/EHighlightRendering.cs | 122 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace monocat
{
/// <summary>
/// 网络管理器
/// </summary>
public class EventLoop
{
// 逻辑处理可以使用一个独立线程,与网络的线程分开
private System.Threading.Thread myThread;
/// <summary>
/// 更新消息队列的时间间隔
/// </summary>
public int update_sleep = 30;
/// <summary>
/// 代理回调函数
/// </summary>
public delegate void OnReceive( NetPacket packet );
// 每个消息对应一个OnReceive函数
private Dictionary<string, OnReceive> m_callbacks;
// 每个消息对应一个handler对象
private Dictionary<string, NetworkHandler> m_handlers;
// 存储消息的队列
private Queue Packets = new System.Collections.Queue();
/// <summary>
/// frame count
/// </summary>
private int m_frameCount = 0;
/// <summary>
/// 多少帧清理一次垃圾, 0 表示不清理
/// </summary>
protected int m_GCFrameCount = 30;
public EventLoop()
{
m_callbacks = new Dictionary<string, OnReceive>();
m_handlers = new Dictionary<string, NetworkHandler>();
// 注册连接成功,丢失连接消息
AddCallback("OnAccepted", OnAccepted);
AddCallback("OnConnected", OnConnected);
AddCallback("OnConnectFailed", OnConnectFailed);
AddCallback("OnLost", OnLost);
}
// 注册消息
public void AddCallback(string msgid, OnReceive handler)
{
if (m_callbacks.ContainsKey(msgid))
return;
m_callbacks.Add(msgid, handler);
}
public void AddHandler(string msgid, NetworkHandler handler)
{
if (m_handlers.ContainsKey(msgid))
return;
m_handlers.Add(msgid, handler);
}
protected virtual void UpdateMain()
{
}
// 数据包入队
public void AddPacket( NetPacket packet )
{
lock (Packets)
{
Packets.Enqueue(packet);
}
}
// 数据包出队
public NetPacket GetPacket()
{
lock (Packets)
{
if (Packets.Count == 0)
return null;
return (NetPacket)Packets.Dequeue();
}
}
// 开始执行另一个线程处理逻辑
public void StartThreadUpdate()
{
// 为逻辑部分建立新的线程
myThread = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadUpdate));
myThread.Start();
}
/// <summary>
/// 在另一个线程执行Update,更新消息队列
/// </summary>
protected void ThreadUpdate()
{
while (true)
{
// 为了节约cpu, 每次循环暂停30帧
System.Threading.Thread.Sleep(update_sleep);
// 更新消息队列
this.UpdatePacket();
// 更新
this.UpdateMain();
}
}
/// <summary>
/// 更新队列消息(在服务端,通常在另一个线程中执行,在Unity中直接在主线程中执行)
/// </summary>
public void UpdatePacket()
{
NetPacket packet = null;
for (packet = GetPacket(); packet != null; )
{
string msg = "";
// 获得消息标识符
packet.BeginRead(out msg);
OnReceive callback = null;
NetworkHandler handler = null;
if (m_callbacks.TryGetValue(msg, out callback))
{
if (callback != null)
{
callback(packet);
}
}
else if (m_handlers.TryGetValue(msg, out handler))
{
if (handler != null)
{
handler.OnNetworkEvent(packet);
}
}
// 客户端回调
if (packet.mySocket != null && packet.mySocket.callback != null
&& packet.mySocket.msgid.CompareTo(msg)==0) {
packet.mySocket.callback (packet);
packet.mySocket.ClearCallback ();
}
packet = GetPacket ();
}
//this.GC();
}
/// <summary>
/// 强制垃圾回收
/// </summary>
private void GC()
{
if (m_GCFrameCount == 0)
return;
m_frameCount++;
if (m_frameCount % m_GCFrameCount == 0)
{
System.GC.Collect();
m_frameCount = 0;
}
}
// 处理服务器接受客户端的连接
public virtual void OnAccepted(NetPacket packet)
{
}
// 处理客户端取得与服务器的连接
public virtual void OnConnected(NetPacket packet)
{
}
/// <summary>
/// 处理客户端取得与服务器连接失败
/// </summary>
public virtual void OnConnectFailed(NetPacket packet)
{
}
/// <summary>
/// 连接丢失
/// </summary>
public virtual void OnLost(NetPacket packet)
{
}
}
}
| 22.736842 | 99 | 0.50484 | [
"Apache-2.0"
] | gameman100/monocat | monocat/Tcp/EventLoop.cs | 5,296 | C# |
using DevCore.Core.Notifications;
using DevCore.ResultObjects;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace DevCore.WebApi.Filters
{
public class NotificationFilter : IAsyncResultFilter
{
private readonly NotificationContext _notificationContext;
public NotificationFilter(NotificationContext notificationContext)
{
_notificationContext = notificationContext;
}
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
if (_notificationContext.HasNotifications)
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.HttpContext.Response.ContentType = "application/json";
var result = new Result<object>()
{
CodigoRetorno = ResultType.ErroRegraNegocio,
Mensagem = "Error",
Erros = _notificationContext.Notifications.ToList()
};
await context.HttpContext.Response.WriteAsync(JsonSerializer.Serialize(result));
return;
}
await next();
}
}
}
| 25.425532 | 104 | 0.774895 | [
"MIT"
] | fabianoteixeira/DevLibraries | src/DevCore.WebApi/Filters/NotificationFilter.cs | 1,197 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Nasca.Models
{
public class AddtionalNodeInfomation
{
private int distance;
public int getDistance()
{
return distance;
}
public AddtionalNodeInfomation(int distance)
{
this.distance = distance;
}
}
}
| 19.142857 | 52 | 0.61194 | [
"MIT"
] | nomuramasanori/Nasca-net-core | Nasca/Models/AddtionalNodeInfomation.cs | 404 | C# |
namespace HuaweiARInternal
{
using System;
using UnityEngine;
using System.Runtime.InteropServices;
using HuaweiARUnitySDK;
internal static class UtilConstants
{
#if UNITY_EDITOR_WIN
public const string HWAugmentedImageCliBinaryName = "ImageDatabaseTool";
#elif UNITY_EDITOR_LINUX
public const string HWAugmentedImageCliBinaryName = "ImageDatabaseTool_linux";
#elif UNITY_EDITOR_OSX
public const string HWAugmentedImageCliBinaryName = "NoToolInMac";
#endif
#if UNITY_EDITOR_OSX
public const string ARCoreAugmentedImageCliBinaryName = "augmented_image_cli_osx";
#elif UNITY_EDITOR_WIN
public const string ARCoreAugmentedImageCliBinaryName = "augmented_image_cli_win";
#elif UNITY_EDITOR_LINUX
public const string ARCoreAugmentedImageCliBinaryName = "augmented_image_cli_linux";
#endif
}
} | 34.68 | 92 | 0.782007 | [
"MIT"
] | Frans-L/iothon-ar-skeleton | Assets/HuaweiARUnitySDK/Scripts/Utility/UtilConstants.cs | 869 | 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 groundstation-2019-05-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GroundStation.Model
{
/// <summary>
///
/// </summary>
public partial class DescribeContactResponse : AmazonWebServiceResponse
{
private string _contactId;
private ContactStatus _contactStatus;
private List<DataflowDetail> _dataflowList = new List<DataflowDetail>();
private DateTime? _endTime;
private string _errorMessage;
private string _groundStation;
private Elevation _maximumElevation;
private string _missionProfileArn;
private DateTime? _postPassEndTime;
private DateTime? _prePassStartTime;
private string _region;
private string _satelliteArn;
private DateTime? _startTime;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property ContactId.
/// <para>
/// UUID of a contact.
/// </para>
/// </summary>
public string ContactId
{
get { return this._contactId; }
set { this._contactId = value; }
}
// Check to see if ContactId property is set
internal bool IsSetContactId()
{
return this._contactId != null;
}
/// <summary>
/// Gets and sets the property ContactStatus.
/// <para>
/// Status of a contact.
/// </para>
/// </summary>
public ContactStatus ContactStatus
{
get { return this._contactStatus; }
set { this._contactStatus = value; }
}
// Check to see if ContactStatus property is set
internal bool IsSetContactStatus()
{
return this._contactStatus != null;
}
/// <summary>
/// Gets and sets the property DataflowList.
/// <para>
/// List describing source and destination details for each dataflow edge.
/// </para>
/// </summary>
public List<DataflowDetail> DataflowList
{
get { return this._dataflowList; }
set { this._dataflowList = value; }
}
// Check to see if DataflowList property is set
internal bool IsSetDataflowList()
{
return this._dataflowList != null && this._dataflowList.Count > 0;
}
/// <summary>
/// Gets and sets the property EndTime.
/// <para>
/// End time of a contact.
/// </para>
/// </summary>
public DateTime EndTime
{
get { return this._endTime.GetValueOrDefault(); }
set { this._endTime = value; }
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this._endTime.HasValue;
}
/// <summary>
/// Gets and sets the property ErrorMessage.
/// <para>
/// Error message for a contact.
/// </para>
/// </summary>
public string ErrorMessage
{
get { return this._errorMessage; }
set { this._errorMessage = value; }
}
// Check to see if ErrorMessage property is set
internal bool IsSetErrorMessage()
{
return this._errorMessage != null;
}
/// <summary>
/// Gets and sets the property GroundStation.
/// <para>
/// Ground station for a contact.
/// </para>
/// </summary>
public string GroundStation
{
get { return this._groundStation; }
set { this._groundStation = value; }
}
// Check to see if GroundStation property is set
internal bool IsSetGroundStation()
{
return this._groundStation != null;
}
/// <summary>
/// Gets and sets the property MaximumElevation.
/// <para>
/// Maximum elevation angle of a contact.
/// </para>
/// </summary>
public Elevation MaximumElevation
{
get { return this._maximumElevation; }
set { this._maximumElevation = value; }
}
// Check to see if MaximumElevation property is set
internal bool IsSetMaximumElevation()
{
return this._maximumElevation != null;
}
/// <summary>
/// Gets and sets the property MissionProfileArn.
/// <para>
/// ARN of a mission profile.
/// </para>
/// </summary>
public string MissionProfileArn
{
get { return this._missionProfileArn; }
set { this._missionProfileArn = value; }
}
// Check to see if MissionProfileArn property is set
internal bool IsSetMissionProfileArn()
{
return this._missionProfileArn != null;
}
/// <summary>
/// Gets and sets the property PostPassEndTime.
/// <para>
/// Amount of time after a contact ends that you’d like to receive a CloudWatch event
/// indicating the pass has finished.
/// </para>
/// </summary>
public DateTime PostPassEndTime
{
get { return this._postPassEndTime.GetValueOrDefault(); }
set { this._postPassEndTime = value; }
}
// Check to see if PostPassEndTime property is set
internal bool IsSetPostPassEndTime()
{
return this._postPassEndTime.HasValue;
}
/// <summary>
/// Gets and sets the property PrePassStartTime.
/// <para>
/// Amount of time prior to contact start you’d like to receive a CloudWatch event indicating
/// an upcoming pass.
/// </para>
/// </summary>
public DateTime PrePassStartTime
{
get { return this._prePassStartTime.GetValueOrDefault(); }
set { this._prePassStartTime = value; }
}
// Check to see if PrePassStartTime property is set
internal bool IsSetPrePassStartTime()
{
return this._prePassStartTime.HasValue;
}
/// <summary>
/// Gets and sets the property Region.
/// <para>
/// Region of a contact.
/// </para>
/// </summary>
public string Region
{
get { return this._region; }
set { this._region = value; }
}
// Check to see if Region property is set
internal bool IsSetRegion()
{
return this._region != null;
}
/// <summary>
/// Gets and sets the property SatelliteArn.
/// <para>
/// ARN of a satellite.
/// </para>
/// </summary>
public string SatelliteArn
{
get { return this._satelliteArn; }
set { this._satelliteArn = value; }
}
// Check to see if SatelliteArn property is set
internal bool IsSetSatelliteArn()
{
return this._satelliteArn != null;
}
/// <summary>
/// Gets and sets the property StartTime.
/// <para>
/// Start time of a contact.
/// </para>
/// </summary>
public DateTime StartTime
{
get { return this._startTime.GetValueOrDefault(); }
set { this._startTime = value; }
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this._startTime.HasValue;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Tags assigned to a contact.
/// </para>
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 29.421569 | 111 | 0.549261 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/GroundStation/Generated/Model/DescribeContactResponse.cs | 9,007 | C# |
/** This is an automatically generated class by FairyGUI. Please do not modify it. **/
using FairyGUI;
using FairyGUI.Utils;
namespace Common
{
public partial class View_Sale_effect : GComponent
{
public Transition t0;
public const string URL = "ui://ucagdrsifjljpz";
public static View_Sale_effect CreateInstance()
{
return (View_Sale_effect)UIPackage.CreateObject("Common", "Sale_effect");
}
public override void ConstructFromXML(XML xml)
{
base.ConstructFromXML(xml);
t0 = GetTransition("t0");
}
}
} | 24.76 | 86 | 0.630048 | [
"MIT"
] | Noname-Studio/ET | Unity/Assets/Scripts/Client/UI/View/Common/View_Sale_effect.cs | 619 | C# |
using NPOI.DDF;
using NPOI.HSSF.Record;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
using NPOI.SS.Formula.Udf;
using NPOI.SS.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Threading;
namespace NPOI.HSSF.Model
{
/// Low level model implementation of a Workbook. Provides creational methods
/// for Settings and objects contained in the workbook object.
///
/// This file Contains the low level binary records starting at the workbook's BOF and
/// ending with the workbook's EOF. Use HSSFWorkbook for a high level representation.
///
/// The structures of the highlevel API use references to this to perform most of their
/// operations. Its probably Unwise to use these low level structures directly Unless you
/// really know what you're doing. I recommend you Read the Microsoft Excel 97 Developer's
/// Kit (Microsoft Press) and the documentation at http://sc.openoffice.org/excelfileformat.pdf
/// before even attempting to use this.
///
///
/// @author Luc Girardin (luc dot girardin at macrofocus dot com)
/// @author Sergei Kozello (sergeikozello at mail.ru)
/// @author Shawn Laubach (slaubach at apache dot org) (Data Formats)
/// @author Andrew C. Oliver (acoliver at apache dot org)
/// @author Brian Sanders (bsanders at risklabs dot com) - custom palette
/// @author Dan Sherman (dsherman at Isisph.com)
/// @author Glen Stampoultzis (glens at apache.org)
/// @see org.apache.poi.hssf.usermodel.HSSFWorkbook
/// @version 1.0-pre
[Serializable]
public class InternalWorkbook
{
/// Excel silently truncates long sheet names to 31 chars.
/// This constant is used to ensure uniqueness in the first 31 chars
private const int MAX_SENSITIVE_SHEET_NAME_LEN = 31;
/// constant used to Set the "codepage" wherever "codepage" is Set in records
/// (which is duplciated in more than one record)
private const short CODEPAGE = 1200;
/// this Contains the Worksheet record objects
[NonSerialized]
protected WorkbookRecordList records = new WorkbookRecordList();
/// this Contains a reference to the SSTRecord so that new stings can be Added
/// to it.
[NonSerialized]
protected SSTRecord sst;
[NonSerialized]
private LinkTable linkTable;
/// holds the "boundsheet" records (aka bundlesheet) so that they can have their
/// reference to their "BOF" marker
protected List<BoundSheetRecord> boundsheets;
protected List<FormatRecord> formats;
protected List<HyperlinkRecord> hyperlinks;
protected int numxfs;
protected int numfonts;
private int maxformatid = -1;
private bool uses1904datewindowing;
[NonSerialized]
private DrawingManager2 drawingManager;
private IList escherBSERecords;
[NonSerialized]
private WindowOneRecord windowOne;
[NonSerialized]
private FileSharingRecord fileShare;
[NonSerialized]
private WriteAccessRecord writeAccess;
[NonSerialized]
private WriteProtectRecord writeProtect;
private Dictionary<string, NameCommentRecord> commentRecords;
public int NumRecords => records.Count;
/// Gets the number of font records
///
/// @return number of font records in the "font table"
public int NumberOfFontRecords => numfonts;
/// Returns the position of the backup record.
public BackupRecord BackupRecord => (BackupRecord)records[records.Backuppos];
/// returns the number of boundsheet objects contained in this workbook.
///
/// @return number of BoundSheet records
public int NumSheets => boundsheets.Count;
/// Get the number of ExtendedFormat records contained in this workbook.
///
/// @return int count of ExtendedFormat records
public int NumExFormats => numxfs;
public int Size
{
get
{
int num = 0;
SSTRecord sSTRecord = null;
for (int i = 0; i < records.Count; i++)
{
NPOI.HSSF.Record.Record record = records[i];
if (record.Sid != 449 || ((RecalcIdRecord)record).IsNeeded)
{
if (record is SSTRecord)
{
sSTRecord = (SSTRecord)record;
}
num = ((record.Sid != 255 || sSTRecord == null) ? (num + record.RecordSize) : (num + sSTRecord.CalcExtSSTRecordSize()));
}
}
return num;
}
}
/// lazy initialization
/// Note - creating the link table causes creation of 1 EXTERNALBOOK and 1 EXTERNALSHEET record
private LinkTable OrCreateLinkTable
{
get
{
if (linkTable == null)
{
linkTable = new LinkTable((short)NumSheets, records);
}
return linkTable;
}
}
/// Gets the total number of names
/// @return number of names
public int NumNames
{
get
{
if (linkTable == null)
{
return 0;
}
return linkTable.NumNames;
}
}
/// Returns the list of FormatRecords in the workbook.
/// @return ArrayList of FormatRecords in the notebook
public List<FormatRecord> Formats => formats;
public IList Hyperlinks => hyperlinks;
public IList Records => records.Records;
/// Whether date windowing is based on 1/2/1904 or 1/1/1900.
/// Some versions of Excel (Mac) can save workbooks using 1904 date windowing.
///
/// @return true if using 1904 date windowing
public bool IsUsing1904DateWindowing => uses1904datewindowing;
/// Returns the custom palette in use for this workbook; if a custom palette record
/// does not exist, then it is Created.
public PaletteRecord CustomPalette
{
get
{
int palettepos = records.Palettepos;
PaletteRecord paletteRecord;
if (palettepos != -1)
{
NPOI.HSSF.Record.Record record = records[palettepos];
if (!(record is PaletteRecord))
{
throw new Exception("InternalError: Expected PaletteRecord but got a '" + record + "'");
}
paletteRecord = (PaletteRecord)record;
}
else
{
paletteRecord = CreatePalette();
records.Add(1, paletteRecord);
records.Palettepos = 1;
}
return paletteRecord;
}
}
public WindowOneRecord WindowOne => windowOne;
public DrawingManager2 DrawingManager => drawingManager;
public WriteProtectRecord WriteProtect
{
get
{
if (writeProtect == null)
{
writeProtect = new WriteProtectRecord();
int num = 0;
for (num = 0; num < records.Count && !(records[num] is BOFRecord); num++)
{
}
records.Add(num + 1, writeProtect);
}
return writeProtect;
}
}
public WriteAccessRecord WriteAccess
{
get
{
if (writeAccess == null)
{
writeAccess = (WriteAccessRecord)CreateWriteAccess();
int num = 0;
for (num = 0; num < records.Count && !(records[num] is InterfaceEndRecord); num++)
{
}
records.Add(num + 1, writeAccess);
}
return writeAccess;
}
}
public FileSharingRecord FileSharing
{
get
{
if (fileShare == null)
{
fileShare = new FileSharingRecord();
int num = 0;
for (num = 0; num < records.Count && !(records[num] is WriteAccessRecord); num++)
{
}
records.Add(num + 1, fileShare);
}
return fileShare;
}
}
/// is the workbook protected with a password (not encrypted)?
public bool IsWriteProtected
{
get
{
if (fileShare == null)
{
return false;
}
FileSharingRecord fileSharing = FileSharing;
return fileSharing.ReadOnly == 1;
}
}
/// Get or create RecalcIdRecord
///
/// @see org.apache.poi.hssf.usermodel.HSSFWorkbook#setForceFormulaRecalculation(boolean)
public RecalcIdRecord RecalcId
{
get
{
RecalcIdRecord recalcIdRecord = (RecalcIdRecord)FindFirstRecordBySid(449);
if (recalcIdRecord == null)
{
recalcIdRecord = new RecalcIdRecord();
int num = FindFirstRecordLocBySid(140);
records.Add(num + 1, recalcIdRecord);
}
return recalcIdRecord;
}
}
/// Creates new Workbook with no intitialization --useless right now
/// @see #CreateWorkbook(List)
public InternalWorkbook()
{
records = new WorkbookRecordList();
boundsheets = new List<BoundSheetRecord>();
formats = new List<FormatRecord>();
hyperlinks = new List<HyperlinkRecord>();
numxfs = 0;
numfonts = 0;
maxformatid = -1;
uses1904datewindowing = false;
escherBSERecords = new List<EscherBSERecord>();
commentRecords = new Dictionary<string, NameCommentRecord>();
}
/// Read support for low level
/// API. Pass in an array of Record objects, A Workbook
/// object is constructed and passed back with all of its initialization Set
/// to the passed in records and references to those records held. Unlike Sheet
/// workbook does not use an offset (its assumed to be 0) since its first in a file.
/// If you need an offset then construct a new array with a 0 offset or Write your
/// own ;-p.
///
/// @param recs an array of Record objects
/// @return Workbook object
public static InternalWorkbook CreateWorkbook(List<NPOI.HSSF.Record.Record> recs)
{
InternalWorkbook internalWorkbook = new InternalWorkbook();
List<NPOI.HSSF.Record.Record> list = new List<NPOI.HSSF.Record.Record>(recs.Count / 3);
internalWorkbook.records.Records = list;
int i;
for (i = 0; i < recs.Count; i++)
{
NPOI.HSSF.Record.Record record = recs[i];
if (record.Sid == 10)
{
list.Add(record);
break;
}
switch (record.Sid)
{
case 133:
internalWorkbook.boundsheets.Add((BoundSheetRecord)record);
internalWorkbook.records.Bspos = i;
goto default;
case 252:
internalWorkbook.sst = (SSTRecord)record;
goto default;
case 49:
internalWorkbook.records.Fontpos = i;
internalWorkbook.numfonts++;
goto default;
case 224:
internalWorkbook.records.Xfpos = i;
internalWorkbook.numxfs++;
goto default;
case 317:
internalWorkbook.records.Tabpos = i;
goto default;
case 18:
internalWorkbook.records.Protpos = i;
goto default;
case 64:
internalWorkbook.records.Backuppos = i;
goto default;
case 23:
throw new Exception("Extern sheet is part of LinkTable");
case 24:
case 430:
internalWorkbook.linkTable = new LinkTable(recs, i, internalWorkbook.records, internalWorkbook.commentRecords);
i += internalWorkbook.linkTable.RecordCount - 1;
break;
case 1054:
internalWorkbook.formats.Add((FormatRecord)record);
internalWorkbook.maxformatid = ((internalWorkbook.maxformatid >= ((FormatRecord)record).IndexCode) ? internalWorkbook.maxformatid : ((FormatRecord)record).IndexCode);
goto default;
case 34:
internalWorkbook.uses1904datewindowing = (((DateWindow1904Record)record).Windowing == 1);
goto default;
case 146:
internalWorkbook.records.Palettepos = i;
goto default;
case 61:
internalWorkbook.windowOne = (WindowOneRecord)record;
goto default;
case 92:
internalWorkbook.writeAccess = (WriteAccessRecord)record;
goto default;
case 134:
internalWorkbook.writeProtect = (WriteProtectRecord)record;
goto default;
case 91:
internalWorkbook.fileShare = (FileSharingRecord)record;
goto default;
case 2196:
{
NameCommentRecord nameCommentRecord = (NameCommentRecord)record;
internalWorkbook.commentRecords[nameCommentRecord.NameText] = nameCommentRecord;
goto default;
}
default:
list.Add(record);
break;
}
}
for (; i < recs.Count; i++)
{
NPOI.HSSF.Record.Record record2 = recs[i];
short sid = record2.Sid;
if (sid == 440)
{
internalWorkbook.hyperlinks.Add((HyperlinkRecord)record2);
}
}
if (internalWorkbook.windowOne == null)
{
internalWorkbook.windowOne = (WindowOneRecord)CreateWindowOne();
}
return internalWorkbook;
}
/// gets the name comment record
/// @param nameRecord name record who's comment is required.
/// @return name comment record or <code>null</code> if there isn't one for the given name.
public NameCommentRecord GetNameCommentRecord(NameRecord nameRecord)
{
if (commentRecords.ContainsKey(nameRecord.NameText))
{
return commentRecords[nameRecord.NameText];
}
return null;
}
/// Creates an empty workbook object with three blank sheets and all the empty
/// fields. Use this to Create a workbook from scratch.
public static InternalWorkbook CreateWorkbook()
{
InternalWorkbook internalWorkbook = new InternalWorkbook();
List<NPOI.HSSF.Record.Record> list = new List<NPOI.HSSF.Record.Record>(30);
internalWorkbook.records.Records = list;
List<FormatRecord> list2 = new List<FormatRecord>(8);
list.Add(CreateBOF());
list.Add(new InterfaceHdrRecord(1200));
list.Add(CreateMMS());
list.Add(InterfaceEndRecord.Instance);
list.Add(CreateWriteAccess());
list.Add(CreateCodepage());
list.Add(CreateDSF());
list.Add(CreateTabId());
internalWorkbook.records.Tabpos = list.Count - 1;
list.Add(CreateFnGroupCount());
list.Add(CreateWindowProtect());
list.Add(CreateProtect());
internalWorkbook.records.Protpos = list.Count - 1;
list.Add(CreatePassword());
list.Add(CreateProtectionRev4());
list.Add(CreatePasswordRev4());
internalWorkbook.windowOne = (WindowOneRecord)CreateWindowOne();
list.Add(internalWorkbook.windowOne);
list.Add(CreateBackup());
internalWorkbook.records.Backuppos = list.Count - 1;
list.Add(CreateHideObj());
list.Add(CreateDateWindow1904());
list.Add(CreatePrecision());
list.Add(CreateRefreshAll());
list.Add(CreateBookBool());
list.Add(CreateFont());
list.Add(CreateFont());
list.Add(CreateFont());
list.Add(CreateFont());
internalWorkbook.records.Fontpos = list.Count - 1;
internalWorkbook.numfonts = 4;
for (int i = 0; i <= 7; i++)
{
NPOI.HSSF.Record.Record record = CreateFormat(i);
internalWorkbook.maxformatid = ((internalWorkbook.maxformatid >= ((FormatRecord)record).IndexCode) ? internalWorkbook.maxformatid : ((FormatRecord)record).IndexCode);
list2.Add((FormatRecord)record);
list.Add(record);
}
internalWorkbook.formats = list2;
for (int j = 0; j < 21; j++)
{
list.Add(CreateExtendedFormat(j));
internalWorkbook.numxfs++;
}
internalWorkbook.records.Xfpos = list.Count - 1;
for (int k = 0; k < 6; k++)
{
list.Add(CreateStyle(k));
}
list.Add(CreateUseSelFS());
int num = 1;
for (int l = 0; l < num; l++)
{
BoundSheetRecord item = (BoundSheetRecord)CreateBoundSheet(l);
list.Add(item);
internalWorkbook.boundsheets.Add(item);
internalWorkbook.records.Bspos = list.Count - 1;
}
list.Add(CreateCountry());
for (int m = 0; m < num; m++)
{
internalWorkbook.OrCreateLinkTable.CheckExternSheet(m);
}
internalWorkbook.sst = new SSTRecord();
list.Add(internalWorkbook.sst);
list.Add(CreateExtendedSST());
list.Add(EOFRecord.instance);
return internalWorkbook;
}
/// Retrieves the Builtin NameRecord that matches the name and index
/// There shouldn't be too many names to make the sequential search too slow
/// @param name byte representation of the builtin name to match
/// @param sheetIndex Index to match
/// @return null if no builtin NameRecord matches
public NameRecord GetSpecificBuiltinRecord(byte name, int sheetIndex)
{
return OrCreateLinkTable.GetSpecificBuiltinRecord(name, sheetIndex);
}
public ExternalSheet GetExternalSheet(int externSheetIndex)
{
string[] externalBookAndSheetName = linkTable.GetExternalBookAndSheetName(externSheetIndex);
if (externalBookAndSheetName == null)
{
return null;
}
return new ExternalSheet(externalBookAndSheetName[0], externalBookAndSheetName[1]);
}
public ExternalName GetExternalName(int externSheetIndex, int externNameIndex)
{
string text = linkTable.ResolveNameXText(externSheetIndex, externNameIndex);
if (text == null)
{
return null;
}
int ix = linkTable.ResolveNameXIx(externSheetIndex, externNameIndex);
return new ExternalName(text, externNameIndex, ix);
}
/// Removes the specified Builtin NameRecord that matches the name and index
/// @param name byte representation of the builtin to match
/// @param sheetIndex zero-based sheet reference
public void RemoveBuiltinRecord(byte name, int sheetIndex)
{
linkTable.RemoveBuiltinRecord(name, sheetIndex);
}
/// Gets the font record at the given index in the font table. Remember
/// "There is No Four" (someone at M$ must have gone to Rocky Horror one too
/// many times)
///
/// @param idx the index to look at (0 or greater but NOT 4)
/// @return FontRecord located at the given index
public FontRecord GetFontRecordAt(int idx)
{
int num = idx;
if (num > 4)
{
num--;
}
if (num > numfonts - 1)
{
throw new IndexOutOfRangeException("There are only " + numfonts + " font records, you asked for " + idx);
}
return (FontRecord)records[records.Fontpos - (numfonts - 1) + num];
}
/// Creates a new font record and Adds it to the "font table". This causes the
/// boundsheets to move down one, extended formats to move down (so this function moves
/// those pointers as well)
///
/// @return FontRecord that was just Created
public FontRecord CreateNewFont()
{
FontRecord fontRecord = (FontRecord)CreateFont();
records.Add(records.Fontpos + 1, fontRecord);
records.Fontpos += 1;
numfonts++;
return fontRecord;
}
/// Check if the cloned sheet has drawings. If yes, then allocate a new drawing group ID and
/// re-generate shape IDs
///
/// @param sheet the cloned sheet
public void CloneDrawings(InternalSheet sheet)
{
FindDrawingGroup();
if (drawingManager != null)
{
int num = sheet.AggregateDrawingRecords(drawingManager, CreateIfMissing: false);
if (num != -1)
{
EscherAggregate escherAggregate = (EscherAggregate)sheet.FindFirstRecordBySid(9876);
EscherContainerRecord escherContainer = escherAggregate.GetEscherContainer();
if (escherContainer != null)
{
EscherDggRecord dgg = drawingManager.GetDgg();
int num2 = drawingManager.FindNewDrawingGroupId();
dgg.AddCluster(num2, 0);
dgg.DrawingsSaved++;
EscherDgRecord escherDgRecord = null;
IEnumerator enumerator = escherContainer.ChildRecords.GetEnumerator();
while (enumerator.MoveNext())
{
object current = enumerator.Current;
if (current is EscherDgRecord)
{
escherDgRecord = (EscherDgRecord)current;
escherDgRecord.Options = (short)(num2 << 4);
}
else if (current is EscherContainerRecord)
{
new ArrayList();
EscherContainerRecord escherContainerRecord = (EscherContainerRecord)current;
IEnumerator enumerator2 = escherContainerRecord.ChildRecords.GetEnumerator();
while (enumerator2.MoveNext())
{
EscherContainerRecord escherContainerRecord2 = (EscherContainerRecord)enumerator2.Current;
foreach (EscherRecord childRecord in escherContainerRecord2.ChildRecords)
{
switch (childRecord.RecordId)
{
case -4086:
{
EscherSpRecord escherSpRecord = (EscherSpRecord)childRecord;
int shapeId = drawingManager.AllocateShapeId((short)num2, escherDgRecord);
escherDgRecord.NumShapes--;
escherSpRecord.ShapeId = shapeId;
break;
}
case -4085:
{
EscherOptRecord escherOptRecord = (EscherOptRecord)childRecord;
EscherSimpleProperty escherSimpleProperty = (EscherSimpleProperty)escherOptRecord.Lookup(260);
if (escherSimpleProperty != null)
{
int propertyValue = escherSimpleProperty.PropertyValue;
EscherBSERecord bSERecord = GetBSERecord(propertyValue);
bSERecord.Ref++;
}
break;
}
}
}
}
}
}
}
}
}
}
/// Sets the BOF for a given sheet
///
/// @param sheetnum the number of the sheet to Set the positing of the bof for
/// @param pos the actual bof position
public void SetSheetBof(int sheetIndex, int pos)
{
CheckSheets(sheetIndex);
GetBoundSheetRec(sheetIndex).PositionOfBof = pos;
}
/// Sets the name for a given sheet. If the boundsheet record doesn't exist and
/// its only one more than we have, go ahead and Create it. If its > 1 more than
/// we have, except
///
/// @param sheetnum the sheet number (0 based)
/// @param sheetname the name for the sheet
public void SetSheetName(int sheetnum, string sheetname)
{
CheckSheets(sheetnum);
if (sheetname.Length > 31)
{
sheetname = sheetname.Substring(0, 31);
}
BoundSheetRecord boundSheetRecord = boundsheets[sheetnum];
boundSheetRecord.Sheetname = sheetname;
}
private BoundSheetRecord GetBoundSheetRec(int sheetIndex)
{
return boundsheets[sheetIndex];
}
/// Determines whether a workbook Contains the provided sheet name.
///
/// @param name the name to test (case insensitive match)
/// @param excludeSheetIdx the sheet to exclude from the Check or -1 to include all sheets in the Check.
/// @return true if the sheet Contains the name, false otherwise.
public bool ContainsSheetName(string name, int excludeSheetIdx)
{
string text = name;
if (text.Length > 31)
{
text = text.Substring(0, 31);
}
for (int i = 0; i < boundsheets.Count; i++)
{
BoundSheetRecord boundSheetRec = GetBoundSheetRec(i);
if (excludeSheetIdx != i)
{
string text2 = boundSheetRec.Sheetname;
if (text2.Length > 31)
{
text2 = text2.Substring(0, 31);
}
if (text.Equals(text2, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
return false;
}
/// Sets the name for a given sheet forcing the encoding. This is STILL A BAD IDEA.
/// Poi now automatically detects Unicode
///
/// @deprecated 3-Jan-06 Simply use SetSheetNam e(int sheetnum, String sheetname)
/// @param sheetnum the sheet number (0 based)
/// @param sheetname the name for the sheet
public void SetSheetName(int sheetnum, string sheetname, short encoding)
{
CheckSheets(sheetnum);
BoundSheetRecord boundSheetRecord = boundsheets[sheetnum];
boundSheetRecord.Sheetname = sheetname;
}
/// Sets the order of appearance for a given sheet.
///
/// @param sheetname the name of the sheet to reorder
/// @param pos the position that we want to Insert the sheet into (0 based)
public void SetSheetOrder(string sheetname, int pos)
{
int sheetIndex = GetSheetIndex(sheetname);
BoundSheetRecord item = boundsheets[sheetIndex];
boundsheets.RemoveAt(sheetIndex);
boundsheets.Insert(pos, item);
}
/// Gets the name for a given sheet.
///
/// @param sheetnum the sheet number (0 based)
/// @return sheetname the name for the sheet
public string GetSheetName(int sheetIndex)
{
return GetBoundSheetRec(sheetIndex).Sheetname;
}
/// Gets the hidden flag for a given sheet.
///
/// @param sheetnum the sheet number (0 based)
/// @return True if sheet is hidden
public bool IsSheetHidden(int sheetnum)
{
return GetBoundSheetRec(sheetnum).IsHidden;
}
/// Gets the hidden flag for a given sheet.
/// Note that a sheet could instead be
/// set to be very hidden, which is different
/// ({@link #isSheetVeryHidden(int)})
///
/// @param sheetnum the sheet number (0 based)
/// @return True if sheet is hidden
public bool IsSheetVeryHidden(int sheetnum)
{
return GetBoundSheetRec(sheetnum).IsVeryHidden;
}
/// Hide or Unhide a sheet
///
/// @param sheetnum The sheet number
/// @param hidden True to mark the sheet as hidden, false otherwise
public void SetSheetHidden(int sheetnum, bool hidden)
{
BoundSheetRecord boundSheetRecord = boundsheets[sheetnum];
boundSheetRecord.IsHidden = hidden;
}
/// Hide or unhide a sheet.
/// 0 = not hidden
/// 1 = hidden
/// 2 = very hidden.
///
/// @param sheetnum The sheet number
/// @param hidden 0 for not hidden, 1 for hidden, 2 for very hidden
public void SetSheetHidden(int sheetnum, int hidden)
{
BoundSheetRecord boundSheetRec = GetBoundSheetRec(sheetnum);
bool isHidden = false;
bool isVeryHidden = false;
switch (hidden)
{
case 1:
isHidden = true;
break;
case 2:
isVeryHidden = true;
break;
default:
throw new ArgumentException("Invalid hidden flag " + hidden + " given, must be 0, 1 or 2");
case 0:
break;
}
boundSheetRec.IsHidden = isHidden;
boundSheetRec.IsVeryHidden = isVeryHidden;
}
/// Get the sheet's index
/// @param name sheet name
/// @return sheet index or -1 if it was not found.
public int GetSheetIndex(string name)
{
int result = -1;
for (int i = 0; i < boundsheets.Count; i++)
{
string sheetName = GetSheetName(i);
if (sheetName.Equals(name, StringComparison.OrdinalIgnoreCase))
{
result = i;
break;
}
}
return result;
}
/// if we're trying to Address one more sheet than we have, go ahead and Add it! if we're
/// trying to Address >1 more than we have throw an exception!
private void CheckSheets(int sheetnum)
{
if (boundsheets.Count <= sheetnum)
{
if (boundsheets.Count + 1 <= sheetnum)
{
throw new Exception("Sheet number out of bounds!");
}
BoundSheetRecord boundSheetRecord = (BoundSheetRecord)CreateBoundSheet(sheetnum);
records.Add(records.Bspos + 1, boundSheetRecord);
records.Bspos += 1;
boundsheets.Add(boundSheetRecord);
OrCreateLinkTable.CheckExternSheet(sheetnum);
FixTabIdRecord();
}
}
public void RemoveSheet(int sheetnum)
{
if (boundsheets.Count > sheetnum)
{
records.Remove(records.Bspos - (boundsheets.Count - 1) + sheetnum);
boundsheets.RemoveAt(sheetnum);
FixTabIdRecord();
}
int num = sheetnum + 1;
for (int i = 0; i < NumNames; i++)
{
NameRecord nameRecord = GetNameRecord(i);
if (nameRecord.SheetNumber == num)
{
nameRecord.SheetNumber = 0;
}
else if (nameRecord.SheetNumber > num)
{
nameRecord.SheetNumber--;
}
}
}
/// <summary>
/// make the tabid record look like the current situation.
/// </summary>
/// <returns>number of bytes written in the TabIdRecord</returns>
private int FixTabIdRecord()
{
TabIdRecord tabIdRecord = (TabIdRecord)records[records.Tabpos];
int recordSize = tabIdRecord.RecordSize;
short[] array = new short[boundsheets.Count];
for (short num = 0; num < array.Length; num = (short)(num + 1))
{
array[num] = num;
}
tabIdRecord.SetTabIdArray(array);
return tabIdRecord.RecordSize - recordSize;
}
/// Retrieves the index of the given font
public int GetFontIndex(FontRecord font)
{
for (int i = 0; i <= numfonts; i++)
{
FontRecord fontRecord = (FontRecord)records[records.Fontpos - (numfonts - 1) + i];
if (fontRecord == font)
{
if (i > 3)
{
return i + 1;
}
return i;
}
}
throw new ArgumentException("Could not find that font!");
}
/// Returns the StyleRecord for the given
/// xfIndex, or null if that ExtendedFormat doesn't
/// have a Style set.
public StyleRecord GetStyleRecord(int xfIndex)
{
bool flag = false;
for (int i = records.Xfpos; i < records.Count; i++)
{
if (flag)
{
break;
}
NPOI.HSSF.Record.Record record = records[i];
if (!(record is ExtendedFormatRecord))
{
if (record is StyleRecord)
{
StyleRecord styleRecord = (StyleRecord)record;
if (styleRecord.XFIndex == xfIndex)
{
return styleRecord;
}
}
else
{
flag = true;
}
}
}
return null;
}
/// Gets the ExtendedFormatRecord at the given 0-based index
///
/// @param index of the Extended format record (0-based)
/// @return ExtendedFormatRecord at the given index
public ExtendedFormatRecord GetExFormatAt(int index)
{
int num = records.Xfpos - (numxfs - 1);
num += index;
return (ExtendedFormatRecord)records[num];
}
/// Creates a new Cell-type Extneded Format Record and Adds it to the end of
/// ExtendedFormatRecords collection
///
/// @return ExtendedFormatRecord that was Created
public ExtendedFormatRecord CreateCellXF()
{
ExtendedFormatRecord extendedFormatRecord = CreateExtendedFormat();
records.Add(records.Xfpos + 1, extendedFormatRecord);
records.Xfpos += 1;
numxfs++;
return extendedFormatRecord;
}
/// Adds a string to the SST table and returns its index (if its a duplicate
/// just returns its index and update the counts) ASSUMES compressed Unicode
/// (meaning 8bit)
///
/// @param string the string to be Added to the SSTRecord
///
/// @return index of the string within the SSTRecord
public int AddSSTString(UnicodeString str)
{
if (sst == null)
{
InsertSST();
}
return sst.AddString(str);
}
/// given an index into the SST table, this function returns the corresponding String value
/// @return String containing the SST String
public UnicodeString GetSSTString(int str)
{
if (sst == null)
{
InsertSST();
}
return sst.GetString(str);
}
/// use this function to Add a Shared String Table to an existing sheet (say
/// generated by a different java api) without an sst....
/// @see #CreateSST()
/// @see org.apache.poi.hssf.record.SSTRecord
public void InsertSST()
{
sst = new SSTRecord();
records.Add(records.Count - 1, CreateExtendedSST());
records.Add(records.Count - 2, sst);
}
/// Serializes all records int the worksheet section into a big byte array. Use
/// this to Write the Workbook out.
/// @param offset of the data to be written
/// @param data array of bytes to Write this to
public int Serialize(int offset, byte[] data)
{
int num = 0;
SSTRecord sSTRecord = null;
int num2 = 0;
bool flag = false;
for (int i = 0; i < records.Count; i++)
{
NPOI.HSSF.Record.Record record = records[i];
if (record.Sid != 449 || ((RecalcIdRecord)record).IsNeeded)
{
int num3 = 0;
if (record is SSTRecord)
{
sSTRecord = (SSTRecord)record;
num2 = num;
}
if (record.Sid == 255 && sSTRecord != null)
{
record = sSTRecord.CreateExtSSTRecord(num2 + offset);
}
if (record is BoundSheetRecord)
{
if (!flag)
{
for (int j = 0; j < boundsheets.Count; j++)
{
num3 += boundsheets[j].Serialize(num + offset + num3, data);
}
flag = true;
}
}
else
{
num3 = record.Serialize(num + offset, data);
}
num += num3;
}
}
return num;
}
/// Perform any work necessary before the workbook is about to be serialized.
///
/// Include in it ant code that modifies the workbook record stream and affects its size.
public void PreSerialize()
{
if (records.Tabpos > 0)
{
TabIdRecord tabIdRecord = (TabIdRecord)records[records.Tabpos];
if (tabIdRecord._tabids.Length < boundsheets.Count)
{
FixTabIdRecord();
}
}
}
/// Creates the BOF record
/// @see org.apache.poi.hssf.record.BOFRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a BOFRecord
private static NPOI.HSSF.Record.Record CreateBOF()
{
BOFRecord bOFRecord = new BOFRecord();
bOFRecord.Version = 1536;
bOFRecord.Type = BOFRecordType.Workbook;
bOFRecord.Build = 4307;
bOFRecord.BuildYear = 1996;
bOFRecord.HistoryBitMask = 65;
bOFRecord.RequiredVersion = 6;
return bOFRecord;
}
/// Creates the InterfaceHdr record
/// @see org.apache.poi.hssf.record.InterfaceHdrRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a InterfaceHdrRecord
[Obsolete]
protected NPOI.HSSF.Record.Record CreateInterfaceHdr()
{
return null;
}
/// Creates an MMS record
/// @see org.apache.poi.hssf.record.MMSRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a MMSRecord
private static NPOI.HSSF.Record.Record CreateMMS()
{
MMSRecord mMSRecord = new MMSRecord();
mMSRecord.AddMenuCount = 0;
mMSRecord.DelMenuCount = 0;
return mMSRecord;
}
/// Creates the InterfaceEnd record
/// @see org.apache.poi.hssf.record.InterfaceEndRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a InterfaceEndRecord
[Obsolete]
protected NPOI.HSSF.Record.Record CreateInterfaceEnd()
{
return null;
}
/// Creates the WriteAccess record containing the logged in user's name
/// @see org.apache.poi.hssf.record.WriteAccessRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a WriteAccessRecord
private static NPOI.HSSF.Record.Record CreateWriteAccess()
{
WriteAccessRecord writeAccessRecord = new WriteAccessRecord();
string text = "NPOI";
try
{
string text2 = Environment.UserName;
if (string.IsNullOrEmpty(text2))
{
text2 = text;
}
writeAccessRecord.Username = text2;
return writeAccessRecord;
}
catch (SecurityException)
{
writeAccessRecord.Username = text;
return writeAccessRecord;
}
}
/// Creates the Codepage record containing the constant stored in CODEPAGE
/// @see org.apache.poi.hssf.record.CodepageRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a CodepageRecord
private static NPOI.HSSF.Record.Record CreateCodepage()
{
CodepageRecord codepageRecord = new CodepageRecord();
codepageRecord.Codepage = 1200;
return codepageRecord;
}
/// Creates the DSF record containing a 0 since HSSF can't even Create Dual Stream Files
/// @see org.apache.poi.hssf.record.DSFRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a DSFRecord
private static NPOI.HSSF.Record.Record CreateDSF()
{
return new DSFRecord(isBiff5BookStreamPresent: false);
}
/// Creates the TabId record containing an array of 0,1,2. This release of HSSF
/// always has the default three sheets, no less, no more.
/// @see org.apache.poi.hssf.record.TabIdRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a TabIdRecord
private static NPOI.HSSF.Record.Record CreateTabId()
{
TabIdRecord tabIdRecord = new TabIdRecord();
short[] array = new short[1];
short[] tabIdArray = array;
tabIdRecord.SetTabIdArray(tabIdArray);
return tabIdRecord;
}
/// Creates the FnGroupCount record containing the Magic number constant of 14.
/// @see org.apache.poi.hssf.record.FnGroupCountRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a FnGroupCountRecord
private static NPOI.HSSF.Record.Record CreateFnGroupCount()
{
FnGroupCountRecord fnGroupCountRecord = new FnGroupCountRecord();
fnGroupCountRecord.Count = 14;
return fnGroupCountRecord;
}
/// Creates the WindowProtect record with protect Set to false.
/// @see org.apache.poi.hssf.record.WindowProtectRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a WindowProtectRecord
private static NPOI.HSSF.Record.Record CreateWindowProtect()
{
return new WindowProtectRecord(protect: false);
}
/// Creates the Protect record with protect Set to false.
/// @see org.apache.poi.hssf.record.ProtectRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a ProtectRecord
private static ProtectRecord CreateProtect()
{
return new ProtectRecord(isProtected: false);
}
/// Creates the Password record with password Set to 0.
/// @see org.apache.poi.hssf.record.PasswordRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a PasswordRecord
private static NPOI.HSSF.Record.Record CreatePassword()
{
return new PasswordRecord(0);
}
/// Creates the ProtectionRev4 record with protect Set to false.
/// @see org.apache.poi.hssf.record.ProtectionRev4Record
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a ProtectionRev4Record
private static ProtectionRev4Record CreateProtectionRev4()
{
return new ProtectionRev4Record(protect: false);
}
/// Creates the PasswordRev4 record with password Set to 0.
/// @see org.apache.poi.hssf.record.PasswordRev4Record
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a PasswordRev4Record
private static NPOI.HSSF.Record.Record CreatePasswordRev4()
{
return new PasswordRev4Record(0);
}
/// Creates the WindowOne record with the following magic values:
/// horizontal hold - 0x168
/// vertical hold - 0x10e
/// width - 0x3a5c
/// height - 0x23be
/// options - 0x38
/// selected tab - 0
/// Displayed tab - 0
/// num selected tab- 0
/// tab width ratio - 0x258
/// @see org.apache.poi.hssf.record.WindowOneRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a WindowOneRecord
private static NPOI.HSSF.Record.Record CreateWindowOne()
{
WindowOneRecord windowOneRecord = new WindowOneRecord();
windowOneRecord.HorizontalHold = 360;
windowOneRecord.VerticalHold = 270;
windowOneRecord.Width = 14940;
windowOneRecord.Height = 9150;
windowOneRecord.Options = 56;
windowOneRecord.ActiveSheetIndex = 0;
windowOneRecord.FirstVisibleTab = 0;
windowOneRecord.NumSelectedTabs = 1;
windowOneRecord.TabWidthRatio = 600;
return windowOneRecord;
}
/// Creates the Backup record with backup Set to 0. (loose the data, who cares)
/// @see org.apache.poi.hssf.record.BackupRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a BackupRecord
private static NPOI.HSSF.Record.Record CreateBackup()
{
BackupRecord backupRecord = new BackupRecord();
backupRecord.Backup = 0;
return backupRecord;
}
/// Creates the HideObj record with hide object Set to 0. (don't hide)
/// @see org.apache.poi.hssf.record.HideObjRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a HideObjRecord
private static NPOI.HSSF.Record.Record CreateHideObj()
{
HideObjRecord hideObjRecord = new HideObjRecord();
hideObjRecord.SetHideObj(0);
return hideObjRecord;
}
/// Creates the DateWindow1904 record with windowing Set to 0. (don't window)
/// @see org.apache.poi.hssf.record.DateWindow1904Record
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a DateWindow1904Record
private static NPOI.HSSF.Record.Record CreateDateWindow1904()
{
DateWindow1904Record dateWindow1904Record = new DateWindow1904Record();
dateWindow1904Record.Windowing = 0;
return dateWindow1904Record;
}
/// Creates the Precision record with precision Set to true. (full precision)
/// @see org.apache.poi.hssf.record.PrecisionRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a PrecisionRecord
private static NPOI.HSSF.Record.Record CreatePrecision()
{
PrecisionRecord precisionRecord = new PrecisionRecord();
precisionRecord.FullPrecision = true;
return precisionRecord;
}
/// Creates the RefreshAll record with refreshAll Set to true. (refresh all calcs)
/// @see org.apache.poi.hssf.record.RefreshAllRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a RefreshAllRecord
private static NPOI.HSSF.Record.Record CreateRefreshAll()
{
return new RefreshAllRecord(refreshAll: false);
}
/// Creates the BookBool record with saveLinkValues Set to 0. (don't save link values)
/// @see org.apache.poi.hssf.record.BookBoolRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a BookBoolRecord
private static NPOI.HSSF.Record.Record CreateBookBool()
{
BookBoolRecord bookBoolRecord = new BookBoolRecord();
bookBoolRecord.SaveLinkValues = 0;
return bookBoolRecord;
}
/// Creates a Font record with the following magic values:
/// fontheight = 0xc8
/// attributes = 0x0
/// color palette index = 0x7fff
/// bold weight = 0x190
/// Font Name Length = 5
/// Font Name = Arial
///
/// @see org.apache.poi.hssf.record.FontRecord
/// @see org.apache.poi.hssf.record.Record
/// @return record containing a FontRecord
private static NPOI.HSSF.Record.Record CreateFont()
{
FontRecord fontRecord = new FontRecord();
fontRecord.FontHeight = 200;
fontRecord.Attributes = 0;
fontRecord.ColorPaletteIndex = short.MaxValue;
fontRecord.BoldWeight = 400;
fontRecord.FontName = "Arial";
return fontRecord;
}
/// Creates an ExtendedFormatRecord object
/// @param id the number of the extended format record to Create (meaning its position in
/// a file as MS Excel would Create it.)
///
/// @return record containing an ExtendedFormatRecord
/// @see org.apache.poi.hssf.record.ExtendedFormatRecord
/// @see org.apache.poi.hssf.record.Record
private static NPOI.HSSF.Record.Record CreateExtendedFormat(int id)
{
ExtendedFormatRecord extendedFormatRecord = new ExtendedFormatRecord();
switch (id)
{
case 0:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = 0;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 1:
extendedFormatRecord.FontIndex = 1;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 2:
extendedFormatRecord.FontIndex = 1;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 3:
extendedFormatRecord.FontIndex = 2;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 4:
extendedFormatRecord.FontIndex = 2;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 5:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 6:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 7:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 8:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 9:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 10:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 11:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 12:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 13:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 14:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -3072;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 15:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = 1;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = 0;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 16:
extendedFormatRecord.FontIndex = 1;
extendedFormatRecord.FormatIndex = 43;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -2048;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 17:
extendedFormatRecord.FontIndex = 1;
extendedFormatRecord.FormatIndex = 41;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -2048;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 18:
extendedFormatRecord.FontIndex = 1;
extendedFormatRecord.FormatIndex = 44;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -2048;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 19:
extendedFormatRecord.FontIndex = 1;
extendedFormatRecord.FormatIndex = 42;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -2048;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 20:
extendedFormatRecord.FontIndex = 1;
extendedFormatRecord.FormatIndex = 9;
extendedFormatRecord.CellOptions = -11;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = -2048;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 21:
extendedFormatRecord.FontIndex = 5;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = 1;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = 2048;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 22:
extendedFormatRecord.FontIndex = 6;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = 1;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = 23552;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 23:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 49;
extendedFormatRecord.CellOptions = 1;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = 23552;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 24:
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 8;
extendedFormatRecord.CellOptions = 1;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = 23552;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
case 25:
extendedFormatRecord.FontIndex = 6;
extendedFormatRecord.FormatIndex = 8;
extendedFormatRecord.CellOptions = 1;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = 23552;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
break;
}
return extendedFormatRecord;
}
/// Creates an default cell type ExtendedFormatRecord object.
/// @return ExtendedFormatRecord with intial defaults (cell-type)
private static ExtendedFormatRecord CreateExtendedFormat()
{
ExtendedFormatRecord extendedFormatRecord = new ExtendedFormatRecord();
extendedFormatRecord.FontIndex = 0;
extendedFormatRecord.FormatIndex = 0;
extendedFormatRecord.CellOptions = 1;
extendedFormatRecord.AlignmentOptions = 32;
extendedFormatRecord.IndentionOptions = 0;
extendedFormatRecord.BorderOptions = 0;
extendedFormatRecord.PaletteOptions = 0;
extendedFormatRecord.AdtlPaletteOptions = 0;
extendedFormatRecord.FillPaletteOptions = 8384;
extendedFormatRecord.TopBorderPaletteIdx = 8;
extendedFormatRecord.BottomBorderPaletteIdx = 8;
extendedFormatRecord.LeftBorderPaletteIdx = 8;
extendedFormatRecord.RightBorderPaletteIdx = 8;
return extendedFormatRecord;
}
/// Creates a new StyleRecord, for the given Extended
/// Format index, and adds it onto the end of the
/// records collection
public StyleRecord CreateStyleRecord(int xfIndex)
{
StyleRecord styleRecord = new StyleRecord();
styleRecord.XFIndex = (short)xfIndex;
int num = -1;
for (int i = records.Xfpos; i < records.Count; i++)
{
if (num != -1)
{
break;
}
NPOI.HSSF.Record.Record record = records[i];
if (!(record is ExtendedFormatRecord) && !(record is StyleRecord))
{
num = i;
}
}
if (num == -1)
{
throw new InvalidOperationException("No XF Records found!");
}
records.Add(num, styleRecord);
return styleRecord;
}
/// Creates a StyleRecord object
/// @param id the number of the style record to Create (meaning its position in
/// a file as MS Excel would Create it.
/// @return record containing a StyleRecord
/// @see org.apache.poi.hssf.record.StyleRecord
/// @see org.apache.poi.hssf.record.Record
private static NPOI.HSSF.Record.Record CreateStyle(int id)
{
StyleRecord styleRecord = new StyleRecord();
switch (id)
{
case 0:
styleRecord.XFIndex = -32752;
styleRecord.SetBuiltinStyle(3);
styleRecord.OutlineStyleLevel = 255;
break;
case 1:
styleRecord.XFIndex = -32751;
styleRecord.SetBuiltinStyle(6);
styleRecord.OutlineStyleLevel = 255;
break;
case 2:
styleRecord.XFIndex = -32750;
styleRecord.SetBuiltinStyle(4);
styleRecord.OutlineStyleLevel = 255;
break;
case 3:
styleRecord.XFIndex = -32749;
styleRecord.SetBuiltinStyle(7);
styleRecord.OutlineStyleLevel = 255;
break;
case 4:
styleRecord.XFIndex = short.MinValue;
styleRecord.SetBuiltinStyle(0);
styleRecord.OutlineStyleLevel = 255;
break;
case 5:
styleRecord.XFIndex = -32748;
styleRecord.SetBuiltinStyle(5);
styleRecord.OutlineStyleLevel = 255;
break;
}
return styleRecord;
}
/// Creates a palette record initialized to the default palette
/// @return a PaletteRecord instance populated with the default colors
/// @see org.apache.poi.hssf.record.PaletteRecord
private static PaletteRecord CreatePalette()
{
return new PaletteRecord();
}
/// Creates the UseSelFS object with the use natural language flag Set to 0 (false)
/// @return record containing a UseSelFSRecord
/// @see org.apache.poi.hssf.record.UseSelFSRecord
/// @see org.apache.poi.hssf.record.Record
private static UseSelFSRecord CreateUseSelFS()
{
return new UseSelFSRecord(b: false);
}
/// Create a "bound sheet" or "bundlesheet" (depending who you ask) record
/// Always Sets the sheet's bof to 0. You'll need to Set that yourself.
/// @param id either sheet 0,1 or 2.
/// @return record containing a BoundSheetRecord
/// @see org.apache.poi.hssf.record.BoundSheetRecord
/// @see org.apache.poi.hssf.record.Record
private static NPOI.HSSF.Record.Record CreateBoundSheet(int id)
{
return new BoundSheetRecord("Sheet" + (id + 1));
}
/// Creates the Country record with the default country Set to 1
/// and current country Set to 7 in case of russian locale ("ru_RU") and 1 otherwise
/// @return record containing a CountryRecord
/// @see org.apache.poi.hssf.record.CountryRecord
/// @see org.apache.poi.hssf.record.Record
private static NPOI.HSSF.Record.Record CreateCountry()
{
CountryRecord countryRecord = new CountryRecord();
countryRecord.DefaultCountry = 1;
if (Thread.CurrentThread.CurrentCulture.Name.Equals("ru_RU"))
{
countryRecord.CurrentCountry = 7;
}
else
{
countryRecord.CurrentCountry = 1;
}
return countryRecord;
}
/// Creates the ExtendedSST record with numstrings per bucket Set to 0x8. HSSF
/// doesn't yet know what to do with this thing, but we Create it with nothing in
/// it hardly just to make Excel happy and our sheets look like Excel's
///
/// @return record containing an ExtSSTRecord
/// @see org.apache.poi.hssf.record.ExtSSTRecord
/// @see org.apache.poi.hssf.record.Record
private static NPOI.HSSF.Record.Record CreateExtendedSST()
{
ExtSSTRecord extSSTRecord = new ExtSSTRecord();
extSSTRecord.NumStringsPerBucket = 8;
return extSSTRecord;
}
/// Finds the sheet name by his extern sheet index
/// @param num extern sheet index
/// @return sheet name
public string FindSheetNameFromExternSheet(int externSheetIndex)
{
int indexToInternalSheet = linkTable.GetIndexToInternalSheet(externSheetIndex);
if (indexToInternalSheet < 0)
{
return "";
}
if (indexToInternalSheet >= boundsheets.Count)
{
return "";
}
return GetSheetName(indexToInternalSheet);
}
/// Finds the sheet index for a particular external sheet number.
/// @param externSheetNumber The external sheet number to Convert
/// @return The index to the sheet found.
public int GetSheetIndexFromExternSheetIndex(int externSheetNumber)
{
return linkTable.GetSheetIndexFromExternSheetIndex(externSheetNumber);
}
/// returns the extern sheet number for specific sheet number ,
/// if this sheet doesn't exist in extern sheet , Add it
/// @param sheetNumber sheet number
/// @return index to extern sheet
public int CheckExternSheet(int sheetNumber)
{
return OrCreateLinkTable.CheckExternSheet(sheetNumber);
}
public int GetExternalSheetIndex(string workbookName, string sheetName)
{
return OrCreateLinkTable.GetExternalSheetIndex(workbookName, sheetName);
}
/// @param name the name of an external function, typically a name of a UDF
/// @param udf locator of user-defiend functions to resolve names of VBA and Add-In functions
/// @return the external name or null
public NameXPtg GetNameXPtg(string name, UDFFinder udf)
{
LinkTable orCreateLinkTable = OrCreateLinkTable;
NameXPtg nameXPtg = orCreateLinkTable.GetNameXPtg(name);
if (nameXPtg == null && udf.FindFunction(name) != null)
{
nameXPtg = orCreateLinkTable.AddNameXPtg(name);
}
return nameXPtg;
}
/// Gets the name record
/// @param index name index
/// @return name record
public NameRecord GetNameRecord(int index)
{
return linkTable.GetNameRecord(index);
}
/// Creates new name
/// @return new name record
public NameRecord CreateName()
{
return AddName(new NameRecord());
}
/// Creates new name
/// @return new name record
public NameRecord AddName(NameRecord name)
{
OrCreateLinkTable.AddName(name);
return name;
}
/// Generates a NameRecord to represent a built-in region
/// @return a new NameRecord Unless the index is invalid
public NameRecord CreateBuiltInName(byte builtInName, int index)
{
if (index == -1 || index + 1 > 32767)
{
throw new ArgumentException("Index is not valid [" + index + "]");
}
NameRecord nameRecord = new NameRecord(builtInName, (short)index);
AddName(nameRecord);
return nameRecord;
}
/// Removes the name
/// @param namenum name index
public void RemoveName(int namenum)
{
if (linkTable.NumNames > namenum)
{
int num = FindFirstRecordLocBySid(24);
records.Remove(num + namenum);
linkTable.RemoveName(namenum);
}
}
/// If a {@link NameCommentRecord} is added or the name it references
/// is renamed, then this will update the lookup cache for it.
public void UpdateNameCommentRecordCache(NameCommentRecord commentRecord)
{
if (commentRecords.ContainsValue(commentRecord))
{
foreach (KeyValuePair<string, NameCommentRecord> commentRecord2 in commentRecords)
{
if (commentRecord2.Value.Equals(commentRecord))
{
commentRecords.Remove(commentRecord2.Key);
break;
}
}
}
commentRecords[commentRecord.NameText] = commentRecord;
}
/// Returns a format index that matches the passed in format. It does not tie into HSSFDataFormat.
/// @param format the format string
/// @param CreateIfNotFound Creates a new format if format not found
/// @return the format id of a format that matches or -1 if none found and CreateIfNotFound
public short GetFormat(string format, bool CreateIfNotFound)
{
IEnumerator enumerator = formats.GetEnumerator();
while (enumerator.MoveNext())
{
FormatRecord formatRecord = (FormatRecord)enumerator.Current;
if (formatRecord.FormatString.Equals(format))
{
return (short)formatRecord.IndexCode;
}
}
if (CreateIfNotFound)
{
return (short)CreateFormat(format);
}
return -1;
}
/// Creates a FormatRecord, Inserts it, and returns the index code.
/// @param format the format string
/// @return the index code of the format record.
/// @see org.apache.poi.hssf.record.FormatRecord
/// @see org.apache.poi.hssf.record.Record
public int CreateFormat(string formatString)
{
maxformatid = ((maxformatid >= 164) ? ((short)(maxformatid + 1)) : 164);
FormatRecord formatRecord = new FormatRecord(maxformatid, formatString);
int i;
for (i = 0; i < records.Count && records[i].Sid != 1054; i++)
{
}
i += formats.Count;
formats.Add(formatRecord);
records.Add(i, formatRecord);
return maxformatid;
}
/// Creates a FormatRecord object
/// @param id the number of the format record to create (meaning its position in
/// a file as M$ Excel would create it.)
private static FormatRecord CreateFormat(int id)
{
switch (id)
{
case 0:
return new FormatRecord(5, BuiltinFormats.GetBuiltinFormat(5));
case 1:
return new FormatRecord(6, BuiltinFormats.GetBuiltinFormat(6));
case 2:
return new FormatRecord(7, BuiltinFormats.GetBuiltinFormat(7));
case 3:
return new FormatRecord(8, BuiltinFormats.GetBuiltinFormat(8));
case 4:
return new FormatRecord(42, BuiltinFormats.GetBuiltinFormat(42));
case 5:
return new FormatRecord(41, BuiltinFormats.GetBuiltinFormat(41));
case 6:
return new FormatRecord(44, BuiltinFormats.GetBuiltinFormat(44));
case 7:
return new FormatRecord(43, BuiltinFormats.GetBuiltinFormat(43));
default:
throw new ArgumentException("Unexpected id " + id);
}
}
/// Returns the first occurance of a record matching a particular sid.
public NPOI.HSSF.Record.Record FindFirstRecordBySid(short sid)
{
IEnumerator enumerator = records.GetEnumerator();
while (enumerator.MoveNext())
{
NPOI.HSSF.Record.Record record = (NPOI.HSSF.Record.Record)enumerator.Current;
if (record.Sid == sid)
{
return record;
}
}
return null;
}
/// Returns the index of a record matching a particular sid.
/// @param sid The sid of the record to match
/// @return The index of -1 if no match made.
public int FindFirstRecordLocBySid(short sid)
{
int num = 0;
IEnumerator enumerator = records.GetEnumerator();
while (enumerator.MoveNext())
{
NPOI.HSSF.Record.Record record = (NPOI.HSSF.Record.Record)enumerator.Current;
if (record.Sid == sid)
{
return num;
}
num++;
}
return -1;
}
/// Returns the next occurance of a record matching a particular sid.
public NPOI.HSSF.Record.Record FindNextRecordBySid(short sid, int pos)
{
int num = 0;
IEnumerator enumerator = records.GetEnumerator();
while (enumerator.MoveNext())
{
NPOI.HSSF.Record.Record record = (NPOI.HSSF.Record.Record)enumerator.Current;
if (record.Sid == sid && num++ == pos)
{
return record;
}
}
return null;
}
/// Finds the primary drawing Group, if one already exists
public DrawingManager2 FindDrawingGroup()
{
if (drawingManager != null)
{
return drawingManager;
}
IEnumerator enumerator = records.GetEnumerator();
while (enumerator.MoveNext())
{
NPOI.HSSF.Record.Record record = (NPOI.HSSF.Record.Record)enumerator.Current;
if (record is DrawingGroupRecord)
{
DrawingGroupRecord drawingGroupRecord = (DrawingGroupRecord)record;
drawingGroupRecord.ProcessChildRecords();
EscherContainerRecord escherContainer = drawingGroupRecord.GetEscherContainer();
if (escherContainer != null)
{
EscherDggRecord escherDggRecord = null;
EscherContainerRecord escherContainerRecord = null;
IEnumerator enumerator2 = escherContainer.ChildRecords.GetEnumerator();
while (enumerator2.MoveNext())
{
EscherRecord escherRecord = (EscherRecord)enumerator2.Current;
if (escherRecord is EscherDggRecord)
{
escherDggRecord = (EscherDggRecord)escherRecord;
}
else if (escherRecord.RecordId == -4095)
{
escherContainerRecord = (EscherContainerRecord)escherRecord;
}
}
if (escherDggRecord != null)
{
drawingManager = new DrawingManager2(escherDggRecord);
if (escherContainerRecord != null)
{
foreach (EscherRecord childRecord in escherContainerRecord.ChildRecords)
{
if (childRecord is EscherBSERecord)
{
escherBSERecords.Add((EscherBSERecord)childRecord);
}
}
}
return drawingManager;
}
}
}
}
int num = FindFirstRecordLocBySid(235);
if (num != -1)
{
DrawingGroupRecord drawingGroupRecord2 = (DrawingGroupRecord)records[num];
EscherDggRecord escherDggRecord2 = null;
EscherContainerRecord escherContainerRecord2 = null;
IEnumerator enumerator4 = drawingGroupRecord2.EscherRecords.GetEnumerator();
while (enumerator4.MoveNext())
{
EscherRecord escherRecord2 = (EscherRecord)enumerator4.Current;
if (escherRecord2 is EscherDggRecord)
{
escherDggRecord2 = (EscherDggRecord)escherRecord2;
}
else if (escherRecord2.RecordId == -4095)
{
escherContainerRecord2 = (EscherContainerRecord)escherRecord2;
}
}
if (escherDggRecord2 != null)
{
drawingManager = new DrawingManager2(escherDggRecord2);
if (escherContainerRecord2 != null)
{
foreach (EscherRecord childRecord2 in escherContainerRecord2.ChildRecords)
{
if (childRecord2 is EscherBSERecord)
{
escherBSERecords.Add((EscherBSERecord)childRecord2);
}
}
}
}
}
return drawingManager;
}
/// Creates a primary drawing Group record. If it already
/// exists then it's modified.
public void CreateDrawingGroup()
{
if (drawingManager == null)
{
EscherContainerRecord escherContainerRecord = new EscherContainerRecord();
EscherDggRecord escherDggRecord = new EscherDggRecord();
EscherOptRecord escherOptRecord = new EscherOptRecord();
EscherSplitMenuColorsRecord escherSplitMenuColorsRecord = new EscherSplitMenuColorsRecord();
escherContainerRecord.RecordId = -4096;
escherContainerRecord.Options = 15;
escherDggRecord.RecordId = -4090;
escherDggRecord.Options = 0;
escherDggRecord.ShapeIdMax = 1024;
escherDggRecord.NumShapesSaved = 0;
escherDggRecord.DrawingsSaved = 0;
escherDggRecord.FileIdClusters = new EscherDggRecord.FileIdCluster[0];
drawingManager = new DrawingManager2(escherDggRecord);
EscherContainerRecord escherContainerRecord2 = null;
if (escherBSERecords.Count > 0)
{
escherContainerRecord2 = new EscherContainerRecord();
escherContainerRecord2.RecordId = -4095;
escherContainerRecord2.Options = (short)((escherBSERecords.Count << 4) | 0xF);
IEnumerator enumerator = escherBSERecords.GetEnumerator();
while (enumerator.MoveNext())
{
EscherRecord record = (EscherRecord)enumerator.Current;
escherContainerRecord2.AddChildRecord(record);
}
}
escherOptRecord.RecordId = -4085;
escherOptRecord.Options = 51;
escherOptRecord.AddEscherProperty(new EscherBoolProperty(191, 524296));
escherOptRecord.AddEscherProperty(new EscherRGBProperty(385, 134217793));
escherOptRecord.AddEscherProperty(new EscherRGBProperty(448, 134217792));
escherSplitMenuColorsRecord.RecordId = -3810;
escherSplitMenuColorsRecord.Options = 64;
escherSplitMenuColorsRecord.Color1 = 134217741;
escherSplitMenuColorsRecord.Color2 = 134217740;
escherSplitMenuColorsRecord.Color3 = 134217751;
escherSplitMenuColorsRecord.Color4 = 268435703;
escherContainerRecord.AddChildRecord(escherDggRecord);
if (escherContainerRecord2 != null)
{
escherContainerRecord.AddChildRecord(escherContainerRecord2);
}
escherContainerRecord.AddChildRecord(escherOptRecord);
escherContainerRecord.AddChildRecord(escherSplitMenuColorsRecord);
int num = FindFirstRecordLocBySid(235);
if (num == -1)
{
DrawingGroupRecord drawingGroupRecord = new DrawingGroupRecord();
drawingGroupRecord.AddEscherRecord(escherContainerRecord);
int num2 = FindFirstRecordLocBySid(140);
Records.Insert(num2 + 1, drawingGroupRecord);
}
else
{
DrawingGroupRecord drawingGroupRecord2 = new DrawingGroupRecord();
drawingGroupRecord2.AddEscherRecord(escherContainerRecord);
Records[num] = drawingGroupRecord2;
}
}
}
/// Removes the given font record from the
/// file's list. This will make all
/// subsequent font indicies drop by one,
/// so you'll need to update those yourself!
public void RemoveFontRecord(FontRecord rec)
{
records.Remove(rec);
numfonts--;
}
/// Removes the given ExtendedFormatRecord record from the
/// file's list. This will make all
/// subsequent font indicies drop by one,
/// so you'll need to update those yourself!
public void RemoveExFormatRecord(ExtendedFormatRecord rec)
{
records.Remove(rec);
numxfs--;
}
/// <summary>
/// Removes ExtendedFormatRecord record with given index from the file's list. This will make all
/// subsequent font indicies drop by one,so you'll need to update those yourself!
/// </summary>
/// <param name="index">index of the Extended format record (0-based)</param>
public void RemoveExFormatRecord(int index)
{
int pos = records.Xfpos - (numxfs - 1) + index;
records.Remove(pos);
numxfs--;
}
public EscherBSERecord GetBSERecord(int pictureIndex)
{
return (EscherBSERecord)escherBSERecords[pictureIndex - 1];
}
public int AddBSERecord(EscherBSERecord e)
{
CreateDrawingGroup();
escherBSERecords.Add(e);
int index = FindFirstRecordLocBySid(235);
DrawingGroupRecord drawingGroupRecord = (DrawingGroupRecord)Records[index];
EscherContainerRecord escherContainerRecord = (EscherContainerRecord)drawingGroupRecord.GetEscherRecord(0);
EscherContainerRecord escherContainerRecord2;
if (escherContainerRecord.GetChild(1).RecordId == -4095)
{
escherContainerRecord2 = (EscherContainerRecord)escherContainerRecord.GetChild(1);
}
else
{
escherContainerRecord2 = new EscherContainerRecord();
escherContainerRecord2.RecordId = -4095;
List<EscherRecord> childRecords = escherContainerRecord.ChildRecords;
childRecords.Insert(1, escherContainerRecord2);
escherContainerRecord.ChildRecords = childRecords;
}
escherContainerRecord2.Options = (short)((escherBSERecords.Count << 4) | 0xF);
escherContainerRecord2.AddChildRecord(e);
return escherBSERecords.Count;
}
/// protect a workbook with a password (not encypted, just Sets Writeprotect
/// flags and the password.
/// @param password to Set
public void WriteProtectWorkbook(string password, string username)
{
FileSharingRecord fileSharing = FileSharing;
WriteAccessRecord writeAccessRecord = WriteAccess;
WriteProtectRecord writeProtect2 = WriteProtect;
fileSharing.ReadOnly = 1;
fileSharing.Password = FileSharingRecord.HashPassword(password);
fileSharing.Username = username;
writeAccessRecord.Username = username;
}
/// Removes the Write protect flag
public void UnwriteProtectWorkbook()
{
records.Remove(fileShare);
records.Remove(WriteProtect);
fileShare = null;
writeProtect = null;
}
/// @param reFindex Index to REF entry in EXTERNSHEET record in the Link Table
/// @param definedNameIndex zero-based to DEFINEDNAME or EXTERNALNAME record
/// @return the string representation of the defined or external name
public string ResolveNameXText(int reFindex, int definedNameIndex)
{
return linkTable.ResolveNameXText(reFindex, definedNameIndex);
}
public NameRecord CloneFilter(int filterDbNameIndex, int newSheetIndex)
{
NameRecord nameRecord = GetNameRecord(filterDbNameIndex);
int externSheetIndex = CheckExternSheet(newSheetIndex);
Ptg[] nameDefinition = nameRecord.NameDefinition;
for (int i = 0; i < nameDefinition.Length; i++)
{
Ptg ptg = nameDefinition[i];
if (ptg is Area3DPtg)
{
Area3DPtg area3DPtg = (Area3DPtg)((OperandPtg)ptg).Copy();
area3DPtg.ExternSheetIndex = externSheetIndex;
nameDefinition[i] = area3DPtg;
}
else if (ptg is Ref3DPtg)
{
Ref3DPtg ref3DPtg = (Ref3DPtg)((OperandPtg)ptg).Copy();
ref3DPtg.ExternSheetIndex = externSheetIndex;
nameDefinition[i] = ref3DPtg;
}
}
NameRecord nameRecord2 = CreateBuiltInName(13, newSheetIndex + 1);
nameRecord2.NameDefinition = nameDefinition;
nameRecord2.IsHiddenName = true;
return nameRecord2;
}
/// Updates named ranges due to moving of cells
public void UpdateNamesAfterCellShift(FormulaShifter shifter)
{
for (int i = 0; i < NumNames; i++)
{
NameRecord nameRecord = GetNameRecord(i);
Ptg[] nameDefinition = nameRecord.NameDefinition;
if (shifter.AdjustFormula(nameDefinition, nameRecord.SheetNumber))
{
nameRecord.NameDefinition = nameDefinition;
}
}
}
/// Changes an external referenced file to another file.
/// A formular in Excel which refers a cell in another file is saved in two parts:
/// The referenced file is stored in an reference table. the row/cell information is saved separate.
/// This method invokation will only change the reference in the lookup-table itself.
/// @param oldUrl The old URL to search for and which is to be replaced
/// @param newUrl The URL replacement
/// @return true if the oldUrl was found and replaced with newUrl. Otherwise false
public bool ChangeExternalReference(string oldUrl, string newUrl)
{
return linkTable.ChangeExternalReference(oldUrl, newUrl);
}
}
}
| 32.63422 | 171 | 0.703783 | [
"MIT"
] | iNeverSleeeeep/NPOI-For-Unity | NPOI.HSSF.Model/InternalWorkbook.cs | 76,103 | C# |
using System.Threading.Tasks;
using CodeTest.Accounting.BFF.Models;
using CodeTest.Accounting.ServiceClients;
using Microsoft.Extensions.Logging;
namespace CodeTest.Accounting.BFF.Core
{
public class AccountsOrchestrator
{
private readonly ILogger<AccountsOrchestrator> _logger;
private readonly AccountsServiceClient _accountsServiceClient;
private readonly CustomersServiceClient _customersServiceClient;
private readonly TransactionsServiceClient _transactionsServiceClient;
public AccountsOrchestrator(
ILogger<AccountsOrchestrator> logger,
AccountsServiceClient accountsServiceClient,
CustomersServiceClient customersServiceClient,
TransactionsServiceClient transactionsServiceClient)
{
_logger = logger;
_accountsServiceClient = accountsServiceClient;
_customersServiceClient = customersServiceClient;
_transactionsServiceClient = transactionsServiceClient;
}
public async Task OpenAccountAsync(OpenAccountDto input)
{
if (!await CheckCustomerValidity(input))
{
throw new CustomerNotValidException();
}
var account = await _accountsServiceClient.PostAsync(new AccountDto
{
CustomerId = input.CustomerId,
InitialCredit = input.InitialCredit
});
// if the account balance is positive, create a new transaction
if (input.InitialCredit.HasValue && input.InitialCredit.Value > 0)
{
await _transactionsServiceClient.PostAsync(new TransactionDto
{
AccountId = account.Id,
Amount = input.InitialCredit.Value
});
}
}
private async Task<bool> CheckCustomerValidity(OpenAccountDto input)
{
try
{
var customer = await _customersServiceClient.GetAsync(input.CustomerId);
// we can do more validity checks here
if (customer == null)
{
return false;
}
return true;
}
catch (CustomerApiException e)
{
_logger.LogError(e, "Error received from Consumers service");
return false;
}
}
}
}
| 33.418919 | 88 | 0.599272 | [
"MIT"
] | andreicojocaru/codetest-accounting | src/CodeTest.Accounting.BFF/Core/AccountsOrchestrator.cs | 2,475 | C# |
using System;
using UnityEngine;
using System.Collections;
public class InputManagerScript : MonoBehaviour {
private GameManagerScript _gameManager;
private MoveTokensScript _moveManager;
private GameObject _selected = null;
public Camera camera;
public virtual void Start () {
_moveManager = GetComponent<MoveTokensScript>();
_gameManager = GetComponent<GameManagerScript>();
}
public virtual void SelectToken(){
if (!Input.GetMouseButtonDown(0)) return;
var mousePos = camera.ScreenToWorldPoint(Input.mousePosition);
<<<<<<< HEAD
Collider2D collider = Physics2D.OverlapPoint(mousePos);
if(collider != null){
if(_selected == null){
_selected = collider.gameObject;//I'm not 100% sure what this line means.
//I think it's saying that if the collider doesn't overlap with something (the sprite?) then the gameObj is null.
} else {
Vector2 pos1 = _gameManager.GetPositionOfTokenInGrid(_selected);
Vector2 pos2 = _gameManager.GetPositionOfTokenInGrid(collider.gameObject);
//I think this is saying that if the position of the token and the position of the collider match up, then use the MoveTokenScript to swap the tokens.
if(Mathf.Abs((pos1.x - pos2.x) + (pos1.y - pos2.y)) == 1){
_moveManager.SetupTokenExchange(_selected, pos1, collider.gameObject, pos2, true);
}
_selected = null;
}
=======
var overlapPoint = Physics2D.OverlapPoint(mousePos);
if (ReferenceEquals(overlapPoint, null)) return;
if(ReferenceEquals(_selected, null))
{
_selected = overlapPoint.gameObject;
}
else
{
var pos1 = _gameManager.GetPositionOfTokenInGrid(_selected);
var pos2 = _gameManager.GetPositionOfTokenInGrid(overlapPoint.gameObject);
if(Math.Abs(Mathf.Abs((pos1.x - pos2.x) + (pos1.y - pos2.y)) - 1) < 0.01f){
_moveManager.SetupTokenExchange(_selected, pos1, overlapPoint.gameObject, pos2, true);
>>>>>>> origin/master
}
<<<<<<< HEAD
}
public int CommentFunc(int x, int y){
return x - y;//I have a better understanding of return statements but I'm still sort of iffy on it.
//I mean this is InputManager and the return is the input but where is that input going?
//what is x and y referring to? The x/y axis? The pos1.x/y? Those are the same maybe?
//Is there a debug tool that can help with that?
Debug.Log("Input Manager return statement");
//I guess this doesn't work.
=======
_selected = null;
}
>>>>>>> origin/master
}
}
| 34.226667 | 156 | 0.68173 | [
"Unlicense"
] | VaWilkerson/VirginiaWilkerson | Match 3/Assets/Scripts/InputManagerScript.cs | 2,569 | C# |
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace Timesheets.Data
{
[Table("time_entries")]
public class TimeEntryRecord
{
[Column("id")] public long Id { get; private set; }
[Column("project_id")] public long ProjectId { get; private set; }
[Column("user_id")] public long UserId { get; private set; }
[Column("date")] public DateTime Date { get; private set; }
[Column("hours")] public int Hours { get; private set; }
private TimeEntryRecord()
{
}
public TimeEntryRecord(long projectId, long userId, DateTime date, int hours) :
this(default(long), projectId, userId, date, hours)
{
}
public TimeEntryRecord(long id, long projectId, long userId, DateTime date, int hours)
{
Id = id;
ProjectId = projectId;
UserId = userId;
Date = date;
Hours = hours;
}
}
} | 29.909091 | 94 | 0.579534 | [
"BSD-2-Clause"
] | vmware-tanzu-learning/pal-tracker-distributed-dotnet | Components/Timesheets/Data/TimeEntryRecord.cs | 987 | C# |
/*
* Avalon Mud Client
*
* @project lead : Blake Pell
* @website : http://www.blakepell.com
* @copyright : Copyright (c), 2018-2021 All rights reserved.
* @license : MIT
*/
namespace Avalon.Common.Scripting
{
/// <summary>
/// A class that tracks statistics for the scripting environment as a whole.
/// </summary>
public class ScriptStatistics : INotifyPropertyChanged
{
/// <summary>
/// An object for thread locking access to resources.
/// </summary>
private object _lockObject = new();
private int _scriptsActive = 0;
/// <summary>
/// The number of scripts that are currently active in the <see cref="ScriptHost"/>.
/// </summary>
public int ScriptsActive
{
get => _scriptsActive;
set
{
lock (_lockObject)
{
_scriptsActive = value;
}
OnPropertyChanged(nameof(ScriptsActive));
}
}
private int _runCount = 0;
/// <summary>
/// The total number of scripts that have been run.
/// </summary>
public int RunCount
{
get => _runCount;
set
{
lock (_lockObject)
{
_runCount = value;
}
OnPropertyChanged(nameof(RunCount));
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChanged?.Invoke(this, e);
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| 25.724638 | 92 | 0.509296 | [
"MIT"
] | blakepell/AvalonMudClient | src/Avalon.Common/Scripting/ScriptStatistics.cs | 1,777 | C# |
using System;
using System.Collections.Generic;
#nullable disable
namespace api.Models.Ttv
{
public partial class DimOrganisationMedium
{
public int DimOrganizationId { get; set; }
public string MediaUri { get; set; }
public string LanguageVariant { get; set; }
public string SourceId { get; set; }
public string SourceDescription { get; set; }
public DateTime? Created { get; set; }
public DateTime? Modified { get; set; }
public virtual DimOrganization DimOrganization { get; set; }
}
}
| 27.095238 | 68 | 0.652021 | [
"MIT"
] | CSCfi/research-fi-mydata | aspnetcore/src/api/Models/Ttv/DimOrganisationMedium.cs | 571 | 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
#region Usings
using System;
using System.Collections.Generic;
#endregion
namespace DotNetNuke.Common.Utilities
{
/// <summary>
/// Extensions for enumeration of KeyValue Paire
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// To the key value pairs.
/// </summary>
/// <param name="enumType">Type of the enum defined by GetType.</param>
/// <returns>A list of Key Value pairs</returns>
public static List<KeyValuePair<int, string>> ToKeyValuePairs(this Enum enumType)
{
var pairs = new List<KeyValuePair<int, string>>();
var names = Enum.GetNames(enumType.GetType());
var values = Enum.GetValues(enumType.GetType());
for (var i = 0; i < values.Length; i++)
{
pairs.Add(new KeyValuePair<int, string>((int) values.GetValue(i), names[i]));
}
return pairs;
}
}
}
| 33.055556 | 93 | 0.602521 | [
"MIT"
] | MaiklT/Dnn.Platform | DNN Platform/Library/Common/Utilities/EnumExtensions.cs | 1,192 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using URSA.Web.Mapping;
namespace URSA.Web.Description.Http
{
internal class UriTemplateBuilder : ICloneable
{
internal static readonly Regex VariableTemplateRegex = new Regex("\\{(?<ExpansionType>[/?&#\\.;])*(?<ParameterName>[^*}]+)(?<ListIndicator>[*]*)\\}");
private readonly bool _isRegexMode;
private readonly Type _controlledEntityType;
private readonly SegmentList _segments;
private readonly QueryStringList _queryString;
internal UriTemplateBuilder(Type controlledEntityType, bool isRegexMode = false)
: this(new SegmentList(controlledEntityType, isRegexMode), new QueryStringList(controlledEntityType, isRegexMode), controlledEntityType, isRegexMode)
{
}
private UriTemplateBuilder(SegmentList segments, QueryStringList queryString, Type controlledEntityType, bool isRegexMode = false)
{
_controlledEntityType = controlledEntityType;
_isRegexMode = isRegexMode;
_segments = segments;
_queryString = queryString;
}
internal string Segments { get { return _segments.ToString(); } }
internal string QueryString { get { return _queryString.ToString(); } }
/// <summary>Performs an implicit conversion from <see cref="UriTemplateBuilder"/> to <see cref="String"/>.</summary>
/// <param name="uriTemplate">The URI template.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator String(UriTemplateBuilder uriTemplate)
{
return uriTemplate == null ? null : uriTemplate.ToString();
}
/// <inheritdoc />
public override string ToString()
{
return String.Format("{0}{1}{2}", (_isRegexMode ? String.Empty : "/"), Segments, QueryString);
}
/// <summary>Returns a <see cref="System.String" /> that represents this instance.</summary>
/// <param name="withQueryString">If set to <c>true</c> with query string; otherwise without.</param>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
public string ToString(bool withQueryString)
{
return (withQueryString ? ToString() : String.Format("{0}{1}", (_isRegexMode ? String.Empty : "/"), Segments));
}
/// <inheritdoc />
object ICloneable.Clone()
{
return Clone();
}
internal void Add(string part, MappingAttribute source, ICustomAttributeProvider member, bool hasDefaultValue = false)
{
part = (_isRegexMode ? ((source is FromQueryStringAttribute) ? part.Replace("=[^&]+", String.Empty) : part) : part).Trim('/');
if (part.Length == 0)
{
return;
}
(source is FromQueryStringAttribute ? (UriTemplatePartList)_queryString : _segments).Add(part, source, member, hasDefaultValue);
}
internal UriTemplateBuilder Clone(bool? isRegexMode = null)
{
return new UriTemplateBuilder(
new SegmentList(_controlledEntityType, isRegexMode ?? _isRegexMode, _segments),
new QueryStringList(_controlledEntityType, isRegexMode ?? _isRegexMode, _queryString),
_controlledEntityType,
isRegexMode ?? _isRegexMode);
}
internal class UriTemplatePart
{
internal UriTemplatePart(string part, MappingAttribute source, ICustomAttributeProvider member, bool hasDefaultValue = false)
{
Part = ((source is FromQueryStringAttribute) && (part[0] == '&') ? part.Substring(1) : part);
Source = source;
Member = member;
HasDefaultValue = hasDefaultValue;
}
internal string Part { get; private set; }
internal MappingAttribute Source { get; private set; }
internal ICustomAttributeProvider Member { get; private set; }
internal bool HasDefaultValue { get; private set; }
/// <inheritdoc />
[ExcludeFromCodeCoverage]
[SuppressMessage("Microsoft.Design", "CA0000:ExcludeFromCodeCoverage", Justification = "No testable logic.")]
public override string ToString()
{
return Part;
}
}
internal abstract class UriTemplatePartList : List<UriTemplatePart>
{
protected UriTemplatePartList(Type controlledEntityType, bool isRegexMode, IEnumerable<UriTemplatePart> parts = null) : base(parts ?? new UriTemplatePart[0])
{
ControlledEntityType = controlledEntityType;
IsRegexMode = isRegexMode;
}
protected Type ControlledEntityType { get; private set; }
protected bool IsRegexMode { get; private set; }
internal virtual void Add(string part, MappingAttribute source, ICustomAttributeProvider member, bool hasDefaultValue = false)
{
Add(new UriTemplatePart(part, source, member, hasDefaultValue));
}
}
internal class SegmentList : UriTemplatePartList
{
internal SegmentList(Type controlledEntityType, bool isRegexMode, IEnumerable<UriTemplatePart> parts = null) : base(controlledEntityType, isRegexMode, parts)
{
}
/// <inheritdoc />
public override string ToString()
{
if (Count == 0)
{
return String.Empty;
}
if (!IsRegexMode)
{
return String.Join("/", this.Select(segment => segment.Part));
}
StringBuilder result = new StringBuilder(256);
foreach (var segment in this)
{
result.AppendFormat("{0}/{1}{2}", (segment.HasDefaultValue ? "(" : String.Empty), segment.Part, (segment.HasDefaultValue ? ")?" : String.Empty));
}
return result.ToString();
}
internal override void Add(string part, MappingAttribute source, ICustomAttributeProvider member, bool hasDefaultValue = false)
{
base.Add(part, source, member, hasDefaultValue);
if (ControlledEntityType == null)
{
return;
}
int indexOf = -1;
Type implementation;
var identifierSegment = this
.Where((item, index) => (item.Source is FromUrlAttribute) && (item.Member is ParameterInfo) &&
((implementation = ControlledEntityType.GetInterfaces().First(@interface => (@interface.IsGenericType) && (@interface.GetGenericTypeDefinition() == typeof(IControlledEntity<>)))) != null) &&
(((ParameterInfo)item.Member).ParameterType == implementation.GetProperty("Key").PropertyType) &&
((indexOf = index) != -1))
.FirstOrDefault();
if ((indexOf <= 1) || ((indexOf > 1) && (!(this[indexOf - 1].Member is MethodInfo))))
{
return;
}
this[indexOf] = this[indexOf - 1];
this[indexOf - 1] = identifierSegment;
}
}
internal class QueryStringList : UriTemplatePartList
{
internal QueryStringList(Type controlledEntityType, bool isRegexMode, IEnumerable<UriTemplatePart> parts = null) : base(controlledEntityType, isRegexMode, parts)
{
}
/// <inheritdoc />
[ExcludeFromCodeCoverage]
[SuppressMessage("Microsoft.Design", "CA0000:ExcludeFromCodeCoverage", Justification = "No testable logic.")]
public override string ToString()
{
if (Count == 0)
{
return String.Empty;
}
return (IsRegexMode ? AsRegularExpresion() : AsUrlTemplate());
}
private string AsRegularExpresion()
{
StringBuilder fixedParameters = new StringBuilder(128);
int optionalParameters = 0;
foreach (var parameter in this)
{
optionalParameters += ((parameter.HasDefaultValue) || (!((ParameterInfo)parameter.Member).ParameterType.IsValueType) ? 1 : 0);
var match = VariableTemplateRegex.Match(((FromQueryStringAttribute)parameter.Source).UrlTemplate);
var parameterName = match.Groups["ParameterName"].Value;
fixedParameters.Append(fixedParameters.Length == 0 ? "([?&](" : "|");
fixedParameters.Append(Regex.Escape(parameterName));
}
if (fixedParameters.Length > 0)
{
fixedParameters.AppendFormat(")=[^&]{0}){1}", (optionalParameters == 0 ? "+" : "*"), (optionalParameters == 0 ? "{1,}" : "{0,}"));
}
return fixedParameters.ToString();
}
private string AsUrlTemplate()
{
StringBuilder fixedParameters = new StringBuilder(128);
StringBuilder optionalParameters = new StringBuilder(128);
foreach (var parameter in this)
{
var match = VariableTemplateRegex.Match(((FromQueryStringAttribute)parameter.Source).UrlTemplate);
var parameterName = match.Groups["ParameterName"].Value;
if ((parameter.HasDefaultValue) || (!((ParameterInfo)parameter.Member).ParameterType.IsValueType))
{
optionalParameters.Append(optionalParameters.Length == 0 ? "{&" : ",");
optionalParameters.Append(parameterName + match.Groups["ListIndicator"].Value);
}
else
{
fixedParameters.Append("&");
fixedParameters.AppendFormat("{0}={{{0}}}", parameterName);
}
}
if (optionalParameters.Length > 0)
{
optionalParameters.Append("}");
}
if (fixedParameters.Length > 0)
{
fixedParameters.Remove(0, 1).Insert(0, "?");
}
else if (optionalParameters.Length > 0)
{
optionalParameters.Remove(1, 1).Insert(1, "?");
}
return fixedParameters.Append(optionalParameters).ToString();
}
}
}
} | 42.28626 | 214 | 0.561784 | [
"BSD-3-Clause"
] | CharlesOkwuagwu/URSA | URSA.Http/Description/UriTemplateBuilder.cs | 11,081 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
namespace ILCompiler.Compiler.CppCodeGen
{
/// <summary>
/// Similar to a StringBuilder but handles proper formatting of C/C++ code by supporting indentation.
///
/// Principle to remember: new lines have to be requested when the output needs to be on a new line.
/// When a new line is printed via <see cref="AppendLine"/> indentation is performed.
///
/// Use <see cref="Indent"/> and <see cref="Exdent"/> to increase/decrease the level of indentation.
/// </summary>
public class CppGenerationBuffer
{
/// <summary>
/// Initialize new instance
/// </summary>
public CppGenerationBuffer()
{
_builder = new StringBuilder();
}
/// <summary>
/// Level of indentation used so far.
/// </summary>
private int _indent;
/// <summary>
/// Builder where all additions are done.
/// </summary>
private StringBuilder _builder;
/// <summary>
/// Increase level of indentation by one.
/// </summary>
public void Indent()
{
_indent++;
}
/// <summary>
/// Decrease level of indentation by one.
/// </summary>
public void Exdent()
{
_indent--;
}
/// <summary>
/// Append string <param name="s"/> to content.
/// </summary>
/// <param name="s">String value to print.</param>
public void Append(string s)
{
_builder.Append(s);
}
/// <summary>
/// Append integer <param name="i"/> in decimal format to content.
/// </summary>
/// <param name="i">Integer value to print.</param>
public void Append(int i)
{
_builder.Append(i);
}
/// <summary>
/// Append character <param name="c"/> to content.
/// </summary>
/// <param name="c">Character value to print.</param>
public void Append(char c)
{
_builder.Append(c);
}
/// <summary>
/// Append an empty new line without emitting any indentation.
/// Useful to just skip a line.
/// </summary>
public void AppendEmptyLine()
{
_builder.AppendLine();
}
/// <summary>
/// Append an empty new line and the required number of tabs.
/// </summary>
public void AppendLine()
{
_builder.AppendLine();
for (int i = 0; i < _indent; i++)
_builder.Append('\t');
}
/// <summary>
/// Clear current content.
/// </summary>
public void Clear()
{
_builder.Clear();
}
/// <summary>
/// Export current content as a string.
/// </summary>
/// <returns>String representation of current content.</returns>
public override string ToString()
{
return _builder.ToString();
}
}
}
| 27.810345 | 105 | 0.517359 | [
"MIT"
] | AntonLapounov/corert | src/ILCompiler.CppCodeGen/src/CppCodeGen/CppGenerationBuffer.cs | 3,226 | 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("ProjetoModeloDDD.MVC")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProjetoModeloDDD.MVC")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8553fc33-34e9-4bfd-9d1f-dfd63b2c397a")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38 | 84 | 0.752924 | [
"Apache-2.0"
] | fabianomarcos/ASP-NET-MVC-MODELO-DDD | ProjetoModeloDDD/ProjetoModeloDDD.MVC/Properties/AssemblyInfo.cs | 1,371 | C# |
using MediatR;
namespace CompanyName.MyMeetings.Modules.Administration.Application.Contracts
{
public interface IQuery<out TResult> : IRequest<TResult>
{
}
} | 21.375 | 77 | 0.754386 | [
"MIT"
] | Ahmetcanb/modular-monolith-with-ddd | src/Modules/Administration/Application/Contracts/IQuery.cs | 173 | C# |
using System;
namespace UnhandledException
{
class Program
{
static void Main(string[] args)
{
Do();
DoNot();
}
private static void Do()
{
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
// You can catch unhandled exception without try/catch root execution point.
var ex = (Exception)e.ExceptionObject;
Console.WriteLine($"UnhandledException occured. {ex.GetType().FullName}, {ex.Message}, {ex.StackTrace}");
// if you want handle exception as normal, you may able to use Exit(int);
//Environment.Exit(1);
};
Hoge();
}
private static void DoNot()
{
try
{
// It may better avoid try/catch root execution for global escape.
Hoge()
}
catch (Exception ex)
{
Console.WriteLine($"UnhandledException occured. {ex.GetType().FullName}, {ex.Message}, {ex.StackTrace}");
}
}
private static void Hoge()
{
throw new Exception("");
}
}
}
| 26.869565 | 121 | 0.490291 | [
"MIT"
] | guitarrapc/CSharpPracticesLab | exception/UnhandledException/Program.cs | 1,236 | 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 ValidationCaseGenerator.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", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal 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)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ValidationCaseGenerator.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)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 43.890625 | 189 | 0.61659 | [
"Apache-2.0"
] | neerajmathur/UMETRIX | HostingApplication/Properties/Resources.Designer.cs | 2,811 | C# |
using MediatR;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using VisaD.Application.Common.Configurations;
namespace VisaD.Application.Users.Commands
{
public class CreateLoginTokenCommand : IRequest<string>
{
public int UserId { get; set; }
public string Username { get; set; }
public string OrganizationName { get; set; }
public string Role { get; set; }
public class Handler : IRequestHandler<CreateLoginTokenCommand, string>
{
private readonly AuthConfiguration authConfiguration;
public Handler(IOptions<AuthConfiguration> options)
{
this.authConfiguration = options.Value;
}
public Task<string> Handle(CreateLoginTokenCommand request, CancellationToken cancellationToken)
{
var claims = new List<Claim> {
new Claim("username", request.Username),
new Claim(JwtRegisteredClaimNames.Jti, request.UserId.ToString()),
new Claim("organizationName", request.OrganizationName ?? string.Empty),
new Claim("role", request.Role)
};
var expires = DateTime.Now.AddHours(authConfiguration.ValidHours);
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authConfiguration.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
authConfiguration.Issuer,
authConfiguration.Audience,
claims,
expires: expires,
signingCredentials: creds
);
string tokenString = new JwtSecurityTokenHandler()
.WriteToken(token);
return Task.FromResult(tokenString);
}
}
}
}
| 29.516667 | 99 | 0.748165 | [
"MIT"
] | governmentbg/nacid-visad | VisaD.Application/Users/Commands/CreateLoginTokenCommand.cs | 1,773 | C# |
// Copyright 2020 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.
using Xamarin.Forms;
namespace SafeAuthenticatorApp.Controls
{
public enum GradientOrientation
{
Vertical,
Horizontal
}
public class GradientContentView : ContentView
{
public GradientOrientation Orientation
{
get => (GradientOrientation)GetValue(OrientationProperty);
set => SetValue(OrientationProperty, value);
}
public static readonly BindableProperty OrientationProperty = BindableProperty.Create(
nameof(Orientation),
typeof(GradientOrientation),
typeof(GradientContentView),
GradientOrientation.Vertical);
public Color StartColor
{
get => (Color)GetValue(StartColorProperty);
set => SetValue(StartColorProperty, value);
}
public static readonly BindableProperty StartColorProperty = BindableProperty.Create(
nameof(EndColor),
typeof(Color),
typeof(GradientContentView),
Color.Default);
public Color EndColor
{
get => (Color)GetValue(EndColorProperty);
set => SetValue(EndColorProperty, value);
}
public static readonly BindableProperty EndColorProperty = BindableProperty.Create(
nameof(EndColor),
typeof(Color),
typeof(GradientContentView),
Color.Default);
}
}
| 33.084746 | 95 | 0.651127 | [
"MIT",
"BSD-3-Clause"
] | maidsafe/sn_authenticator_mobile | SafeAuthenticator/Controls/GradientContentView.cs | 1,954 | C# |
/*
* Intersight REST API
*
* This is Intersight REST API
*
* OpenAPI spec version: 1.0.9-262
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = intersight.Client.SwaggerDateConverter;
namespace intersight.Model
{
/// <summary>
/// Type derived from AbstractTriggerDetails describe specific actions which devops users can perform within a micro service. The actions are often remediations for bugs. For example, processing of a notification may fail because of a defect. Once the bug is fixed, it may be necessary to reprocess the notification to recover any missed state changes. The subtype NotificationTrigger implements such a capability. Introduce a new capability by - Defining a new subtype extending from AbstractTriggerDetails. - Implement the Triggerable interface defined in barcelona/mos/devops/TriggerBi.go.
/// </summary>
[DataContract]
public partial class DevopsAbstractTriggerDetails : IEquatable<DevopsAbstractTriggerDetails>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DevopsAbstractTriggerDetails" /> class.
/// </summary>
[JsonConstructorAttribute]
public DevopsAbstractTriggerDetails()
{
}
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DevopsAbstractTriggerDetails {\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as DevopsAbstractTriggerDetails);
}
/// <summary>
/// Returns true if DevopsAbstractTriggerDetails instances are equal
/// </summary>
/// <param name="other">Instance of DevopsAbstractTriggerDetails to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DevopsAbstractTriggerDetails other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return false;
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 36.035088 | 597 | 0.634129 | [
"Apache-2.0"
] | ategaw-cisco/intersight-powershell | csharp/swaggerClient/src/intersight/Model/DevopsAbstractTriggerDetails.cs | 4,108 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using CgBarBackend.Models;
using CgBarBackend.Repositories;
using Microsoft.Extensions.Configuration;
namespace CgBarBackend.Services
{
public class BarTender : IBarTender
{
private readonly IBarTenderRepository _barTenderRepository;
private readonly ConcurrentDictionary<string, Patron> _patrons = new();
private readonly List<string> _drinks = new();
public IReadOnlyList<string> Drinks => _drinks.AsReadOnly();
private readonly List<string> _politeWords = new();
public IReadOnlyList<string> PoliteWords => _politeWords.AsReadOnly();
private readonly List<BarTenderMessage> _messages = new();
public IReadOnlyList<BarTenderMessage> Messages => _messages.AsReadOnly();
private readonly object _bannedPatronsLock = new();
private readonly List<string> _bannedPatrons = new();
private readonly Timer _cleanupTimer = new();
private readonly int _drinkExpireTimeInMinutes = 30;
private readonly int _patronExpireTimeInMinutes = 60;
private readonly int _expireTimeIntervalInMilliseconds = 60000;
private readonly ConcurrentQueue<Order> _orders = new();
private readonly Timer _processTimer = new();
private readonly int _processTimeIntervalInMilliseconds = 1000;
private Random _random = new Random((int)DateTime.Now.Ticks);
public event EventHandler<Patron> PatronAdded;
public event EventHandler<string> PatronExpired;
public event EventHandler<Patron> DrinkDelivered;
public event EventHandler<string> DrinkExpired;
public event EventHandler<Patron> PatronPolitenessChanged;
public event EventHandler<string> BarTenderSpeaks;
public BarTender(IConfiguration configuration, IBarTenderRepository barTenderRepository)
{
_barTenderRepository = barTenderRepository;
int.TryParse(configuration["BarTender:DrinkExpireTimeInMinutes"], out _drinkExpireTimeInMinutes);
int.TryParse(configuration["BarTender:PatronExpireTimeInMinutes"], out _patronExpireTimeInMinutes);
int.TryParse(configuration["BarTender:ExpireTimeIntervalInMilliseconds"], out _expireTimeIntervalInMilliseconds);
int.TryParse(configuration["BarTender:ProcessTimeIntervalInMilliseconds"], out _processTimeIntervalInMilliseconds);
_cleanupTimer.Interval = _expireTimeIntervalInMilliseconds;
_cleanupTimer.Elapsed += (sender, args) => Cleanup();
_cleanupTimer.Start();
_processTimer.Interval = _processTimeIntervalInMilliseconds;
_processTimer.Elapsed += ProcessOrder;
_processTimer.Start();
}
public void AddPatron(string screenName, string name, string profileImage, string byScreenName = null)
{
if (_bannedPatrons.Contains(screenName) || _bannedPatrons.Contains(byScreenName))
{
return;
}
if (_patrons.ContainsKey(screenName))
{
return;
}
var patron = new Patron
{ ScreenName = screenName, Name = name, ProfileImage = profileImage, LastDrinkDelivered = DateTime.Now };
_patrons.TryAdd(screenName, patron);
PatronAdded?.Invoke(this, patron);
_barTenderRepository.SavePatrons(Patrons); // this is call synchronously because we don't want to wait for this to complete
}
public bool PatronExists(string screenName) => _patrons.ContainsKey(screenName);
public void OrderDrink(string screenName, string drink, bool polite = false, string byScreenName = null)
{
if (_bannedPatrons.Contains(screenName) || _bannedPatrons.Contains(byScreenName))
{
return;
}
if (_patrons.ContainsKey(screenName) == false)
{
return;
}
_orders.Enqueue(new Order(screenName, drink));
_barTenderRepository.SaveOrders(_orders);
HandlePoliteness(byScreenName ?? screenName, polite);
}
public void RefillDrink(string screenName, bool polite = false, string byScreenName = null)
{
if (_patrons.ContainsKey(screenName) == false)
{
return;
}
if (_patrons[screenName].LastOrderedDrink == null || _patrons[screenName].LastOrderedDrink.Length < 0)
{
return;
}
OrderDrink(screenName, _patrons[screenName].LastOrderedDrink, polite, byScreenName);
}
public bool BanPatron(string screenName)
{
if (_bannedPatrons.Contains(screenName))
{
return false;
}
if (_patrons.ContainsKey(screenName) && _patrons.Remove(screenName, out _))
{
PatronExpired?.Invoke(this, screenName);
}
lock (_bannedPatronsLock)
{
_bannedPatrons.Add(screenName);
_barTenderRepository.SaveBannedPatrons(_bannedPatrons).ConfigureAwait(false);
return true;
}
}
public bool UnBanPatron(string screenName)
{
if (_bannedPatrons.Contains(screenName) == false)
{
return false;
}
lock (_bannedPatronsLock)
{
_bannedPatrons.Remove(screenName);
_barTenderRepository.SaveBannedPatrons(_bannedPatrons).ConfigureAwait(false);
return true;
}
}
public bool AddDrink(string name)
{
if (_drinks.Contains(name))
{
return false;
}
_drinks.Add(name);
_barTenderRepository.SaveDrinks(_drinks).ConfigureAwait(false);
return true;
}
public bool RemoveDrink(string name)
{
if (_drinks.Contains(name) == false)
{
return false;
}
_drinks.Remove(name);
_barTenderRepository.SaveDrinks(_drinks).ConfigureAwait(false);
return true;
}
public bool AddPoliteWord(string name)
{
if (_politeWords.Contains(name))
{
return false;
}
_politeWords.Add(name);
_barTenderRepository.SavePoliteWords(_politeWords).ConfigureAwait(false);
return true;
}
public bool RemovePoliteWord(string name)
{
if (_politeWords.Contains(name) == false)
{
return false;
}
_politeWords.Remove(name);
_barTenderRepository.SavePoliteWords(_politeWords).ConfigureAwait(false);
return true;
}
public bool AddMessage(BarTenderMessage message)
{
if (_messages.Contains(message))
{
return false;
}
_messages.Add(message);
_barTenderRepository.SaveMessages(_messages).ConfigureAwait(false);
return true;
}
public bool RemoveMessage(int index)
{
if (_messages.Count < index+1)
{
return false;
}
_messages.RemoveAt(index);
_barTenderRepository.SaveMessages(_messages).ConfigureAwait(false);
return true;
}
public IEnumerable<Patron> Patrons => _patrons.Values.AsEnumerable();
public async Task Load()
{
_patrons.Clear();
foreach (var patron in await _barTenderRepository.LoadPatrons().ConfigureAwait(false) ?? new Patron[0])
{
_patrons.TryAdd(patron.ScreenName, patron);
}
_bannedPatrons.Clear();
foreach (var bannedPatron in await _barTenderRepository.LoadBannedPatrons().ConfigureAwait(false) ?? new string[0])
{
_bannedPatrons.Add(bannedPatron);
}
_drinks.Clear();
foreach (var drink in await _barTenderRepository.LoadDrinks().ConfigureAwait(false) ?? new string[0])
{
_drinks.Add(drink);
}
_politeWords.Clear();
foreach (var politeWord in await _barTenderRepository.LoadPoliteWords().ConfigureAwait(false) ?? new string[0])
{
_politeWords.Add(politeWord);
}
_orders.Clear();
foreach (var order in await _barTenderRepository.LoadOrders().ConfigureAwait(false) ?? new Order[0])
{
_orders.Enqueue(order);
}
_messages.Clear();
foreach (var message in await _barTenderRepository.LoadMessages().ConfigureAwait(false) ?? new BarTenderMessage[0])
{
_messages.Add(message);
}
}
private void Cleanup()
{
var drinkTimeCheck = DateTime.Now.AddMinutes(-1 * _drinkExpireTimeInMinutes);
var activeTimeCheck = DateTime.Now.AddMinutes(-1 * _patronExpireTimeInMinutes);
foreach (var patron in _patrons)
{
if (patron.Value.LastDrinkDelivered < activeTimeCheck && _patrons.Remove(patron.Key, out _))
{
PatronExpired?.Invoke(this, patron.Key);
continue;
}
if (patron.Value.LastDrinkDelivered < drinkTimeCheck)
{
if (patron.Value.Drink != "_empty" && patron.Value.Drink == null)
{
patron.Value.Drink = "_empty";
DrinkExpired?.Invoke(this, patron.Key);
}
}
}
_barTenderRepository.SavePatrons(Patrons).ConfigureAwait(false);
}
private void ProcessOrder(object sender, ElapsedEventArgs e)
{
if (_orders.TryDequeue(out var order) == false)
{
return;
}
_patrons[order.ScreenName].Drink = order.Drink;
_patrons[order.ScreenName].LastOrderedDrink = order.Drink;
_patrons[order.ScreenName].LastDrinkDelivered = DateTime.Now;
DrinkDelivered?.Invoke(this, _patrons[order.ScreenName]);
_barTenderRepository.SaveOrders(_orders);
var messages = _messages.Where(m => string.Equals(m.Target,order.ScreenName,StringComparison.InvariantCultureIgnoreCase)).ToList();
if (messages.Any() == false)
{
messages = _messages.Where(m => m.Target == null || m.Target.Trim().Length == 0).ToList();
}
var message = messages[_random.Next(0, messages.Count)].Template;
message = message.Replace("{{drink}}", order.Drink, StringComparison.InvariantCultureIgnoreCase).Replace("{{screenName}}", order.ScreenName, StringComparison.InvariantCultureIgnoreCase);
BarTenderSpeaks?.Invoke(this,message);
}
private void HandlePoliteness(string patronScreenName, bool polite)
{
var orderingPatron = _patrons[patronScreenName];
if (orderingPatron == null)
{
return;
}
var wasPolite = orderingPatron.IsPolite;
if (polite)
{
orderingPatron.IncreasePolitenessLevel();
}
else
{
orderingPatron.DecreasePolitenessLevel();
}
if (wasPolite != orderingPatron.IsPolite)
{
PatronPolitenessChanged?.Invoke(this, orderingPatron);
}
}
}
}
| 36.374622 | 198 | 0.587292 | [
"MIT"
] | LottePitcher/CodegardenBar | CgBarBackend/Services/BarTender.cs | 12,042 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Promitor.Scraper.Host.Scheduling.Interfaces;
/*
* Based on example by Maarten Balliauw - https://blog.maartenballiauw.be/post/2017/08/01/building-a-scheduled-cache-updater-in-aspnet-core-2.html
* Thank you!
*/
namespace Promitor.Scraper.Host.Scheduling.Infrastructure.Extensions
{
public static class SchedulerExtensions
{
public static IServiceCollection AddScheduler(this IServiceCollection services, EventHandler<UnobservedTaskExceptionEventArgs> unobservedTaskExceptionHandler)
{
return services.AddSingleton<IHostedService, SchedulerHostedService>(serviceProvider =>
{
var instance = new SchedulerHostedService(serviceProvider.GetServices<IScheduledTask>());
instance.UnobservedTaskException += unobservedTaskExceptionHandler;
return instance;
});
}
}
} | 40.68 | 166 | 0.737463 | [
"MIT"
] | jdevalk2/promitor | src/Promitor.Scraper.Host/Scheduling/Infrastructure/Extensions/SchedulerExtensions.cs | 1,019 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FMCApp.Web.Models.ViewModels.VisualizationModels.Shared;
namespace FMCApp.Services.Interfaces
{
public interface IHomeService
{
IndexNewsMoviesViewModel GetIndexModelInfo();
}
}
| 21 | 62 | 0.772894 | [
"MIT"
] | ItsoDimitrov/ASP.NET-Core-MVC-Project | src/Services/FMCApp.Services/Interfaces/IHomeService.cs | 275 | C# |
using System.Xml.Serialization;
namespace PrtgAPI.CodeGenerator.Xml
{
[XmlRoot("GenericArg")]
public class GenericArgXml : IGenericArg
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("description")]
public string Description { get; set; }
[XmlAttribute("constraint")]
public string Constraint { get; set; }
}
}
| 22.388889 | 47 | 0.622829 | [
"MIT"
] | ericsp59/PrtgAPI | src/Tools/PrtgAPI.CodeGenerator/Xml/GenericArgXml.cs | 405 | C# |
/*
Copyright (c) 2018-2021 Festo AG & Co. KG <https://www.festo.com/net/de_de/Forms/web/contact_international>
Author: Michael Hoffmeister
Copyright (c) 2019-2021 PHOENIX CONTACT GmbH & Co. KG <opensource@phoenixcontact.com>,
author: Andreas Orzelski
This source code is licensed under the Apache License 2.0 (see LICENSE.txt).
This source code may use other Open Source software components (see LICENSE.txt).
*/
// resharper disable all
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AdminShellNS;
using BlazorUI;
using static AdminShellNS.AdminShellV20;
namespace BlazorUI.Data
{
public class SubmodelText
{
public string text { get; set; }
}
public class AASService
{
public AASService()
{
Program.NewDataAvailable += (s, a) =>
{
NewDataAvailable?.Invoke(s, a);
};
}
public event EventHandler NewDataAvailable;
public List<Item> GetTree(blazorSessionService bi, Item selectedNode, IList<Item> ExpandedNodes)
{
Item.updateVisibleTree(bi.items, selectedNode, ExpandedNodes);
return bi.items;
}
public void syncSubTree(Item item)
{
if (item.Tag is SubmodelElementCollection)
{
var smec = item.Tag as SubmodelElementCollection;
if (item.Childs.Count() != smec.value.Count)
{
createSMECItems(item, smec, item.envIndex);
}
}
}
public void buildTree(blazorSessionService bi)
{
bi.items = new List<Item>();
for (int i = 0; i < 1; i++)
{
Item root = new Item();
root.envIndex = i;
if (bi.env != null)
{
root.Text = bi.env.AasEnv.AdministrationShells[0].idShort;
root.Tag = bi.env.AasEnv.AdministrationShells[0];
if (true)
{
List<Item> childs = new List<Item>();
foreach (var sm in bi.env.AasEnv.Submodels)
{
if (sm?.idShort != null)
{
var smItem = new Item();
smItem.envIndex = i;
smItem.Text = sm.idShort;
smItem.Tag = sm;
childs.Add(smItem);
List<Item> smChilds = new List<Item>();
if (sm.submodelElements != null)
foreach (var sme in sm.submodelElements)
{
var smeItem = new Item();
smeItem.envIndex = i;
smeItem.Text = sme.submodelElement.idShort;
smeItem.Tag = sme.submodelElement;
smeItem.ParentContainer = sm;
smeItem.Wrapper = sme;
smChilds.Add(smeItem);
if (sme.submodelElement is SubmodelElementCollection)
{
var smec = sme.submodelElement as SubmodelElementCollection;
createSMECItems(smeItem, smec, i);
}
if (sme.submodelElement is Operation)
{
var o = sme.submodelElement as Operation;
createOperationItems(smeItem, o, i);
}
if (sme.submodelElement is Entity)
{
var e = sme.submodelElement as Entity;
createEntityItems(smeItem, e, i);
}
}
smItem.Childs = smChilds;
foreach (var c in smChilds)
c.parent = smItem;
}
}
root.Childs = childs;
foreach (var c in childs)
c.parent = root;
bi.items.Add(root);
}
}
}
}
void createSMECItems(Item smeRootItem, SubmodelElementCollection smec, int i)
{
List<Item> smChilds = new List<Item>();
foreach (var sme in smec.value)
{
if (sme?.submodelElement != null)
{
var smeItem = new Item();
smeItem.envIndex = i;
smeItem.Text = sme.submodelElement.idShort;
smeItem.Tag = sme.submodelElement;
smeItem.ParentContainer = smec;
smeItem.Wrapper = sme;
smChilds.Add(smeItem);
if (sme.submodelElement is SubmodelElementCollection)
{
var smecNext = sme.submodelElement as SubmodelElementCollection;
createSMECItems(smeItem, smecNext, i);
}
if (sme.submodelElement is Operation)
{
var o = sme.submodelElement as Operation;
createOperationItems(smeItem, o, i);
}
if (sme.submodelElement is Entity)
{
var e = sme.submodelElement as Entity;
createEntityItems(smeItem, e, i);
}
}
}
smeRootItem.Childs = smChilds;
foreach (var c in smChilds)
c.parent = smeRootItem;
}
void createOperationItems(Item smeRootItem, Operation op, int i)
{
List<Item> smChilds = new List<Item>();
foreach (var v in op.inputVariable)
{
var smeItem = new Item();
smeItem.envIndex = i;
smeItem.Text = v.value.submodelElement.idShort;
smeItem.Type = "In";
smeItem.Tag = v.value.submodelElement;
smChilds.Add(smeItem);
}
foreach (var v in op.outputVariable)
{
var smeItem = new Item();
smeItem.envIndex = i;
smeItem.Text = v.value.submodelElement.idShort;
smeItem.Type = "Out";
smeItem.Tag = v.value.submodelElement;
smChilds.Add(smeItem);
}
foreach (var v in op.inoutputVariable)
{
var smeItem = new Item();
smeItem.envIndex = i;
smeItem.Text = v.value.submodelElement.idShort;
smeItem.Type = "InOut";
smeItem.Tag = v.value.submodelElement;
smChilds.Add(smeItem);
}
smeRootItem.Childs = smChilds;
foreach (var c in smChilds)
c.parent = smeRootItem;
}
void createEntityItems(Item smeRootItem, Entity e, int i)
{
List<Item> smChilds = new List<Item>();
foreach (var s in e.statements)
{
if (s?.submodelElement != null)
{
var smeItem = new Item();
smeItem.envIndex = i;
smeItem.Text = s.submodelElement.idShort;
smeItem.Type = "In";
smeItem.Tag = s.submodelElement;
smChilds.Add(smeItem);
}
}
smeRootItem.Childs = smChilds;
foreach (var c in smChilds)
c.parent = smeRootItem;
}
public ListOfSubmodels GetSubmodels(blazorSessionService bi)
{
return bi.env.AasEnv.Submodels;
}
}
}
| 38.628959 | 107 | 0.43411 | [
"Apache-2.0"
] | JMayrbaeurl/aasx-package-explorer | src/BlazorUI/Data/AASService.cs | 8,539 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the meteringmarketplace-2016-01-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AWSMarketplaceMetering.Model
{
/// <summary>
/// Container for the parameters to the ResolveCustomer operation.
/// ResolveCustomer is called by a SaaS application during the registration process. When
/// a buyer visits your website during the registration process, the buyer submits a registration
/// token through their browser. The registration token is resolved through this API to
/// obtain a CustomerIdentifier and product code.
/// </summary>
public partial class ResolveCustomerRequest : AmazonAWSMarketplaceMeteringRequest
{
private string _registrationToken;
/// <summary>
/// Gets and sets the property RegistrationToken.
/// <para>
/// When a buyer visits your website during the registration process, the buyer submits
/// a registration token through the browser. The registration token is resolved to obtain
/// a CustomerIdentifier and product code.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string RegistrationToken
{
get { return this._registrationToken; }
set { this._registrationToken = value; }
}
// Check to see if RegistrationToken property is set
internal bool IsSetRegistrationToken()
{
return this._registrationToken != null;
}
}
} | 36.046875 | 117 | 0.694842 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/AWSMarketplaceMetering/Generated/Model/ResolveCustomerRequest.cs | 2,307 | C# |
/*
* Time Series API For Digital Portals
*
* Time series data, end-of-day or intraday, tick-by-tick or subsampled. Additional vendor-specific endpoints provide a modified interface for seamless integration with the ChartIQ chart library.
*
* The version of the OpenAPI document: 2
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.TimeSeriesAPIforDigitalPortals.Client.OpenAPIDateConverter;
namespace FactSet.SDK.TimeSeriesAPIforDigitalPortals.Model
{
/// <summary>
/// Date and time range for the time series. The `start` and `end` boundaries must be aligned to `granularity`. That is, the numerical value is an integral multiple of the time span value represented by `granularity`.
/// </summary>
[DataContract(Name = "_vendor_chartIQ_timeSeries_intraday_subsample_list_data_range")]
public partial class VendorChartIQTimeSeriesIntradaySubsampleListDataRange : IEquatable<VendorChartIQTimeSeriesIntradaySubsampleListDataRange>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="VendorChartIQTimeSeriesIntradaySubsampleListDataRange" /> class.
/// </summary>
[JsonConstructorAttribute]
protected VendorChartIQTimeSeriesIntradaySubsampleListDataRange() { }
/// <summary>
/// Initializes a new instance of the <see cref="VendorChartIQTimeSeriesIntradaySubsampleListDataRange" /> class.
/// </summary>
/// <param name="start">The starting point of the time range (inclusive). The data accessible in the past is limited to a few weeks at most. (required).</param>
/// <param name="end">The ending point of the time range (exclusive). Dates in the future are not allowed. (required).</param>
public VendorChartIQTimeSeriesIntradaySubsampleListDataRange(string start = default(string), string end = default(string))
{
// to ensure "start" is required (not null)
if (start == null) {
throw new ArgumentNullException("start is a required property for VendorChartIQTimeSeriesIntradaySubsampleListDataRange and cannot be null");
}
this.Start = start;
// to ensure "end" is required (not null)
if (end == null) {
throw new ArgumentNullException("end is a required property for VendorChartIQTimeSeriesIntradaySubsampleListDataRange and cannot be null");
}
this.End = end;
}
/// <summary>
/// The starting point of the time range (inclusive). The data accessible in the past is limited to a few weeks at most.
/// </summary>
/// <value>The starting point of the time range (inclusive). The data accessible in the past is limited to a few weeks at most.</value>
[DataMember(Name = "start", IsRequired = true, EmitDefaultValue = false)]
public string Start { get; set; }
/// <summary>
/// The ending point of the time range (exclusive). Dates in the future are not allowed.
/// </summary>
/// <value>The ending point of the time range (exclusive). Dates in the future are not allowed.</value>
[DataMember(Name = "end", IsRequired = true, EmitDefaultValue = false)]
public string End { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class VendorChartIQTimeSeriesIntradaySubsampleListDataRange {\n");
sb.Append(" Start: ").Append(Start).Append("\n");
sb.Append(" End: ").Append(End).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as VendorChartIQTimeSeriesIntradaySubsampleListDataRange);
}
/// <summary>
/// Returns true if VendorChartIQTimeSeriesIntradaySubsampleListDataRange instances are equal
/// </summary>
/// <param name="input">Instance of VendorChartIQTimeSeriesIntradaySubsampleListDataRange to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(VendorChartIQTimeSeriesIntradaySubsampleListDataRange input)
{
if (input == null)
{
return false;
}
return
(
this.Start == input.Start ||
(this.Start != null &&
this.Start.Equals(input.Start))
) &&
(
this.End == input.End ||
(this.End != null &&
this.End.Equals(input.End))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Start != null)
{
hashCode = (hashCode * 59) + this.Start.GetHashCode();
}
if (this.End != null)
{
hashCode = (hashCode * 59) + this.End.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 42.777778 | 261 | 0.616883 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/TimeSeriesAPIforDigitalPortals/v3/src/FactSet.SDK.TimeSeriesAPIforDigitalPortals/Model/VendorChartIQTimeSeriesIntradaySubsampleListDataRange.cs | 6,930 | C# |
using DryIoc;
namespace Compori.Alphaplan.Plugin.Support.DryIoc.Extensions
{
public static class CommonVersion2100287Extension
{
/// <summary>
/// Register the the protocol provider support for version 2100.287.
/// </summary>
/// <param name="registrator">The registrator.</param>
/// <returns>IRegistrator.</returns>
public static IRegistrator WithProtocolProviderVersion2100287(this IRegistrator registrator)
{
if (registrator == null)
{
return null;
}
registrator.Register<Common.IProtocolProvider, Common.ProtocolProvider>(reuse: Reuse.Singleton);
registrator.Register<Common.IErrorScopeFactory, Common.ErrorScopeFactory>(reuse: Reuse.Singleton);
return registrator;
}
}
}
| 35.166667 | 110 | 0.640995 | [
"BSD-3-Clause"
] | compori/dotnet-alphaplan-plugin-core | src/Support2100287.DryIoc/Extensions/CommonVersion2100287Extension.cs | 846 | C# |
using System;
namespace SalesTaxes_Library.Presentation.Domain
{
/// <summary>
/// The shop billing details
/// </summary>
public class ReceiptBillingCompany
{
public ReceiptBillingCompany(
string companyName,
string holderName,
string address,
string email,
string phone,
string webSite)
{
if (string.IsNullOrWhiteSpace(companyName))
{
throw new ArgumentException($"'{nameof(companyName)}' cannot be null or whitespace", nameof(companyName));
}
if (string.IsNullOrWhiteSpace(holderName))
{
throw new ArgumentException($"'{nameof(holderName)}' cannot be null or whitespace", nameof(holderName));
}
CompanyName = companyName;
HolderName = holderName;
// The other fields are optional
Address = address;
Email = email;
Phone = phone;
WebSite = webSite;
}
public string CompanyName { get; }
public string HolderName { get; }
public string Address { get; }
public string Email { get; }
public string Phone { get; }
public string WebSite { get; }
}
}
| 28.434783 | 122 | 0.54893 | [
"Unlicense"
] | FrancescoBonizzi/lastminute-interview | SalesTaxes-ClientConsole/SalesTaxes-Library/Presentation/Domain/ReceiptBillingCompany.cs | 1,310 | C# |
using System.Collections.Generic;
using AElf.Standards.ACS1;
using AElf.Standards.ACS3;
using AElf.Contracts.MultiToken;
using AElf.Sdk.CSharp;
using AElf.Types;
using Google.Protobuf.WellKnownTypes;
namespace AElf.Contracts.CrossChain
{
public partial class CrossChainContract
{
#region Views
public override MethodFees GetMethodFee(StringValue input)
{
if (new List<string>
{
nameof(ProposeCrossChainIndexing), nameof(ReleaseCrossChainIndexingProposal)
}.Contains(input.Value))
{
return new MethodFees
{
MethodName = input.Value
};
}
return State.TransactionFees[input.Value];
}
public override AuthorityInfo GetMethodFeeController(Empty input)
{
RequiredMethodFeeControllerSet();
return State.MethodFeeController.Value;
}
#endregion
public override Empty SetMethodFee(MethodFees input)
{
foreach (var methodFee in input.Fees)
{
AssertValidToken(methodFee.Symbol, methodFee.BasicFee);
}
RequiredMethodFeeControllerSet();
Assert(Context.Sender == State.MethodFeeController.Value.OwnerAddress, "Unauthorized to set method fee.");
State.TransactionFees[input.MethodName] = input;
return new Empty();
}
public override Empty ChangeMethodFeeController(AuthorityInfo input)
{
RequiredMethodFeeControllerSet();
AssertSenderAddressWith(State.MethodFeeController.Value.OwnerAddress);
var organizationExist = CheckOrganizationExist(input);
Assert(organizationExist, "Invalid authority input.");
State.MethodFeeController.Value = input;
return new Empty();
}
#region private methods
private void RequiredMethodFeeControllerSet()
{
if (State.MethodFeeController.Value != null) return;
SetContractStateRequired(State.ParliamentContract, SmartContractConstants.ParliamentContractSystemName);
var defaultAuthority = new AuthorityInfo
{
OwnerAddress = State.ParliamentContract.GetDefaultOrganizationAddress.Call(new Empty()),
ContractAddress = State.ParliamentContract.Value
};
State.MethodFeeController.Value = defaultAuthority;
}
private void AssertSenderAddressWith(Address address)
{
Assert(Context.Sender == address, "Unauthorized behavior.");
}
private bool CheckOrganizationExist(AuthorityInfo authorityInfo)
{
return Context.Call<BoolValue>(authorityInfo.ContractAddress,
nameof(AuthorizationContractContainer.AuthorizationContractReferenceState.ValidateOrganizationExist),
authorityInfo.OwnerAddress).Value;
}
private void AssertValidToken(string symbol, long amount)
{
Assert(amount >= 0, "Invalid amount.");
if (State.TokenContract.Value == null)
{
State.TokenContract.Value =
Context.GetContractAddressByName(SmartContractConstants.TokenContractSystemName);
}
var tokenInfoInput = new GetTokenInfoInput {Symbol = symbol};
var tokenInfo = State.TokenContract.GetTokenInfo.Call(tokenInfoInput);
Assert(tokenInfo != null && !string.IsNullOrEmpty(tokenInfo.Symbol), $"Token is not found. {symbol}");
}
#endregion
}
} | 34.342593 | 118 | 0.626314 | [
"MIT"
] | TreasureMouse/TreasureMouse | contract/TreasureMouse.Contracts.CrossChain/CrossChainContract_ACS1_TransactionFeeProvider.cs | 3,709 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xom.Core.Exceptions
{
public class XomDataSerializationPropertyTypeMismatchException : XomDataSerializationException
{
public Type SourceType { get; private set; }
public string SourceName { get; private set; }
public Type TargetType { get; private set; }
public string TargetName { get; private set; }
public XomDataSerializationPropertyTypeMismatchException(Type sourceType, string sourceName, Type targetType, string targetName)
: base(string.Format("The source property {0} ({1}) has an incompatible type with the target property {2} ({3})",
sourceName, sourceType, targetName, targetType))
{
SourceName = sourceName;
TargetName = targetName;
SourceType = SourceType;
TargetType = targetType;
}
}
}
| 36.888889 | 136 | 0.662651 | [
"MIT"
] | KallDrexx/Xom | Xom.Core/Exceptions/XomDataSerializationPropertyTypeMismatchException.cs | 998 | C# |
using System.Reflection;
// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("9.0.041121.31")]
[assembly: AssemblyFileVersion("9.0.041121.31")]
| 27.666667 | 77 | 0.73494 | [
"MIT"
] | 7amza123/azu | lib/SharedAssemblyInfo.cs | 332 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal static class IVsHierarchyExtensions
{
public static bool TryGetItemProperty<T>(this IVsHierarchy hierarchy, uint itemId, int propertyId, [MaybeNull] [NotNullWhen(returnValue: true)] out T value)
{
if (ErrorHandler.Failed(hierarchy.GetProperty(itemId, propertyId, out var property)) ||
!(property is T))
{
value = default;
return false;
}
value = (T)property;
return true;
}
public static bool TryGetProperty<T>(this IVsHierarchy hierarchy, int propertyId, [MaybeNull] [NotNullWhen(returnValue: true)] out T value)
{
const uint root = VSConstants.VSITEMID_ROOT;
return hierarchy.TryGetItemProperty(root, propertyId, out value);
}
public static bool TryGetProperty<T>(this IVsHierarchy hierarchy, __VSHPROPID propertyId, [MaybeNull] [NotNullWhen(returnValue: true)] out T value)
{
return hierarchy.TryGetProperty((int)propertyId, out value);
}
public static bool TryGetItemProperty<T>(this IVsHierarchy hierarchy, uint itemId, __VSHPROPID propertyId, [MaybeNull] [NotNullWhen(returnValue: true)] out T value)
{
return hierarchy.TryGetItemProperty(itemId, (int)propertyId, out value);
}
public static bool TryGetGuidProperty(this IVsHierarchy hierarchy, int propertyId, out Guid guid)
{
return ErrorHandler.Succeeded(hierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, propertyId, out guid));
}
public static bool TryGetGuidProperty(this IVsHierarchy hierarchy, __VSHPROPID propertyId, out Guid guid)
{
return ErrorHandler.Succeeded(hierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)propertyId, out guid));
}
public static bool TryGetProject(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out EnvDTE.Project? project)
{
return hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_ExtObject, out project);
}
public static bool TryGetName(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out string? name)
{
return hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_Name, out name);
}
public static bool TryGetItemName(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? name)
{
return hierarchy.TryGetItemProperty(itemId, __VSHPROPID.VSHPROPID_Name, out name);
}
public static bool TryGetCanonicalName(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? name)
{
return ErrorHandler.Succeeded(hierarchy.GetCanonicalName(itemId, out name));
}
public static bool TryGetParentHierarchy(this IVsHierarchy hierarchy, [NotNullWhen(returnValue: true)] out IVsHierarchy? parentHierarchy)
{
return hierarchy.TryGetProperty(__VSHPROPID.VSHPROPID_ParentHierarchy, out parentHierarchy);
}
public static bool TryGetTypeGuid(this IVsHierarchy hierarchy, out Guid typeGuid)
{
return hierarchy.TryGetGuidProperty(__VSHPROPID.VSHPROPID_TypeGuid, out typeGuid);
}
public static bool TryGetTargetFrameworkMoniker(this IVsHierarchy hierarchy, uint itemId, [NotNullWhen(returnValue: true)] out string? targetFrameworkMoniker)
{
return hierarchy.TryGetItemProperty(itemId, (int)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker, out targetFrameworkMoniker);
}
public static uint TryGetItemId(this IVsHierarchy hierarchy, string moniker)
{
if (ErrorHandler.Succeeded(hierarchy.ParseCanonicalName(moniker, out var itemid)))
{
return itemid;
}
return VSConstants.VSITEMID_NIL;
}
public static string? TryGetProjectFilePath(this IVsHierarchy hierarchy)
{
if (ErrorHandler.Succeeded(((IVsProject3)hierarchy).GetMkDocument((uint)VSConstants.VSITEMID.Root, out var projectFilePath)) && !string.IsNullOrEmpty(projectFilePath))
{
return projectFilePath;
}
return null;
}
}
}
| 42.567568 | 179 | 0.682751 | [
"Apache-2.0"
] | HenrikWM/roslyn | src/VisualStudio/Core/Def/Implementation/ProjectSystem/Extensions/IVsHierarchyExtensions.cs | 4,727 | C# |
using System.Drawing;
using ReClassNET.Memory;
using ReClassNET.UI;
namespace ReClassNET.Nodes
{
public class DoubleNode : BaseNumericNode
{
public override int MemorySize => 8;
public override void GetUserInterfaceInfo(out string name, out Image icon)
{
name = "Double";
icon = Properties.Resources.B16x16_Button_Double;
}
public override Size Draw(ViewInfo view, int x, int y)
{
return DrawNumeric(view, x, y, Icons.Double, "Double", ReadValueFromMemory(view.Memory).ToString("0.000"), null);
}
public override void Update(HotSpot spot)
{
base.Update(spot);
if (spot.Id == 0)
{
if (double.TryParse(spot.Text, out var val))
{
spot.Memory.Process.WriteRemoteMemory(spot.Address, val);
}
}
}
public double ReadValueFromMemory(MemoryBuffer memory)
{
return memory.ReadDouble(Offset);
}
}
}
| 21.097561 | 116 | 0.69711 | [
"MIT"
] | Rob--/ReClass.NET | ReClass.NET/Nodes/DoubleNode.cs | 867 | C# |
namespace YMApp.ECommerce.Pictures.Authorization
{
/// <summary>
/// 定义系统的权限名称的字符串常量。
/// <see cref="PictureAuthorizationProvider" />中对权限的定义.
///</summary>
public static class PicturePermissions
{
/// <summary>
/// Picture权限节点
///</summary>
public const string Node = "Pages.Picture";
/// <summary>
/// Picture查询授权
///</summary>
public const string Query = "Pages.Picture.Query";
/// <summary>
/// Picture创建权限
///</summary>
public const string Create = "Pages.Picture.Create";
/// <summary>
/// Picture修改权限
///</summary>
public const string Edit = "Pages.Picture.Edit";
/// <summary>
/// Picture删除权限
///</summary>
public const string Delete = "Pages.Picture.Delete";
/// <summary>
/// Picture批量删除权限
///</summary>
public const string BatchDelete = "Pages.Picture.BatchDelete";
/// <summary>
/// Picture导出Excel
///</summary>
public const string ExportExcel="Pages.Picture.ExportExcel";
}
}
| 18.849057 | 64 | 0.623624 | [
"MIT"
] | yannis123/YMApp | src/ymapp-aspnet-core/src/YMApp.Core/ECommerce/Pictures/Authorization/PicturePermissions.cs | 1,101 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WastePermits.Model.EarlyBound
{
/// <summary>
/// Collection of system users that routinely collaborate. Teams can be used to simplify record sharing and provide team members with common access to organization data when team members belong to different Business Units.
/// </summary>
[System.Runtime.Serialization.DataContractAttribute()]
[Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("team")]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")]
public partial class Team : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
public static class Fields
{
public const string AdministratorId = "administratorid";
public const string AzureActiveDirectoryObjectId = "azureactivedirectoryobjectid";
public const string BusinessUnitId = "businessunitid";
public const string CreatedBy = "createdby";
public const string CreatedOn = "createdon";
public const string CreatedOnBehalfBy = "createdonbehalfby";
public const string defra_is_area_team = "defra_is_area_team";
public const string defra_maximum_writeoff_allowed = "defra_maximum_writeoff_allowed";
public const string defra_maximum_writeoff_allowed_Base = "defra_maximum_writeoff_allowed_base";
public const string Description = "description";
public const string EMailAddress = "emailaddress";
public const string ExchangeRate = "exchangerate";
public const string ImportSequenceNumber = "importsequencenumber";
public const string IsDefault = "isdefault";
public const string ModifiedBy = "modifiedby";
public const string ModifiedOn = "modifiedon";
public const string ModifiedOnBehalfBy = "modifiedonbehalfby";
public const string Name = "name";
public const string OrganizationId = "organizationid";
public const string OverriddenCreatedOn = "overriddencreatedon";
public const string ProcessId = "processid";
public const string QueueId = "queueid";
public const string RegardingObjectId = "regardingobjectid";
public const string StageId = "stageid";
public const string SystemManaged = "systemmanaged";
public const string TeamId = "teamid";
public const string Id = "teamid";
public const string TeamTemplateId = "teamtemplateid";
public const string TeamType = "teamtype";
public const string TransactionCurrencyId = "transactioncurrencyid";
public const string TraversedPath = "traversedpath";
public const string VersionNumber = "versionnumber";
public const string YomiName = "yominame";
public const string lk_team_createdonbehalfby = "lk_team_createdonbehalfby";
public const string lk_team_modifiedonbehalfby = "lk_team_modifiedonbehalfby";
public const string lk_teambase_administratorid = "lk_teambase_administratorid";
public const string lk_teambase_createdby = "lk_teambase_createdby";
public const string lk_teambase_modifiedby = "lk_teambase_modifiedby";
}
/// <summary>
/// Default Constructor.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode()]
public Team() :
base(EntityLogicalName)
{
}
public const string EntityLogicalName = "team";
public const string PrimaryIdAttribute = "teamid";
public const string PrimaryNameAttribute = "name";
public const int EntityTypeCode = 9;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
[System.Diagnostics.DebuggerNonUserCode()]
private void OnPropertyChanged(string propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
[System.Diagnostics.DebuggerNonUserCode()]
private void OnPropertyChanging(string propertyName)
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName));
}
}
/// <summary>
/// Unique identifier of the user primary responsible for the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("administratorid")]
public Microsoft.Xrm.Sdk.EntityReference AdministratorId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("administratorid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("AdministratorId");
this.SetAttributeValue("administratorid", value);
this.OnPropertyChanged("AdministratorId");
}
}
/// <summary>
/// The Azure active directory object Id for a group.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("azureactivedirectoryobjectid")]
public System.Nullable<System.Guid> AzureActiveDirectoryObjectId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("azureactivedirectoryobjectid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("AzureActiveDirectoryObjectId");
this.SetAttributeValue("azureactivedirectoryobjectid", value);
this.OnPropertyChanged("AzureActiveDirectoryObjectId");
}
}
/// <summary>
/// Unique identifier of the business unit with which the team is associated.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("businessunitid")]
public Microsoft.Xrm.Sdk.EntityReference BusinessUnitId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("businessunitid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("BusinessUnitId");
this.SetAttributeValue("businessunitid", value);
this.OnPropertyChanged("BusinessUnitId");
}
}
/// <summary>
/// Unique identifier of the user who created the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")]
public Microsoft.Xrm.Sdk.EntityReference CreatedBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdby");
}
}
/// <summary>
/// Date and time when the team was created.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")]
public System.Nullable<System.DateTime> CreatedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("createdon");
}
}
/// <summary>
/// Unique identifier of the delegate user who created the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")]
public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdonbehalfby");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("CreatedOnBehalfBy");
this.SetAttributeValue("createdonbehalfby", value);
this.OnPropertyChanged("CreatedOnBehalfBy");
}
}
/// <summary>
///
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("defra_is_area_team")]
public System.Nullable<bool> defra_is_area_team
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<bool>>("defra_is_area_team");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("defra_is_area_team");
this.SetAttributeValue("defra_is_area_team", value);
this.OnPropertyChanged("defra_is_area_team");
}
}
/// <summary>
/// The maximum write off users are allowed to execute on an application.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("defra_maximum_writeoff_allowed")]
public Microsoft.Xrm.Sdk.Money defra_maximum_writeoff_allowed
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.Money>("defra_maximum_writeoff_allowed");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("defra_maximum_writeoff_allowed");
this.SetAttributeValue("defra_maximum_writeoff_allowed", value);
this.OnPropertyChanged("defra_maximum_writeoff_allowed");
}
}
/// <summary>
/// Value of the Maximum Write-off Allowed in base currency.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("defra_maximum_writeoff_allowed_base")]
public Microsoft.Xrm.Sdk.Money defra_maximum_writeoff_allowed_Base
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.Money>("defra_maximum_writeoff_allowed_base");
}
}
/// <summary>
/// Description of the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("description")]
public string Description
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("description");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("Description");
this.SetAttributeValue("description", value);
this.OnPropertyChanged("Description");
}
}
/// <summary>
/// Email address for the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("emailaddress")]
public string EMailAddress
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("emailaddress");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("EMailAddress");
this.SetAttributeValue("emailaddress", value);
this.OnPropertyChanged("EMailAddress");
}
}
/// <summary>
/// Exchange rate for the currency associated with the team with respect to the base currency.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("exchangerate")]
public System.Nullable<decimal> ExchangeRate
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<decimal>>("exchangerate");
}
}
/// <summary>
/// Unique identifier of the data import or data migration that created this record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("importsequencenumber")]
public System.Nullable<int> ImportSequenceNumber
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<int>>("importsequencenumber");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ImportSequenceNumber");
this.SetAttributeValue("importsequencenumber", value);
this.OnPropertyChanged("ImportSequenceNumber");
}
}
/// <summary>
/// Information about whether the team is a default business unit team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("isdefault")]
public System.Nullable<bool> IsDefault
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<bool>>("isdefault");
}
}
/// <summary>
/// Unique identifier of the user who last modified the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")]
public Microsoft.Xrm.Sdk.EntityReference ModifiedBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedby");
}
}
/// <summary>
/// Date and time when the team was last modified.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedon")]
public System.Nullable<System.DateTime> ModifiedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("modifiedon");
}
}
/// <summary>
/// Unique identifier of the delegate user who last modified the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")]
public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedonbehalfby");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ModifiedOnBehalfBy");
this.SetAttributeValue("modifiedonbehalfby", value);
this.OnPropertyChanged("ModifiedOnBehalfBy");
}
}
/// <summary>
/// Name of the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("name")]
public string Name
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("name");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("Name");
this.SetAttributeValue("name", value);
this.OnPropertyChanged("Name");
}
}
/// <summary>
/// Unique identifier of the organization associated with the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")]
public System.Nullable<System.Guid> OrganizationId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("organizationid");
}
}
/// <summary>
/// Date and time that the record was migrated.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overriddencreatedon")]
public System.Nullable<System.DateTime> OverriddenCreatedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("overriddencreatedon");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("OverriddenCreatedOn");
this.SetAttributeValue("overriddencreatedon", value);
this.OnPropertyChanged("OverriddenCreatedOn");
}
}
/// <summary>
/// Shows the ID of the process.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("processid")]
public System.Nullable<System.Guid> ProcessId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("processid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ProcessId");
this.SetAttributeValue("processid", value);
this.OnPropertyChanged("ProcessId");
}
}
/// <summary>
/// Unique identifier of the default queue for the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("queueid")]
public Microsoft.Xrm.Sdk.EntityReference QueueId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("queueid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("QueueId");
this.SetAttributeValue("queueid", value);
this.OnPropertyChanged("QueueId");
}
}
/// <summary>
/// Choose the record that the team relates to.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("regardingobjectid")]
public Microsoft.Xrm.Sdk.EntityReference RegardingObjectId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("regardingobjectid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("RegardingObjectId");
this.SetAttributeValue("regardingobjectid", value);
this.OnPropertyChanged("RegardingObjectId");
}
}
/// <summary>
/// Shows the ID of the stage.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("stageid")]
public System.Nullable<System.Guid> StageId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("stageid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("StageId");
this.SetAttributeValue("stageid", value);
this.OnPropertyChanged("StageId");
}
}
/// <summary>
/// Select whether the team will be managed by the system.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("systemmanaged")]
public System.Nullable<bool> SystemManaged
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<bool>>("systemmanaged");
}
}
/// <summary>
/// Unique identifier for the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("teamid")]
public System.Nullable<System.Guid> TeamId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("teamid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("TeamId");
this.SetAttributeValue("teamid", value);
if (value.HasValue)
{
base.Id = value.Value;
}
else
{
base.Id = System.Guid.Empty;
}
this.OnPropertyChanged("TeamId");
}
}
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("teamid")]
public override System.Guid Id
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return base.Id;
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.TeamId = value;
}
}
/// <summary>
/// Shows the team template that is associated with the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("teamtemplateid")]
public Microsoft.Xrm.Sdk.EntityReference TeamTemplateId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("teamtemplateid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("TeamTemplateId");
this.SetAttributeValue("teamtemplateid", value);
this.OnPropertyChanged("TeamTemplateId");
}
}
/// <summary>
/// Select the team type.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("teamtype")]
public Microsoft.Xrm.Sdk.OptionSetValue TeamType
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("teamtype");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("TeamType");
this.SetAttributeValue("teamtype", value);
this.OnPropertyChanged("TeamType");
}
}
/// <summary>
/// Unique identifier of the currency associated with the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("transactioncurrencyid")]
public Microsoft.Xrm.Sdk.EntityReference TransactionCurrencyId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("transactioncurrencyid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("TransactionCurrencyId");
this.SetAttributeValue("transactioncurrencyid", value);
this.OnPropertyChanged("TransactionCurrencyId");
}
}
/// <summary>
/// For internal use only.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("traversedpath")]
public string TraversedPath
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("traversedpath");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("TraversedPath");
this.SetAttributeValue("traversedpath", value);
this.OnPropertyChanged("TraversedPath");
}
}
/// <summary>
/// Version number of the team.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("versionnumber")]
public System.Nullable<long> VersionNumber
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<long>>("versionnumber");
}
}
/// <summary>
/// Pronunciation of the full name of the team, written in phonetic hiragana or katakana characters.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("yominame")]
public string YomiName
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("yominame");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("YomiName");
this.SetAttributeValue("yominame", value);
this.OnPropertyChanged("YomiName");
}
}
/// <summary>
/// 1:N defra_areacomment_team_owningteam
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("defra_areacomment_team_owningteam")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_areacomment> defra_areacomment_team_owningteam
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_areacomment>("defra_areacomment_team_owningteam", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("defra_areacomment_team_owningteam");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_areacomment>("defra_areacomment_team_owningteam", null, value);
this.OnPropertyChanged("defra_areacomment_team_owningteam");
}
}
/// <summary>
/// 1:N defra_notification_team_owningteam
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("defra_notification_team_owningteam")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_notification> defra_notification_team_owningteam
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_notification>("defra_notification_team_owningteam", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("defra_notification_team_owningteam");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_notification>("defra_notification_team_owningteam", null, value);
this.OnPropertyChanged("defra_notification_team_owningteam");
}
}
/// <summary>
/// 1:N defra_team_defra_application_areaid
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("defra_team_defra_application_areaid")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_application> defra_team_defra_application_areaid
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_application>("defra_team_defra_application_areaid", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("defra_team_defra_application_areaid");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_application>("defra_team_defra_application_areaid", null, value);
this.OnPropertyChanged("defra_team_defra_application_areaid");
}
}
/// <summary>
/// 1:N defra_team_defra_permit_area_team
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("defra_team_defra_permit_area_team")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_permit> defra_team_defra_permit_area_team
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_permit>("defra_team_defra_permit_area_team", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("defra_team_defra_permit_area_team");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_permit>("defra_team_defra_permit_area_team", null, value);
this.OnPropertyChanged("defra_team_defra_permit_area_team");
}
}
/// <summary>
/// 1:N defra_team_systemuser_defaultteam
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("defra_team_systemuser_defaultteam")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.SystemUser> defra_team_systemuser_defaultteam
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.SystemUser>("defra_team_systemuser_defaultteam", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("defra_team_systemuser_defaultteam");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.SystemUser>("defra_team_systemuser_defaultteam", null, value);
this.OnPropertyChanged("defra_team_systemuser_defaultteam");
}
}
/// <summary>
/// 1:N team_accounts
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_accounts")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.Account> team_accounts
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.Account>("team_accounts", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_accounts");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.Account>("team_accounts", null, value);
this.OnPropertyChanged("team_accounts");
}
}
/// <summary>
/// 1:N team_contacts
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_contacts")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.Contact> team_contacts
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.Contact>("team_contacts", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_contacts");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.Contact>("team_contacts", null, value);
this.OnPropertyChanged("team_contacts");
}
}
/// <summary>
/// 1:N team_defra_activity
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_activity")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_activity> team_defra_activity
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_activity>("team_defra_activity", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_activity");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_activity>("team_defra_activity", null, value);
this.OnPropertyChanged("team_defra_activity");
}
}
/// <summary>
/// 1:N team_defra_activitytype
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_activitytype")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_activitytype> team_defra_activitytype
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_activitytype>("team_defra_activitytype", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_activitytype");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_activitytype>("team_defra_activitytype", null, value);
this.OnPropertyChanged("team_defra_activitytype");
}
}
/// <summary>
/// 1:N team_defra_address
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_address")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_address> team_defra_address
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_address>("team_defra_address", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_address");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_address>("team_defra_address", null, value);
this.OnPropertyChanged("team_defra_address");
}
}
/// <summary>
/// 1:N team_defra_addressdetails
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_addressdetails")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_addressdetails> team_defra_addressdetails
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_addressdetails>("team_defra_addressdetails", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_addressdetails");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_addressdetails>("team_defra_addressdetails", null, value);
this.OnPropertyChanged("team_defra_addressdetails");
}
}
/// <summary>
/// 1:N team_defra_application
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_application")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_application> team_defra_application
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_application>("team_defra_application", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_application");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_application>("team_defra_application", null, value);
this.OnPropertyChanged("team_defra_application");
}
}
/// <summary>
/// 1:N team_defra_application_subtypes
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_application_subtypes")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_application_subtypes> team_defra_application_subtypes
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_application_subtypes>("team_defra_application_subtypes", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_application_subtypes");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_application_subtypes>("team_defra_application_subtypes", null, value);
this.OnPropertyChanged("team_defra_application_subtypes");
}
}
/// <summary>
/// 1:N team_defra_applicationanswer
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationanswer")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationanswer> team_defra_applicationanswer
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationanswer>("team_defra_applicationanswer", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationanswer");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationanswer>("team_defra_applicationanswer", null, value);
this.OnPropertyChanged("team_defra_applicationanswer");
}
}
/// <summary>
/// 1:N team_defra_applicationcontact
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationcontact")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationcontact> team_defra_applicationcontact
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationcontact>("team_defra_applicationcontact", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationcontact");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationcontact>("team_defra_applicationcontact", null, value);
this.OnPropertyChanged("team_defra_applicationcontact");
}
}
/// <summary>
/// 1:N team_defra_applicationdocument
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationdocument")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationdocument> team_defra_applicationdocument
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationdocument>("team_defra_applicationdocument", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationdocument");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationdocument>("team_defra_applicationdocument", null, value);
this.OnPropertyChanged("team_defra_applicationdocument");
}
}
/// <summary>
/// 1:N team_defra_applicationline
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationline")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationline> team_defra_applicationline
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationline>("team_defra_applicationline", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationline");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationline>("team_defra_applicationline", null, value);
this.OnPropertyChanged("team_defra_applicationline");
}
}
/// <summary>
/// 1:N team_defra_applicationprice
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationprice")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationprice> team_defra_applicationprice
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationprice>("team_defra_applicationprice", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationprice");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationprice>("team_defra_applicationprice", null, value);
this.OnPropertyChanged("team_defra_applicationprice");
}
}
/// <summary>
/// 1:N team_defra_applicationquestion
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationquestion")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationquestion> team_defra_applicationquestion
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationquestion>("team_defra_applicationquestion", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationquestion");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationquestion>("team_defra_applicationquestion", null, value);
this.OnPropertyChanged("team_defra_applicationquestion");
}
}
/// <summary>
/// 1:N team_defra_applicationquestiongroup
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationquestiongroup")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationquestiongroup> team_defra_applicationquestiongroup
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationquestiongroup>("team_defra_applicationquestiongroup", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationquestiongroup");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationquestiongroup>("team_defra_applicationquestiongroup", null, value);
this.OnPropertyChanged("team_defra_applicationquestiongroup");
}
}
/// <summary>
/// 1:N team_defra_applicationquestionoption
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationquestionoption")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationquestionoption> team_defra_applicationquestionoption
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationquestionoption>("team_defra_applicationquestionoption", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationquestionoption");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationquestionoption>("team_defra_applicationquestionoption", null, value);
this.OnPropertyChanged("team_defra_applicationquestionoption");
}
}
/// <summary>
/// 1:N team_defra_applicationtask
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationtask")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationtask> team_defra_applicationtask
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationtask>("team_defra_applicationtask", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationtask");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationtask>("team_defra_applicationtask", null, value);
this.OnPropertyChanged("team_defra_applicationtask");
}
}
/// <summary>
/// 1:N team_defra_applicationtaskdefinition
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_applicationtaskdefinition")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_applicationtaskdefinition> team_defra_applicationtaskdefinition
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationtaskdefinition>("team_defra_applicationtaskdefinition", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_applicationtaskdefinition");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_applicationtaskdefinition>("team_defra_applicationtaskdefinition", null, value);
this.OnPropertyChanged("team_defra_applicationtaskdefinition");
}
}
/// <summary>
/// 1:N team_defra_configuration
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_configuration")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_configuration> team_defra_configuration
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_configuration>("team_defra_configuration", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_configuration");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_configuration>("team_defra_configuration", null, value);
this.OnPropertyChanged("team_defra_configuration");
}
}
/// <summary>
/// 1:N team_defra_country
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_country")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_country> team_defra_country
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_country>("team_defra_country", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_country");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_country>("team_defra_country", null, value);
this.OnPropertyChanged("team_defra_country");
}
}
/// <summary>
/// 1:N team_defra_dulymadechecklist
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_dulymadechecklist")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_dulymadechecklist> team_defra_dulymadechecklist
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_dulymadechecklist>("team_defra_dulymadechecklist", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_dulymadechecklist");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_dulymadechecklist>("team_defra_dulymadechecklist", null, value);
this.OnPropertyChanged("team_defra_dulymadechecklist");
}
}
/// <summary>
/// 1:N team_defra_exception
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_exception")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_exception> team_defra_exception
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_exception>("team_defra_exception", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_exception");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_exception>("team_defra_exception", null, value);
this.OnPropertyChanged("team_defra_exception");
}
}
/// <summary>
/// 1:N team_defra_facility
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_facility")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_facility> team_defra_facility
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_facility>("team_defra_facility", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_facility");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_facility>("team_defra_facility", null, value);
this.OnPropertyChanged("team_defra_facility");
}
}
/// <summary>
/// 1:N team_defra_facilitytype
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_facilitytype")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_facilitytype> team_defra_facilitytype
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_facilitytype>("team_defra_facilitytype", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_facilitytype");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_facilitytype>("team_defra_facilitytype", null, value);
this.OnPropertyChanged("team_defra_facilitytype");
}
}
/// <summary>
/// 1:N team_defra_industryscheme
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_industryscheme")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_industryscheme> team_defra_industryscheme
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_industryscheme>("team_defra_industryscheme", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_industryscheme");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_industryscheme>("team_defra_industryscheme", null, value);
this.OnPropertyChanged("team_defra_industryscheme");
}
}
/// <summary>
/// 1:N team_defra_item
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_item")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_item> team_defra_item
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_item>("team_defra_item", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_item");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_item>("team_defra_item", null, value);
this.OnPropertyChanged("team_defra_item");
}
}
/// <summary>
/// 1:N team_defra_item_application_question
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_item_application_question")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_item_application_question> team_defra_item_application_question
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_item_application_question>("team_defra_item_application_question", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_item_application_question");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_item_application_question>("team_defra_item_application_question", null, value);
this.OnPropertyChanged("team_defra_item_application_question");
}
}
/// <summary>
/// 1:N team_defra_itemapplicationtaskdefinition
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_itemapplicationtaskdefinition")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_itemapplicationtaskdefinition> team_defra_itemapplicationtaskdefinition
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_itemapplicationtaskdefinition>("team_defra_itemapplicationtaskdefinition", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_itemapplicationtaskdefinition");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_itemapplicationtaskdefinition>("team_defra_itemapplicationtaskdefinition", null, value);
this.OnPropertyChanged("team_defra_itemapplicationtaskdefinition");
}
}
/// <summary>
/// 1:N team_defra_itemdetail
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_itemdetail")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_itemdetail> team_defra_itemdetail
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_itemdetail>("team_defra_itemdetail", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_itemdetail");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_itemdetail>("team_defra_itemdetail", null, value);
this.OnPropertyChanged("team_defra_itemdetail");
}
}
/// <summary>
/// 1:N team_defra_itemdetailtype
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_itemdetailtype")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_itemdetailtype> team_defra_itemdetailtype
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_itemdetailtype>("team_defra_itemdetailtype", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_itemdetailtype");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_itemdetailtype>("team_defra_itemdetailtype", null, value);
this.OnPropertyChanged("team_defra_itemdetailtype");
}
}
/// <summary>
/// 1:N team_defra_itemtype
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_itemtype")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_itemtype> team_defra_itemtype
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_itemtype>("team_defra_itemtype", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_itemtype");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_itemtype>("team_defra_itemtype", null, value);
this.OnPropertyChanged("team_defra_itemtype");
}
}
/// <summary>
/// 1:N team_defra_location
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_location")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_location> team_defra_location
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_location>("team_defra_location", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_location");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_location>("team_defra_location", null, value);
this.OnPropertyChanged("team_defra_location");
}
}
/// <summary>
/// 1:N team_defra_locationdetails
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_locationdetails")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_locationdetails> team_defra_locationdetails
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_locationdetails>("team_defra_locationdetails", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_locationdetails");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_locationdetails>("team_defra_locationdetails", null, value);
this.OnPropertyChanged("team_defra_locationdetails");
}
}
/// <summary>
/// 1:N team_defra_managementsystem
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_managementsystem")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_managementsystem> team_defra_managementsystem
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_managementsystem>("team_defra_managementsystem", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_managementsystem");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_managementsystem>("team_defra_managementsystem", null, value);
this.OnPropertyChanged("team_defra_managementsystem");
}
}
/// <summary>
/// 1:N team_defra_operatingtechnique
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_operatingtechnique")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_operatingtechnique> team_defra_operatingtechnique
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_operatingtechnique>("team_defra_operatingtechnique", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_operatingtechnique");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_operatingtechnique>("team_defra_operatingtechnique", null, value);
this.OnPropertyChanged("team_defra_operatingtechnique");
}
}
/// <summary>
/// 1:N team_defra_payment
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_payment")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_payment> team_defra_payment
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_payment>("team_defra_payment", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_payment");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_payment>("team_defra_payment", null, value);
this.OnPropertyChanged("team_defra_payment");
}
}
/// <summary>
/// 1:N team_defra_paymenttransaction
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_paymenttransaction")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_paymenttransaction> team_defra_paymenttransaction
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_paymenttransaction>("team_defra_paymenttransaction", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_paymenttransaction");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_paymenttransaction>("team_defra_paymenttransaction", null, value);
this.OnPropertyChanged("team_defra_paymenttransaction");
}
}
/// <summary>
/// 1:N team_defra_permit
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_permit")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_permit> team_defra_permit
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_permit>("team_defra_permit", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_permit");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_permit>("team_defra_permit", null, value);
this.OnPropertyChanged("team_defra_permit");
}
}
/// <summary>
/// 1:N team_defra_permit_lines
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_permit_lines")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_permit_lines> team_defra_permit_lines
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_permit_lines>("team_defra_permit_lines", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_permit_lines");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_permit_lines>("team_defra_permit_lines", null, value);
this.OnPropertyChanged("team_defra_permit_lines");
}
}
/// <summary>
/// 1:N team_defra_preapplication
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_preapplication")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_preapplication> team_defra_preapplication
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_preapplication>("team_defra_preapplication", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_preapplication");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_preapplication>("team_defra_preapplication", null, value);
this.OnPropertyChanged("team_defra_preapplication");
}
}
/// <summary>
/// 1:N team_defra_saveandreturn
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_saveandreturn")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_saveandreturn> team_defra_saveandreturn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_saveandreturn>("team_defra_saveandreturn", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_saveandreturn");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_saveandreturn>("team_defra_saveandreturn", null, value);
this.OnPropertyChanged("team_defra_saveandreturn");
}
}
/// <summary>
/// 1:N team_defra_secureconfiguration
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_secureconfiguration")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_secureconfiguration> team_defra_secureconfiguration
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_secureconfiguration>("team_defra_secureconfiguration", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_secureconfiguration");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_secureconfiguration>("team_defra_secureconfiguration", null, value);
this.OnPropertyChanged("team_defra_secureconfiguration");
}
}
/// <summary>
/// 1:N team_defra_sitemapsecurity
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_sitemapsecurity")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_sitemapsecurity> team_defra_sitemapsecurity
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_sitemapsecurity>("team_defra_sitemapsecurity", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_sitemapsecurity");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_sitemapsecurity>("team_defra_sitemapsecurity", null, value);
this.OnPropertyChanged("team_defra_sitemapsecurity");
}
}
/// <summary>
/// 1:N team_defra_standardrule
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_standardrule")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_standardrule> team_defra_standardrule
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_standardrule>("team_defra_standardrule", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_standardrule");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_standardrule>("team_defra_standardrule", null, value);
this.OnPropertyChanged("team_defra_standardrule");
}
}
/// <summary>
/// 1:N team_defra_standardruletype
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_standardruletype")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_standardruletype> team_defra_standardruletype
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_standardruletype>("team_defra_standardruletype", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_standardruletype");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_standardruletype>("team_defra_standardruletype", null, value);
this.OnPropertyChanged("team_defra_standardruletype");
}
}
/// <summary>
/// 1:N team_defra_tasktype
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_tasktype")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_tasktype> team_defra_tasktype
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_tasktype>("team_defra_tasktype", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_tasktype");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_tasktype>("team_defra_tasktype", null, value);
this.OnPropertyChanged("team_defra_tasktype");
}
}
/// <summary>
/// 1:N team_defra_town
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_town")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_town> team_defra_town
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_town>("team_defra_town", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_town");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_town>("team_defra_town", null, value);
this.OnPropertyChanged("team_defra_town");
}
}
/// <summary>
/// 1:N team_defra_wasteparams
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_wasteparams")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_wasteparams> team_defra_wasteparams
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_wasteparams>("team_defra_wasteparams", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_wasteparams");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_wasteparams>("team_defra_wasteparams", null, value);
this.OnPropertyChanged("team_defra_wasteparams");
}
}
/// <summary>
/// 1:N team_defra_wastetype
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_wastetype")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_wastetype> team_defra_wastetype
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_wastetype>("team_defra_wastetype", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_wastetype");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_wastetype>("team_defra_wastetype", null, value);
this.OnPropertyChanged("team_defra_wastetype");
}
}
/// <summary>
/// 1:N team_defra_wastetypedetail
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_wastetypedetail")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_wastetypedetail> team_defra_wastetypedetail
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_wastetypedetail>("team_defra_wastetypedetail", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_wastetypedetail");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_wastetypedetail>("team_defra_wastetypedetail", null, value);
this.OnPropertyChanged("team_defra_wastetypedetail");
}
}
/// <summary>
/// 1:N team_defra_webdata
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_defra_webdata")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.defra_webdata> team_defra_webdata
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.defra_webdata>("team_defra_webdata", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_defra_webdata");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.defra_webdata>("team_defra_webdata", null, value);
this.OnPropertyChanged("team_defra_webdata");
}
}
/// <summary>
/// 1:N team_incidents
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_incidents")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.Incident> team_incidents
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.Incident>("team_incidents", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_incidents");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.Incident>("team_incidents", null, value);
this.OnPropertyChanged("team_incidents");
}
}
/// <summary>
/// N:N teammembership_association
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("teammembership_association")]
public System.Collections.Generic.IEnumerable<WastePermits.Model.EarlyBound.SystemUser> teammembership_association
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<WastePermits.Model.EarlyBound.SystemUser>("teammembership_association", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("teammembership_association");
this.SetRelatedEntities<WastePermits.Model.EarlyBound.SystemUser>("teammembership_association", null, value);
this.OnPropertyChanged("teammembership_association");
}
}
/// <summary>
/// N:1 lk_team_createdonbehalfby
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_team_createdonbehalfby")]
public WastePermits.Model.EarlyBound.SystemUser lk_team_createdonbehalfby
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<WastePermits.Model.EarlyBound.SystemUser>("lk_team_createdonbehalfby", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("lk_team_createdonbehalfby");
this.SetRelatedEntity<WastePermits.Model.EarlyBound.SystemUser>("lk_team_createdonbehalfby", null, value);
this.OnPropertyChanged("lk_team_createdonbehalfby");
}
}
/// <summary>
/// N:1 lk_team_modifiedonbehalfby
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_team_modifiedonbehalfby")]
public WastePermits.Model.EarlyBound.SystemUser lk_team_modifiedonbehalfby
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<WastePermits.Model.EarlyBound.SystemUser>("lk_team_modifiedonbehalfby", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("lk_team_modifiedonbehalfby");
this.SetRelatedEntity<WastePermits.Model.EarlyBound.SystemUser>("lk_team_modifiedonbehalfby", null, value);
this.OnPropertyChanged("lk_team_modifiedonbehalfby");
}
}
/// <summary>
/// N:1 lk_teambase_administratorid
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("administratorid")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_teambase_administratorid")]
public WastePermits.Model.EarlyBound.SystemUser lk_teambase_administratorid
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<WastePermits.Model.EarlyBound.SystemUser>("lk_teambase_administratorid", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("lk_teambase_administratorid");
this.SetRelatedEntity<WastePermits.Model.EarlyBound.SystemUser>("lk_teambase_administratorid", null, value);
this.OnPropertyChanged("lk_teambase_administratorid");
}
}
/// <summary>
/// N:1 lk_teambase_createdby
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_teambase_createdby")]
public WastePermits.Model.EarlyBound.SystemUser lk_teambase_createdby
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<WastePermits.Model.EarlyBound.SystemUser>("lk_teambase_createdby", null);
}
}
/// <summary>
/// N:1 lk_teambase_modifiedby
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_teambase_modifiedby")]
public WastePermits.Model.EarlyBound.SystemUser lk_teambase_modifiedby
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<WastePermits.Model.EarlyBound.SystemUser>("lk_teambase_modifiedby", null);
}
}
/// <summary>
/// Constructor for populating via LINQ queries given a LINQ anonymous type
/// <param name="anonymousType">LINQ anonymous type.</param>
/// </summary>
[System.Diagnostics.DebuggerNonUserCode()]
public Team(object anonymousType) :
this()
{
foreach (var p in anonymousType.GetType().GetProperties())
{
var value = p.GetValue(anonymousType, null);
var name = p.Name.ToLower();
if (name.EndsWith("enum") && value.GetType().BaseType == typeof(System.Enum))
{
value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value);
name = name.Remove(name.Length - "enum".Length);
}
switch (name)
{
case "id":
base.Id = (System.Guid)value;
Attributes["teamid"] = base.Id;
break;
case "teamid":
var id = (System.Nullable<System.Guid>) value;
if(id == null){ continue; }
base.Id = id.Value;
Attributes[name] = base.Id;
break;
case "formattedvalues":
// Add Support for FormattedValues
FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value);
break;
default:
Attributes[name] = value;
break;
}
}
}
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("teamtype")]
public virtual Team_TeamType? TeamTypeEnum
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return ((Team_TeamType?)(EntityOptionSetEnum.GetEnum(this, "teamtype")));
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
TeamType = value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null;
}
}
}
} | 35.500998 | 223 | 0.749086 | [
"Unlicense"
] | DEFRA/license-and-permitting-dynamics | Crm/WastePermits/Defra.Lp.WastePermits/Model/EarlyBound/Entities/Team.cs | 71,144 | 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("Blog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Blog")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c0e6f8aa-d44e-4b20-a601-26e22058c023")]
// 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.189189 | 84 | 0.744913 | [
"MIT"
] | PacktPublishing/-Introducing-Test-Driven-Development-in-C- | Section 8/8.2&8.3 - Blog/Blog/Properties/AssemblyInfo.cs | 1,379 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cynosura.Studio.Generator;
using Cynosura.Studio.Generator.Models;
using Microsoft.Extensions.DependencyInjection;
namespace Cynosura.Studio.CliTool.Commands
{
public class GenerateCommand: AppCommand
{
private readonly Dictionary<string, Func<IEnumerable<string>, Task<bool>>> _actions;
public GenerateCommand(string solutionDirectory, string feed, string src, string templateName, ServiceProvider serviceProvider)
: base(solutionDirectory, feed, src, templateName, serviceProvider)
{
_actions = new Dictionary<string, Func<IEnumerable<string>, Task<bool>>>
{
{"entity", GenerateEntityActionAsync},
{"enum", GenerateEnumActionAsync},
{"all", GenerateAllActionAsync},
{
"help", (_) =>
{
Console.Write(Help());
return Task.FromResult(true);
}
}
};
}
public override async Task<bool> ExecuteAsync(string[] args)
{
var command = args.FirstOrDefault();
if (!string.IsNullOrEmpty(command) && _actions.ContainsKey(command))
{
return await _actions[command].Invoke(GetArguments(args.Skip(1)));
}
else
{
Console.Write(Help());
return false;
}
}
private async Task<bool> GenerateAllActionAsync(IEnumerable<string> arg)
{
var accessor = new SolutionAccessor(SolutionDirectory);
var entities = await accessor.GetEntitiesAsync();
foreach (var entity in entities.Where(w => !w.IsAbstract))
{
await GenerateEntityAsync(entity.Name);
Console.WriteLine($"Entity {entity.Name} generated successfully");
}
var enums = await accessor.GetEnumsAsync();
foreach (var en in enums)
{
await GenerateEnumAsync(en.Name);
Console.WriteLine($"Enum {en.Name} generated successfully");
}
return true;
}
private async Task<bool> GenerateEnumActionAsync(IEnumerable<string> args)
{
var ar = args as string[] ?? args.ToArray();
if (ar.Length != 1)
{
Console.WriteLine($"Command syntax: {CliApp.CommandName} generate enum <enumName>");
return false;
}
var name = ar.FirstOrDefault();
await GenerateEnumAsync(name);
Console.WriteLine($"Enum {name} generated successfully");
return true;
}
private async Task GenerateEnumAsync(string name)
{
var accessor = new SolutionAccessor(SolutionDirectory);
var enums = await accessor.GetEnumsAsync();
var generator = ServiceProvider.GetService<EnumGenerator>();
var en = enums.FirstOrDefault(f => f.Name == name);
if (en == null)
{
throw new Exception($"Enum {name} not found");
}
await generator.GenerateEnumAsync(accessor, en);
await generator.GenerateEnumViewAsync(accessor, en);
}
private async Task<bool> GenerateEntityActionAsync(IEnumerable<string> args)
{
var ar = args as string[] ?? args.ToArray();
if (ar.Length != 1)
{
Console.WriteLine($"Command syntax: {CliApp.CommandName} generate entity <entityName>");
return false;
}
var name = ar.FirstOrDefault();
await GenerateEntityAsync(name);
Console.WriteLine($"Entity {name} generated successfully");
return true;
}
private async Task GenerateEntityAsync(string name)
{
var accessor = new SolutionAccessor(SolutionDirectory);
var entities = await accessor.GetEntitiesAsync();
var generator = ServiceProvider.GetService<EntityGenerator>();
var entity = entities.FirstOrDefault(f => f.Name == name);
if (entity == null)
{
throw new Exception($"Entity {name} not found");
}
await generator.GenerateEntityAsync(accessor, entity);
await generator.GenerateEntityViewAsync(accessor, entity);
}
public override string Help()
{
return $"{CliApp.CommandName} generate <action>\r\n" +
$"Available actions: \r\n{string.Join("\r\n", _actions.Keys.Select(s => $"\t{s}"))}\r\n";
}
}
}
| 37.859375 | 135 | 0.558811 | [
"MIT"
] | CynosuraPlatform/Cynosura.Studio | Cynosura.Studio.CliTool/Commands/GenerateCommand.cs | 4,848 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using SelfLoadRO.DataAccess;
using SelfLoadRO.DataAccess.ERCLevel;
namespace SelfLoadRO.DataAccess.Sql.ERCLevel
{
/// <summary>
/// DAL SQL Server implementation of <see cref="ID11_CityRoadCollDal"/>
/// </summary>
public partial class D11_CityRoadCollDal : ID11_CityRoadCollDal
{
/// <summary>
/// Loads a D11_CityRoadColl collection from the database.
/// </summary>
/// <param name="parent_City_ID">The Parent City ID.</param>
/// <returns>A data reader to the D11_CityRoadColl.</returns>
public IDataReader Fetch(int parent_City_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetD11_CityRoadColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_City_ID", parent_City_ID).DbType = DbType.Int32;
return cmd.ExecuteReader();
}
}
}
}
}
| 34.8 | 106 | 0.600985 | [
"MIT"
] | CslaGenFork/CslaGenFork | trunk/Samples/DeepLoad/DAL-DR/SelfLoadRO.DataAccess.Sql/ERCLevel/D11_CityRoadCollDal.Designer.cs | 1,218 | C# |
#region
using System;
using System.Threading.Tasks;
#endregion
namespace ESS.Framework.Common.Remoting
{
public class ResponseFuture
{
private readonly TaskCompletionSource<RemotingResponse> _taskSource;
public ResponseFuture(RemotingRequest request, long timeoutMillis, TaskCompletionSource<RemotingResponse> taskSource)
{
Request = request;
TimeoutMillis = timeoutMillis;
_taskSource = taskSource;
BeginTime = DateTime.Now;
}
public DateTime BeginTime { get; private set; }
public long TimeoutMillis { get; private set; }
public RemotingRequest Request { get; private set; }
public bool IsTimeout()
{
return (DateTime.Now - BeginTime).TotalMilliseconds > TimeoutMillis;
}
public void SetResponse(RemotingResponse response)
{
_taskSource.TrySetResult(response);
}
public void SetException(Exception exception)
{
_taskSource.TrySetException(exception);
}
}
} | 26.609756 | 125 | 0.63978 | [
"Apache-2.0"
] | wh-ess/ess | Framework/ESS.Framework.Common/Remoting/ResponseFuture.cs | 1,093 | C# |
#pragma checksum "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "844c91561babeb5de74a83004e931a3cfccc7f7c"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_DataModel_Details), @"mvc.1.0.view", @"/Views/DataModel/Details.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "D:\source\repos\clean\Happy_Analysis\Views\_ViewImports.cshtml"
using Happy_Analysis;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "D:\source\repos\clean\Happy_Analysis\Views\_ViewImports.cshtml"
using Happy_Analysis.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"844c91561babeb5de74a83004e931a3cfccc7f7c", @"/Views/DataModel/Details.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b827355e4c919c13976806e5f9a62459315d66b8", @"/Views/_ViewImports.cshtml")]
public class Views_DataModel_Details : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Happy_Analysis.Models.DataModel>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n");
#nullable restore
#line 3 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
ViewData["Title"] = "Details";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>Details</h1>\r\n\r\n<div>\r\n <h4>DataModel</h4>\r\n <hr />\r\n <dl class=\"row\">\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 14 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Name));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 17 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayFor(model => model.Name));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 20 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Percentage1));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 23 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayFor(model => model.Percentage1));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 26 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Percentage2));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 29 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayFor(model => model.Percentage2));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 32 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Percentage3));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 35 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayFor(model => model.Percentage3));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 38 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Percentage4));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 41 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayFor(model => model.Percentage4));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 44 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Percentage5));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 47 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayFor(model => model.Percentage5));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 50 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Percentage6));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 53 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayFor(model => model.Percentage6));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n ");
#nullable restore
#line 56 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Created));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n ");
#nullable restore
#line 59 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
Write(Html.DisplayFor(model => model.Created));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </dd>\r\n </dl>\r\n</div>\r\n<div>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "844c91561babeb5de74a83004e931a3cfccc7f7c9012", async() => {
WriteLiteral("Edit");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 64 "D:\source\repos\clean\Happy_Analysis\Views\DataModel\Details.cshtml"
WriteLiteral(Model.ID);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(" |\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "844c91561babeb5de74a83004e931a3cfccc7f7c11142", async() => {
WriteLiteral("Back to List");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</div>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<Happy_Analysis.Models.DataModel> Html { get; private set; }
}
}
#pragma warning restore 1591
| 50.281853 | 298 | 0.69838 | [
"MIT"
] | alyssaolivia/Happy-Analysis | obj/Debug/netcoreapp3.1/Razor/Views/DataModel/Details.cshtml.g.cs | 13,023 | C# |
using Content.Server.Chemistry.Components;
using Content.Server.Coordinates.Helpers;
using Content.Shared.Audio;
using Content.Shared.Chemistry.Components;
using Content.Shared.Sound;
using JetBrains.Annotations;
using Robust.Shared.Audio;
using Robust.Shared.Map;
using Robust.Shared.Player;
namespace Content.Server.Chemistry.ReactionEffects
{
[UsedImplicitly]
[DataDefinition]
public sealed class FoamAreaReactionEffect : AreaReactionEffect
{
protected override SolutionAreaEffectComponent? GetAreaEffectComponent(EntityUid entity)
{
return IoCManager.Resolve<IEntityManager>().GetComponentOrNull<FoamSolutionAreaEffectComponent>(entity);
}
public static void SpawnFoam(string entityPrototype, EntityCoordinates coords, Solution? contents, int amount, float duration, float spreadDelay,
float removeDelay, SoundSpecifier sound, IEntityManager? entityManager = null)
{
entityManager ??= IoCManager.Resolve<IEntityManager>();
var ent = entityManager.SpawnEntity(entityPrototype, coords.SnapToGrid());
var areaEffectComponent = entityManager.GetComponentOrNull<FoamSolutionAreaEffectComponent>(ent);
if (areaEffectComponent == null)
{
Logger.Error("Couldn't get AreaEffectComponent from " + entityPrototype);
IoCManager.Resolve<IEntityManager>().QueueDeleteEntity(ent);
return;
}
if (contents != null)
areaEffectComponent.TryAddSolution(contents);
areaEffectComponent.Start(amount, duration, spreadDelay, removeDelay);
SoundSystem.Play(sound.GetSound(), Filter.Pvs(ent), ent, AudioHelpers.WithVariation(0.125f));
}
}
}
| 39.777778 | 153 | 0.703911 | [
"MIT"
] | EmoGarbage404/space-station-14 | Content.Server/Chemistry/ReactionEffects/FoamAreaReactionEffect.cs | 1,792 | C# |
using LeetCode_Solutions.helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shouldly;
namespace LeetCode_Solutions.LinkedList
{
/*
* Given a linked list, swap every two adjacent nodes and return its head.
* You may not modify the values in the list's nodes, only nodes itself may be changed.
*
* Given 1->2->3->4, you should return the list as 2->1->4->3.
*/
[TestClass]
public class SwapNodeInPairs
{
[TestMethod]
public void LinkedListSwapNodeInPairs_WithNormalCase()
{
var originLists = ListNodeHelpers.CreateLinkedList(new int[4] { 1, 2, 3, 4 });
var result = ListNodeHelpers.CreateLinkedList(new int[4] { 2, 1, 4, 3 });
ListNodeHelpers.ListToString(SwapNodeInPairsWithRecursion(originLists)).ShouldBe(ListNodeHelpers.ListToString(result));
}
public ListNode SwapNodeInPairsWithRecursion(ListNode head)
{
if (head?.next == null) return head;
var p = SwapNodeInPairsWithRecursion(head.next.next);
var n2 = head.next;
n2.next = head;
head.next = p;
return n2;
}
}
}
| 33.333333 | 131 | 0.630833 | [
"MIT"
] | ZeyuWangGit/Leetcode_Question_And_Solution | LeetCode_Solutions/LinkedList/SwapNodeInPairs.cs | 1,202 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\opmapi.h(182,1)
namespace DirectN
{
public enum _OPM_DPCP_PROTECTION_LEVEL
{
OPM_DPCP_OFF = 0,
OPM_DPCP_ON = 1,
OPM_DPCP_FORCE_ULONG = 2147483647,
}
}
| 24 | 83 | 0.625 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/_OPM_DPCP_PROTECTION_LEVEL.cs | 266 | C# |
using System;
using System.Collections.Generic;
namespace Edison.Core.Common.Models
{
public class ChatReportModel
{
public Guid ReportId { get; set; }
public string ChannelId { get; set; }
public ChatUserModel User { get; set; }
public List<ChatReportLogModel> ReportLogs { get; set; }
public DateTime? EndDate { get; set; }
public string ETag { get; set; }
}
}
| 26.5625 | 64 | 0.635294 | [
"MIT"
] | Mahesh1998/ProjectEdison | Edison.Core/Edison.Core.Common/Models/ChatReport/ChatReportModel.cs | 427 | C# |
#pragma checksum "C:\Users\lli\Desktop\MultithreadingwithCCookbookSecondEdition_Code\MultithreadingwithCCookbookSecondEdition_Code\Chapter11\Recipe3\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "69FC751654CD6576153E0A3584FE5648"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Recipe3
{
partial class MainPage : global::Windows.UI.Xaml.Controls.Page
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
private global::Windows.UI.Xaml.Controls.TextBlock Clock;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
private bool _contentLoaded;
/// <summary>
/// InitializeComponent()
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
global::System.Uri resourceLocator = new global::System.Uri("ms-appx:///MainPage.xaml");
global::Windows.UI.Xaml.Application.LoadComponent(this, resourceLocator, global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application);
}
}
}
| 41.333333 | 240 | 0.630184 | [
"MIT"
] | llibetter/Multithreading-with-CSharp-CookBook | Chapter11/Recipe3/obj/x86/Debug/MainPage.g.i.cs | 1,738 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02. OrderedBag")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02. OrderedBag")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("6b53e764-fa7d-44e4-91d4-5926fa6e3334")]
// 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.864865 | 84 | 0.743041 | [
"MIT"
] | niki-funky/Telerik_Academy | Programming/Data Structures and Algorithms/04. Algo/04. Advanced Data Structures/02. OrderedBag/Properties/AssemblyInfo.cs | 1,404 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.Network
{
/// <summary>
/// Manages the association between a Network Interface and a Load Balancer's Backend Address Pool.
///
/// > This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/r/network_interface_backend_address_pool_association.html.markdown.
/// </summary>
public partial class NetworkInterfaceBackendAddressPoolAssociation : Pulumi.CustomResource
{
/// <summary>
/// The ID of the Load Balancer Backend Address Pool which this Network Interface which should be connected to. Changing this forces a new resource to be created.
/// </summary>
[Output("backendAddressPoolId")]
public Output<string> BackendAddressPoolId { get; private set; } = null!;
/// <summary>
/// The Name of the IP Configuration within the Network Interface which should be connected to the Backend Address Pool. Changing this forces a new resource to be created.
/// </summary>
[Output("ipConfigurationName")]
public Output<string> IpConfigurationName { get; private set; } = null!;
/// <summary>
/// The ID of the Network Interface. Changing this forces a new resource to be created.
/// </summary>
[Output("networkInterfaceId")]
public Output<string> NetworkInterfaceId { get; private set; } = null!;
/// <summary>
/// Create a NetworkInterfaceBackendAddressPoolAssociation resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public NetworkInterfaceBackendAddressPoolAssociation(string name, NetworkInterfaceBackendAddressPoolAssociationArgs args, CustomResourceOptions? options = null)
: base("azure:network/networkInterfaceBackendAddressPoolAssociation:NetworkInterfaceBackendAddressPoolAssociation", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, ""))
{
}
private NetworkInterfaceBackendAddressPoolAssociation(string name, Input<string> id, NetworkInterfaceBackendAddressPoolAssociationState? state = null, CustomResourceOptions? options = null)
: base("azure:network/networkInterfaceBackendAddressPoolAssociation:NetworkInterfaceBackendAddressPoolAssociation", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing NetworkInterfaceBackendAddressPoolAssociation resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static NetworkInterfaceBackendAddressPoolAssociation Get(string name, Input<string> id, NetworkInterfaceBackendAddressPoolAssociationState? state = null, CustomResourceOptions? options = null)
{
return new NetworkInterfaceBackendAddressPoolAssociation(name, id, state, options);
}
}
public sealed class NetworkInterfaceBackendAddressPoolAssociationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The ID of the Load Balancer Backend Address Pool which this Network Interface which should be connected to. Changing this forces a new resource to be created.
/// </summary>
[Input("backendAddressPoolId", required: true)]
public Input<string> BackendAddressPoolId { get; set; } = null!;
/// <summary>
/// The Name of the IP Configuration within the Network Interface which should be connected to the Backend Address Pool. Changing this forces a new resource to be created.
/// </summary>
[Input("ipConfigurationName", required: true)]
public Input<string> IpConfigurationName { get; set; } = null!;
/// <summary>
/// The ID of the Network Interface. Changing this forces a new resource to be created.
/// </summary>
[Input("networkInterfaceId", required: true)]
public Input<string> NetworkInterfaceId { get; set; } = null!;
public NetworkInterfaceBackendAddressPoolAssociationArgs()
{
}
}
public sealed class NetworkInterfaceBackendAddressPoolAssociationState : Pulumi.ResourceArgs
{
/// <summary>
/// The ID of the Load Balancer Backend Address Pool which this Network Interface which should be connected to. Changing this forces a new resource to be created.
/// </summary>
[Input("backendAddressPoolId")]
public Input<string>? BackendAddressPoolId { get; set; }
/// <summary>
/// The Name of the IP Configuration within the Network Interface which should be connected to the Backend Address Pool. Changing this forces a new resource to be created.
/// </summary>
[Input("ipConfigurationName")]
public Input<string>? IpConfigurationName { get; set; }
/// <summary>
/// The ID of the Network Interface. Changing this forces a new resource to be created.
/// </summary>
[Input("networkInterfaceId")]
public Input<string>? NetworkInterfaceId { get; set; }
public NetworkInterfaceBackendAddressPoolAssociationState()
{
}
}
}
| 51.184615 | 207 | 0.680643 | [
"ECL-2.0",
"Apache-2.0"
] | apollo2030/pulumi-azure | sdk/dotnet/Network/NetworkInterfaceBackendAddressPoolAssociation.cs | 6,654 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Dev.Plugin.Data.EFCore.Data
{
public static class DbContextExtensions
{
#region Utilities
/// <summary>
/// Get SQL commands from the script
/// </summary>
/// <param name="sql">SQL script</param>
/// <returns>List of commands</returns>
private static IList<string> GetCommandsFromScript(string sql)
{
var commands = new List<string>();
//origin from the Microsoft.EntityFrameworkCore.Migrations.SqlServerMigrationsSqlGenerator.Generate method
sql = Regex.Replace(sql, @"\\\r?\n", string.Empty);
var batches = Regex.Split(sql, @"^\s*(GO[ \t]+[0-9]+|GO)(?:\s+|$)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
for (var i = 0; i < batches.Length; i++)
{
if (string.IsNullOrWhiteSpace(batches[i]) || batches[i].StartsWith("GO", StringComparison.OrdinalIgnoreCase))
continue;
var count = 1;
if (i != batches.Length - 1 && batches[i + 1].StartsWith("GO", StringComparison.OrdinalIgnoreCase))
{
var match = Regex.Match(batches[i + 1], "([0-9]+)");
if (match.Success)
count = int.Parse(match.Value);
}
var builder = new StringBuilder();
for (var j = 0; j < count; j++)
{
builder.Append(batches[i]);
if (i == batches.Length - 1)
builder.AppendLine();
}
commands.Add(builder.ToString());
}
return commands;
}
#endregion Utilities
public static void SetupDatabase(this IDevDbContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
string sql = context.GenerateCreateScript();
var sqlCommands = GetCommandsFromScript(sql);
foreach (var command in sqlCommands)
context.ExecuteSqlCommand(command);
}
}
} | 34.723077 | 130 | 0.534781 | [
"Apache-2.0"
] | DevBetterNet/ffn | webapi/src/plugins/Dev.Plugin.Data.EFCore/Data/DbContextExtensions.cs | 2,259 | C# |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Threading;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Processor;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
#pragma warning disable IDE0079 // remove unnecessary pragmas
#pragma warning disable IDE0063 // using can be simplified, we don't
namespace Thrift.Server
{
/// <summary>
/// Server that uses C# built-in ThreadPool to spawn threads when handling requests.
/// </summary>
public class TThreadPoolAsyncServer : TServer
{
private const int DEFAULT_MIN_THREADS = -1; // use .NET ThreadPool defaults
private const int DEFAULT_MAX_THREADS = -1; // use .NET ThreadPool defaults
private volatile bool stop = false;
private CancellationToken ServerCancellationToken;
public struct Configuration
{
public int MinWorkerThreads;
public int MaxWorkerThreads;
public int MinIOThreads;
public int MaxIOThreads;
public Configuration(int min = DEFAULT_MIN_THREADS, int max = DEFAULT_MAX_THREADS)
{
MinWorkerThreads = min;
MaxWorkerThreads = max;
MinIOThreads = min;
MaxIOThreads = max;
}
public Configuration(int minWork, int maxWork, int minIO, int maxIO)
{
MinWorkerThreads = minWork;
MaxWorkerThreads = maxWork;
MinIOThreads = minIO;
MaxIOThreads = maxIO;
}
}
public TThreadPoolAsyncServer(ITAsyncProcessor processor, TServerTransport serverTransport, ILogger logger = null)
: this(new TSingletonProcessorFactory(processor), serverTransport,
null, null, // defaults to TTransportFactory()
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
new Configuration(), logger)
{
}
public TThreadPoolAsyncServer(ITAsyncProcessor processor,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(new TSingletonProcessorFactory(processor), serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
new Configuration())
{
}
public TThreadPoolAsyncServer(ITProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(processorFactory, serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
new Configuration())
{
}
public TThreadPoolAsyncServer(ITProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
int minThreadPoolThreads, int maxThreadPoolThreads, ILogger logger= null)
: this(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory,
inputProtocolFactory, outputProtocolFactory,
new Configuration(minThreadPoolThreads, maxThreadPoolThreads),
logger)
{
}
public TThreadPoolAsyncServer(ITProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
Configuration threadConfig,
ILogger logger = null)
: base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory,
inputProtocolFactory, outputProtocolFactory, logger)
{
lock (typeof(TThreadPoolAsyncServer))
{
if ((threadConfig.MaxWorkerThreads > 0) || (threadConfig.MaxIOThreads > 0))
{
ThreadPool.GetMaxThreads(out int work, out int comm);
if (threadConfig.MaxWorkerThreads > 0)
work = threadConfig.MaxWorkerThreads;
if (threadConfig.MaxIOThreads > 0)
comm = threadConfig.MaxIOThreads;
if (!ThreadPool.SetMaxThreads(work, comm))
throw new Exception("Error: could not SetMaxThreads in ThreadPool");
}
if ((threadConfig.MinWorkerThreads > 0) || (threadConfig.MinIOThreads > 0))
{
ThreadPool.GetMinThreads(out int work, out int comm);
if (threadConfig.MinWorkerThreads > 0)
work = threadConfig.MinWorkerThreads;
if (threadConfig.MinIOThreads > 0)
comm = threadConfig.MinIOThreads;
if (!ThreadPool.SetMinThreads(work, comm))
throw new Exception("Error: could not SetMinThreads in ThreadPool");
}
}
}
/// <summary>
/// Use new ThreadPool thread for each new client connection.
/// </summary>
public override async Task ServeAsync(CancellationToken cancellationToken)
{
ServerCancellationToken = cancellationToken;
try
{
try
{
ServerTransport.Listen();
}
catch (TTransportException ttx)
{
LogError("Error, could not listen on ServerTransport: " + ttx);
return;
}
//Fire the preServe server event when server is up but before any client connections
if (ServerEventHandler != null)
await ServerEventHandler.PreServeAsync(cancellationToken);
while (!(stop || ServerCancellationToken.IsCancellationRequested))
{
try
{
TTransport client = await ServerTransport.AcceptAsync(cancellationToken);
_ = Task.Run(async () => await ExecuteAsync(client), cancellationToken); // intentionally ignoring retval
}
catch (TaskCanceledException)
{
stop = true;
}
catch (TTransportException ttx)
{
if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted)
{
LogError(ttx.ToString());
}
}
}
if (stop)
{
try
{
ServerTransport.Close();
}
catch (TTransportException ttx)
{
LogError("TServerTransport failed on close: " + ttx.Message);
}
stop = false;
}
}
finally
{
ServerCancellationToken = default;
}
}
/// <summary>
/// Loops on processing a client forever
/// threadContext will be a TTransport instance
/// </summary>
/// <param name="threadContext"></param>
private async Task ExecuteAsync(TTransport client)
{
var cancellationToken = ServerCancellationToken;
using (client)
{
ITAsyncProcessor processor = ProcessorFactory.GetAsyncProcessor(client, this);
TTransport inputTransport = null;
TTransport outputTransport = null;
TProtocol inputProtocol = null;
TProtocol outputProtocol = null;
object connectionContext = null;
try
{
try
{
inputTransport = InputTransportFactory.GetTransport(client);
outputTransport = OutputTransportFactory.GetTransport(client);
inputProtocol = InputProtocolFactory.GetProtocol(inputTransport);
outputProtocol = OutputProtocolFactory.GetProtocol(outputTransport);
//Recover event handler (if any) and fire createContext server event when a client connects
if (ServerEventHandler != null)
connectionContext = await ServerEventHandler.CreateContextAsync(inputProtocol, outputProtocol, cancellationToken);
//Process client requests until client disconnects
while (!stop)
{
if (! await inputTransport.PeekAsync(cancellationToken))
break;
//Fire processContext server event
//N.B. This is the pattern implemented in C++ and the event fires provisionally.
//That is to say it may be many minutes between the event firing and the client request
//actually arriving or the client may hang up without ever makeing a request.
if (ServerEventHandler != null)
await ServerEventHandler.ProcessContextAsync(connectionContext, inputTransport, cancellationToken);
//Process client request (blocks until transport is readable)
if (! await processor.ProcessAsync(inputProtocol, outputProtocol, cancellationToken))
break;
}
}
catch (TTransportException)
{
//Usually a client disconnect, expected
}
catch (Exception x)
{
//Unexpected
LogError("Error: " + x);
}
//Fire deleteContext server event after client disconnects
if (ServerEventHandler != null)
await ServerEventHandler.DeleteContextAsync(connectionContext, inputProtocol, outputProtocol, cancellationToken);
}
finally
{
//Close transports
inputTransport?.Close();
outputTransport?.Close();
// disposable stuff should be disposed
inputProtocol?.Dispose();
outputProtocol?.Dispose();
inputTransport?.Dispose();
outputTransport?.Dispose();
}
}
}
public override void Stop()
{
stop = true;
ServerTransport?.Close();
}
}
}
| 41.288079 | 142 | 0.551207 | [
"Apache-2.0"
] | BioDataAnalysis/thrift | lib/netstd/Thrift/Server/TThreadPoolAsyncServer.cs | 12,469 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using LeanCloud.Core.Internal;
using LeanCloud.Storage.Internal;
namespace LeanCloud.Engine.Rpc
{
public interface IRpc
{
}
public static class RpcExtensions
{
public static async Task<object> InvokeAsync(this MethodInfo @this, object obj, params object[] parameters)
{
dynamic awaitable = @this.Invoke(obj, parameters);
await awaitable;
return awaitable.GetAwaiter().GetResult();
}
public static RpcServer UseRpc(this IRpc host, RpcServer server)
{
var tupple = host.ReflectRpcFunctions();
tupple.ForEach(t =>
{
server.Register(t.Item1, t.Item2);
});
return server;
}
public static List<(string, RpcFunctionDelegate)> ReflectRpcFunctions(this IRpc rpcHost)
{
var hostType = rpcHost.GetType();
var methods = hostType.GetMethods();
var tupple = new List<(string, RpcFunctionDelegate)>();
foreach (var method in methods)
{
var hookAttributes = method.GetCustomAttributes(typeof(RpcAttribute), false);
if (hookAttributes.Length == 1)
{
var rpcAttribute = (RpcAttribute)hookAttributes[0];
RpcFunctionDelegate rpcFunction = async (context) =>
{
var pas = BindParamters(method, context);
object result = null;
object host = null;
if (!method.IsStatic)
{
host = rpcHost;
}
if (method.ReturnType == typeof(Task))
{
Task awaitable = (Task)method.Invoke(host, pas);
await awaitable;
}
else if (method.ReturnType == typeof(void))
{
method.Invoke(host, pas);
}
else if (method.ReturnType.IsGenericType)
{
if (method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
result = await method.InvokeAsync(host, pas);
else
{
result = method.Invoke(host, pas);
}
}
else
{
result = method.Invoke(host, pas);
}
var encodedObject = PointerOrLocalIdEncoder.Instance.Encode(result);
var resultWrapper = new Dictionary<string, object>()
{
{ "results" , encodedObject }
};
if (context is StorageRpcContext storageRpcContext)
{
storageRpcContext.Response.MetaText = Json.Encode(resultWrapper);
}
};
var hostName = rpcHost.ReflectRpcHostName();
var methodName = rpcAttribute.Name ?? method.Name;
var rpcMethodName = $"{hostName}_{methodName}";
if (!method.IsStatic)
{
var hostId = rpcHost.ReflectRpcHostIdPropertyValue();
rpcMethodName = $"{hostName}_{hostId}_{methodName}";
}
var mixedResult = (rpcMethodName, rpcFunction);
tupple.Add(mixedResult);
}
}
return tupple;
}
public static object[] BindParamters(MethodInfo memberInfo, RpcContext context)
{
List<object> result = new List<object>();
ParameterInfo[] rpcParameters = memberInfo.GetParameters();
if (context is StorageRpcContext storageRpcContext)
{
var pObjs = storageRpcContext.Request.Body["args"] as List<object>;
for (int i = 0; i < rpcParameters.Length - 1; i++)
{
var pInfo = rpcParameters[i];
var pObj = AVDecoder.Instance.Decode(pObjs[i]);
var pValue = pObj;
result.Add(pValue);
}
result.Add(context);
}
return result.ToArray();
}
public static string ReflectRpcHostName(this IRpc rpcHost)
{
var hostType = rpcHost.GetType();
var hostAttribute = hostType.GetCustomAttribute<RpcHostAttribute>();
if (hostAttribute == null)
{
if (rpcHost is AVObject avobj)
{
return avobj.ClassName;
}
}
var hostName = string.IsNullOrEmpty(hostAttribute.Name) ? hostType.Name : hostAttribute.Name;
return hostName;
}
public static string ReflectRpcHostIdPropertyValue(this IRpc rpcHost)
{
PropertyInfo[] props = rpcHost.GetType().GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
if (attr is RpcHostIdAttribute idAttr)
{
return prop.GetValue(rpcHost).ToString();
}
}
}
if (rpcHost is AVObject avobj)
{
return avobj.ObjectId;
}
return "";
}
}
public delegate Task RpcFunctionDelegate(RpcContext context);
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public sealed class RpcHostAttribute : Attribute
{
public string Name { get; set; }
public RpcHostAttribute(string name = null)
{
Name = name;
}
}
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class RpcHostIdAttribute : Attribute
{
public RpcHostIdAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class RpcAttribute : Attribute
{
public string Name { get; set; }
public RpcAttribute(string name = null)
{
Name = name;
}
}
}
| 35.245 | 116 | 0.470847 | [
"Apache-2.0"
] | leancloud/leanegine-dotnet-sdk | src/Rpc/IRpc.cs | 7,051 | C# |
/*
http://www.cgsoso.com/forum-211-1.html
CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源!
CGSOSO 主打游戏开发,影视设计等CG资源素材。
插件如若商用,请务必官网购买!
daily assets update for try.
U should buy the asset from home store if u use it in your project!
*/
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Math.Raw;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecP256K1Point
: AbstractFpPoint
{
/**
* Create a point which encodes with point compression.
*
* @param curve
* the curve to use
* @param x
* affine x co-ordinate
* @param y
* affine y co-ordinate
*
* @deprecated Use ECCurve.createPoint to construct points
*/
public SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
: this(curve, x, y, false)
{
}
/**
* Create a point that encodes with or without point compresion.
*
* @param curve
* the curve to use
* @param x
* affine x co-ordinate
* @param y
* affine y co-ordinate
* @param withCompression
* if true encode with point compression
*
* @deprecated per-point compression property will be removed, refer
* {@link #getEncoded(bool)}
*/
public SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
: base(curve, x, y, withCompression)
{
if ((x == null) != (y == null))
throw new ArgumentException("Exactly one of the field elements is null");
}
internal SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs,
bool withCompression)
: base(curve, x, y, zs, withCompression)
{
}
protected override ECPoint Detach()
{
return new SecP256K1Point(null, AffineXCoord, AffineYCoord);
}
public override ECPoint Add(ECPoint b)
{
if (this.IsInfinity)
return b;
if (b.IsInfinity)
return this;
if (this == b)
return Twice();
ECCurve curve = this.Curve;
SecP256K1FieldElement X1 = (SecP256K1FieldElement)this.RawXCoord, Y1 = (SecP256K1FieldElement)this.RawYCoord;
SecP256K1FieldElement X2 = (SecP256K1FieldElement)b.RawXCoord, Y2 = (SecP256K1FieldElement)b.RawYCoord;
SecP256K1FieldElement Z1 = (SecP256K1FieldElement)this.RawZCoords[0];
SecP256K1FieldElement Z2 = (SecP256K1FieldElement)b.RawZCoords[0];
uint c;
uint[] tt1 = Nat256.CreateExt();
uint[] t2 = Nat256.Create();
uint[] t3 = Nat256.Create();
uint[] t4 = Nat256.Create();
bool Z1IsOne = Z1.IsOne;
uint[] U2, S2;
if (Z1IsOne)
{
U2 = X2.x;
S2 = Y2.x;
}
else
{
S2 = t3;
SecP256K1Field.Square(Z1.x, S2);
U2 = t2;
SecP256K1Field.Multiply(S2, X2.x, U2);
SecP256K1Field.Multiply(S2, Z1.x, S2);
SecP256K1Field.Multiply(S2, Y2.x, S2);
}
bool Z2IsOne = Z2.IsOne;
uint[] U1, S1;
if (Z2IsOne)
{
U1 = X1.x;
S1 = Y1.x;
}
else
{
S1 = t4;
SecP256K1Field.Square(Z2.x, S1);
U1 = tt1;
SecP256K1Field.Multiply(S1, X1.x, U1);
SecP256K1Field.Multiply(S1, Z2.x, S1);
SecP256K1Field.Multiply(S1, Y1.x, S1);
}
uint[] H = Nat256.Create();
SecP256K1Field.Subtract(U1, U2, H);
uint[] R = t2;
SecP256K1Field.Subtract(S1, S2, R);
// Check if b == this or b == -this
if (Nat256.IsZero(H))
{
if (Nat256.IsZero(R))
{
// this == b, i.e. this must be doubled
return this.Twice();
}
// this == -b, i.e. the result is the point at infinity
return curve.Infinity;
}
uint[] HSquared = t3;
SecP256K1Field.Square(H, HSquared);
uint[] G = Nat256.Create();
SecP256K1Field.Multiply(HSquared, H, G);
uint[] V = t3;
SecP256K1Field.Multiply(HSquared, U1, V);
SecP256K1Field.Negate(G, G);
Nat256.Mul(S1, G, tt1);
c = Nat256.AddBothTo(V, V, G);
SecP256K1Field.Reduce32(c, G);
SecP256K1FieldElement X3 = new SecP256K1FieldElement(t4);
SecP256K1Field.Square(R, X3.x);
SecP256K1Field.Subtract(X3.x, G, X3.x);
SecP256K1FieldElement Y3 = new SecP256K1FieldElement(G);
SecP256K1Field.Subtract(V, X3.x, Y3.x);
SecP256K1Field.MultiplyAddToExt(Y3.x, R, tt1);
SecP256K1Field.Reduce(tt1, Y3.x);
SecP256K1FieldElement Z3 = new SecP256K1FieldElement(H);
if (!Z1IsOne)
{
SecP256K1Field.Multiply(Z3.x, Z1.x, Z3.x);
}
if (!Z2IsOne)
{
SecP256K1Field.Multiply(Z3.x, Z2.x, Z3.x);
}
ECFieldElement[] zs = new ECFieldElement[] { Z3 };
return new SecP256K1Point(curve, X3, Y3, zs, IsCompressed);
}
public override ECPoint Twice()
{
if (this.IsInfinity)
return this;
ECCurve curve = this.Curve;
SecP256K1FieldElement Y1 = (SecP256K1FieldElement)this.RawYCoord;
if (Y1.IsZero)
return curve.Infinity;
SecP256K1FieldElement X1 = (SecP256K1FieldElement)this.RawXCoord, Z1 = (SecP256K1FieldElement)this.RawZCoords[0];
uint c;
uint[] Y1Squared = Nat256.Create();
SecP256K1Field.Square(Y1.x, Y1Squared);
uint[] T = Nat256.Create();
SecP256K1Field.Square(Y1Squared, T);
uint[] M = Nat256.Create();
SecP256K1Field.Square(X1.x, M);
c = Nat256.AddBothTo(M, M, M);
SecP256K1Field.Reduce32(c, M);
uint[] S = Y1Squared;
SecP256K1Field.Multiply(Y1Squared, X1.x, S);
c = Nat.ShiftUpBits(8, S, 2, 0);
SecP256K1Field.Reduce32(c, S);
uint[] t1 = Nat256.Create();
c = Nat.ShiftUpBits(8, T, 3, 0, t1);
SecP256K1Field.Reduce32(c, t1);
SecP256K1FieldElement X3 = new SecP256K1FieldElement(T);
SecP256K1Field.Square(M, X3.x);
SecP256K1Field.Subtract(X3.x, S, X3.x);
SecP256K1Field.Subtract(X3.x, S, X3.x);
SecP256K1FieldElement Y3 = new SecP256K1FieldElement(S);
SecP256K1Field.Subtract(S, X3.x, Y3.x);
SecP256K1Field.Multiply(Y3.x, M, Y3.x);
SecP256K1Field.Subtract(Y3.x, t1, Y3.x);
SecP256K1FieldElement Z3 = new SecP256K1FieldElement(M);
SecP256K1Field.Twice(Y1.x, Z3.x);
if (!Z1.IsOne)
{
SecP256K1Field.Multiply(Z3.x, Z1.x, Z3.x);
}
return new SecP256K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed);
}
public override ECPoint TwicePlus(ECPoint b)
{
if (this == b)
return ThreeTimes();
if (this.IsInfinity)
return b;
if (b.IsInfinity)
return Twice();
ECFieldElement Y1 = this.RawYCoord;
if (Y1.IsZero)
return b;
return Twice().Add(b);
}
public override ECPoint ThreeTimes()
{
if (this.IsInfinity || this.RawYCoord.IsZero)
return this;
// NOTE: Be careful about recursions between TwicePlus and ThreeTimes
return Twice().Add(this);
}
public override ECPoint Negate()
{
if (IsInfinity)
return this;
return new SecP256K1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed);
}
}
}
#endif
| 30.181818 | 125 | 0.512743 | [
"MIT"
] | zhoumingliang/test-git-subtree | Assets/RotateMe/Scripts/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/ec/custom/sec/SecP256K1Point.cs | 8,726 | C# |
using System.Collections.Generic;
using Android.App;
using Android.Graphics;
using Android.OS;
using Android.Support.V4.Content;
using Android.Support.V7.Widget;
using Android.Support.V7.Widget.Helper;
using Android.Util;
using BaseRecyclerViewAdapterHelper.Sample.Adapter;
using BaseRecyclerViewAdapterHelper.Sample.Base;
using BaseRecyclerViewAdapterHelper.Sample.Util;
using CymChad.BaseRecyclerViewAdapterHelper.Adapter.Base;
using CymChad.BaseRecyclerViewAdapterHelper.Adapter.Base.Callback;
namespace BaseRecyclerViewAdapterHelper.Sample
{
[Activity]
public class ItemDragAndSwipeUseActivity : BaseActivity
{
new static string Tag => Java.Lang.Class.FromType(typeof(ItemDragAndSwipeUseActivity)).SimpleName;
RecyclerView _recyclerView;
List<string> _data;
ItemDragAdapter _adapter;
ItemTouchHelper _itemTouchHelper;
ItemDragAndSwipeCallback _itemDragAndSwipeCallback;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_item_touch_use);
SetBackBtn();
SetTitle("ItemDrag And Swipe");
_recyclerView = FindViewById<RecyclerView>(Resource.Id.rv_list);
_recyclerView.SetLayoutManager(new LinearLayoutManager(this));
_data = GenerateData(50);
var paint = new Paint();
paint.AntiAlias = true;
paint.TextSize = 20;
paint.Color = Color.Black;
_adapter = new ItemDragAdapter(_data);
_adapter.ItemDragStart += (s, e) =>
{
Log.Debug(Tag, "drag start");
var holder = e.ViewHolder as BaseViewHolder;
// holder.SetTextColor(Resource.Id.tv, Color.White);
};
_adapter.ItemDragMoving += (s, e) =>
{
Log.Debug(Tag, $"move from: {e.Source.AdapterPosition} to: {e.Target.AdapterPosition}");
};
_adapter.ItemDragEnd += (s, e) =>
{
Log.Debug(Tag, "drag end");
var holder = e.ViewHolder as BaseViewHolder;
// holder.SetTextColor(Resource.Id.tv, Color.Black);
};
_adapter.ItemSwipeStart += (s, e) =>
{
Log.Debug(Tag, "view swiped start: " + e.Pos);
var holder = e.ViewHolder as BaseViewHolder;
// holder.SetTextColor(Resource.Id.tv, Color.White);
};
_adapter.ClearView += (s, e) =>
{
Log.Debug(Tag, "View reset: " + e.Pos);
var holder = e.ViewHolder as BaseViewHolder;
// holder.SetTextColor(Resource.Id.tv, Color.Black);
};
_adapter.ItemSwiped += (s, e) =>
{
Log.Debug(Tag, "View Swiped: " + e.Pos);
};
_adapter.ItemSwipeMoving += (s, e) =>
{
e.Canvas.DrawColor(new Color(ContextCompat.GetColor(this, Resource.Color.color_light_blue)));
// e.Canvas.DrawText("Just some text", 0, 40, paint);
};
_itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(_adapter);
_itemTouchHelper = new ItemTouchHelper(_itemDragAndSwipeCallback);
_itemTouchHelper.AttachToRecyclerView(_recyclerView);
//_itemDragAndSwipeCallback.SetDragMoveFlags(ItemTouchHelper.Left | ItemTouchHelper.Right | ItemTouchHelper.Up | ItemTouchHelper.Down);
_itemDragAndSwipeCallback.SetSwipeMoveFlags(ItemTouchHelper.Start | ItemTouchHelper.End);
_adapter.EnableSwipeItem();
_adapter.EnableDragItem(_itemTouchHelper);
_recyclerView.SetAdapter(_adapter);
_adapter.ItemClick += (s, e) =>
{
ToastUtils.ShowShortToast("点击了" + e.Position);
};
}
List<string> GenerateData(int size)
{
var data = new List<string>(size);
for (int i=0; i < size; i++)
{
data.Add("item " + i);
}
return data;
}
}
}
| 38.336364 | 147 | 0.594498 | [
"Apache-2.0"
] | dminta/BaseRecyclerViewAdapterHelperXamarinAndroidBinding | BaseRecyclerViewAdapterHelper.Sample/ItemDragAndSwipeUseActivity.cs | 4,225 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20200701.Outputs
{
/// <summary>
/// Allow to exclude some variable satisfy the condition for the WAF check.
/// </summary>
[OutputType]
public sealed class OwaspCrsExclusionEntryResponse
{
/// <summary>
/// The variable to be excluded.
/// </summary>
public readonly string MatchVariable;
/// <summary>
/// When matchVariable is a collection, operator used to specify which elements in the collection this exclusion applies to.
/// </summary>
public readonly string Selector;
/// <summary>
/// When matchVariable is a collection, operate on the selector to specify which elements in the collection this exclusion applies to.
/// </summary>
public readonly string SelectorMatchOperator;
[OutputConstructor]
private OwaspCrsExclusionEntryResponse(
string matchVariable,
string selector,
string selectorMatchOperator)
{
MatchVariable = matchVariable;
Selector = selector;
SelectorMatchOperator = selectorMatchOperator;
}
}
}
| 32.434783 | 142 | 0.656166 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20200701/Outputs/OwaspCrsExclusionEntryResponse.cs | 1,492 | C# |
using System;
using System.IO;
using System.Text;
namespace SharpZebra.Commands
{
public partial class ZPLCommands
{
/// <summary>
/// Initializes printer print speed, tear off, alignment, width and darkness
/// </summary>
/// <param name="settings">The variable containing all required settings</param>
/// <returns>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] ClearPrinter(Printing.PrinterSettings settings)
{
//^MMT: Tear off Mode. ^PRp,s,b: print speed (print, slew, backfeed) (2,4,5,6,8,9,10,11,12).
//~TA###: Tear off position (must be 3 digits). ^LS####: Left shift. ^LHx,y: Label home. ^SD##x: Set Darkness (00 to 30). ^PWx: Label width
//^XA^MMT^PR4,12,12~TA000^LS-20^LH0,12~SD19^PW750
_stringCounter = 0;
_printerSettings = settings;
return Encoding.GetEncoding(850).GetBytes(string.Format("^XA^MMT^PR{0},12,12~TA{1:000}^LH{2},{3}~SD{4:00}^PW{5}", settings.PrintSpeed,
settings.AlignTearOff, settings.AlignLeft, settings.AlignTop, settings.Darkness, settings.Width + settings.AlignLeft));
}
/// <summary>
/// Instruct the Zebra printer to print labels
/// </summary>
/// <param name="copies">The number of identical copies of the label to print</param>
/// <returns>>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] PrintBuffer(int copies = 1)
{
return Encoding.GetEncoding(850).GetBytes(copies > 1 ? $"^PQ{copies}^XZ" : "^XZ");
}
/// <summary>
/// Instruct the Zebra printer to print a barcode. Currently only 3of9, Code128, UPC_A and EAN13 are supported.
/// </summary>
/// <param name="left">Distance in dots from the left of the label</param>
/// <param name="top">Distance in dots to the top of the label</param>
/// <param name="height">Height in dots of the barcode</param>
/// <param name="rotation">Rotate field.</param>
/// <param name="barcode">Type and parameters of the barcode to print.</param>
/// <param name="readable">Enable text to be printed at the bottom of the barcode.</param>
/// <param name="barcodeData">Text to encode in the barcode</param>
/// <returns>>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] BarCodeWrite(int left, int top, int height, ElementDrawRotation rotation, Barcode barcode, bool readable, string barcodeData)
{
var encodedReadable = readable ? "Y" : "N";
switch (barcode.Type)
{
case BarcodeType.CODE39_STD_EXT:
return Encoding.GetEncoding(850).GetBytes(
$"^FO{left},{top}^BY{barcode.BarWidthNarrow}^B3{(char) rotation},,{height},{encodedReadable}^FD{barcodeData}^FS");
case BarcodeType.CODE128_AUTO:
return Encoding.GetEncoding(850).GetBytes(
$"^FO{left},{top}^BY{barcode.BarWidthNarrow}^BC{(char) rotation},{height},{encodedReadable}^FD{barcodeData}^FS");
case BarcodeType.UPC_A:
return Encoding.GetEncoding(850).GetBytes(
$"^FO{left},{top}^BY{barcode.BarWidthNarrow}^BU{(char) rotation},{height},{encodedReadable}^FD{barcodeData}^FS");
case BarcodeType.EAN13:
return Encoding.GetEncoding(850).GetBytes(string.Format("^FO{0},{1}^BY{2}^BE{3},{4},{5}^FD{6}^FS", left, top,
barcode.BarWidthNarrow, (char)rotation, height, encodedReadable, barcodeData));
default:
throw new ApplicationException("Barcode not yet supported by SharpZebra library.");
}
}
/// <summary>
/// Writes Data Matrix Bar Code for ZPL.
/// ZPL Command: ^BX.
/// Manual: <see href="https://www.zebra.com/content/dam/zebra/manuals/printers/common/programming/zpl-zbi2-pm-en.pdf#page=122"/>
/// </summary>
/// <param name="left">Horizontal axis.</param>
/// <param name="top">Vertical axis.</param>
/// <param name="height">Height is determined by dimension and data that is encoded.</param>
/// <param name="rotation">Rotate field.</param>
/// <param name="text">Text to be encoded</param>
/// <param name="qualityLevel">Version of Data Matrix.</param>
/// <param name="aspectRatio">Choices the symbol, it is possible encode the same data in two forms of Data Matrix, a square form or rectangular.</param>
/// <returns>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] DataMatrixWrite(int left, int top, ElementDrawRotation rotation, int height, string text, QualityLevel qualityLevel = QualityLevel.ECC_200, AspectRatio aspectRatio = AspectRatio.SQUARE)
{
var rotationValue = (char)rotation;
var qualityLevelValue = (int)qualityLevel;
var aspectRatioValue = (int)aspectRatio;
return Encoding.GetEncoding(850).GetBytes($"^FO{left},{top}^BX{rotationValue}, {height},{qualityLevelValue},,,,,{aspectRatioValue},^FD{text}^FS");
}
/// <summary>
/// Writes text using the printer's (hopefully) built-in font.
/// <see href="https://www.zebra.com/content/dam/zebra/manuals/printers/common/programming/zpl-zbi2-pm-en.pdf#page=1336"/>
/// ZPL Command: ^A.
/// Manual: <see href="https://www.zebra.com/content/dam/zebra/manuals/printers/common/programming/zpl-zbi2-pm-en.pdf#page=42"/>
/// </summary>
/// <param name="left">Horizontal axis.</param>
/// <param name="top">Vertical axis.</param>
/// <param name="rotation">Rotate field.</param>
/// <param name="font">ZebraFont to print with. Note: these enum names do not match printer output</param>
/// <param name="height">Height of text in dots. 10-32000, or 0 to scale based on width</param>
/// <param name="width">Width of text in dots. 10-32000, default or 0 to scale based on height</param>
/// <param name="text">Text to be written</param>
/// <param name="codepage">The text encoding page the printer is set to use</param>
/// <returns>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
[Obsolete("Use ZPLFont instead of ZebraFont.")]
public static byte[] TextWrite(int left, int top, ElementDrawRotation rotation, ZebraFont font, int height, int width = 0, string text = "", int codepage = 850)
{
return string.IsNullOrEmpty(text)
? new byte[0]
: Encoding.GetEncoding(codepage)
.GetBytes($"^FO{left},{top}^A{(char) font}{(char) rotation},{height},{width}{FixTilde(text)}FH");
}
/// <summary>
/// Writes text using the printer's (hopefully) built-in font.
/// <see href="https://www.zebra.com/content/dam/zebra/manuals/printers/common/programming/zpl-zbi2-pm-en.pdf#page=1336"/>
/// ZPL Command: ^A.
/// Manual: <see href="https://www.zebra.com/content/dam/zebra/manuals/printers/common/programming/zpl-zbi2-pm-en.pdf#page=42"/>
/// </summary>
/// <param name="left">Horizontal axis.</param>
/// <param name="top">Vertical axis.</param>
/// <param name="rotation">Rotate field.</param>
/// <param name="font">ZPLFont to print with.</param>
/// <param name="height">Height of text in dots. 10-32000, or 0 to scale based on width</param>
/// <param name="width">Width of text in dots. 10-32000, default or 0 to scale based on height</param>
/// <param name="text">Text to be written</param>
/// <param name="codepage">The text encoding page the printer is set to use</param>
/// <returns>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] TextWrite(int left, int top, ElementDrawRotation rotation, ZPLFont font, int height, int width = 0, string text = "", int codepage = 850)
{
return string.IsNullOrEmpty(text)
? new byte[0]
: Encoding.GetEncoding(codepage)
.GetBytes($"^FO{left},{top}^A{(char) font}{(char) rotation},{height},{width}{FixTilde(text)}");
}
/// <summary>
/// Writes text using a font previously uploaded to the printer.
/// ZPL Command: ^A@.
/// Manual: <see href="https://www.zebra.com/content/dam/zebra/manuals/printers/common/programming/zpl-zbi2-pm-en.pdf#page=44"/>
/// </summary>
/// <param name="left">Horizontal axis.</param>
/// <param name="top">Vertical axis.</param>
/// <param name="rotation">Rotate field.</param>
/// <param name="fontName">The name of the font from the printer's directory listing (ends in .FNT)</param>
/// <param name="storageArea">The drive the font is stored on. From your printer's directory listing.</param>
/// <param name="height">Height of text in dots for scalable fonts, nearest magnification found for bitmapped fonts (R, E, B or A)</param>
/// <param name="text">Text to be written</param>
/// <param name="codepage">The text encoding page the printer is set to use</param>
/// <returns>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] TextWrite(int left, int top, ElementDrawRotation rotation, string fontName, char storageArea, int height, string text, int codepage = 850)
{
var rotationValue = (char) rotation;
return string.IsNullOrEmpty(text)
? new byte[0]
: Encoding.GetEncoding(codepage).GetBytes(string.Format("^A@{0},{1},{1},{2}:{3}^FO{4},{5}{6}",
rotationValue, height, storageArea, fontName, left, top, FixTilde(text)));
}
/// <summary>
/// Writes text using a font previously uploaded to the printer. Prints with the last used font.
/// ZPL Command: ^A@.
/// Manual: <see href="https://www.zebra.com/content/dam/zebra/manuals/printers/common/programming/zpl-zbi2-pm-en.pdf#page=44"/>
/// </summary>
/// <param name="left">Horizontal axis.</param>
/// <param name="top">Vertical axis.</param>
/// <param name="rotation">Rotate field.</param>
/// <param name="height">Height of text in dots for scalable fonts, nearest magnification found for bitmapped fonts (R, E, B or A)</param>
/// <param name="text">Text to be written</param>
/// <param name="codepage">The text encoding page the printer is set to use</param>
/// <returns>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] TextWrite(int left, int top, ElementDrawRotation rotation, int height, string text, int codepage = 850)
{
//uses last specified font
return string.IsNullOrEmpty(text)
? new byte[0]
: Encoding.GetEncoding(codepage)
.GetBytes($"^A@{(char) rotation},{height}^FO{left},{top}{FixTilde(text)}");
}
/// <summary>
/// Encases a Textwrite into a alignable box. Top left corner is determined in the TextWrite command.
/// </summary>
/// <param name="width">Width of the box to align the text inside</param>
/// <param name="alignment">Left, right, centered, justified</param>
/// <param name="textCommand">Results of a TextWrite command</param>
/// <returns>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] TextAlign(int width, Alignment alignment, byte[] textCommand)
{
return TextAlign(width, alignment, 1, 0, 0, textCommand);
}
/// <summary>
/// Encases a Textwrite into a alignable box with custom line heights and a maximum height. Top left corner is determined in the TextWrite command.
/// </summary>
/// <param name="width">Width of the alignment box</param>
/// <param name="alignment">Left, right, centered, justified</param>
/// <param name="maxLines">maximum lines to allow the text wrap before cutting it off</param>
/// <param name="lineSpacing">dots between each line</param>
/// <param name="indentSize">dots to indent after the first line</param>
/// <param name="textCommand">Results of a TextWrite command</param>
/// <param name="codepage">The text encoding page the printer is set to use</param>
/// <returns>Array of bytes containing ZPLII data to be sent to the Zebra printer.</returns>
public static byte[] TextAlign(int width, Alignment alignment, int maxLines, int lineSpacing, int indentSize, byte[] textCommand, int codepage = 850)
{
//limits from ZPL Manual:
//width [0,9999]
//maxLines [1,9999]
//lineSpacing [-9999,9999]
//indentSize [0,9999]
var alignmentValue = (char) alignment;
var stream = new MemoryStream();
var writer = new BinaryWriter(stream);
writer.Write(textCommand, 0, textCommand.Length - 3); //strip ^FS from given command
var s = $"^FB{width},{maxLines},{lineSpacing},{alignmentValue},{indentSize}^FS";
writer.Write(Encoding.GetEncoding(codepage).GetBytes(s));
return stream.ToArray();
}
public static byte[] LineWrite(int left, int top, int lineThickness, int right, int bottom)
{
var height = top - bottom;
var width = right - left;
var diagonal = height * width < 0 ? 'L' : 'R';
var l = Math.Min(left, right);
var t = Math.Min(top, bottom);
height = Math.Abs(height);
width = Math.Abs(width);
//zpl requires that straight lines are drawn with GB (Graphic-Box)
if (width < lineThickness)
return BoxWrite(left - lineThickness / 2, top, lineThickness, width, height, 0);
if (height < lineThickness)
return BoxWrite(left, top - lineThickness / 2, lineThickness, width, height, 0);
return Encoding.GetEncoding(850).GetBytes($"^FO{l},{t}^GD{width},{height},{lineThickness},,{diagonal}^FS");
}
public static byte[] BoxWrite(int left, int top, int lineThickness, int width, int height, int rounding)
{
return Encoding.GetEncoding(850).GetBytes(
$"^FO{left},{top}^GB{Math.Max(width, lineThickness)},{Math.Max(height, lineThickness)},{lineThickness},,{rounding}^FS");
}
private static string FixTilde(string text)
{
if (string.IsNullOrEmpty(text)) return text;
if (!text.Contains("~"))
return $"^FD{text}^FS";
if (text.Contains("_"))
throw new ApplicationException("Tilde character is not supported with underscore in same command");
return $"^FH^FD{text.Replace("~", "_7e")}^FS";
}
/*
public static string FormDelete(string formName)
{
return string.Format("FK\"{0}\"\n", formName);
}
public static string FormCreateBegin(string formName)
{
return string.Format("{0}FS\"{1}\"\n", FormDelete(formName), formName);
}
public static string FormCreateFinish()
{
return string.Format("FE\n");
}
*/
}
}
| 58.96337 | 214 | 0.602473 | [
"MIT"
] | gilby125/sharpzebra | Com.SharpZebra/Commands/StandardZPLCommand.cs | 16,099 | C# |
namespace DK.Api.Areas.HelpPage
{
/// <summary>
/// Indicates whether the sample is used for request or response
/// </summary>
public enum SampleDirection
{
Request = 0,
Response
}
} | 20.272727 | 68 | 0.596413 | [
"MIT"
] | RyxolSolutions/web.api.elearning | DK.Api/Areas/HelpPage/SampleGeneration/SampleDirection.cs | 223 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using static Interop;
using static Interop.ComCtl32;
namespace System.Windows.Forms
{
public partial class ListView
{
[ListBindable(false)]
public class SelectedListViewItemCollection : IList
{
private readonly ListView owner;
/// A caching mechanism for key accessor
/// We use an index here rather than control so that we don't have lifetime
/// issues by holding on to extra references.
private int lastAccessedIndex = -1;
/* C#r: protected */
public SelectedListViewItemCollection(ListView owner)
{
this.owner = owner;
}
private ListViewItem[] SelectedItemArray
{
get
{
if (owner.IsHandleCreated)
{
int cnt = unchecked((int)(long)User32.SendMessageW(owner, (User32.WM)LVM.GETSELECTEDCOUNT));
ListViewItem[] lvitems = new ListViewItem[cnt];
int displayIndex = -1;
for (int i = 0; i < cnt; i++)
{
int fidx = unchecked((int)(long)User32.SendMessageW(owner, (User32.WM)LVM.GETNEXTITEM, (IntPtr)displayIndex, (IntPtr)LVNI.SELECTED));
if (fidx > -1)
{
lvitems[i] = owner.Items[fidx];
displayIndex = fidx;
}
else
{
throw new InvalidOperationException(SR.SelectedNotEqualActual);
}
}
return lvitems;
}
else
{
if (owner.savedSelectedItems is not null)
{
ListViewItem[] cloned = new ListViewItem[owner.savedSelectedItems.Count];
for (int i = 0; i < owner.savedSelectedItems.Count; i++)
{
cloned[i] = owner.savedSelectedItems[i];
}
return cloned;
}
else
{
return Array.Empty<ListViewItem>();
}
}
}
}
/// <summary>
/// Number of currently selected items.
/// </summary>
[Browsable(false)]
public int Count
{
get
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
if (owner.IsHandleCreated)
{
return unchecked((int)(long)User32.SendMessageW(owner, (User32.WM)LVM.GETSELECTEDCOUNT));
}
else
{
if (owner.savedSelectedItems is not null)
{
return owner.savedSelectedItems.Count;
}
return 0;
}
}
}
/// <summary>
/// Selected item in the list.
/// </summary>
public ListViewItem this[int index]
{
get
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
if (index < 0 || index >= Count)
{
throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index));
}
if (owner.IsHandleCreated)
{
// Count through the selected items in the ListView, until
// we reach the 'index'th selected item.
//
int fidx = -1;
for (int count = 0; count <= index; count++)
{
fidx = unchecked((int)(long)User32.SendMessageW(owner, (User32.WM)LVM.GETNEXTITEM, (IntPtr)fidx, (IntPtr)LVNI.SELECTED));
Debug.Assert(fidx != -1, "Invalid index returned from LVM_GETNEXTITEM");
}
return owner.Items[fidx];
}
else
{
Debug.Assert(owner.savedSelectedItems is not null, "Null selected items collection");
return owner.savedSelectedItems[index];
}
}
}
/// <summary>
/// Retrieves the child control with the specified key.
/// </summary>
public virtual ListViewItem this[string key]
{
get
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
// We do not support null and empty string as valid keys.
if (string.IsNullOrEmpty(key))
{
return null;
}
// Search for the key in our collection
int index = IndexOfKey(key);
if (IsValidIndex(index))
{
return this[index];
}
else
{
return null;
}
}
}
object IList.this[int index]
{
get
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
return this[index];
}
set
{
// SelectedListViewItemCollection is read-only
throw new NotSupportedException();
}
}
bool IList.IsFixedSize
{
get
{
return true;
}
}
public bool IsReadOnly
{
get
{
return true;
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
int IList.Add(object value)
{
// SelectedListViewItemCollection is read-only
throw new NotSupportedException();
}
void IList.Insert(int index, object value)
{
// SelectedListViewItemCollection is read-only
throw new NotSupportedException();
}
/// <summary>
/// Determines if the index is valid for the collection.
/// </summary>
private bool IsValidIndex(int index)
{
return (index >= 0) && (index < Count);
}
void IList.Remove(object value)
{
// SelectedListViewItemCollection is read-only
throw new NotSupportedException();
}
void IList.RemoveAt(int index)
{
// SelectedListViewItemCollection is read-only
throw new NotSupportedException();
}
/// <summary>
/// Unselects all items.
/// </summary>
public void Clear()
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
ListViewItem[] items = SelectedItemArray;
for (int i = 0; i < items.Length; i++)
{
items[i].Selected = false;
}
}
/// <summary>
/// Returns true if the collection contains an item with the specified key, false otherwise.
/// </summary>
public virtual bool ContainsKey(string key)
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
return IsValidIndex(IndexOfKey(key));
}
public bool Contains(ListViewItem item)
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
return IndexOf(item) != -1;
}
bool IList.Contains(object item)
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
if (item is ListViewItem)
{
return Contains((ListViewItem)item);
}
else
{
return false;
}
}
public void CopyTo(Array dest, int index)
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
if (Count > 0)
{
System.Array.Copy(SelectedItemArray, 0, dest, index, Count);
}
}
public IEnumerator GetEnumerator()
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
ListViewItem[] items = SelectedItemArray;
if (items is not null)
{
return items.GetEnumerator();
}
else
{
return Array.Empty<ListViewItem>().GetEnumerator();
}
}
public int IndexOf(ListViewItem item)
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
ListViewItem[] items = SelectedItemArray;
for (int index = 0; index < items.Length; ++index)
{
if (items[index] == item)
{
return index;
}
}
return -1;
}
int IList.IndexOf(object item)
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
if (item is ListViewItem)
{
return IndexOf((ListViewItem)item);
}
else
{
return -1;
}
}
/// <summary>
/// The zero-based index of the first occurrence of value within the entire CollectionBase, if found; otherwise, -1.
/// </summary>
public virtual int IndexOfKey(string key)
{
if (owner.VirtualMode)
{
throw new InvalidOperationException(SR.ListViewCantAccessSelectedItemsCollectionWhenInVirtualMode);
}
// Step 0 - Arg validation
if (string.IsNullOrEmpty(key))
{
return -1; // we dont support empty or null keys.
}
// step 1 - check the last cached item
if (IsValidIndex(lastAccessedIndex))
{
if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true))
{
return lastAccessedIndex;
}
}
// step 2 - search for the item
for (int i = 0; i < Count; i++)
{
if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true))
{
lastAccessedIndex = i;
return i;
}
}
// step 3 - we didn't find it. Invalidate the last accessed index and return -1.
lastAccessedIndex = -1;
return -1;
}
}
}
}
| 33.242991 | 161 | 0.425288 | [
"MIT"
] | adamsitnik/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ListView.SelectedListViewItemCollection.cs | 14,230 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace UiPath.Web.Client20204.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class ListResultDtoNameValueDto
{
/// <summary>
/// Initializes a new instance of the ListResultDtoNameValueDto class.
/// </summary>
public ListResultDtoNameValueDto()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ListResultDtoNameValueDto class.
/// </summary>
public ListResultDtoNameValueDto(IList<NameValueDto> items = default(IList<NameValueDto>))
{
Items = items;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "Items")]
public IList<NameValueDto> Items { get; set; }
}
}
| 27.711111 | 98 | 0.613472 | [
"MIT"
] | AFWberlin/orchestrator-powershell | UiPath.Web.Client/generated20204/Models/ListResultDtoNameValueDto.cs | 1,247 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AwsNative.QuickSight
{
/// <summary>
/// Definition of the AWS::QuickSight::DataSet Resource Type.
/// </summary>
[AwsNativeResourceType("aws-native:quicksight:DataSet")]
public partial class DataSet : Pulumi.CustomResource
{
/// <summary>
/// <p>The Amazon Resource Name (ARN) of the resource.</p>
/// </summary>
[Output("arn")]
public Output<string> Arn { get; private set; } = null!;
[Output("awsAccountId")]
public Output<string?> AwsAccountId { get; private set; } = null!;
/// <summary>
/// <p>Groupings of columns that work together in certain QuickSight features. Currently, only geospatial hierarchy is supported.</p>
/// </summary>
[Output("columnGroups")]
public Output<ImmutableArray<Outputs.DataSetColumnGroup>> ColumnGroups { get; private set; } = null!;
[Output("columnLevelPermissionRules")]
public Output<ImmutableArray<Outputs.DataSetColumnLevelPermissionRule>> ColumnLevelPermissionRules { get; private set; } = null!;
/// <summary>
/// <p>The amount of SPICE capacity used by this dataset. This is 0 if the dataset isn't
/// imported into SPICE.</p>
/// </summary>
[Output("consumedSpiceCapacityInBytes")]
public Output<double> ConsumedSpiceCapacityInBytes { get; private set; } = null!;
/// <summary>
/// <p>The time that this dataset was created.</p>
/// </summary>
[Output("createdTime")]
public Output<string> CreatedTime { get; private set; } = null!;
[Output("dataSetId")]
public Output<string?> DataSetId { get; private set; } = null!;
[Output("fieldFolders")]
public Output<Outputs.DataSetFieldFolderMap?> FieldFolders { get; private set; } = null!;
[Output("importMode")]
public Output<Pulumi.AwsNative.QuickSight.DataSetImportMode?> ImportMode { get; private set; } = null!;
[Output("ingestionWaitPolicy")]
public Output<Outputs.DataSetIngestionWaitPolicy?> IngestionWaitPolicy { get; private set; } = null!;
/// <summary>
/// <p>The last time that this dataset was updated.</p>
/// </summary>
[Output("lastUpdatedTime")]
public Output<string> LastUpdatedTime { get; private set; } = null!;
[Output("logicalTableMap")]
public Output<Outputs.DataSetLogicalTableMap?> LogicalTableMap { get; private set; } = null!;
/// <summary>
/// <p>The display name for the dataset.</p>
/// </summary>
[Output("name")]
public Output<string?> Name { get; private set; } = null!;
/// <summary>
/// <p>The list of columns after all transforms. These columns are available in templates,
/// analyses, and dashboards.</p>
/// </summary>
[Output("outputColumns")]
public Output<ImmutableArray<Outputs.DataSetOutputColumn>> OutputColumns { get; private set; } = null!;
/// <summary>
/// <p>A list of resource permissions on the dataset.</p>
/// </summary>
[Output("permissions")]
public Output<ImmutableArray<Outputs.DataSetResourcePermission>> Permissions { get; private set; } = null!;
[Output("physicalTableMap")]
public Output<Outputs.DataSetPhysicalTableMap?> PhysicalTableMap { get; private set; } = null!;
[Output("rowLevelPermissionDataSet")]
public Output<Outputs.DataSetRowLevelPermissionDataSet?> RowLevelPermissionDataSet { get; private set; } = null!;
/// <summary>
/// <p>Contains a map of the key-value pairs for the resource tag or tags assigned to the dataset.</p>
/// </summary>
[Output("tags")]
public Output<ImmutableArray<Outputs.DataSetTag>> Tags { get; private set; } = null!;
/// <summary>
/// Create a DataSet resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public DataSet(string name, DataSetArgs? args = null, CustomResourceOptions? options = null)
: base("aws-native:quicksight:DataSet", name, args ?? new DataSetArgs(), MakeResourceOptions(options, ""))
{
}
private DataSet(string name, Input<string> id, CustomResourceOptions? options = null)
: base("aws-native:quicksight:DataSet", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing DataSet resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static DataSet Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new DataSet(name, id, options);
}
}
public sealed class DataSetArgs : Pulumi.ResourceArgs
{
[Input("awsAccountId")]
public Input<string>? AwsAccountId { get; set; }
[Input("columnGroups")]
private InputList<Inputs.DataSetColumnGroupArgs>? _columnGroups;
/// <summary>
/// <p>Groupings of columns that work together in certain QuickSight features. Currently, only geospatial hierarchy is supported.</p>
/// </summary>
public InputList<Inputs.DataSetColumnGroupArgs> ColumnGroups
{
get => _columnGroups ?? (_columnGroups = new InputList<Inputs.DataSetColumnGroupArgs>());
set => _columnGroups = value;
}
[Input("columnLevelPermissionRules")]
private InputList<Inputs.DataSetColumnLevelPermissionRuleArgs>? _columnLevelPermissionRules;
public InputList<Inputs.DataSetColumnLevelPermissionRuleArgs> ColumnLevelPermissionRules
{
get => _columnLevelPermissionRules ?? (_columnLevelPermissionRules = new InputList<Inputs.DataSetColumnLevelPermissionRuleArgs>());
set => _columnLevelPermissionRules = value;
}
[Input("dataSetId")]
public Input<string>? DataSetId { get; set; }
[Input("fieldFolders")]
public Input<Inputs.DataSetFieldFolderMapArgs>? FieldFolders { get; set; }
[Input("importMode")]
public Input<Pulumi.AwsNative.QuickSight.DataSetImportMode>? ImportMode { get; set; }
[Input("ingestionWaitPolicy")]
public Input<Inputs.DataSetIngestionWaitPolicyArgs>? IngestionWaitPolicy { get; set; }
[Input("logicalTableMap")]
public Input<Inputs.DataSetLogicalTableMapArgs>? LogicalTableMap { get; set; }
/// <summary>
/// <p>The display name for the dataset.</p>
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
[Input("permissions")]
private InputList<Inputs.DataSetResourcePermissionArgs>? _permissions;
/// <summary>
/// <p>A list of resource permissions on the dataset.</p>
/// </summary>
public InputList<Inputs.DataSetResourcePermissionArgs> Permissions
{
get => _permissions ?? (_permissions = new InputList<Inputs.DataSetResourcePermissionArgs>());
set => _permissions = value;
}
[Input("physicalTableMap")]
public Input<Inputs.DataSetPhysicalTableMapArgs>? PhysicalTableMap { get; set; }
[Input("rowLevelPermissionDataSet")]
public Input<Inputs.DataSetRowLevelPermissionDataSetArgs>? RowLevelPermissionDataSet { get; set; }
[Input("tags")]
private InputList<Inputs.DataSetTagArgs>? _tags;
/// <summary>
/// <p>Contains a map of the key-value pairs for the resource tag or tags assigned to the dataset.</p>
/// </summary>
public InputList<Inputs.DataSetTagArgs> Tags
{
get => _tags ?? (_tags = new InputList<Inputs.DataSetTagArgs>());
set => _tags = value;
}
public DataSetArgs()
{
}
}
}
| 42.324444 | 153 | 0.628478 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/QuickSight/DataSet.cs | 9,523 | C# |
using Godot;
using System;
/**
* Handles managing the advisor screens.
* Showing them, hiding them... maybe some other things eventually.
* This is part of the effort to de-centralize from Game.cs and be more event driven.
*/
public class Advisors : CenterContainer
{
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
//Center the advisor container. Following directions at https://docs.godotengine.org/en/stable/tutorials/gui/size_and_anchors.html?highlight=anchor
//Also taking advantage of it being 1024x768, as the directions didn't really work. This is not 100% ideal (would be great for a general-purpose solution to work),
//but does work with the current graphics independent of resolution.
this.Hide();
}
// // Called every frame. 'delta' is the elapsed time since the previous frame.
// public override void _Process(float delta)
// {
//
// }
private void ShowLatestAdvisor()
{
GD.Print("Received request to show latest advisor");
if (this.GetChildCount() == 0) {
DomesticAdvisor advisor = new DomesticAdvisor();
AddChild(advisor);
}
this.Show();
}
private void _on_Advisor_hide()
{
this.Hide();
}
private void OnShowSpecificAdvisor(string advisorType)
{
if (advisorType.Equals("F1")) {
if (this.GetChildCount() == 0) {
DomesticAdvisor advisor = new DomesticAdvisor();
AddChild(advisor);
}
this.Show();
}
}
public override void _UnhandledInput(InputEvent @event)
{
if (this.Visible) {
if (@event is InputEventKey eventKey)
{
//As I've added more shortcuts, I've realized checking all of them here could be irksome.
//For now, I'm thinking it would make more sense to process or allow through the ones that should go through,
//as most of the global ones should *not* go through here.
if (eventKey.Pressed)
{
if (eventKey.Scancode == (int)Godot.KeyList.Escape) {
this.Hide();
GetTree().SetInputAsHandled();
}
else {
GD.Print("Advisor received a key press; stopping propagation.");
GetTree().SetInputAsHandled();
}
}
}
}
}
}
| 27.253165 | 166 | 0.687413 | [
"MIT"
] | C7-Game/Prototype | C7/UIElements/Advisors/Advisors.cs | 2,153 | C# |
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
namespace <%= botName %>.Triggers
{
public class StaticFilesTrigger
{
private const string StaticFilesDirectory = "wwwroot";
private readonly FileExtensionContentTypeProvider _provider;
public StaticFilesTrigger()
{
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".lu"] = "application/vnd.microsoft.lu";
provider.Mappings[".qna"] = "application/vnd.microsoft.qna";
_provider = provider;
}
[FunctionName("StaticFiles")]
public async Task<IActionResult> RunAsync(
[HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "{*path}")] HttpRequest request,
string path,
ExecutionContext context)
{
if (!TryGetFilePath(context, path, out string filePath) ||
!_provider.TryGetContentType(filePath, out string contentType))
{
return new NotFoundResult();
}
return new FileStreamResult(new FileStream(filePath, FileMode.Open), contentType);
}
private bool TryGetFilePath(ExecutionContext context, string relativePath, out string result)
{
result = null;
if (string.IsNullOrEmpty(relativePath))
{
return false;
}
string filePath = Path.GetFullPath(
Path.Join(
context.FunctionAppDirectory,
StaticFilesDirectory,
relativePath));
var file = new FileInfo(filePath);
if (!file.Exists)
{
return false;
}
result = file.FullName;
return true;
}
}
}
| 30.029851 | 102 | 0.586978 | [
"MIT"
] | QPC-database/botframework-components | generators/generator-bot-adaptive/generators/app/templates/dotnet/functions/Triggers/StaticFilesTrigger.cs | 2,012 | C# |
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSix
{
[Migration("6.0.0", 0, Constants.System.UmbracoMigrationName)]
public class RenameCmsTabTable : MigrationBase
{
public RenameCmsTabTable(ISqlSyntaxProvider sqlSyntax, ILogger logger) : base(sqlSyntax, logger)
{
}
public override void Up()
{
Rename.Table("cmsTab").To("cmsPropertyTypeGroup");
}
public override void Down()
{
Rename.Table("cmsPropertyTypeGroup").To("cmsTab");
}
}
} | 28.083333 | 104 | 0.658754 | [
"MIT"
] | filipesousa20/Umbraco-CMS-V7 | src/Umbraco.Core/Persistence/Migrations/Upgrades/TargetVersionSix/RenameCmsTabTable.cs | 676 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.PostgreSQL
{
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>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<PostgreSQLManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(PostgreSQLManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the PostgreSQLManagementClient
/// </summary>
public PostgreSQLManagementClient Client { get; private set; }
/// <summary>
/// Lists all of the available REST API operations.
/// </summary>
/// <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<OperationListResult>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.DBforPostgreSQL/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("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<OperationListResult>();
_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<OperationListResult>(_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;
}
}
}
| 41.842105 | 217 | 0.564046 | [
"MIT"
] | 0xced/azure-sdk-for-net | src/SDKs/PostgreSQL/Management.PostgreSQL/Generated/Operations.cs | 9,540 | C# |
using System;
namespace Bridge
{
/// <summary>
/// Specifies full path name of the entity (namespace+entity), when emitting JavaScript-equivalent
/// code. This overrides the inferred namespace.class.method name, for example.
/// </summary>
/// <remarks>
/// Use "Object" (with quotes) to hide its type in JavaScript-level (useful when you create
/// a hidden class to fill several public classes' methods).
/// </remarks>
[NonScriptable]
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Delegate | AttributeTargets.Property | AttributeTargets.Parameter)]
public sealed class NameAttribute : Attribute
{
public NameAttribute(string value)
{
}
}
} | 41.095238 | 259 | 0.704519 | [
"Apache-2.0"
] | Cheatoid/CSharp.lua | test/BridgeNetTests/BridgeAttributes/src/NameAttribute.cs | 865 | C# |
using System.Threading.Tasks;
using Abp.Configuration;
using Abp.Zero.Configuration;
using AAC.ABPDemo.Authorization.Accounts.Dto;
using AAC.ABPDemo.Authorization.Users;
namespace AAC.ABPDemo.Authorization.Accounts
{
public class AccountAppService : ABPDemoAppServiceBase, IAccountAppService
{
// from: http://regexlib.com/REDetails.aspx?regexp_id=1923
public const string PasswordRegex = "(?=^.{8,}$)(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s)[0-9a-zA-Z!@#$%^&*()]*$";
private readonly UserRegistrationManager _userRegistrationManager;
public AccountAppService(
UserRegistrationManager userRegistrationManager)
{
_userRegistrationManager = userRegistrationManager;
}
public async Task<IsTenantAvailableOutput> IsTenantAvailable(IsTenantAvailableInput input)
{
var tenant = await TenantManager.FindByTenancyNameAsync(input.TenancyName);
if (tenant == null)
{
return new IsTenantAvailableOutput(TenantAvailabilityState.NotFound);
}
if (!tenant.IsActive)
{
return new IsTenantAvailableOutput(TenantAvailabilityState.InActive);
}
return new IsTenantAvailableOutput(TenantAvailabilityState.Available, tenant.Id);
}
public async Task<RegisterOutput> Register(RegisterInput input)
{
var user = await _userRegistrationManager.RegisterAsync(
input.Name,
input.Surname,
input.EmailAddress,
input.UserName,
input.Password,
true // Assumed email address is always confirmed. Change this if you want to implement email confirmation.
);
var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);
return new RegisterOutput
{
CanLogin = user.IsActive && (user.IsEmailConfirmed || !isEmailConfirmationRequiredForLogin)
};
}
}
}
| 37.344828 | 174 | 0.642198 | [
"MIT"
] | Ramos66/ABPDemo | aspnet-core/src/AAC.ABPDemo.Application/Authorization/Accounts/AccountAppService.cs | 2,166 | C# |
/*
* Copyright (c) 2019 ETH Zürich, Educational Development and Technology (LET)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Lockdown.Contracts;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Service.Operations
{
internal class LockdownOperation : SessionOperation
{
private IFeatureConfigurationBackup backup;
private IFeatureConfigurationFactory factory;
private IFeatureConfigurationMonitor monitor;
private ILogger logger;
private Guid groupId;
public LockdownOperation(
IFeatureConfigurationBackup backup,
IFeatureConfigurationFactory factory,
IFeatureConfigurationMonitor monitor,
ILogger logger,
SessionContext sessionContext) : base(sessionContext)
{
this.backup = backup;
this.factory = factory;
this.monitor = monitor;
this.logger = logger;
}
public override OperationResult Perform()
{
groupId = Guid.NewGuid();
var success = true;
var sid = Context.Configuration.UserSid;
var userName = Context.Configuration.UserName;
var configurations = new []
{
(factory.CreateChangePasswordConfiguration(groupId, sid, userName), Context.Configuration.Settings.Service.DisablePasswordChange),
(factory.CreateChromeNotificationConfiguration(groupId, sid, userName), Context.Configuration.Settings.Service.DisableChromeNotifications),
(factory.CreateEaseOfAccessConfiguration(groupId), Context.Configuration.Settings.Service.DisableEaseOfAccessOptions),
(factory.CreateLockWorkstationConfiguration(groupId, sid, userName), Context.Configuration.Settings.Service.DisableUserLock),
(factory.CreateMachinePowerOptionsConfiguration(groupId), Context.Configuration.Settings.Service.DisablePowerOptions),
(factory.CreateNetworkOptionsConfiguration(groupId), Context.Configuration.Settings.Service.DisableNetworkOptions),
(factory.CreateRemoteConnectionConfiguration(groupId), Context.Configuration.Settings.Service.DisableRemoteConnections),
(factory.CreateSignoutConfiguration(groupId, sid, userName), Context.Configuration.Settings.Service.DisableSignout),
(factory.CreateSwitchUserConfiguration(groupId), Context.Configuration.Settings.Service.DisableUserSwitch),
(factory.CreateTaskManagerConfiguration(groupId, sid, userName), Context.Configuration.Settings.Service.DisableTaskManager),
(factory.CreateUserPowerOptionsConfiguration(groupId, sid, userName), Context.Configuration.Settings.Service.DisablePowerOptions),
(factory.CreateVmwareOverlayConfiguration(groupId, sid, userName), Context.Configuration.Settings.Service.DisableVmwareOverlay),
(factory.CreateWindowsUpdateConfiguration(groupId), Context.Configuration.Settings.Service.DisableWindowsUpdate)
};
logger.Info($"Attempting to perform lockdown (feature configuration group: {groupId})...");
foreach (var (configuration, disable) in configurations)
{
success &= TrySet(configuration, disable);
if (!success)
{
break;
}
}
if (success)
{
monitor.Start();
logger.Info("Lockdown successful.");
}
else
{
logger.Error("Lockdown was not successful!");
}
return success ? OperationResult.Success : OperationResult.Failed;
}
public override OperationResult Revert()
{
logger.Info($"Attempting to revert lockdown (feature configuration group: {groupId})...");
var configurations = backup.GetBy(groupId);
var success = true;
monitor.Reset();
foreach (var configuration in configurations)
{
success &= TryRestore(configuration);
}
if (success)
{
logger.Info("Lockdown reversion successful.");
}
else
{
logger.Warn("Lockdown reversion was not successful!");
}
return success ? OperationResult.Success : OperationResult.Failed;
}
private bool TryRestore(IFeatureConfiguration configuration)
{
var success = configuration.Restore();
if (success)
{
backup.Delete(configuration);
}
else
{
logger.Error($"Failed to restore {configuration}!");
}
return success;
}
private bool TrySet(IFeatureConfiguration configuration, bool disable)
{
var success = false;
var status = FeatureConfigurationStatus.Undefined;
configuration.Initialize();
backup.Save(configuration);
if (disable)
{
success = configuration.DisableFeature();
status = FeatureConfigurationStatus.Disabled;
}
else
{
success = configuration.EnableFeature();
status = FeatureConfigurationStatus.Enabled;
}
if (success)
{
monitor.Observe(configuration, status);
}
else
{
logger.Error($"Failed to configure {configuration}!");
}
return success;
}
}
}
| 30.7375 | 143 | 0.749695 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | junbaor/seb-win-refactoring | SafeExamBrowser.Service/Operations/LockdownOperation.cs | 4,921 | C# |
using Unity.Collections;
using UnityEngine;
namespace Newtonsoft.Json.UnityConverters.Scripting
{
public class RangeIntConverter : PartialConverter<RangeInt>
{
protected override void ReadValue(ref RangeInt value, string name, JsonReader reader, JsonSerializer serializer)
{
switch (name) {
case nameof(value.start):
value.start = reader.ReadAsInt32() ?? 0;
break;
case nameof(value.length):
value.length = reader.ReadAsInt32() ?? 0;
break;
}
}
protected override void WriteJsonProperties(JsonWriter writer, RangeInt value, JsonSerializer serializer)
{
writer.WritePropertyName(nameof(value.start));
writer.WriteValue(value.start);
writer.WritePropertyName(nameof(value.length));
writer.WriteValue(value.length);
}
}
}
| 32.233333 | 120 | 0.594623 | [
"MIT"
] | DefCon1VR/Newtonsoft.Json-for-Unity.Converters | Packages/Newtonsoft.Json-for-Unity.Converters/UnityConverters/Scripting/RangeIntConverter.cs | 969 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var firstNumber = int.Parse(Console.ReadLine());
var secondNumber = int.Parse(Console.ReadLine());
var maximumSum = int.Parse(Console.ReadLine());
var totalSum = 0;
var counter = 0;
for (int firstDigit = firstNumber; firstDigit >= 1; firstDigit--)
{
for (int secondDigit = 1; secondDigit <= secondNumber; secondDigit++)
{
if (totalSum > maximumSum)
{
break;
}
//Console.Write($"{firstDigit} {secondDigit}; ");
totalSum = totalSum + (3 * (firstDigit * secondDigit));
counter++;
}
}
if (totalSum >= maximumSum)
{
Console.WriteLine();
Console.WriteLine($"{counter} combinations");
Console.WriteLine($"Sum: {totalSum} >= {maximumSum}");
}
else
{
Console.WriteLine();
Console.WriteLine($"{counter} combinations");
Console.WriteLine($"Sum: {totalSum}");
}
}
}
}
| 27.037037 | 85 | 0.464384 | [
"MIT"
] | stefankon/CShomeworkAndLabIssues | CSharp-Conditional-Statements-and-Loops-Exercises/ConsoleApp1/p12.TestNumbers.cs | 1,462 | C# |
using System;
using System.Data;
using Oracle.ManagedDataAccess.Client;
namespace ODP.NET_CICQN_JSON_21c
{
//This app demonstrates how to use Client Initiated Continquous Query Notification (CICQN) and
// JSON (OSON) data type with Oracle Database 21c. Works with autonomous, cloud, or on-premises DB.
//Setup steps:
//1) "GRANT CHANGE NOTIFICATION TO <USER>" to use CICQN
//2) Create the J_PURCHASEORDER table and insert a JSON document into it. See SQL script.
//3) Use ODP.NET 21c and Oracle Database 21c to run the console app code.
//4) Populate the Constants class below with your app-specific values and run.
class Program
{
static class Constants
{
//Enter your user id, password, and DB info, such as net service name,
// Easy Connect Plus, or connect descriptor
public const string ConString = "User Id=<USER>;Password=<PASSWORD>;Data Source=<NET SERVICE NAME>;Connection Timeout=30;";
//Enter directories where your *.ora files and your wallet are located, if applicable
public const string TnsDir = @"<DIRECTORY WITH *.ORA FILES, IF APPLICABLE>";
public const string WalletDir = @"<WALLET DIRECTORY, IF APPLICABLE>";
//Set the query to execute and JSON column to retrieve
public const string Query = "select PO_DOCUMENT from J_PURCHASEORDER";
public const string JsonColumn = "PO_DOCUMENT";
}
static void Main()
{
//Directory where your cloud or database credentials are located, if applicable
OracleConfiguration.TnsAdmin = Constants.TnsDir;
OracleConfiguration.WalletLocation = Constants.WalletDir;
//Turn on Client Initiated Continuous Query Notification
OracleConfiguration.UseClientInitiatedCQN = true;
using (OracleConnection con = new OracleConnection(Constants.ConString))
{
using (OracleCommand cmd = con.CreateCommand())
{
try
{
con.Open();
Console.WriteLine("Successfully connected to Oracle Database");
Console.WriteLine();
//CQN setup
OracleDependency dep = new OracleDependency(cmd);
cmd.Notification.IsNotifiedOnce = false;
dep.OnChange += new OnChangeEventHandler(JSON_Notification);
//Retrieve purchase order stored as JSON (OSON) type
//Store JSON data as string in disconnected DataSet
cmd.CommandText = Constants.Query;
OracleDataAdapter da = new OracleDataAdapter(cmd);
using (DataSet ds = new DataSet())
{
da.Fill(ds);
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
//Output the query result to the console
Console.WriteLine(row[Constants.JsonColumn].ToString());
}
}
//While result set is disconnected from database, modify the purchase
// order data through ODT or SQL*Plus, such as with the following SQL:
//UPDATE j_purchaseorder SET po_document = json_transform(po_document, SET '$.LastUpdated' = SYSDATE);
//Changing the data on database triggers the CICQN event handler.
//Each time the update statement runs, a new notification will be sent to the app.
Console.ReadLine();
}
da.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
public static void JSON_Notification(object src, OracleNotificationEventArgs args)
{
//Each time event handler launches, it retrieves the updated purchase order details
//Note that the LastUpdated entry has been changed.
Console.WriteLine();
Console.WriteLine("Change detected.");
using (OracleConnection con = new OracleConnection(Constants.ConString))
{
using (OracleCommand cmd = con.CreateCommand())
{
try
{
con.Open();
cmd.CommandText = Constants.Query;
OracleDataAdapter da = new OracleDataAdapter(cmd);
using (DataSet ds = new DataSet())
{
da.Fill(ds);
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
Console.WriteLine(row[Constants.JsonColumn].ToString());
}
}
}
da.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}
/* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. */
/******************************************************************************
*
* You may not use the identified files except in compliance with The MIT
* License (the "License.")
*
* You may obtain a copy of the License at
* https://github.com/oracle/Oracle.NET/blob/master/LICENSE
*
* 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.
*
*****************************************************************************/
| 44.482993 | 135 | 0.509711 | [
"MIT"
] | LaudateCorpus1/dotnet-db-samples | session-demos/2021/cicqn-json/cicqn-json.cs | 6,539 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.ServiceBus.Latest
{
/// <summary>
/// Description of Rule Resource.
/// Latest API Version: 2017-04-01.
/// </summary>
[Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-native:servicebus:Rule'.")]
[AzureNativeResourceType("azure-native:servicebus/latest:Rule")]
public partial class Rule : Pulumi.CustomResource
{
/// <summary>
/// Represents the filter actions which are allowed for the transformation of a message that have been matched by a filter expression.
/// </summary>
[Output("action")]
public Output<Outputs.ActionResponse?> Action { get; private set; } = null!;
/// <summary>
/// Properties of correlationFilter
/// </summary>
[Output("correlationFilter")]
public Output<Outputs.CorrelationFilterResponse?> CorrelationFilter { get; private set; } = null!;
/// <summary>
/// Filter type that is evaluated against a BrokeredMessage.
/// </summary>
[Output("filterType")]
public Output<string?> FilterType { get; private set; } = null!;
/// <summary>
/// Resource name
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Properties of sqlFilter
/// </summary>
[Output("sqlFilter")]
public Output<Outputs.SqlFilterResponse?> SqlFilter { get; private set; } = null!;
/// <summary>
/// Resource type
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Rule resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Rule(string name, RuleArgs args, CustomResourceOptions? options = null)
: base("azure-native:servicebus/latest:Rule", name, args ?? new RuleArgs(), MakeResourceOptions(options, ""))
{
}
private Rule(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:servicebus/latest:Rule", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:servicebus/latest:Rule"},
new Pulumi.Alias { Type = "azure-native:servicebus:Rule"},
new Pulumi.Alias { Type = "azure-nextgen:servicebus:Rule"},
new Pulumi.Alias { Type = "azure-native:servicebus/v20170401:Rule"},
new Pulumi.Alias { Type = "azure-nextgen:servicebus/v20170401:Rule"},
new Pulumi.Alias { Type = "azure-native:servicebus/v20180101preview:Rule"},
new Pulumi.Alias { Type = "azure-nextgen:servicebus/v20180101preview:Rule"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Rule resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Rule Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Rule(name, id, options);
}
}
public sealed class RuleArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Represents the filter actions which are allowed for the transformation of a message that have been matched by a filter expression.
/// </summary>
[Input("action")]
public Input<Inputs.ActionArgs>? Action { get; set; }
/// <summary>
/// Properties of correlationFilter
/// </summary>
[Input("correlationFilter")]
public Input<Inputs.CorrelationFilterArgs>? CorrelationFilter { get; set; }
/// <summary>
/// Filter type that is evaluated against a BrokeredMessage.
/// </summary>
[Input("filterType")]
public Input<Pulumi.AzureNative.ServiceBus.Latest.FilterType>? FilterType { get; set; }
/// <summary>
/// The namespace name
/// </summary>
[Input("namespaceName", required: true)]
public Input<string> NamespaceName { get; set; } = null!;
/// <summary>
/// Name of the Resource group within the Azure subscription.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The rule name.
/// </summary>
[Input("ruleName")]
public Input<string>? RuleName { get; set; }
/// <summary>
/// Properties of sqlFilter
/// </summary>
[Input("sqlFilter")]
public Input<Inputs.SqlFilterArgs>? SqlFilter { get; set; }
/// <summary>
/// The subscription name.
/// </summary>
[Input("subscriptionName", required: true)]
public Input<string> SubscriptionName { get; set; } = null!;
/// <summary>
/// The topic name.
/// </summary>
[Input("topicName", required: true)]
public Input<string> TopicName { get; set; } = null!;
public RuleArgs()
{
}
}
}
| 39.417647 | 142 | 0.589464 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/ServiceBus/Latest/Rule.cs | 6,701 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
/// <summary>
/// An <see cref="IModelBinderProvider"/> for models which specify an <see cref="IModelBinder"/>
/// using <see cref="BindingInfo.BinderType"/>.
/// </summary>
public class BinderTypeModelBinderProvider : IModelBinderProvider
{
/// <inheritdoc />
public IModelBinder? GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.BindingInfo.BinderType is Type binderType)
{
return new BinderTypeModelBinder(binderType);
}
return null;
}
}
| 27.096774 | 96 | 0.67619 | [
"MIT"
] | Aezura/aspnetcore | src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinderProvider.cs | 840 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.