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
// Copyright (c) pCYSl5EDgo. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace MSPack.Processor.CLI { public class DepsJson { public RuntimeTarget runtimeTarget { get; set; } public CompilationOptions compilationOptions { get; set; } public Dictionary<string, Dictionary<string, RuntimeInfo>> targets { get; set; } public Dictionary<string, LibraryInfo> libraries { get; set; } } }
29.842105
102
0.686067
[ "MIT" ]
pCYSl5EDgo/MSPack-Processor
src/CommandLineInterface/deps.json/DepsJson.cs
569
C#
using CairoDesktop.Common.Logging; using System; using System.Diagnostics; using System.Windows; using System.Windows.Interop; using System.Windows.Media; namespace CairoDesktop { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); if (Configuration.Settings.Instance.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; } private static bool errorVisible = false; private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); string version = fvi.FileVersion; string inner = ""; if (e.Exception.InnerException != null) inner = "\r\n\r\nInner exception:\r\nMessage: " + e.Exception.InnerException.Message + "\r\nTarget Site: " + e.Exception.InnerException.TargetSite + "\r\n\r\n" + e.Exception.InnerException.StackTrace; string msg = "Would you like to restart Cairo?\r\n\r\nPlease submit a bug report with a screenshot of this error. Thanks! \r\nMessage: " + e.Exception.Message + "\r\nTarget Site: " + e.Exception.TargetSite + "\r\nVersion: " + version + "\r\n\r\n" + e.Exception.StackTrace + inner; CairoLogger.Instance.Error(msg, e.Exception); string dMsg; if (msg.Length > 1000) dMsg = msg.Substring(0, 999) + "..."; else dMsg = msg; try { if (!errorVisible) { errorVisible = true; // Automatically restart for known render thread failure messages. if (e.Exception.Message.StartsWith("UCEERR_RENDERTHREADFAILURE")) { CairoDesktop.Startup.Restart(); Environment.FailFast("Automatically restarted Cairo due to a render thread failure."); } else { if (MessageBox.Show(dMsg, "Cairo Desktop Error", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) { // it's like getting a morning coffee. CairoDesktop.Startup.Restart(); Environment.FailFast("User restarted Cairo due to an exception."); } } errorVisible = false; } } catch { // If this fails we're probably up the creek. Abandon ship! CairoDesktop.Startup.Shutdown(); } e.Handled = true; } } }
38.45679
292
0.559551
[ "Apache-2.0" ]
dekiertanna/cairoshell
Cairo Desktop/Cairo Desktop/App.xaml.cs
3,117
C#
namespace JiraAssistant.Domain.NavigationMessages { public class OpenAgileBoardPickupMessage { } }
15.571429
50
0.770642
[ "MIT" ]
sceeter89/jira-client
JiraAssistant.Domain/NavigationMessages/OpenAgileBoardPickupMessage.cs
111
C#
using System; using Mochizuki.Fantasma.Extensions; using NUnit.Framework; namespace Mochizuki.Fantasma.Tests.Extensions { [TestFixture] internal class MethodInfoExtensionsTest { public interface IInterfaceA { void MethodA(); } public class InterfaceImplClassA : IInterfaceA { public void MethodA() { } } public abstract class BaseClassA { public abstract void MethodA(); } public class AbstractImplClassA : BaseClassA { public override void MethodA() { } } public class ClassA { public virtual void MethodA() { } } public class InheritClassA : ClassA { public override void MethodA() { } } [Test] [TestCase(typeof(InterfaceImplClassA), "MethodA", false)] [TestCase(typeof(AbstractImplClassA), "MethodA", true)] [TestCase(typeof(ClassA), "MethodA", false)] [TestCase(typeof(InheritClassA), "MethodA", true)] public void IsOverrideTest(Type t, string m, bool expected) { var method = t.GetMethod(m); Assert.AreEqual(expected, method.IsOverride()); } } }
24.169811
67
0.568306
[ "MIT" ]
mika-archived/Unity-Fantasma
Assets/Mochizuki/Fantasma/Tests/Extensions/MethodInfoExtensionsTest.cs
1,283
C#
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using Cube.Collections; using NUnit.Framework; namespace Cube.Tests { /* --------------------------------------------------------------------- */ /// /// ObservableCollectionTest /// /// <summary> /// Represents the test for the ObservableBase(T) collection. /// </summary> /// /* --------------------------------------------------------------------- */ [TestFixture] class ObservableCollectionTest { #region Tests /* ----------------------------------------------------------------- */ /// /// Invoke /// /// <summary> /// Confirms that CollectinChanged events are fired. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Invoke() { var src = new TestCollection<int>(); for (var i = 0; i < 3; ++i) src.Add(i); var count = 0; src.CollectionChanged += (s, e) => ++count; for (var i = 0; i < 3; ++i) src.Add(i); Assert.That(count, Is.EqualTo(3), "CollectionChanged"); Assert.That(src.Count(), Is.EqualTo(6), "Count"); } /* ----------------------------------------------------------------- */ /// /// Invoke_SynchronizationContext /// /// <summary> /// Confirms that CollectinChanged events are fired with the /// provided dispatcher. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Invoke_SynchronizationContext() { var src = new TestCollection<int>(); src.Set(new ContextDispatcher(new(), true)); for (var i = 0; i < 10; ++i) src.Add(i); var count = 0; src.CollectionChanged += (s, e) => ++count; for (var i = 0; i < 10; ++i) src.Add(i); Assert.That(count, Is.EqualTo(10), "CollectionChanged"); Assert.That(src.Count(), Is.EqualTo(20), "Count"); } #endregion } /* --------------------------------------------------------------------- */ /// /// TestCollection /// /// <summary> /// Represents the dummy collection that implements IEnumerable(T) /// and INotifiCollectionChanged interfaces. /// </summary> /// /* --------------------------------------------------------------------- */ class TestCollection<T> : ObservableBase<T> { #region Constructors /* ----------------------------------------------------------------- */ /// /// TestCollection /// /// <summary> /// Initializes a new instance of the TestCollection class. /// </summary> /// /* ----------------------------------------------------------------- */ public TestCollection() { _inner.CollectionChanged += (s, e) => OnCollectionChanged(e); } #endregion #region Methods /* ----------------------------------------------------------------- */ /// /// Set /// /// <summary> /// Sets the specified dispatcher. /// </summary> /// /* ----------------------------------------------------------------- */ public void Set(Dispatcher dispatcher) => Dispatcher = dispatcher; /* ----------------------------------------------------------------- */ /// /// Add /// /// <summary> /// Adds the specified value. /// </summary> /// /* ----------------------------------------------------------------- */ public void Add(T value) => _inner.Add(value); /* --------------------------------------------------------------------- */ /// /// GetEnumerator /// /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// /* --------------------------------------------------------------------- */ public override IEnumerator<T> GetEnumerator() => _inner.GetEnumerator(); #endregion #region Implementations /* ----------------------------------------------------------------- */ /// /// Dispose /// /// <summary> /// Releases the unmanaged resources used by the object and /// optionally releases the managed resources. /// </summary> /// /// <param name="disposing"> /// true to release both managed and unmanaged resources; /// false to release only unmanaged resources. /// </param> /// /* ----------------------------------------------------------------- */ protected override void Dispose(bool disposing) => _inner.Clear(); #endregion #region Fields private readonly ObservableCollection<T> _inner = new(); #endregion } }
32.351351
83
0.394319
[ "Apache-2.0" ]
cube-soft/Cube.Core
Tests/Core/Sources/Collections/ObservableTest.cs
5,987
C#
using System.Diagnostics.CodeAnalysis; using SCUMSLang.SyntaxTree.Definitions; namespace SCUMSLang.SyntaxTree.References { internal interface IHasParentBlock { [NotNull] BlockDefinition? ParentBlock { get; set; } [MemberNotNullWhen(true, nameof(ParentBlock))] bool HasParentBlock { get; } } }
22.666667
54
0.697059
[ "MIT" ]
SCUMSLang/SCUMSLang
src/SCUMSLang/src/SyntaxTree/References/IHasParentBlock.cs
342
C#
namespace AdventureGameCreator.Entities { public class Treasure : Item { } }
12.857143
40
0.666667
[ "MIT" ]
AdventureGameCreator/AdventureGameCreator
Assets/AdventureGameCreator/Entities/Treasure.cs
92
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; namespace Ezfx.Csv { public static partial class CsvContext { public static T[] ReadFile<T>(string path, string tableName, CsvConfig config) where T : new() { #if NET20 || NET35 || NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 if (path.GetIsOleDb()) { DataTable table = GetDataTable(path, tableName); return ReadDataTable<T>(table, config); } else { return ReadFile<T>(path, config); } #else return ReadFile<T>(path, config); #endif } public static T[] ReadDataTable<T>(DataTable table, CsvConfig config) where T : new() { List<T> ts = new List<T>(); for (int i = 0; i < table.Rows.Count; i++) { ts.Add(Read<T>(table.Rows[i], config)); } return ts.ToArray(); } private static T Read<T>(DataRow dataRow, CsvConfig config) where T : new() { if (config == null) { return ReadByTitle<T>(dataRow); } switch (config.MappingType) { case CsvMappingType.Title: return ReadByTitle<T>(dataRow); case CsvMappingType.Order: return ReadByOrder<T>(dataRow); default: return ReadByTitle<T>(dataRow); } } private static T ReadByOrder<T>(DataRow dataRow) where T : new() { T result = new T(); Type t = typeof(T); List<PropertyInfo> pis = t.GetProperties().ToList(); for (int i = 0; i < dataRow.ItemArray.Length; i++) { PropertyInfo pi = GetPropertyInfo(pis, i); if (pi != null) { pi.SetValue(result, dataRow[i].ToString(), null); } } return result; } private static T ReadByTitle<T>(DataRow dataRow) where T : new() { T result = new T(); Type t = typeof(T); List<PropertyInfo> pis = t.GetProperties().ToList(); for (int i = 0; i < dataRow.ItemArray.Length; i++) { PropertyInfo pi = GetPropertyInfo(pis, dataRow.Table.Columns[i].ColumnName); if (pi != null) { pi.SetValue(result, dataRow[i].ToString(),null); } } return result; } } }
29.870968
114
0.472282
[ "Apache-2.0" ]
EricWebsmith/csv2entity
Core/Ezfx.Csv/Core/CsvContext`1_DB.cs
2,780
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 sesv2-2019-09-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SimpleEmailV2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleEmailV2.Model.Internal.MarshallTransformations { /// <summary> /// CreateDedicatedIpPool Request Marshaller /// </summary> public class CreateDedicatedIpPoolRequestMarshaller : IMarshaller<IRequest, CreateDedicatedIpPoolRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateDedicatedIpPoolRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateDedicatedIpPoolRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SimpleEmailV2"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-09-27"; request.HttpMethod = "POST"; request.ResourcePath = "/v2/email/dedicated-ip-pools"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetPoolName()) { context.Writer.WritePropertyName("PoolName"); context.Writer.Write(publicRequest.PoolName); } if(publicRequest.IsSetTags()) { context.Writer.WritePropertyName("Tags"); context.Writer.WriteArrayStart(); foreach(var publicRequestTagsListValue in publicRequest.Tags) { context.Writer.WriteObjectStart(); var marshaller = TagMarshaller.Instance; marshaller.Marshall(publicRequestTagsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreateDedicatedIpPoolRequestMarshaller _instance = new CreateDedicatedIpPoolRequestMarshaller(); internal static CreateDedicatedIpPoolRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateDedicatedIpPoolRequestMarshaller Instance { get { return _instance; } } } }
36.08547
157
0.61748
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/SimpleEmailV2/Generated/Model/Internal/MarshallTransformations/CreateDedicatedIpPoolRequestMarshaller.cs
4,222
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using HubSpot.Model; namespace HubSpot.Contacts.Filters { public class SearchContactFilter : ContactFilter { private readonly string _searchQuery; public SearchContactFilter(string searchQuery) { _searchQuery = searchQuery ?? throw new ArgumentNullException(nameof(searchQuery)); } protected override async Task<(IReadOnlyList<Model.Contacts.Contact> list, bool hasMore, long? offset)> Get(IHubSpotClient client, IReadOnlyList<IProperty> propertiesToQuery, long? offset) { var response = await client.Contacts.SearchAsync(_searchQuery, propertiesToQuery, 25, offset); return (response.Contacts, response.HasMore, response.Offset); } } }
35.782609
196
0.710814
[ "MIT" ]
Kralizek/hubspot-dotnet-sdk
src/HubSpot/Contacts/Filters/SearchContactFilter.cs
825
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> : IMoveTypeService where TService : AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> where TTypeDeclarationSyntax : SyntaxNode where TNamespaceDeclarationSyntax : SyntaxNode where TMemberDeclarationSyntax : SyntaxNode where TCompilationUnitSyntax : SyntaxNode { private enum OperationKind { MoveType, RenameType, RenameFile } public async Task<ImmutableArray<CodeAction>> GetRefactoringAsync( Document document, TextSpan textSpan, CancellationToken cancellationToken) { if (textSpan.IsEmpty) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var nodeToAnalyze = root.FindToken(textSpan.Start).GetAncestor<TTypeDeclarationSyntax>(); if (nodeToAnalyze != null) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsOnTypeHeader(root, textSpan.Start)) { var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var state = State.Generate( semanticDocument, textSpan, nodeToAnalyze, cancellationToken); if (state != null) { var actions = CreateActions(state, cancellationToken); Debug.Assert(actions.Count() != 0, "No code actions found for MoveType Refactoring"); return actions; } } } } return ImmutableArray<CodeAction>.Empty; } private ImmutableArray<CodeAction> CreateActions(State state, CancellationToken cancellationToken) { var actions = new List<CodeAction>(); var manyTypes = MultipleTopLevelTypeDeclarationInSourceDocument(state.SemanticDocument.Root); var isNestedType = IsNestedType(state.TypeNode); var suggestedFileNames = GetSuggestedFileNames( state.TypeNode, isNestedType, state.TypeName, state.SemanticDocument.Document.Name, state.SemanticDocument.SemanticModel, cancellationToken); // (1) Add Move type to new file code action: // case 1: There are multiple type declarations in current document. offer, move to new file. // case 2: This is a nested type, offer to move to new file. // case 3: If there is a single type decl in current file, *do not* offer move to new file, // rename actions are sufficient in this case. if (manyTypes || isNestedType) { foreach (var fileName in suggestedFileNames) { actions.Add(GetCodeAction(state, fileName, operationKind: OperationKind.MoveType)); } } // (2) Add rename file and rename type code actions: // Case: No type declaration in file matches the file name. if (!AnyTopLevelTypeMatchesDocumentName(state, cancellationToken)) { foreach (var fileName in suggestedFileNames) { actions.Add(GetCodeAction(state, fileName, operationKind: OperationKind.RenameFile)); } // only if the document name can be legal identifier in the language, // offer to rename type with document name if (state.IsDocumentNameAValidIdentifier) { actions.Add(GetCodeAction( state, fileName: state.DocumentNameWithoutExtension, operationKind: OperationKind.RenameType)); } } return actions.ToImmutableArray(); } private CodeAction GetCodeAction(State state, string fileName, OperationKind operationKind) => new MoveTypeCodeAction((TService)this, state, operationKind, fileName); private bool IsNestedType(TTypeDeclarationSyntax typeNode) => typeNode.Parent is TTypeDeclarationSyntax; /// <summary> /// checks if there is a single top level type declaration in a document /// </summary> /// <remarks> /// optimized for perf, uses Skip(1).Any() instead of Count() > 1 /// </remarks> private bool MultipleTopLevelTypeDeclarationInSourceDocument(SyntaxNode root) => TopLevelTypeDeclarations(root).Skip(1).Any(); private static IEnumerable<TTypeDeclarationSyntax> TopLevelTypeDeclarations(SyntaxNode root) => root.DescendantNodes(n => (n is TCompilationUnitSyntax || n is TNamespaceDeclarationSyntax)) .OfType<TTypeDeclarationSyntax>(); private bool AnyTopLevelTypeMatchesDocumentName(State state, CancellationToken cancellationToken) { var root = state.SemanticDocument.Root; var semanticModel = state.SemanticDocument.SemanticModel; return TopLevelTypeDeclarations(root).Any( typeDeclaration => { var typeName = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken).Name; return TypeMatchesDocumentName( typeDeclaration, typeName, state.DocumentNameWithoutExtension, semanticModel, cancellationToken); }); } /// <summary> /// checks if type name matches its parent document name, per style rules. /// </summary> /// <remarks> /// Note: For a nested type, a matching document name could be just the type name or a /// dotted qualified name of its type hierarchy. /// </remarks> protected static bool TypeMatchesDocumentName( TTypeDeclarationSyntax typeNode, string typeName, string documentNameWithoutExtension, SemanticModel semanticModel, CancellationToken cancellationToken) { // If it is not a nested type, we compare the unqualified type name with the document name. // If it is a nested type, the type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs` var namesMatch = typeName.Equals(documentNameWithoutExtension, StringComparison.CurrentCulture); if (!namesMatch) { var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken); var fileNameParts = documentNameWithoutExtension.Split('.'); // qualified type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs` return typeNameParts.SequenceEqual(fileNameParts, StringComparer.CurrentCulture); } return namesMatch; } private IEnumerable<string> GetSuggestedFileNames( TTypeDeclarationSyntax typeNode, bool isNestedType, string typeName, string documentNameWithExtension, SemanticModel semanticModel, CancellationToken cancellationToken) { var fileExtension = Path.GetExtension(documentNameWithExtension); var standaloneName = typeName + fileExtension; // If it is a nested type, we should match type hierarchy's name parts with the file name. if (isNestedType) { var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken); var dottedName = typeNameParts.Join(".") + fileExtension; return new List<string> { standaloneName, dottedName }; } else { return SpecializedCollections.SingletonEnumerable(standaloneName); } } private static IEnumerable<string> GetTypeNamePartsForNestedTypeNode( TTypeDeclarationSyntax typeNode, SemanticModel semanticModel, CancellationToken cancellationToken) => typeNode.AncestorsAndSelf() .OfType<TTypeDeclarationSyntax>() .Select(n => semanticModel.GetDeclaredSymbol(n, cancellationToken).Name) .Reverse(); } }
45.507177
174
0.622227
[ "Apache-2.0" ]
AdamSpeight2008/roslyn-1
src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.cs
9,513
C#
#region License //The MIT License (MIT) //Copyright (c) 2014 Konrad Huber //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #endregion using VEF.Model.Settings; namespace XIDE.Core.Settings { public class ProjectSettingsItem : AbstractSettingsItem { public ProjectSettingsItem(string title, int priority, AbstractSettings settings) : base(title, settings) { this.Priority = priority; } } }
37.410256
89
0.749143
[ "MIT" ]
devxkh/FrankE
Editor/VEX/Modules/Core/VEX.Core.Shared/Settings/ProjectSettingsItem.cs
1,461
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Dialogs.Choices; using Microsoft.Bot.Connector.Authentication; using Microsoft.Bot.Schema; namespace Microsoft.BotBuilderSamples.SkillBot.Dialogs { public class SsoSkillDialog : ComponentDialog { private readonly string _connectionName; public SsoSkillDialog(string connectionName) : base(nameof(SsoSkillDialog)) { _connectionName = connectionName; if (string.IsNullOrWhiteSpace(_connectionName)) { throw new ArgumentException("\"ConnectionName\" is not set in configuration"); } AddDialog(new SsoSkillSignInDialog(_connectionName)); AddDialog(new ChoicePrompt("ActionStepPrompt")); var waterfallSteps = new WaterfallStep[] { PromptActionStepAsync, HandleActionStepAsync, PromptFinalStepAsync }; AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps)); InitialDialogId = nameof(WaterfallDialog); } private async Task<DialogTurnResult> PromptActionStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var messageText = "What SSO action would you like to perform on the skill?"; var repromptMessageText = "That was not a valid choice, please select a valid choice."; var options = new PromptOptions { Prompt = MessageFactory.Text(messageText, messageText, InputHints.ExpectingInput), RetryPrompt = MessageFactory.Text(repromptMessageText, repromptMessageText, InputHints.ExpectingInput), Choices = await GetPromptChoicesAsync(stepContext, cancellationToken) }; // Prompt the user to select a skill. return await stepContext.PromptAsync("ActionStepPrompt", options, cancellationToken); } private async Task<List<Choice>> GetPromptChoicesAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Try to get the token for the current user to determine if it is logged in or not. var userId = stepContext.Context.Activity?.From?.Id; var userTokenClient = stepContext.Context.TurnState.Get<UserTokenClient>(); var token = await userTokenClient.GetUserTokenAsync(userId, _connectionName, stepContext.Context.Activity?.ChannelId, null, cancellationToken); // Present different choices depending on the user's sign in status. var promptChoices = new List<Choice>(); if (token == null) { promptChoices.Add(new Choice("Login to the skill")); } else { promptChoices.Add(new Choice("Logout from the skill")); promptChoices.Add(new Choice("Show token")); } promptChoices.Add(new Choice("End")); return promptChoices; } private async Task<DialogTurnResult> HandleActionStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var action = ((FoundChoice)stepContext.Result).Value.ToLowerInvariant(); var userId = stepContext.Context.Activity?.From?.Id; var userTokenClient = stepContext.Context.TurnState.Get<UserTokenClient>(); switch (action) { case "login to the skill": // The SsoSkillSignInDialog will just show the user token if the user logged on to the root bot. return await stepContext.BeginDialogAsync(nameof(SsoSkillSignInDialog), null, cancellationToken); case "logout from the skill": // This will just clear the token from the skill. await userTokenClient.SignOutUserAsync(userId, _connectionName, stepContext.Context.Activity?.ChannelId, cancellationToken); await stepContext.Context.SendActivityAsync("You have been signed out.", cancellationToken: cancellationToken); return await stepContext.NextAsync(cancellationToken: cancellationToken); case "show token": var token = await userTokenClient.GetUserTokenAsync(userId, _connectionName, stepContext.Context.Activity?.ChannelId, null, cancellationToken); if (token == null) { await stepContext.Context.SendActivityAsync("User has no cached token.", cancellationToken: cancellationToken); } else { await stepContext.Context.SendActivityAsync($"Here is your current SSO token for the skill: {token.Token}", cancellationToken: cancellationToken); } return await stepContext.NextAsync(cancellationToken: cancellationToken); case "end": // Ends the interaction with the skill. return new DialogTurnResult(DialogTurnStatus.Complete); default: // This should never be hit since the previous prompt validates the choice. throw new InvalidOperationException($"Unrecognized action: {action}"); } } private async Task<DialogTurnResult> PromptFinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Restart the dialog (we will exit when the user says "end"). return await stepContext.ReplaceDialogAsync(InitialDialogId, null, cancellationToken); } } }
45.923664
170
0.639295
[ "MIT" ]
Aliacf21/BotBuilder-Samples
samples/csharp_dotnetcore/82.skills-sso-cloudadapter/SkillBot/Dialogs/SsoSkillDialog.cs
6,018
C#
using System; namespace MoviesDatabase.Core.Entities { public abstract class Entity { public Guid Id { get; set; } } }
14.1
38
0.631206
[ "Apache-2.0" ]
ilievv/movies-database-api
src/MoviesDatabase.Core/Entities/Entity.cs
143
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network.Models; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.Network { /// <summary> A class representing collection of P2SVpnGateway and their operations over its parent. </summary> public partial class P2SVpnGatewayCollection : ArmCollection, IEnumerable<P2SVpnGateway>, IAsyncEnumerable<P2SVpnGateway> { private readonly ClientDiagnostics _clientDiagnostics; private readonly P2SVpnGatewaysRestOperations _p2sVpnGatewaysRestClient; /// <summary> Initializes a new instance of the <see cref="P2SVpnGatewayCollection"/> class for mocking. </summary> protected P2SVpnGatewayCollection() { } /// <summary> Initializes a new instance of P2SVpnGatewayCollection class. </summary> /// <param name="parent"> The resource representing the parent resource. </param> internal P2SVpnGatewayCollection(ArmResource parent) : base(parent) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _p2sVpnGatewaysRestClient = new P2SVpnGatewaysRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); } /// <summary> Gets the valid resource type for this object. </summary> protected override ResourceType ValidResourceType => ResourceGroup.ResourceType; // Collection level operations. /// <summary> Creates a virtual wan p2s vpn gateway if it doesn&apos;t exist else updates the existing gateway. </summary> /// <param name="gatewayName"> The name of the gateway. </param> /// <param name="p2SVpnGatewayParameters"> Parameters supplied to create or Update a virtual wan p2s vpn gateway. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="gatewayName"/> or <paramref name="p2SVpnGatewayParameters"/> is null. </exception> public virtual P2SVpnGatewayCreateOrUpdateOperation CreateOrUpdate(string gatewayName, P2SVpnGatewayData p2SVpnGatewayParameters, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (gatewayName == null) { throw new ArgumentNullException(nameof(gatewayName)); } if (p2SVpnGatewayParameters == null) { throw new ArgumentNullException(nameof(p2SVpnGatewayParameters)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.CreateOrUpdate"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, gatewayName, p2SVpnGatewayParameters, cancellationToken); var operation = new P2SVpnGatewayCreateOrUpdateOperation(Parent, _clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, gatewayName, p2SVpnGatewayParameters).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates a virtual wan p2s vpn gateway if it doesn&apos;t exist else updates the existing gateway. </summary> /// <param name="gatewayName"> The name of the gateway. </param> /// <param name="p2SVpnGatewayParameters"> Parameters supplied to create or Update a virtual wan p2s vpn gateway. </param> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="gatewayName"/> or <paramref name="p2SVpnGatewayParameters"/> is null. </exception> public async virtual Task<P2SVpnGatewayCreateOrUpdateOperation> CreateOrUpdateAsync(string gatewayName, P2SVpnGatewayData p2SVpnGatewayParameters, bool waitForCompletion = true, CancellationToken cancellationToken = default) { if (gatewayName == null) { throw new ArgumentNullException(nameof(gatewayName)); } if (p2SVpnGatewayParameters == null) { throw new ArgumentNullException(nameof(p2SVpnGatewayParameters)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.CreateOrUpdate"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, gatewayName, p2SVpnGatewayParameters, cancellationToken).ConfigureAwait(false); var operation = new P2SVpnGatewayCreateOrUpdateOperation(Parent, _clientDiagnostics, Pipeline, _p2sVpnGatewaysRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, gatewayName, p2SVpnGatewayParameters).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Retrieves the details of a virtual wan p2s vpn gateway. </summary> /// <param name="gatewayName"> The name of the gateway. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="gatewayName"/> is null. </exception> public virtual Response<P2SVpnGateway> Get(string gatewayName, CancellationToken cancellationToken = default) { if (gatewayName == null) { throw new ArgumentNullException(nameof(gatewayName)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.Get"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, gatewayName, cancellationToken); if (response.Value == null) throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new P2SVpnGateway(Parent, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Retrieves the details of a virtual wan p2s vpn gateway. </summary> /// <param name="gatewayName"> The name of the gateway. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="gatewayName"/> is null. </exception> public async virtual Task<Response<P2SVpnGateway>> GetAsync(string gatewayName, CancellationToken cancellationToken = default) { if (gatewayName == null) { throw new ArgumentNullException(nameof(gatewayName)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.Get"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, gatewayName, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new P2SVpnGateway(Parent, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="gatewayName"> The name of the gateway. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="gatewayName"/> is null. </exception> public virtual Response<P2SVpnGateway> GetIfExists(string gatewayName, CancellationToken cancellationToken = default) { if (gatewayName == null) { throw new ArgumentNullException(nameof(gatewayName)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.GetIfExists"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, gatewayName, cancellationToken: cancellationToken); return response.Value == null ? Response.FromValue<P2SVpnGateway>(null, response.GetRawResponse()) : Response.FromValue(new P2SVpnGateway(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="gatewayName"> The name of the gateway. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="gatewayName"/> is null. </exception> public async virtual Task<Response<P2SVpnGateway>> GetIfExistsAsync(string gatewayName, CancellationToken cancellationToken = default) { if (gatewayName == null) { throw new ArgumentNullException(nameof(gatewayName)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.GetIfExistsAsync"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, gatewayName, cancellationToken: cancellationToken).ConfigureAwait(false); return response.Value == null ? Response.FromValue<P2SVpnGateway>(null, response.GetRawResponse()) : Response.FromValue(new P2SVpnGateway(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="gatewayName"> The name of the gateway. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="gatewayName"/> is null. </exception> public virtual Response<bool> Exists(string gatewayName, CancellationToken cancellationToken = default) { if (gatewayName == null) { throw new ArgumentNullException(nameof(gatewayName)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.Exists"); scope.Start(); try { var response = GetIfExists(gatewayName, cancellationToken: cancellationToken); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Tries to get details for this resource from the service. </summary> /// <param name="gatewayName"> The name of the gateway. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="gatewayName"/> is null. </exception> public async virtual Task<Response<bool>> ExistsAsync(string gatewayName, CancellationToken cancellationToken = default) { if (gatewayName == null) { throw new ArgumentNullException(nameof(gatewayName)); } using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.ExistsAsync"); scope.Start(); try { var response = await GetIfExistsAsync(gatewayName, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Lists all the P2SVpnGateways in a resource group. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="P2SVpnGateway" /> that may take multiple service requests to iterate over. </returns> public virtual Pageable<P2SVpnGateway> GetAll(CancellationToken cancellationToken = default) { Page<P2SVpnGateway> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.GetAll"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.ListByResourceGroup(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new P2SVpnGateway(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<P2SVpnGateway> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.GetAll"); scope.Start(); try { var response = _p2sVpnGatewaysRestClient.ListByResourceGroupNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new P2SVpnGateway(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Lists all the P2SVpnGateways in a resource group. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="P2SVpnGateway" /> that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<P2SVpnGateway> GetAllAsync(CancellationToken cancellationToken = default) { async Task<Page<P2SVpnGateway>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.GetAll"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.ListByResourceGroupAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new P2SVpnGateway(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<P2SVpnGateway>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.GetAll"); scope.Start(); try { var response = await _p2sVpnGatewaysRestClient.ListByResourceGroupNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new P2SVpnGateway(Parent, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Filters the list of <see cref="P2SVpnGateway" /> for this resource group represented as generic resources. </summary> /// <param name="nameFilter"> The filter used in this operation. </param> /// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param> /// <param name="top"> The number of results to return. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of resource that may take multiple service requests to iterate over. </returns> public virtual Pageable<GenericResource> GetAllAsGenericResources(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.GetAllAsGenericResources"); scope.Start(); try { var filters = new ResourceFilterCollection(P2SVpnGateway.ResourceType); filters.SubstringFilter = nameFilter; return ResourceListOperations.GetAtContext(Parent as ResourceGroup, filters, expand, top, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Filters the list of <see cref="P2SVpnGateway" /> for this resource group represented as generic resources. </summary> /// <param name="nameFilter"> The filter used in this operation. </param> /// <param name="expand"> Comma-separated list of additional properties to be included in the response. Valid values include `createdTime`, `changedTime` and `provisioningState`. </param> /// <param name="top"> The number of results to return. </param> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> An async collection of resource that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<GenericResource> GetAllAsGenericResourcesAsync(string nameFilter, string expand = null, int? top = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("P2SVpnGatewayCollection.GetAllAsGenericResources"); scope.Start(); try { var filters = new ResourceFilterCollection(P2SVpnGateway.ResourceType); filters.SubstringFilter = nameFilter; return ResourceListOperations.GetAtContextAsync(Parent as ResourceGroup, filters, expand, top, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } IEnumerator<P2SVpnGateway> IEnumerable<P2SVpnGateway>.GetEnumerator() { return GetAll().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetAll().GetEnumerator(); } IAsyncEnumerator<P2SVpnGateway> IAsyncEnumerable<P2SVpnGateway>.GetAsyncEnumerator(CancellationToken cancellationToken) { return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); } // Builders. // public ArmBuilder<Azure.ResourceManager.ResourceIdentifier, P2SVpnGateway, P2SVpnGatewayData> Construct() { } } }
52.048077
263
0.631027
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/P2SVpnGatewayCollection.cs
21,652
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; using System.Reflection; namespace Microsoft.AspNet.Mvc { public class ViewComponentContext { public ViewComponentContext([NotNull] TypeInfo componentType, [NotNull] ViewContext viewContext, [NotNull] TextWriter writer) { ComponentType = componentType; ViewContext = viewContext; Writer = writer; } public TypeInfo ComponentType { get; private set; } public ViewContext ViewContext { get; private set; } public TextWriter Writer { get; private set; } } }
29.576923
111
0.672302
[ "Apache-2.0" ]
moljac/Mvc
src/Microsoft.AspNet.Mvc.Core/ViewComponents/ViewComponentContext.cs
769
C#
using System; using System.Collections.Generic; using System.Text; using TTY.Api.Throttle.Extensions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace TTY.Api.Throttle.Redis.Cache { public class RedisCacheOptionsExtension : IApiThrottleOptionsExtension { private readonly Action<RedisCacheOptions> _options; public RedisCacheOptionsExtension(Action<RedisCacheOptions> options) { _options = options; } public void AddServices(IServiceCollection services) { services.TryAddSingleton<IRedisCacheDatabaseProvider, RedisCacheDatabaseProvider>(); services.TryAddSingleton<IThrottleCacheProvider, RedisCacheProvider>(); services.Configure<RedisCacheOptions>(_options); } } }
31.703704
96
0.734813
[ "MIT" ]
chenjian8541/gmp
src/TTY.Api.Throttle/Redis/Cache/RedisCacheOptionsExtension.cs
858
C#
// Copyright (c) 2014, Kinvey, Inc. All rights reserved. // // This software is licensed to you under the Kinvey terms of service located at // http://www.kinvey.com/terms-of-use. By downloading, accessing and/or using this // software, you hereby accept such terms of service (and any agreement referenced // therein) and agree that you have read, understand and agree to be bound by such // terms of service and are of legal age to agree to such terms with Kinvey. // // This software contains valuable confidential and proprietary information of // KINVEY, INC and is subject to applicable licensing agreements. // Unauthorized reproduction, transmission or distribution of this file and its // contents is a violation of applicable laws. using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using RestSharp; using System.Threading; using KinveyXamarin; using System.Threading.Tasks; using System.IO; using SQLite.Net.Platform.XamarinAndroid; using System.Linq; using LinqExtender; using System.Text; using KinveyUtils; using KinveyXamarinAndroid; using Newtonsoft.Json.Linq; namespace AndroidTestDrive { // [Activity (Label = "Android-TestDrive", MainLauncher = true)] // [IntentFilter (new[]{Intent.ActionView}, // Categories=new[]{Intent.CategoryDefault, Intent.CategoryBrowsable}, // DataScheme="kinveyauthdemo" // )] // <intent-filter> // <action android:name="android.intent.action.VIEW" /> // <category android:name="android.intent.category.DEFAULT" /> // <category android:name="android.intent.category.BROWSABLE" /> // <data android:scheme="myredirecturi" /> <!-- This is the scheme which must be changed --> // </intent-filter> public class MainActivity : Activity { int count = 1; //private string appKey = "kid_PeYFqjBcBJ"; //private string appSecret = "3fee066a01784e2ab32a255151ff761b"; private string appKey = "kid_WyYCSd34p"; private string appSecret = "22a381bca79c407cb0efc6585aaed53e"; private static string COLLECTION = "entityCollection"; private static string STABLE_ID = "testdriver"; Client kinveyClient; InMemoryCache<MyEntity> myCache = new InMemoryCache<MyEntity>(); protected override async void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); kinveyClient = new Client.Builder(appKey, appSecret) .setFilePath(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)) .setOfflinePlatform(new SQLitePlatformAndroid()) .setLogger(delegate(string msg) { Console.WriteLine(msg);}) .SetProjectId("517053089453") .build(); Logger.Log ("---------------------------------------------logger"); // kinveyClient.Ping (new KinveyDelegate<PingResponse>{ // onSuccess = (response) => { // RunOnUiThread (() => { // Toast.MakeText(this, "Ping successful!", ToastLength.Short).Show(); // }); // }, // onError = (error) => { // RunOnUiThread (() => { // Toast.MakeText(this, "something went wrong: " + error.Message, ToastLength.Short).Show(); // }); // } // }); //User user = await kinveyClient.User ().LoginAsync (); // kinveyClient.User().LoginWithAuthorizationCodeLoginPage("kinveyAuthDemo://", new KinveyMICDelegate<User>{ onSuccess = (user) => { RunOnUiThread (() => { Toast.MakeText(this, "logged in as: " + user.Id, ToastLength.Short).Show(); }); }, onError = (error) => { RunOnUiThread (() => { Toast.MakeText(this, "something went wrong: " + error.Message, ToastLength.Short).Show(); }); }, OnReadyToRender = (url) => { var uri = Android.Net.Uri.Parse (url); var intent = new Intent (Intent.ActionView, uri); StartActivity (intent); } }); // kinveyClient.User().LoginWithAuthorizationCodeAPI("mjs", "demo", "kinveyAuthDemo://", new KinveyDelegate<User>{ onSuccess = (user) => { RunOnUiThread (() => { Toast.MakeText(this, "logged in as: " + user.Id, ToastLength.Short).Show(); }); }, onError = (error) => { RunOnUiThread (() => { Toast.MakeText(this, "something went wrong: " + error.Message, ToastLength.Short).Show(); }); } }); // // Toast.MakeText(this, "logged in as: " + user.Id, ToastLength.Short).Show(); //kinveyClient.Push ().Initialize(this.ApplicationContext); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.myButton); button.Click += delegate { button.Text = string.Format ("{0} clicks!", count++); }; Button save = FindViewById<Button> (Resource.Id.saveButton); save.Click += delegate { //new Thread (() => saveAndToast (); //).Start (); }; Button load = FindViewById<Button> (Resource.Id.loadButton); load.Click += delegate { //new Thread(() => loadAndToast() ; //).Start(); }; Button loadCache = FindViewById<Button> (Resource.Id.loadWithCacheButton); loadCache.Click += delegate { //new Thread(() => loadFromCacheAndToast() ; //).Start(); }; Button loadQuery = FindViewById<Button> (Resource.Id.loadWithQuery); loadQuery.Click += delegate { //new Thread(() => loadFromQuery(); //).Start(); }; } private async void saveAndToast(){ AsyncAppData<MyEntity> entityCollection = kinveyClient.AppData<MyEntity>(COLLECTION, typeof(MyEntity)); MyEntity ent = new MyEntity(); ent.Email = "test@tester.com"; ent.Name = "James Dean"; ent.ID = STABLE_ID; //entityCollection.setOffline(new SQLiteOfflineStore(), OfflinePolicy.LOCAL_FIRST); try{ MyEntity entity = await entityCollection.SaveAsync (ent); Toast.MakeText (this, "saved: " + entity.Name, ToastLength.Short).Show (); }catch(Exception e){ Toast.MakeText (this, "something went wrong; " + e.Message, ToastLength.Short).Show (); } } private async void loadAndToast(){ AsyncAppData<MyEntity> entityCollection = kinveyClient.AppData<MyEntity>(COLLECTION, typeof(MyEntity)); //entityCollection.setOffline(new SQLiteOfflineStore(), OfflinePolicy.LOCAL_FIRST); MyEntity res = await entityCollection.GetEntityAsync (STABLE_ID); Toast.MakeText(this, "got: " + res.Name, ToastLength.Short).Show(); } private async void loadFromCacheAndToast(){ AsyncAppData<MyEntity> entityCollection = kinveyClient.AppData<MyEntity>(COLLECTION, typeof(MyEntity)); entityCollection.setCache (myCache, CachePolicy.CACHE_FIRST); MyEntity entity = await entityCollection.GetEntityAsync (STABLE_ID); Toast.MakeText (this, "got: " + entity.Name, ToastLength.Short).Show (); } private async void loadFromQuery(){ AsyncAppData<MyEntity> query = kinveyClient.AppData<MyEntity>(COLLECTION, typeof(MyEntity)); // query.setOffline (new SQLiteOfflineStore(), OfflinePolicy.LOCAL_FIRST); var query1 = from cust in query where cust.Name == "James Dean" select cust; Task.Run (() => { foreach (MyEntity e in query1){ Console.WriteLine("got -> " + e.Name); } Console.WriteLine("total at: " + query1.Count()); }); } protected override void OnNewIntent(Intent intent){ base.OnNewIntent (intent); kinveyClient.User ().OnOAuthCallbackRecieved (intent); } } }
29.575397
113
0.677311
[ "Apache-2.0" ]
KinveyApps/TestDrive-Xamarin
android/MainActivity.cs
7,455
C#
using UnityEngine; using System.Collections; using KCore; using KData; using KScene; namespace KCore { public class KColorUtil { /// <summary> /// 解析颜色字符串,两种格式,抄自官方文档 /// Strings that do not begin with '#' will be parsed as literal colors, with the following supported: /// red, cyan, blue, darkblue, lightblue, purple, yellow, lime, fuchsia, white, silver, grey, black, orange, brown, maroon, green, olive, navy, teal, aqua, magenta.. /// </summary> public static Color ParseColor(string colorHtmlString) { Color color; if (ColorUtility.TryParseHtmlString(colorHtmlString, out color)) { return color; } else { Debug.LogError("ParseColor|colorHtmlString|" + colorHtmlString + "|use|Color.black|instead"); return Color.black; } } } }
22.216216
168
0.664234
[ "MIT" ]
beckheng/BBTowerDefense
BBTowerDefense_Client/Assets/Standard Assets/KCore/KColor/KColorUtil.cs
858
C#
using NadekoBot.Core.Services.Database.Models; using Newtonsoft.Json; namespace NadekoBot.Modules.Searches.Common { public interface IStreamResponse { FollowedStream.FType StreamType { get; } string Name { get; } int Viewers { get; } string Title { get; } bool Live { get; } string Game { get; } int Followers { get; } string ApiUrl { get; set; } string Icon { get; } string Preview { get; } } public class StreamResponse : IStreamResponse { public FollowedStream.FType StreamType { get; set; } public string Name { get; set; } public int Viewers { get; set; } public string Title { get; set; } public bool Live { get; set; } public string Game { get; set; } public int Followers { get; set; } public string ApiUrl { get; set; } public string Icon { get; set; } public string Preview { get; set; } } public class SmashcastResponse : IStreamResponse { [JsonProperty("user_name")] public string Name { get; set; } public bool Success { get; set; } = true; public int Followers { get; set; } [JsonProperty("user_logo")] public string UserLogo { get; set; } [JsonProperty("is_live")] public string IsLive { get; set; } public int Viewers => 0; public string Title => ""; public bool Live => IsLive == "1"; public string Game => ""; public string Icon => !string.IsNullOrWhiteSpace(UserLogo) ? "https://edge.sf.hitbox.tv" + UserLogo : ""; public string ApiUrl { get; set; } public FollowedStream.FType StreamType => FollowedStream.FType.Smashcast; [JsonProperty("user_cover")] public string ThumbnailPath { get; set; } public string Preview => !string.IsNullOrWhiteSpace(ThumbnailPath) ? "https://edge.sf.hitbox.tv" + ThumbnailPath : ""; } public class PicartoResponse : IStreamResponse { public class PThumbnail { public string Web { get; set; } } public string Name { get; set; } public int Viewers { get; set; } public string Title { get; set; } [JsonProperty("online")] public bool Live { get; set; } [JsonProperty("category")] public string Game { get; set; } public int Followers { get; set; } public string ApiUrl { get; set; } [JsonProperty("avatar")] public string Icon { get; set; } public FollowedStream.FType StreamType => FollowedStream.FType.Picarto; public PThumbnail Thumbnails { get; set; } public string Preview => Thumbnails?.Web; } public class TwitchResponse : IStreamResponse { public string Error { get; set; } = null; public bool IsLive => Stream != null && Stream.Type == "live"; public StreamInfo Stream { get; set; } public string Name => Stream?.Channel.Name; public class StreamInfo { public int Viewers { get; set; } public string Game { get; set; } public ChannelInfo Channel { get; set; } [JsonProperty("preview")] public TwitchPreview PreviewData { get; set; } [JsonProperty("stream_type")] public string Type { get; set; } public class ChannelInfo { public string Name { get; set; } public string Status { get; set; } public string Logo { get; set; } public int Followers { get; set; } } } public class TwitchPreview { public string Large { get; set; } } public int Viewers => Stream?.Viewers ?? 0; public string Title => Stream?.Channel?.Status; public bool Live => IsLive; public string Game => Stream?.Game; public int Followers => Stream?.Channel?.Followers ?? 0; public string ApiUrl { get; set; } public string Icon => Stream?.Channel?.Logo; public FollowedStream.FType StreamType => FollowedStream.FType.Twitch; public string Preview => Stream?.PreviewData?.Large; } public class MixerResponse : IStreamResponse { public class MixerType { public string Parent { get; set; } public string Name { get; set; } } public class MixerUser { public string AvatarUrl { get; set; } } public class MixerThumbnail { public string Url { get; set; } } [JsonProperty("thumbnail")] public MixerThumbnail ThumbnailData { get; set; } public string ApiUrl { get; set; } public string Error { get; set; } = null; [JsonProperty("online")] public bool IsLive { get; set; } public int ViewersCurrent { get; set; } public string Name { get; set; } public int NumFollowers { get; set; } public MixerType Type { get; set; } public MixerUser User { get; set; } public int Viewers => ViewersCurrent; public string Title => Name; public bool Live => IsLive; public string Game => Type?.Name ?? ""; public int Followers => NumFollowers; public string Icon => User?.AvatarUrl; public FollowedStream.FType StreamType => FollowedStream.FType.Mixer; public string Preview => ThumbnailData?.Url; } }
31.931818
81
0.564947
[ "MIT" ]
Kuromu/NadekoBot
NadekoBot.Core/Modules/Searches/Common/StreamResponses.cs
5,622
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using ActionableRestfulApiErrors.Areas.HelpPage.Models; namespace ActionableRestfulApiErrors.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
55.370968
196
0.654894
[ "MIT" ]
ivanmartinvalle/actionable-restful-api-errors
ActionableRestfulApiErrors/Areas/HelpPage/HelpPageConfigurationExtensions.cs
13,732
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using DrawShape; using DrawShape.Android; using Android.Graphics; [assembly:ExportRenderer (typeof(ShapeView), typeof(ShapeRenderer))] namespace DrawShape.Android { public class ShapeRenderer : ViewRenderer<ShapeView, Shape> { public ShapeRenderer () { } protected override void OnElementChanged (ElementChangedEventArgs<ShapeView> e) { base.OnElementChanged (e); if (e.OldElement != null || this.Element == null) return; SetNativeControl (new Shape (Resources.DisplayMetrics.Density, Context) { ShapeView = Element }); } } }
22
81
0.738245
[ "MIT" ]
chrispellett/Xamarin-Forms-Shape
Android/ShapeRenderer.cs
640
C#
using AutoMapper; using DutchTreat.Data.Entities; using DutchTreat.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.Data { //this is the configuration class for mapping,which is required by startup class when addding service public class DutchMappingProfile :Profile { public DutchMappingProfile() { CreateMap<Order, OrderViewModel>() .ForMember(destination => destination.OrderId, ex => ex.MapFrom(src => src.Id)) .ForMember(destination => destination.OrederNumber, ex => ex.MapFrom(src => src.OrderNumber)) .ReverseMap(); CreateMap<OrderItem, OrderItemViewModel>() .ReverseMap(); } } }
30.769231
109
0.66
[ "MIT" ]
RuchiraGamage/DutchTreat
DutchTreat/Data/DutchMappingProfile.cs
802
C#
using Microsoft.Extensions.Logging; using System; using System.Diagnostics; using System.IO; using System.Net.WebSockets; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace KubeClient.Extensions.WebSockets.Tests { /// <summary> /// Tests for <see cref="KubeApiClient"/>'s exec-in-pod functionality. /// </summary> public class PodExecTests : WebSocketTestBase { /// <summary> /// Create a new <see cref="KubeApiClient"/> exec-in-pod test suite. /// </summary> /// <param name="testOutput"> /// Output for the current test. /// </param> public PodExecTests(ITestOutputHelper testOutput) : base(testOutput) { } /// <summary> /// Verify that the client can request execution of a command in a pod's default container, over a raw WebSocket connection, with only the STDOUT stream enabled. /// </summary> [Fact(DisplayName = "Can exec in pod's default container, raw WebSocket, STDOUT only")] public async Task Exec_DefaultContainer_Raw_StdOut() { const string expectedOutput = "This is text sent to STDOUT."; TestTimeout( TimeSpan.FromSeconds(5) ); await Host.StartAsync(TestCancellation); using (KubeApiClient client = CreateTestClient()) { WebSocket clientSocket = await client.PodsV1().ExecAndConnectRaw( podName: "pod1", command: "/bin/bash", stdin: true, stdout: true, stderr: true ); Assert.Equal(K8sChannelProtocol.V1, clientSocket.SubProtocol); // For WebSockets, the Kubernetes API defaults to the binary channel (v1) protocol. using (clientSocket) { Log.LogInformation("Waiting for server-side WebSocket."); WebSocket serverSocket = await WebSocketTestAdapter.AcceptedPodExecV1Connection; int bytesSent = await SendMultiplexed(serverSocket, K8sChannel.StdOut, expectedOutput); Log.LogInformation("Sent {ByteCount} bytes to server socket; receiving from client socket...", bytesSent); (string receivedText, byte streamIndex, int bytesReceived) = await ReceiveTextMultiplexed(clientSocket); Log.LogInformation("Received {ByteCount} bytes from client socket ('{ReceivedText}', stream {StreamIndex}).", bytesReceived, receivedText, streamIndex); Assert.Equal(K8sChannel.StdOut, streamIndex); Assert.Equal(expectedOutput, receivedText); await Disconnect(clientSocket, serverSocket); WebSocketTestAdapter.Done(); } } } /// <summary> /// Verify that the client can request execution of a command in a pod's default container, multiplexed, with all streams enabled. /// </summary> [Fact(DisplayName = "Can exec in pod's default container, multiplexed, all streams")] public async Task Exec_DefaultContainer_Multiplexed_AllStreams() { const string expectedPrompt = "/root # "; const string expectedCommand = "ls -l /root"; TestTimeout( TimeSpan.FromSeconds(5) ); await Host.StartAsync(TestCancellation); using (KubeApiClient client = CreateTestClient()) { K8sMultiplexer multiplexer = await client.PodsV1().ExecAndConnect( podName: "pod1", command: "/bin/bash", stdin: true, stdout: true, stderr: true ); using (multiplexer) { Stream stdin = multiplexer.GetStdIn(); Stream stdout = multiplexer.GetStdOut(); Log.LogInformation("Waiting for server-side WebSocket."); WebSocket serverSocket = await WebSocketTestAdapter.AcceptedPodExecV1Connection; Log.LogInformation("Server sends prompt."); await SendMultiplexed(serverSocket, K8sChannel.StdOut, expectedPrompt); Log.LogInformation("Server sent prompt."); Log.LogInformation("Client expects prompt."); byte[] receiveBuffer = new byte[2048]; int bytesReceived = await stdout.ReadAsync(receiveBuffer, 0, receiveBuffer.Length, TestCancellation); string prompt = Encoding.ASCII.GetString(receiveBuffer, 0, bytesReceived); Assert.Equal(expectedPrompt, prompt); Log.LogInformation("Client got expected prompt."); Log.LogInformation("Client sends command."); byte[] sendBuffer = Encoding.ASCII.GetBytes(expectedCommand); await stdin.WriteAsync(sendBuffer, 0, sendBuffer.Length, TestCancellation); Log.LogInformation("Client sent command."); Log.LogInformation("Server expects command."); (string command, byte streamIndex, int totalBytes) = await ReceiveTextMultiplexed(serverSocket); Assert.Equal(K8sChannel.StdIn, streamIndex); Assert.Equal(expectedCommand, command); Log.LogInformation("Server got expected command."); Task closeServerSocket = WaitForClose(serverSocket, socketType: "server"); Log.LogInformation("Close enough; we're done."); await multiplexer.Shutdown(TestCancellation); await closeServerSocket; WebSocketTestAdapter.Done(); } } } } }
41.537415
173
0.570586
[ "MIT" ]
AndreasBieber/dotnet-kube-client
test/KubeClient.Extensions.WebSockets.Tests/PodExecTests.cs
6,106
C#
namespace bgTeam.ProcessMessages { using bgTeam.Queues; public interface IEntityMapService { /// <summary> /// Конвертирует сообзение из очереди в объект EntityMap. /// </summary> /// <param name="message">Сообщение из очереди.</param> /// <returns></returns> EntityMap CreateEntityMap(IQueueMessage message); } }
26.266667
66
0.598985
[ "MIT" ]
101stounarm101/bgTeam.Core
src/bgTeam.Core.Esb/ProcessMessages/IEntityMapService.cs
451
C#
using System.Collections.Generic; using UnityEngine; namespace FairyGUI { /// <summary> /// /// </summary> class MaterialPool { List<NMaterial> _items; List<NMaterial> _blendItems; MaterialManager _manager; string[] _variants; public MaterialPool(MaterialManager manager, string[] variants) { _manager = manager; _variants = variants; } public NMaterial Get() { List<NMaterial> items; if (_manager.blendMode == BlendMode.Normal) { if (_items == null) _items = new List<NMaterial>(); items = _items; } else { if (_blendItems == null) _blendItems = new List<NMaterial>(); items = _blendItems; } int cnt = items.Count; NMaterial result = null; for (int i = 0; i < cnt; i++) { NMaterial mat = items[i]; if (mat.frameId == _manager.frameId) { if (mat.clipId == _manager.clipId && mat.blendMode == _manager.blendMode) return mat; } else if (result == null) result = mat; } if (result != null) { result.frameId = _manager.frameId; result.clipId = _manager.clipId; result.blendMode = _manager.blendMode; } else { result = _manager.CreateMaterial(); if (_variants != null) { foreach (string v in _variants) result.EnableKeyword(v); } result.frameId = _manager.frameId; result.clipId = _manager.clipId; result.blendMode = _manager.blendMode; items.Add(result); } return result; } public void Clear() { if (_items != null) _items.Clear(); if (_blendItems != null) _blendItems.Clear(); } public void Dispose() { if (_items != null) { if (Application.isPlaying) { foreach (NMaterial mat in _items) Material.Destroy(mat); } else { foreach (NMaterial mat in _items) Material.DestroyImmediate(mat); } _items = null; } if (_blendItems != null) { if (Application.isPlaying) { foreach (NMaterial mat in _blendItems) Material.Destroy(mat); } else { foreach (NMaterial mat in _blendItems) Material.DestroyImmediate(mat); } _blendItems = null; } } } }
18.428571
78
0.603739
[ "MIT" ]
amyvmiwei/Fishing
Client/Assets/FairyGUI/Scripts/Core/MaterialPool.cs
2,195
C#
#region Using directives using System; using System.Reflection; using System.Runtime.InteropServices; #endregion // 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("SharpLua.Web.TestPages")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpLua.Web.TestPages")] [assembly: AssemblyCopyright("Copyright 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // This sets the default COM visibility of types in the assembly to invisible. // If you need to expose a type to COM, use [ComVisible(true)] on that type. [assembly: ComVisible(false)] // 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("1.0.*")]
33.375
78
0.7603
[ "MIT" ]
Stevie-O/SharpLua
OLD.SharpLua/SharpLua.Web.TestPages/AssemblyInfo.cs
1,070
C#
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated> using System; using System.Collections.Generic; #nullable disable namespace T0001 { public partial class Inassit { public Inassit() { InassitD = new HashSet<InassitD>(); } public string Ccreateownercode { get; set; } public DateTime? Dcreatetime { get; set; } public string Cticketcode { get; set; } public string Cstatus { get; set; } public string Casnid { get; set; } public string Cmemo { get; set; } public string Cdefine1 { get; set; } public string Cdefine2 { get; set; } public DateTime? Cdefine3 { get; set; } public DateTime? Cdefine4 { get; set; } public decimal? Cdefine5 { get; set; } public string Id { get; set; } public decimal? CriticalPart { get; set; } public virtual ICollection<InassitD> InassitD { get; set; } } }
32.09375
97
0.587147
[ "MIT" ]
twoutlook/BlazorServerDbContextExample
BlazorServerEFCoreSample/T0001/Inassit.cs
1,029
C#
using System.Web.Mvc; using Kendo.Mvc.Examples.Models; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using System.Linq; namespace Kendo.Mvc.Examples.Controllers { public partial class GridController : Controller { public ActionResult EditingCustomValidation() { return View(); } public ActionResult EditingCustomValidation_Read([DataSourceRequest] DataSourceRequest request) { return Json(SessionProductRepository.All() .Select(p => new CustomValidationProductViewModel { ProductID = p.ProductID, ProductName = p.ProductName, UnitPrice = p.UnitPrice }).ToDataSourceResult(request) ); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult EditingCustomValidation_Update([DataSourceRequest] DataSourceRequest request, CustomValidationProductViewModel product) { if (product != null && ModelState.IsValid) { var target = SessionProductRepository.One(p => p.ProductID == product.ProductID); if (target != null) { target.ProductName = product.ProductName; target.UnitPrice = product.UnitPrice; SessionProductRepository.Update(target); } } return Json(ModelState.ToDataSourceResult()); } } }
34.2
147
0.568551
[ "MIT" ]
asajin/sf_accounting_001
kendoui/wrappers/aspnetmvc/Examples/Controllers/Web/Grid/EditingCustomValidationController.cs
1,541
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BAFactory.Moira.Core { public abstract class ExecutionResult { public bool Done { get; set; } public bool Undone { get; set; } public String ResultText { get; set; } } }
21.2
47
0.632075
[ "Apache-2.0" ]
carlos-takeapps/moira
Core/Elements/ExecutionResult.cs
320
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.Recruiting { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Former_WorkerObjectIDType : INotifyPropertyChanged { private string typeField; private string valueField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string type { get { return this.typeField; } set { this.typeField = value; this.RaisePropertyChanged("type"); } } [XmlText] public string Value { get { return this.valueField; } set { this.valueField = value; this.RaisePropertyChanged("Value"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
20.622951
136
0.72655
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.Recruiting/Former_WorkerObjectIDType.cs
1,258
C#
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using NuGet.Common; namespace NuGet.Commands { [Command(typeof(NuGetCommand), "list", "ListCommandDescription", UsageSummaryResourceName = "ListCommandUsageSummary", UsageDescriptionResourceName = "ListCommandUsageDescription", UsageExampleResourceName = "ListCommandUsageExamples")] public class ListCommand : Command { private readonly List<string> _sources = new List<string>(); [Option(typeof(NuGetCommand), "ListCommandSourceDescription")] public ICollection<string> Source { get { return _sources; } } [Option(typeof(NuGetCommand), "ListCommandVerboseListDescription")] public bool Verbose { get; set; } [Option(typeof(NuGetCommand), "ListCommandAllVersionsDescription")] public bool AllVersions { get; set; } [Option(typeof(NuGetCommand), "ListCommandPrerelease")] public bool Prerelease { get; set; } public IPackageRepositoryFactory RepositoryFactory { get; private set; } public IPackageSourceProvider SourceProvider { get; private set; } [ImportingConstructor] public ListCommand(IPackageRepositoryFactory packageRepositoryFactory, IPackageSourceProvider sourceProvider) { if (packageRepositoryFactory == null) { throw new ArgumentNullException("packageRepositoryFactory"); } if (sourceProvider == null) { throw new ArgumentNullException("sourceProvider"); } RepositoryFactory = packageRepositoryFactory; SourceProvider = sourceProvider; } [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This call is expensive")] public IEnumerable<IPackage> GetPackages() { IPackageRepository packageRepository = GetRepository(); string searchTerm = Arguments != null ? Arguments.FirstOrDefault() : null; IQueryable<IPackage> packages = packageRepository.Search(searchTerm, Prerelease); if (AllVersions) { return packages.OrderBy(p => p.Id); } else { if (Prerelease && packageRepository.SupportsPrereleasePackages) { packages = packages.Where(p => p.IsAbsoluteLatestVersion); } else { packages = packages.Where(p => p.IsLatestVersion); } } return packages.OrderBy(p => p.Id) .AsEnumerable() .Where(PackageExtensions.IsListed) .Where(p => Prerelease || p.IsReleaseVersion()) .AsCollapsed(); } private IPackageRepository GetRepository() { var repository = AggregateRepositoryHelper.CreateAggregateRepositoryFromSources(RepositoryFactory, SourceProvider, Source); repository.Logger = Console; return repository; } public override void ExecuteCommand() { if (Verbose) { Console.WriteWarning(NuGetResources.Option_VerboseDeprecated); Verbosity = Verbosity.Detailed; } IEnumerable<IPackage> packages = GetPackages(); bool hasPackages = false; if (packages != null) { if (Verbosity == Verbosity.Detailed) { /*********************************************** * Package-Name * 1.0.0.2010 * This is the package Description * * Package-Name-Two * 2.0.0.2010 * This is the second package Description ***********************************************/ foreach (var p in packages) { Console.PrintJustified(0, p.Id); Console.PrintJustified(1, p.Version.ToString()); Console.PrintJustified(1, p.Description); Console.WriteLine(); hasPackages = true; } } else { /*********************************************** * Package-Name 1.0.0.2010 * Package-Name-Two 2.0.0.2010 ***********************************************/ foreach (var p in packages) { Console.PrintJustified(0, p.GetFullName()); hasPackages = true; } } } if (!hasPackages) { Console.WriteLine(NuGetResources.ListCommandNoPackages); } } } }
37.082759
136
0.495444
[ "ECL-2.0", "Apache-2.0" ]
themotleyfool/NuGet
src/CommandLine/Commands/ListCommand.cs
5,379
C#
using MYBAR.CustomControls; using MYBAR.CustomControls.POS; using MYBAR.Helper; using MYBAR.Model; using MYBAR.Raports; using MYBAR.Services; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace MYBAR.View.POS { /// <summary> /// Interaction logic for POS.xaml /// </summary> public partial class POSView : UserControl { public FatureBase fatura; private FatureGrid SelectedGrid; public POSView(FatureBase fat) { InitializeComponent(); fatura = fat; FreeTable.IsEnabled = fatura.TavolinaDropDownEnabled; if(fatura.TavolinaDropDownEnabled==false) { SelectedGrid = MYGRIDOPEN; MYGRID.IsEnabled = false; } else { SelectedGrid = MYGRID; } MYGRID.ParentGUI = this; MYGRID.ItemsSource = fatura.FatureRows; MYGRID.LoadFirstTime(fatura.FatureRows); MYGRIDOPEN.ParentGUI = this; MYGRIDOPEN.ItemsSource = fatura.NewFatureRow; MYGRIDOPEN.Head.Visibility = Visibility.Collapsed; CalculateTotal(); } private void LoadFreeTables() { List<ComboBoxData> l = TavolinaService.getFreeTables(fatura.TavolineId); FreeTable.ItemsSource = l; FreeTable.DisplayMemberPath = "DisplayValue"; FreeTable.SelectedIndex = l.IndexOf(l.Where(x => x.DataValue == fatura.TavolineId).FirstOrDefault()); } public void LoadArtikujt(int id) { Artikujt.Children.Clear(); // var back = App.Current.Resources["shiritibackgroud"] as LinearGradientBrush; loadArikujIntoGUI(FatureService.getMenuItems(id)); } private void loadArikujIntoGUI(List<FatureRow> list) { foreach (var item in list) { Button prod = new Button(); prod.FontSize = 8; prod.Margin = new Thickness(2); prod.Height = 100; prod.Width = 120; StackPanel stack = new StackPanel(); //stack.HorizontalAlignment = HorizontalAlignment.Center; stack.VerticalAlignment = VerticalAlignment.Center; TextBlock text = new TextBlock { Text = item.Asortimenti,FontSize=15,FontWeight=FontWeights.SemiBold, TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Left, Margin=new Thickness(0,0,0,0) }; TextBlock cmim = new TextBlock { Text = ((int)item.Cmim).ToString(), Margin = new Thickness(10, 5, 0, 0), FontWeight = FontWeights.Regular, FontSize = 12, TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Right }; stack.Children.Add(text); stack.Children.Add(cmim); prod.Content = stack; prod.Background = Brushes.White; prod.Click += (s, e) => { //getIfexit var inlistitem = SelectedGrid.getProductInList(item.Productid); if (inlistitem == null) { item.SASI = 1; fatura.ReferenceFatureRows.Add(item); } else { inlistitem.SASI++; } CalculateTotal(); }; Artikujt.Children.Add(prod); } } /// <summary> /// /// get model if exist,or null rather /// </summary> private void UserControl_Loaded(object sender, RoutedEventArgs e) { //set instance to static class Dependency.POS = this; EventManager.RegisterClassHandler(typeof(TextBox), UIElement.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyHandleMouseButton), true); EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText), true); BrushConverter bc = new BrushConverter(); //var backborder = App.Current.Resources["shiritibackgroud"] as LinearGradientBrush; var back = (Brush)bc.ConvertFrom("#57bc90"); var list = FatureService.getMenuCategories(); foreach (var t in list) { Border border = new Border(); Button b = new Button(); b.Padding = new Thickness(2, 10, 2, 10); b.Content = t.Name; b.FontSize = 22; b.Margin = new Thickness(1, 1, 1, 1); b.FontWeight = FontWeights.Bold; b.FontFamily = new FontFamily("Bookman"); b.Background = back; b.Foreground = Brushes.White; b.HorizontalContentAlignment = HorizontalAlignment.Left; //tuple as Tag with two parameters ,id and name of menucategories b.Tag = Tuple.Create(t.Id, t.Name); b.Click += (s,ev) => { LoadArtikujt(t.Id); }; border.Child = b; Grupet.Children.Add(border); } if (list.Count > 0) { LoadArtikujt(list[0].Id); } LoadFreeTables(); //set one reference for all object types } public void CalculateTotal() { decimal sum = 0; sum = fatura.GetTotal(); Total.Content = sum.ToString("#,#0.00"); } private void Printo_Click(object sender, RoutedEventArgs e) { var d =new LoadingDialog(); d.ShowDialog(); } private void FreeTable_SelectionChanged(object sender, SelectionChangedEventArgs e) { var itemselected = FreeTable.SelectedItem as ComboBoxData; fatura.TaVolineOnlineId = itemselected.DataValueOnline; fatura.TavolineId = itemselected.DataValue; } private void Ruaj_Click(object sender, RoutedEventArgs e) { if (fatura.CanCloseOrSaveTable()) { fatura.Save(); CloseTable(); } else { MessageBox.Show("Duhet te shtoni te pakten nje produkt ne liste !"); } } private void CloseTable() { MainWindow m = (MainWindow)App.Current.MainWindow; m.CenterWindow.WindowUser.Content = new Tavolinat(); } private void Dil_Click(object sender, RoutedEventArgs e) { CloseTable(); } private void MbyllFature_Click(object sender, RoutedEventArgs e) { if (fatura.CanCloseOrSaveTable()) { fatura.CloseTable(); CloseTable(); } else { MessageBox.Show("Duhet te shtoni te pakten nje produkt ne liste !"); } } private void FaturePermbledhese_Click(object sender, RoutedEventArgs e) { if (fatura.GetType() == typeof(FatureEdit)) { MainWindow main = (MainWindow)App.Current.MainWindow; if (RegisterData.PM == "1") MbyllFature_Click(null, null); FatureBuilder builder = new FatureBuilder(FatureService.getFaturePreviewPermbledhese(fatura.FatureId)); Printer.PrintFlowDocumentOneCopy(builder.getFaturePermbledheseReceipment(main.UserName)); } } private void FastSearch_KeyUp(object sender, KeyEventArgs e) { string name = FastSearch.Text; Artikujt.Children.Clear(); Thread th = new Thread(() => { var list = FatureService.getMenuItemsByStartName(name); Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate () { if (name != "") loadArikujIntoGUI(list); } ); }); if (e.Key != Key.CapsLock) th.Start(); } private static void SelectivelyHandleMouseButton(object sender, MouseButtonEventArgs e) { var textbox = (sender as TextBox); if (textbox != null && !textbox.IsKeyboardFocusWithin) { if (e.OriginalSource.GetType().Name == "TextBoxView") { e.Handled = true; textbox.Focus(); } } } private static void SelectAllText(object sender, RoutedEventArgs e) { var textBox = e.OriginalSource as TextBox; if (textBox != null) textBox.SelectAll(); } } }
28.43314
243
0.528065
[ "MIT" ]
ademvelika/ADI-BAR
MyBar/MYBAR/View/POSView.xaml.cs
9,783
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.HealthcareApis.Outputs { /// <summary> /// The settings for the CORS configuration of the service instance. /// </summary> [OutputType] public sealed class FhirServiceCorsConfigurationResponse { /// <summary> /// If credentials are allowed via CORS. /// </summary> public readonly bool? AllowCredentials; /// <summary> /// The headers to be allowed via CORS. /// </summary> public readonly ImmutableArray<string> Headers; /// <summary> /// The max age to be allowed via CORS. /// </summary> public readonly int? MaxAge; /// <summary> /// The methods to be allowed via CORS. /// </summary> public readonly ImmutableArray<string> Methods; /// <summary> /// The origins to be allowed via CORS. /// </summary> public readonly ImmutableArray<string> Origins; [OutputConstructor] private FhirServiceCorsConfigurationResponse( bool? allowCredentials, ImmutableArray<string> headers, int? maxAge, ImmutableArray<string> methods, ImmutableArray<string> origins) { AllowCredentials = allowCredentials; Headers = headers; MaxAge = maxAge; Methods = methods; Origins = origins; } } }
29.1
81
0.601375
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/HealthcareApis/Outputs/FhirServiceCorsConfigurationResponse.cs
1,746
C#
using UIWidgets; namespace UIWidgetsSamples.Shops { /// <summary> /// Harbor list view. /// </summary> public class HarborListView : ListViewCustom<HarborListViewComponent,HarborOrderLine> { /// <summary> /// Sets component data with specified item. /// </summary> /// <param name="component">Component.</param> /// <param name="item">Item.</param> protected override void SetData(HarborListViewComponent component, HarborOrderLine item) { component.SetData(item); } /// <summary> /// Set highlights colors of specified component. /// </summary> /// <param name="component">Component.</param> protected override void HighlightColoring(HarborListViewComponent component) { base.HighlightColoring(component); component.Name.color = HighlightedColor; component.BuyPrice.color = HighlightedColor; component.SellPrice.color = HighlightedColor; component.AvailableBuyCount.color = HighlightedColor; component.AvailableSellCount.color = HighlightedColor; } /// <summary> /// Set select colors of specified component. /// </summary> /// <param name="component">Component.</param> protected override void SelectColoring(HarborListViewComponent component) { base.SelectColoring(component); component.Name.color = SelectedColor; component.BuyPrice.color = SelectedColor; component.SellPrice.color = SelectedColor; component.AvailableBuyCount.color = SelectedColor; component.AvailableSellCount.color = SelectedColor; } /// <summary> /// Set default colors of specified component. /// </summary> /// <param name="component">Component.</param> protected override void DefaultColoring(HarborListViewComponent component) { base.DefaultColoring(component); component.Name.color = DefaultColor; component.BuyPrice.color = DefaultColor; component.SellPrice.color = DefaultColor; component.AvailableBuyCount.color = DefaultColor; component.AvailableSellCount.color = DefaultColor; } } }
33.2
90
0.738454
[ "MIT" ]
Winward996/Chat_Socket
Assets/UIWidgets/Sample Assets/Shops/HarborShop/HarborListView.cs
1,994
C#
// Copyright (c) 2015 - 2020 Doozy Entertainment. All Rights Reserved. // This code can only be used under the standard Unity Asset Store End User License Agreement // A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms namespace Doozy.Engine.Touchy { /// <summary> /// Describes a swipe in 8 directions /// </summary> public enum Swipe { /// <summary> /// Unknown swipe direction (disabled state) /// </summary> None = 0, /// <summary> /// Swipe Up-Left (diagonal swipe) /// </summary> UpLeft = 1, /// <summary> /// Swipe Up /// </summary> Up = 2, /// <summary> /// Swipe Up-Right (diagonal swipe) /// </summary> UpRight = 3, /// <summary> /// Swipe Left /// </summary> Left = 4, /// <summary> /// Swipe Right /// </summary> Right = 5, /// <summary> /// Swipe Down-Left (diagonal swipe) /// </summary> DownLeft = 6, /// <summary> /// Swipe Down /// </summary> Down = 7, /// <summary> /// Swipe Down-Right (diagonal swipe) /// </summary> DownRight = 8 } }
23.719298
93
0.470414
[ "MIT" ]
AcidBurn9494/InterviewTask
Assets/Doozy/Engine/Touchy/Enums/Swipe.cs
1,352
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfMovieSystem { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }
21.931034
45
0.715409
[ "MIT" ]
Brevering/Databases_2017_Teamwork
MoviesSystem/WpfMovieSystem/MainWindow.xaml.cs
638
C#
namespace TourOfHeroesDTOs.UserDtos { using System; using System.Collections.Generic; using TourOfHeroesData.Models; using TourOfHeroesMapping.Mapping; using BlogDtos; using CommentDtos; public class GetUserDTO : IMapFrom<ApplicationUser> { public string Id { get; set; } public string Email { get; set; } public string FullName { get; set; } public string JobTitle { get; set; } public string ProfileImage { get; set; } public DateTime RegisteredOn { get; set; } public IEnumerable<CommentDTO> Comments { get; set; } public IEnumerable<GetPostDetailDTO> Blogs { get; set; } } }
22.966667
64
0.647315
[ "MIT" ]
goofy5752/AngularJS
TourOfHeroesWebApi/TourOfHeroesDTOs/UserDtos/GetUserDTO.cs
691
C#
// Copyright 2011 Murray Grant // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MurrayGrant.BabyGame.Components { public class FrameTimerComponent : DrawableGameComponent { private SpriteBatch _SpriteBatch; private System.Diagnostics.Stopwatch _TickStopwatch = new System.Diagnostics.Stopwatch(); private System.Diagnostics.Stopwatch _UpdateStopwatch = new System.Diagnostics.Stopwatch(); private System.Diagnostics.Stopwatch _DrawStopwatch = new System.Diagnostics.Stopwatch(); public TimeSpan LastTickTime { get; private set; } public TimeSpan LastUpdateTime { get; private set; } public TimeSpan LastDrawTime { get; private set; } private SpriteFont _DebugFont; public LoadTimers LoadTimers { get; set; } public FrameTimerComponent(Game g, SpriteBatch sb) : base(g) { this._SpriteBatch = sb; } protected override void LoadContent() { this.LoadFont(); } public void LoadFont() { // TOOD: load fonts based on screen size. if (this._DebugFont == null) this._DebugFont = this.Game.Content.Load<SpriteFont>(@"DejaVu Sans 10"); } public void OnUpdateStart() { this._UpdateStopwatch.Restart(); } public void OnUpdateComplete() { this._UpdateStopwatch.Stop(); this.LastUpdateTime = this._UpdateStopwatch.Elapsed; } public void OnTickStart() { this._TickStopwatch.Restart(); } public void OnTickComplete() { this._TickStopwatch.Stop(); this.LastTickTime = this._TickStopwatch.Elapsed; } public void OnDrawStart() { this._DrawStopwatch.Restart(); } public void OnDrawComplete() { this._DrawStopwatch.Stop(); this.LastDrawTime = this._DrawStopwatch.Elapsed; } public override void Draw(GameTime gameTime) { this._SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); var fps = (float)(1 / gameTime.ElapsedGameTime.TotalSeconds); var updateCalcPercent = this.LastUpdateTime.TotalSeconds / this.Game.TargetElapsedTime.TotalSeconds; var drawCalcPercent = this.LastDrawTime.TotalSeconds / this.Game.TargetElapsedTime.TotalSeconds; var tickCalcPercent = this.LastTickTime.TotalSeconds / this.Game.TargetElapsedTime.TotalSeconds; int babyShapes = 0; var a = this.Game.Components.OfType<AggrigateComponent>(); if (a.Any()) babyShapes = a.First().Components.Count; var s = string.Format("{0:#0.00} fps\nTime in Update(): {1:F2}ms ({2:P2})\nTime in Draw(): {3:F2}ms ({4:P2})\nTotal Tick Estimate(): {5:F2} ({6:P2})\nTotal Load Time: {7:F2}ms, Cfg Load Time: {8:F2}ms, Pkg Load Time: {9:F2}ms\nComponents: {10}, BabyShapes: {11}" , fps, this.LastUpdateTime.TotalMilliseconds, updateCalcPercent, this.LastDrawTime.TotalMilliseconds, drawCalcPercent, this.LastTickTime.TotalMilliseconds, tickCalcPercent, this.LoadTimers.TotalLoadTime.TotalMilliseconds, this.LoadTimers.ConfigLoadTime.TotalMilliseconds, this.LoadTimers.BabyPackageLoadTime.TotalMilliseconds, this.Game.Components.Count, babyShapes); this._SpriteBatch.DrawString(this._DebugFont, s, Vector2.One, Color.Red); this._SpriteBatch.End(); } } }
42.582524
404
0.639079
[ "Apache-2.0" ]
ligos/babybashxna
BabyGame/BabyGame/Components/FrameTimerComponent.cs
4,388
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: ComplexType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type ParentalControlSettings. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(DerivedTypeConverter))] public partial class ParentalControlSettings { /// <summary> /// Initializes a new instance of the <see cref="ParentalControlSettings"/> class. /// </summary> public ParentalControlSettings() { this.ODataType = "microsoft.graph.parentalControlSettings"; } /// <summary> /// Gets or sets countriesBlockedForMinors. /// Specifies the two-letter ISO country codes. Access to the application will be blocked for minors from the countries specified in this list. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "countriesBlockedForMinors", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<string> CountriesBlockedForMinors { get; set; } /// <summary> /// Gets or sets legalAgeGroupRule. /// Specifies the legal age group rule that applies to users of the app. Can be set to one of the following values: ValueDescriptionAllowDefault. Enforces the legal minimum. This means parental consent is required for minors in the European Union and Korea.RequireConsentForPrivacyServicesEnforces the user to specify date of birth to comply with COPPA rules. RequireConsentForMinorsRequires parental consent for ages below 18, regardless of country minor rules.RequireConsentForKidsRequires parental consent for ages below 14, regardless of country minor rules.BlockMinorsBlocks minors from using the app. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "legalAgeGroupRule", Required = Newtonsoft.Json.Required.Default)] public string LegalAgeGroupRule { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } /// <summary> /// Gets or sets @odata.type. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "@odata.type", Required = Newtonsoft.Json.Required.Default)] public string ODataType { get; set; } } }
49.95082
614
0.661963
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/model/ParentalControlSettings.cs
3,047
C#
namespace AnyOf.SourceGenerator { public enum OutputType { Context = 0, Console, File } }
11.636364
32
0.53125
[ "MIT" ]
StefH/AnyOf
src/AnyOfCodeGenerator/OutputType.cs
130
C#
namespace Sculptor.Infrastructure.ConsoleAbstractions { public interface ITerminal { void RenderText(string text); } }
19.857143
54
0.705036
[ "MIT" ]
JSONLewis/Sculptor
Sculptor.Infrastructure/ConsoleAbstractions/ITerminal.cs
141
C#
namespace Kentico.Kontent.Urls.Delivery.QueryParameters.Filters { /// <summary> /// Represents a filter that matches a content item if the specified content element or system attribute doesn't have the specified value. /// </summary> public sealed class NotEqualsFilter : Filter { /// <summary> /// Initializes a new instance of the <see cref="NotEqualsFilter"/> class. /// </summary> /// <param name="elementOrAttributePath">The codename of a content element or system attribute, for example <c>elements.title</c> or <c>system.name</c>.</param> /// <param name="value">The filter value.</param> public NotEqualsFilter(string elementOrAttributePath, string value) : base(elementOrAttributePath, value) { Operator = "[neq]"; } } }
43.736842
168
0.655836
[ "MIT" ]
Kentico/delivery-sdk-net
Kentico.Kontent.Urls/Delivery/QueryParameters/Filters/NotEqualsFilter.cs
833
C#
using OpenRasta.Web; using Ramone.Tests.Common; namespace Ramone.Tests.Server.Handlers { public class ApplicationErrorHandler { public object Get(int code) { return new OperationResult.BadRequest { ResponseResource = new ApplicationError { Message = "Error X", Code = code } }; } } }
19.2
48
0.570313
[ "MIT" ]
ArvoX/Ramone
Ramone.Tests.Server/Handlers/ApplicationErrorHandler.cs
386
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Windows.Input; using Xamarin.Forms; namespace XFCustomControls.Ext { public class Picker : Xamarin.Forms.Picker { private IEnumerable<object> _objectItems; public static readonly new BindableProperty ItemsSourceProperty = BindableProperty.Create(nameof(ItemsSource), typeof(object), typeof(Picker), null, propertyChanged: (bo, o, n) => ((Picker)bo).OnItemsSourcePropertyChanged()); public new object ItemsSource { get { return GetValue(ItemsSourceProperty); } set { SetValue(ItemsSourceProperty, value); } } public static readonly new BindableProperty SelectedItemProperty = BindableProperty.Create(nameof(SelectedItem), typeof(object), typeof(Picker), null, defaultBindingMode: BindingMode.TwoWay, propertyChanged: (bo, o, n) => ((Picker)bo).OnSelectedItemPropertyChanged()); public new object SelectedItem { get { return GetValue(SelectedItemProperty); } set { SetValue(SelectedItemProperty, value); } } public static readonly BindableProperty SelectedItemChangedCommandProperty = BindableProperty.Create(nameof(SelectedItemChangedCommand), typeof(ICommand), typeof(Picker), null, propertyChanged: (bo, o, n) => ((Picker)bo).OnCommandChanged()); public ICommand SelectedItemChangedCommand { get { return (ICommand)GetValue(SelectedItemChangedCommandProperty); } set { SetValue(SelectedItemChangedCommandProperty, value); } } public Picker() { this.SelectedIndexChanged += (sender, e) => this.SelectedItem = this._objectItems.ElementAt(this.SelectedIndex); } private void OnItemsSourcePropertyChanged() { this._objectItems = this.CastObjectToList(); this.PopulatedByIEnumerableItems(this._objectItems); if (this.ItemsSource is INotifyCollectionChanged notifyCollection) this.AssignNotifyCollectionItems(notifyCollection); } private IEnumerable<object> CastObjectToList() { if (this.ItemsSource is Enum) { var items = new List<object>(); foreach (var item in Enum.GetValues(this.ItemsSource.GetType())) items.Add(item); return items; } else if (this.ItemsSource is IEnumerable) return ItemsSource as IEnumerable<object>; return null; } private void OnSelectedItemPropertyChanged() { if (this.ItemsSource == null) return; this.SelectedIndex = this.IndexOf(this.SelectedItem); if (this.SelectedItemChangedCommand != null && this.SelectedItemChangedCommand.CanExecute(this.SelectedItem)) this.SelectedItemChangedCommand.Execute(this.SelectedItem); } private int IndexOf(object value) { var comparer = EqualityComparer<object>.Default; var found = this._objectItems .Select((a, i) => new { a, i }) .FirstOrDefault(x => comparer.Equals(x.a, value)); return found == null ? -1 : found.i; } private void AssignNotifyCollectionItems(INotifyCollectionChanged items) { items.CollectionChanged += (sender, args) => { switch (args.Action) { case NotifyCollectionChangedAction.Add: foreach (var item in args.NewItems) this.AddItem(item); break; case NotifyCollectionChangedAction.Remove: foreach (var item in args.OldItems) this.RemoveItem(item); break; case NotifyCollectionChangedAction.Reset: this.PopulatedByIEnumerableItems(this._objectItems); break; //TODO case NotifyCollectionChangedAction.Move: break; //TODO case NotifyCollectionChangedAction.Replace: break; } }; } private void PopulatedByIEnumerableItems(IEnumerable<object> items) { this.Items.Clear(); foreach (var item in items) this.AddItem(item); } private void AddItem(object item) { if (item != null) this.Items.Add(item.ToString()); } private void RemoveItem(object item) { if (item != null) this.Items.Remove(item.ToString()); } private void OnCommandChanged() { if (SelectedItemChangedCommand != null) { SelectedItemChangedCommand.CanExecuteChanged += CommandCanExecuteChanged; CommandCanExecuteChanged(this, EventArgs.Empty); } else IsEnabled = true; } private void CommandCanExecuteChanged(object sender, EventArgs eventArgs) { ICommand cmd = SelectedItemChangedCommand; if (cmd != null) IsEnabled = cmd.CanExecute(this.SelectedItem); } } }
37.072727
124
0.527056
[ "MIT" ]
AlexeySidorov/XFCustomControls
XFCustomControls.Ext/Picker.cs
6,119
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using BTCPayServer.Payments.Lightning.CLightning; using NBitcoin; namespace BTCPayServer.Tests { public class LightningDTester { ServerTester parent; public LightningDTester(ServerTester parent, string environmentName, string defaultRPC, string defaultHost, Network network) { this.parent = parent; RPC = new CLightningRPCClient(new Uri(parent.GetEnvironment(environmentName, defaultRPC)), network); } public CLightningRPCClient RPC { get; } public string P2PHost { get; } } }
27.916667
132
0.698507
[ "MIT" ]
buypolarbear/btcpayserver
BTCPayServer.Tests/LightningDTester.cs
672
C#
using System; using System.CodeDom.Compiler; using System.Dynamic; using System.Collections.Generic; using TobascoTest.TestEnums; namespace TobascoTest.GeneratedEntity { [GeneratedCode("Tobasco", "1.0.0.0")] [Serializable] public partial class CPK12 : DifferentBase { private string _training; public string Training { get { return _training; } set { SetField(ref _training, value, nameof(Training)); } } private string _duur; public string Duur { get { return _duur; } set { SetField(ref _duur, value, nameof(Duur)); } } private string _kosten; public string Kosten { get { return _kosten; } set { SetField(ref _kosten, value, nameof(Kosten)); } } public override ExpandoObject ToAnonymous() { dynamic anymonous = base.ToAnonymous(); anymonous.Training = Training; anymonous.Duur = Duur; anymonous.Kosten = Kosten; return anymonous; } public override IEnumerable<EntityBase> GetChildren() { foreach (var item in base.GetChildren()) { yield return item; } } } }
20.795918
58
0.71737
[ "Apache-2.0" ]
VictordeBaare/Tobasco
TobascoTest/GeneratedEntity/CPK12_Generated.cs
1,021
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using DocumentFormat.OpenXml.Packaging; using Ap = DocumentFormat.OpenXml.ExtendedProperties; using Vt = DocumentFormat.OpenXml.VariantTypes; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Spreadsheet; using S = DocumentFormat.OpenXml.Spreadsheet; using X15ac = DocumentFormat.OpenXml.Office2013.ExcelAc; using X14 = DocumentFormat.OpenXml.Office2010.Excel; using X15 = DocumentFormat.OpenXml.Office2013.Excel; using Xdr = DocumentFormat.OpenXml.Drawing.Spreadsheet; using A = DocumentFormat.OpenXml.Drawing; using Sle = DocumentFormat.OpenXml.Office2010.Drawing.Slicer; using Thm15 = DocumentFormat.OpenXml.Office2013.Theme; namespace DocumentFormat.OpenXml.Tests.SlicerClass { public class GeneratedDocument { // Creates a SpreadsheetDocument. public void CreatePackage(string filePath) { using(SpreadsheetDocument package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook)) { CreateParts(package); } } // Adds child parts and generates content of the specified part. private void CreateParts(SpreadsheetDocument document) { ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); WorkbookPart workbookPart1 = document.AddWorkbookPart(); GenerateWorkbookPart1Content(workbookPart1); SlicerCachePart slicerCachePart1 = workbookPart1.AddNewPart<SlicerCachePart>("rId3"); GenerateSlicerCachePart1Content(slicerCachePart1); SharedStringTablePart sharedStringTablePart1 = workbookPart1.AddNewPart<SharedStringTablePart>("rId7"); GenerateSharedStringTablePart1Content(sharedStringTablePart1); SlicerCachePart slicerCachePart2 = workbookPart1.AddNewPart<SlicerCachePart>("rId2"); GenerateSlicerCachePart2Content(slicerCachePart2); WorksheetPart worksheetPart1 = workbookPart1.AddNewPart<WorksheetPart>("rId1"); GenerateWorksheetPart1Content(worksheetPart1); TableDefinitionPart tableDefinitionPart1 = worksheetPart1.AddNewPart<TableDefinitionPart>("rId3"); GenerateTableDefinitionPart1Content(tableDefinitionPart1); TableDefinitionPart tableDefinitionPart2 = worksheetPart1.AddNewPart<TableDefinitionPart>("rId2"); GenerateTableDefinitionPart2Content(tableDefinitionPart2); DrawingsPart drawingsPart1 = worksheetPart1.AddNewPart<DrawingsPart>("rId1"); GenerateDrawingsPart1Content(drawingsPart1); SlicersPart slicersPart1 = worksheetPart1.AddNewPart<SlicersPart>("rId4"); GenerateSlicersPart1Content(slicersPart1); WorkbookStylesPart workbookStylesPart1 = workbookPart1.AddNewPart<WorkbookStylesPart>("rId6"); GenerateWorkbookStylesPart1Content(workbookStylesPart1); ThemePart themePart1 = workbookPart1.AddNewPart<ThemePart>("rId5"); GenerateThemePart1Content(themePart1); SlicerCachePart slicerCachePart3 = workbookPart1.AddNewPart<SlicerCachePart>("rId4"); GenerateSlicerCachePart3Content(slicerCachePart3); SetPackageProperties(document); } // Generates content of extendedFilePropertiesPart1. private void GenerateExtendedFilePropertiesPart1Content(ExtendedFilePropertiesPart extendedFilePropertiesPart1) { Ap.Properties properties1 = new Ap.Properties(); properties1.AddNamespaceDeclaration("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); Ap.Application application1 = new Ap.Application(); application1.Text = "Microsoft Excel"; Ap.DocumentSecurity documentSecurity1 = new Ap.DocumentSecurity(); documentSecurity1.Text = "0"; Ap.ScaleCrop scaleCrop1 = new Ap.ScaleCrop(); scaleCrop1.Text = "false"; Ap.HeadingPairs headingPairs1 = new Ap.HeadingPairs(); Vt.VTVector vTVector1 = new Vt.VTVector(){ BaseType = Vt.VectorBaseValues.Variant, Size = (UInt32Value)2U }; Vt.Variant variant1 = new Vt.Variant(); Vt.VTLPSTR vTLPSTR1 = new Vt.VTLPSTR(); vTLPSTR1.Text = "Worksheets"; variant1.Append(vTLPSTR1); Vt.Variant variant2 = new Vt.Variant(); Vt.VTInt32 vTInt321 = new Vt.VTInt32(); vTInt321.Text = "1"; variant2.Append(vTInt321); vTVector1.Append(variant1); vTVector1.Append(variant2); headingPairs1.Append(vTVector1); Ap.TitlesOfParts titlesOfParts1 = new Ap.TitlesOfParts(); Vt.VTVector vTVector2 = new Vt.VTVector(){ BaseType = Vt.VectorBaseValues.Lpstr, Size = (UInt32Value)1U }; Vt.VTLPSTR vTLPSTR2 = new Vt.VTLPSTR(); vTLPSTR2.Text = "Sheet1"; vTVector2.Append(vTLPSTR2); titlesOfParts1.Append(vTVector2); Ap.LinksUpToDate linksUpToDate1 = new Ap.LinksUpToDate(); linksUpToDate1.Text = "false"; Ap.SharedDocument sharedDocument1 = new Ap.SharedDocument(); sharedDocument1.Text = "false"; Ap.HyperlinksChanged hyperlinksChanged1 = new Ap.HyperlinksChanged(); hyperlinksChanged1.Text = "false"; Ap.ApplicationVersion applicationVersion1 = new Ap.ApplicationVersion(); applicationVersion1.Text = "15.0300"; properties1.Append(application1); properties1.Append(documentSecurity1); properties1.Append(scaleCrop1); properties1.Append(headingPairs1); properties1.Append(titlesOfParts1); properties1.Append(linksUpToDate1); properties1.Append(sharedDocument1); properties1.Append(hyperlinksChanged1); properties1.Append(applicationVersion1); extendedFilePropertiesPart1.Properties = properties1; } // Generates content of workbookPart1. private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1) { Workbook workbook1 = new Workbook(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x15" } }; workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); workbook1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); workbook1.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); FileVersion fileVersion1 = new FileVersion(){ ApplicationName = "xl", LastEdited = "6", LowestEdited = "6", BuildVersion = "14420" }; WorkbookProperties workbookProperties1 = new WorkbookProperties(){ DefaultThemeVersion = (UInt32Value)153222U }; AlternateContent alternateContent1 = new AlternateContent(); alternateContent1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); AlternateContentChoice alternateContentChoice1 = new AlternateContentChoice(){ Requires = "x15" }; X15ac.AbsolutePath absolutePath1 = new X15ac.AbsolutePath(){ Url = "D:\\Users\\dito\\Desktop\\TestDocumentResaver\\OpenXmlApiConversion\\Slicer\\" }; absolutePath1.AddNamespaceDeclaration("x15ac", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac"); alternateContentChoice1.Append(absolutePath1); alternateContent1.Append(alternateContentChoice1); BookViews bookViews1 = new BookViews(); WorkbookView workbookView1 = new WorkbookView(){ XWindow = 0, YWindow = 0, WindowWidth = (UInt32Value)26940U, WindowHeight = (UInt32Value)15120U }; bookViews1.Append(workbookView1); Sheets sheets1 = new Sheets(); Sheet sheet1 = new Sheet(){ Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1" }; sheets1.Append(sheet1); DefinedNames definedNames1 = new DefinedNames(); DefinedName definedName1 = new DefinedName(){ Name = "Slicer_Column1" }; definedName1.Text = "#N/A"; DefinedName definedName2 = new DefinedName(){ Name = "Slicer_Column2" }; definedName2.Text = "#N/A"; DefinedName definedName3 = new DefinedName(){ Name = "Slicer_Column3" }; definedName3.Text = "#N/A"; definedNames1.Append(definedName1); definedNames1.Append(definedName2); definedNames1.Append(definedName3); CalculationProperties calculationProperties1 = new CalculationProperties(){ CalculationId = (UInt32Value)152511U }; WorkbookExtensionList workbookExtensionList1 = new WorkbookExtensionList(); WorkbookExtension workbookExtension1 = new WorkbookExtension(){ Uri = "{79F54976-1DA5-4618-B147-4CDE4B953A38}" }; workbookExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); X14.WorkbookProperties workbookProperties2 = new X14.WorkbookProperties(); workbookExtension1.Append(workbookProperties2); WorkbookExtension workbookExtension2 = new WorkbookExtension(){ Uri = "{46BE6895-7355-4a93-B00E-2C351335B9C9}" }; workbookExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); X15.SlicerCaches slicerCaches1 = new X15.SlicerCaches(); slicerCaches1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); X14.SlicerCache slicerCache1 = new X14.SlicerCache(){ Id = "rId2" }; X14.SlicerCache slicerCache2 = new X14.SlicerCache(){ Id = "rId3" }; X14.SlicerCache slicerCache3 = new X14.SlicerCache(){ Id = "rId4" }; slicerCaches1.Append(slicerCache1); slicerCaches1.Append(slicerCache2); slicerCaches1.Append(slicerCache3); workbookExtension2.Append(slicerCaches1); WorkbookExtension workbookExtension3 = new WorkbookExtension(){ Uri = "{140A7094-0E35-4892-8432-C4D2E57EDEB5}" }; workbookExtension3.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); X15.WorkbookProperties workbookProperties3 = new X15.WorkbookProperties(){ ChartTrackingReferenceBase = true }; workbookExtension3.Append(workbookProperties3); workbookExtensionList1.Append(workbookExtension1); workbookExtensionList1.Append(workbookExtension2); workbookExtensionList1.Append(workbookExtension3); workbook1.Append(fileVersion1); workbook1.Append(workbookProperties1); workbook1.Append(alternateContent1); workbook1.Append(bookViews1); workbook1.Append(sheets1); workbook1.Append(definedNames1); workbook1.Append(calculationProperties1); workbook1.Append(workbookExtensionList1); workbookPart1.Workbook = workbook1; } // Generates content of slicerCachePart1. private void GenerateSlicerCachePart1Content(SlicerCachePart slicerCachePart1) { X14.SlicerCacheDefinition slicerCacheDefinition1 = new X14.SlicerCacheDefinition(){ Name = "Slicer_Column2", SourceName = "Column2", MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x" } }; slicerCacheDefinition1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); slicerCacheDefinition1.AddNamespaceDeclaration("x", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); X14.SlicerCacheDefinitionExtensionList slicerCacheDefinitionExtensionList1 = new X14.SlicerCacheDefinitionExtensionList(); SlicerCacheDefinitionExtension slicerCacheDefinitionExtension1 = new SlicerCacheDefinitionExtension(){ Uri = "{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}" }; slicerCacheDefinitionExtension1.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); X15.TableSlicerCache tableSlicerCache1 = new X15.TableSlicerCache(){ TableId = (UInt32Value)1U, Column = (UInt32Value)2U }; slicerCacheDefinitionExtension1.Append(tableSlicerCache1); slicerCacheDefinitionExtensionList1.Append(slicerCacheDefinitionExtension1); slicerCacheDefinition1.Append(slicerCacheDefinitionExtensionList1); slicerCachePart1.SlicerCacheDefinition = slicerCacheDefinition1; } // Generates content of sharedStringTablePart1. private void GenerateSharedStringTablePart1Content(SharedStringTablePart sharedStringTablePart1) { SharedStringTable sharedStringTable1 = new SharedStringTable(){ Count = (UInt32Value)18U, UniqueCount = (UInt32Value)15U }; SharedStringItem sharedStringItem1 = new SharedStringItem(); Text text1 = new Text(); text1.Text = "TEST_A_1"; PhoneticProperties phoneticProperties1 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem1.Append(text1); sharedStringItem1.Append(phoneticProperties1); SharedStringItem sharedStringItem2 = new SharedStringItem(); Text text2 = new Text(); text2.Text = "TEST_A_2"; PhoneticProperties phoneticProperties2 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem2.Append(text2); sharedStringItem2.Append(phoneticProperties2); SharedStringItem sharedStringItem3 = new SharedStringItem(); Text text3 = new Text(); text3.Text = "A"; PhoneticProperties phoneticProperties3 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem3.Append(text3); sharedStringItem3.Append(phoneticProperties3); SharedStringItem sharedStringItem4 = new SharedStringItem(); Text text4 = new Text(); text4.Text = "B"; PhoneticProperties phoneticProperties4 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem4.Append(text4); sharedStringItem4.Append(phoneticProperties4); SharedStringItem sharedStringItem5 = new SharedStringItem(); Text text5 = new Text(); text5.Text = "TEST_B_1"; PhoneticProperties phoneticProperties5 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem5.Append(text5); sharedStringItem5.Append(phoneticProperties5); SharedStringItem sharedStringItem6 = new SharedStringItem(); Text text6 = new Text(); text6.Text = "TEST_B_2"; PhoneticProperties phoneticProperties6 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem6.Append(text6); sharedStringItem6.Append(phoneticProperties6); SharedStringItem sharedStringItem7 = new SharedStringItem(); Text text7 = new Text(); text7.Text = "TETS_A_3"; PhoneticProperties phoneticProperties7 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem7.Append(text7); sharedStringItem7.Append(phoneticProperties7); SharedStringItem sharedStringItem8 = new SharedStringItem(); Text text8 = new Text(); text8.Text = "C"; PhoneticProperties phoneticProperties8 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem8.Append(text8); sharedStringItem8.Append(phoneticProperties8); SharedStringItem sharedStringItem9 = new SharedStringItem(); Text text9 = new Text(); text9.Text = "TEST_B_3"; PhoneticProperties phoneticProperties9 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem9.Append(text9); sharedStringItem9.Append(phoneticProperties9); SharedStringItem sharedStringItem10 = new SharedStringItem(); Text text10 = new Text(); text10.Text = "D"; PhoneticProperties phoneticProperties10 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem10.Append(text10); sharedStringItem10.Append(phoneticProperties10); SharedStringItem sharedStringItem11 = new SharedStringItem(); Text text11 = new Text(); text11.Text = "E"; PhoneticProperties phoneticProperties11 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem11.Append(text11); sharedStringItem11.Append(phoneticProperties11); SharedStringItem sharedStringItem12 = new SharedStringItem(); Text text12 = new Text(); text12.Text = "F"; PhoneticProperties phoneticProperties12 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; sharedStringItem12.Append(text12); sharedStringItem12.Append(phoneticProperties12); SharedStringItem sharedStringItem13 = new SharedStringItem(); Text text13 = new Text(); text13.Text = "Column1"; sharedStringItem13.Append(text13); SharedStringItem sharedStringItem14 = new SharedStringItem(); Text text14 = new Text(); text14.Text = "Column2"; sharedStringItem14.Append(text14); SharedStringItem sharedStringItem15 = new SharedStringItem(); Text text15 = new Text(); text15.Text = "Column3"; sharedStringItem15.Append(text15); sharedStringTable1.Append(sharedStringItem1); sharedStringTable1.Append(sharedStringItem2); sharedStringTable1.Append(sharedStringItem3); sharedStringTable1.Append(sharedStringItem4); sharedStringTable1.Append(sharedStringItem5); sharedStringTable1.Append(sharedStringItem6); sharedStringTable1.Append(sharedStringItem7); sharedStringTable1.Append(sharedStringItem8); sharedStringTable1.Append(sharedStringItem9); sharedStringTable1.Append(sharedStringItem10); sharedStringTable1.Append(sharedStringItem11); sharedStringTable1.Append(sharedStringItem12); sharedStringTable1.Append(sharedStringItem13); sharedStringTable1.Append(sharedStringItem14); sharedStringTable1.Append(sharedStringItem15); sharedStringTablePart1.SharedStringTable = sharedStringTable1; } // Generates content of slicerCachePart2. private void GenerateSlicerCachePart2Content(SlicerCachePart slicerCachePart2) { X14.SlicerCacheDefinition slicerCacheDefinition2 = new X14.SlicerCacheDefinition(){ Name = "Slicer_Column1", SourceName = "Column1", MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x" } }; slicerCacheDefinition2.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); slicerCacheDefinition2.AddNamespaceDeclaration("x", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); X14.SlicerCacheDefinitionExtensionList slicerCacheDefinitionExtensionList2 = new X14.SlicerCacheDefinitionExtensionList(); SlicerCacheDefinitionExtension slicerCacheDefinitionExtension2 = new SlicerCacheDefinitionExtension(){ Uri = "{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}" }; slicerCacheDefinitionExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); X15.TableSlicerCache tableSlicerCache2 = new X15.TableSlicerCache(){ TableId = (UInt32Value)1U, Column = (UInt32Value)1U }; slicerCacheDefinitionExtension2.Append(tableSlicerCache2); slicerCacheDefinitionExtensionList2.Append(slicerCacheDefinitionExtension2); slicerCacheDefinition2.Append(slicerCacheDefinitionExtensionList2); slicerCachePart2.SlicerCacheDefinition = slicerCacheDefinition2; } // Generates content of worksheetPart1. private void GenerateWorksheetPart1Content(WorksheetPart worksheetPart1) { Worksheet worksheet1 = new Worksheet(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x14ac" } }; worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); worksheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); worksheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); SheetDimension sheetDimension1 = new SheetDimension(){ Reference = "A1:G4" }; SheetViews sheetViews1 = new SheetViews(); SheetView sheetView1 = new SheetView(){ TabSelected = true, WorkbookViewId = (UInt32Value)0U }; sheetViews1.Append(sheetView1); SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties(){ DefaultRowHeight = 15D }; Columns columns1 = new Columns(); Column column1 = new Column(){ Min = (UInt32Value)1U, Max = (UInt32Value)3U, Width = 10.5703125D, CustomWidth = true }; Column column2 = new Column(){ Min = (UInt32Value)5U, Max = (UInt32Value)7U, Width = 10.5703125D, CustomWidth = true }; columns1.Append(column1); columns1.Append(column2); SheetData sheetData1 = new SheetData(); Row row1 = new Row(){ RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:7" } }; Cell cell1 = new Cell(){ CellReference = "A1", DataType = CellValues.SharedString }; CellValue cellValue1 = new CellValue(); cellValue1.Text = "12"; cell1.Append(cellValue1); Cell cell2 = new Cell(){ CellReference = "B1", DataType = CellValues.SharedString }; CellValue cellValue2 = new CellValue(); cellValue2.Text = "13"; cell2.Append(cellValue2); Cell cell3 = new Cell(){ CellReference = "C1", DataType = CellValues.SharedString }; CellValue cellValue3 = new CellValue(); cellValue3.Text = "14"; cell3.Append(cellValue3); Cell cell4 = new Cell(){ CellReference = "E1", DataType = CellValues.SharedString }; CellValue cellValue4 = new CellValue(); cellValue4.Text = "12"; cell4.Append(cellValue4); Cell cell5 = new Cell(){ CellReference = "F1", DataType = CellValues.SharedString }; CellValue cellValue5 = new CellValue(); cellValue5.Text = "13"; cell5.Append(cellValue5); Cell cell6 = new Cell(){ CellReference = "G1", DataType = CellValues.SharedString }; CellValue cellValue6 = new CellValue(); cellValue6.Text = "14"; cell6.Append(cellValue6); row1.Append(cell1); row1.Append(cell2); row1.Append(cell3); row1.Append(cell4); row1.Append(cell5); row1.Append(cell6); Row row2 = new Row(){ RowIndex = (UInt32Value)2U, Spans = new ListValue<StringValue>() { InnerText = "1:7" } }; Cell cell7 = new Cell(){ CellReference = "A2", DataType = CellValues.SharedString }; CellValue cellValue7 = new CellValue(); cellValue7.Text = "0"; cell7.Append(cellValue7); Cell cell8 = new Cell(){ CellReference = "B2", DataType = CellValues.SharedString }; CellValue cellValue8 = new CellValue(); cellValue8.Text = "2"; cell8.Append(cellValue8); Cell cell9 = new Cell(){ CellReference = "C2" }; CellValue cellValue9 = new CellValue(); cellValue9.Text = "1"; cell9.Append(cellValue9); Cell cell10 = new Cell(){ CellReference = "E2", DataType = CellValues.SharedString }; CellValue cellValue10 = new CellValue(); cellValue10.Text = "4"; cell10.Append(cellValue10); Cell cell11 = new Cell(){ CellReference = "F2", DataType = CellValues.SharedString }; CellValue cellValue11 = new CellValue(); cellValue11.Text = "9"; cell11.Append(cellValue11); Cell cell12 = new Cell(){ CellReference = "G2" }; CellValue cellValue12 = new CellValue(); cellValue12.Text = "3"; cell12.Append(cellValue12); row2.Append(cell7); row2.Append(cell8); row2.Append(cell9); row2.Append(cell10); row2.Append(cell11); row2.Append(cell12); Row row3 = new Row(){ RowIndex = (UInt32Value)3U, Spans = new ListValue<StringValue>() { InnerText = "1:7" } }; Cell cell13 = new Cell(){ CellReference = "A3", DataType = CellValues.SharedString }; CellValue cellValue13 = new CellValue(); cellValue13.Text = "1"; cell13.Append(cellValue13); Cell cell14 = new Cell(){ CellReference = "B3", DataType = CellValues.SharedString }; CellValue cellValue14 = new CellValue(); cellValue14.Text = "3"; cell14.Append(cellValue14); Cell cell15 = new Cell(){ CellReference = "C3" }; CellValue cellValue15 = new CellValue(); cellValue15.Text = "2"; cell15.Append(cellValue15); Cell cell16 = new Cell(){ CellReference = "E3", DataType = CellValues.SharedString }; CellValue cellValue16 = new CellValue(); cellValue16.Text = "5"; cell16.Append(cellValue16); Cell cell17 = new Cell(){ CellReference = "F3", DataType = CellValues.SharedString }; CellValue cellValue17 = new CellValue(); cellValue17.Text = "10"; cell17.Append(cellValue17); Cell cell18 = new Cell(){ CellReference = "G3" }; CellValue cellValue18 = new CellValue(); cellValue18.Text = "4"; cell18.Append(cellValue18); row3.Append(cell13); row3.Append(cell14); row3.Append(cell15); row3.Append(cell16); row3.Append(cell17); row3.Append(cell18); Row row4 = new Row(){ RowIndex = (UInt32Value)4U, Spans = new ListValue<StringValue>() { InnerText = "1:7" } }; Cell cell19 = new Cell(){ CellReference = "A4", DataType = CellValues.SharedString }; CellValue cellValue19 = new CellValue(); cellValue19.Text = "6"; cell19.Append(cellValue19); Cell cell20 = new Cell(){ CellReference = "B4", DataType = CellValues.SharedString }; CellValue cellValue20 = new CellValue(); cellValue20.Text = "7"; cell20.Append(cellValue20); Cell cell21 = new Cell(){ CellReference = "C4" }; CellValue cellValue21 = new CellValue(); cellValue21.Text = "3"; cell21.Append(cellValue21); Cell cell22 = new Cell(){ CellReference = "E4", DataType = CellValues.SharedString }; CellValue cellValue22 = new CellValue(); cellValue22.Text = "8"; cell22.Append(cellValue22); Cell cell23 = new Cell(){ CellReference = "F4", DataType = CellValues.SharedString }; CellValue cellValue23 = new CellValue(); cellValue23.Text = "11"; cell23.Append(cellValue23); Cell cell24 = new Cell(){ CellReference = "G4" }; CellValue cellValue24 = new CellValue(); cellValue24.Text = "5"; cell24.Append(cellValue24); row4.Append(cell19); row4.Append(cell20); row4.Append(cell21); row4.Append(cell22); row4.Append(cell23); row4.Append(cell24); sheetData1.Append(row1); sheetData1.Append(row2); sheetData1.Append(row3); sheetData1.Append(row4); PhoneticProperties phoneticProperties13 = new PhoneticProperties(){ FontId = (UInt32Value)1U }; PageMargins pageMargins1 = new PageMargins(){ Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D }; S.Drawing drawing1 = new S.Drawing(){ Id = "rId1" }; TableParts tableParts1 = new TableParts(){ Count = (UInt32Value)2U }; TablePart tablePart1 = new TablePart(){ Id = "rId2" }; TablePart tablePart2 = new TablePart(){ Id = "rId3" }; tableParts1.Append(tablePart1); tableParts1.Append(tablePart2); WorksheetExtensionList worksheetExtensionList1 = new WorksheetExtensionList(); WorksheetExtension worksheetExtension1 = new WorksheetExtension(){ Uri = "{3A4CF648-6AED-40f4-86FF-DC5316D8AED3}" }; worksheetExtension1.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); X14.SlicerList slicerList1 = new X14.SlicerList(); slicerList1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); X14.SlicerRef slicerRef1 = new X14.SlicerRef(){ Id = "rId4" }; slicerList1.Append(slicerRef1); worksheetExtension1.Append(slicerList1); worksheetExtensionList1.Append(worksheetExtension1); worksheet1.Append(sheetDimension1); worksheet1.Append(sheetViews1); worksheet1.Append(sheetFormatProperties1); worksheet1.Append(columns1); worksheet1.Append(sheetData1); worksheet1.Append(phoneticProperties13); worksheet1.Append(pageMargins1); worksheet1.Append(drawing1); worksheet1.Append(tableParts1); worksheet1.Append(worksheetExtensionList1); worksheetPart1.Worksheet = worksheet1; } // Generates content of tableDefinitionPart1. private void GenerateTableDefinitionPart1Content(TableDefinitionPart tableDefinitionPart1) { Table table1 = new Table(){ Id = (UInt32Value)2U, Name = "Table2", DisplayName = "Table2", Reference = "E1:G4", TotalsRowShown = false }; AutoFilter autoFilter1 = new AutoFilter(){ Reference = "E1:G4" }; TableColumns tableColumns1 = new TableColumns(){ Count = (UInt32Value)3U }; TableColumn tableColumn1 = new TableColumn(){ Id = (UInt32Value)1U, Name = "Column1" }; TableColumn tableColumn2 = new TableColumn(){ Id = (UInt32Value)2U, Name = "Column2" }; TableColumn tableColumn3 = new TableColumn(){ Id = (UInt32Value)3U, Name = "Column3" }; tableColumns1.Append(tableColumn1); tableColumns1.Append(tableColumn2); tableColumns1.Append(tableColumn3); TableStyleInfo tableStyleInfo1 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table1.Append(autoFilter1); table1.Append(tableColumns1); table1.Append(tableStyleInfo1); tableDefinitionPart1.Table = table1; } // Generates content of tableDefinitionPart2. private void GenerateTableDefinitionPart2Content(TableDefinitionPart tableDefinitionPart2) { Table table2 = new Table(){ Id = (UInt32Value)1U, Name = "Table1", DisplayName = "Table1", Reference = "A1:C4", TotalsRowShown = false }; AutoFilter autoFilter2 = new AutoFilter(){ Reference = "A1:C4" }; TableColumns tableColumns2 = new TableColumns(){ Count = (UInt32Value)3U }; TableColumn tableColumn4 = new TableColumn(){ Id = (UInt32Value)1U, Name = "Column1" }; TableColumn tableColumn5 = new TableColumn(){ Id = (UInt32Value)2U, Name = "Column2" }; TableColumn tableColumn6 = new TableColumn(){ Id = (UInt32Value)3U, Name = "Column3" }; tableColumns2.Append(tableColumn4); tableColumns2.Append(tableColumn5); tableColumns2.Append(tableColumn6); TableStyleInfo tableStyleInfo2 = new TableStyleInfo(){ Name = "TableStyleMedium2", ShowFirstColumn = false, ShowLastColumn = false, ShowRowStripes = true, ShowColumnStripes = false }; table2.Append(autoFilter2); table2.Append(tableColumns2); table2.Append(tableStyleInfo2); tableDefinitionPart2.Table = table2; } // Generates content of drawingsPart1. private void GenerateDrawingsPart1Content(DrawingsPart drawingsPart1) { Xdr.WorksheetDrawing worksheetDrawing1 = new Xdr.WorksheetDrawing(); worksheetDrawing1.AddNamespaceDeclaration("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); worksheetDrawing1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); Xdr.TwoCellAnchor twoCellAnchor1 = new Xdr.TwoCellAnchor(){ EditAs = Xdr.EditAsValues.Absolute }; Xdr.FromMarker fromMarker1 = new Xdr.FromMarker(); Xdr.ColumnId columnId1 = new Xdr.ColumnId(); columnId1.Text = "0"; Xdr.ColumnOffset columnOffset1 = new Xdr.ColumnOffset(); columnOffset1.Text = "0"; Xdr.RowId rowId1 = new Xdr.RowId(); rowId1.Text = "5"; Xdr.RowOffset rowOffset1 = new Xdr.RowOffset(); rowOffset1.Text = "161925"; fromMarker1.Append(columnId1); fromMarker1.Append(columnOffset1); fromMarker1.Append(rowId1); fromMarker1.Append(rowOffset1); Xdr.ToMarker toMarker1 = new Xdr.ToMarker(); Xdr.ColumnId columnId2 = new Xdr.ColumnId(); columnId2.Text = "2"; Xdr.ColumnOffset columnOffset2 = new Xdr.ColumnOffset(); columnOffset2.Text = "209550"; Xdr.RowId rowId2 = new Xdr.RowId(); rowId2.Text = "19"; Xdr.RowOffset rowOffset2 = new Xdr.RowOffset(); rowOffset2.Text = "142875"; toMarker1.Append(columnId2); toMarker1.Append(columnOffset2); toMarker1.Append(rowId2); toMarker1.Append(rowOffset2); AlternateContent alternateContent2 = new AlternateContent(); alternateContent2.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); alternateContent2.AddNamespaceDeclaration("a15", "http://schemas.microsoft.com/office/drawing/2012/main"); AlternateContentChoice alternateContentChoice2 = new AlternateContentChoice(){ Requires = "a15" }; Xdr.GraphicFrame graphicFrame1 = new Xdr.GraphicFrame(){ Macro = "" }; Xdr.NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties1 = new Xdr.NonVisualGraphicFrameProperties(); Xdr.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Xdr.NonVisualDrawingProperties(){ Id = (UInt32Value)2U, Name = "Slicer_1" }; Xdr.NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties1 = new Xdr.NonVisualGraphicFrameDrawingProperties(); nonVisualGraphicFrameProperties1.Append(nonVisualDrawingProperties1); nonVisualGraphicFrameProperties1.Append(nonVisualGraphicFrameDrawingProperties1); Xdr.Transform transform1 = new Xdr.Transform(); A.Offset offset1 = new A.Offset(){ X = 0L, Y = 0L }; A.Extents extents1 = new A.Extents(){ Cx = 0L, Cy = 0L }; transform1.Append(offset1); transform1.Append(extents1); A.Graphic graphic1 = new A.Graphic(); A.GraphicData graphicData1 = new A.GraphicData(){ Uri = "http://schemas.microsoft.com/office/drawing/2010/slicer" }; Sle.Slicer slicer1 = new Sle.Slicer(){ Name = "Slicer_1" }; slicer1.AddNamespaceDeclaration("sle", "http://schemas.microsoft.com/office/drawing/2010/slicer"); graphicData1.Append(slicer1); graphic1.Append(graphicData1); graphicFrame1.Append(nonVisualGraphicFrameProperties1); graphicFrame1.Append(transform1); graphicFrame1.Append(graphic1); alternateContentChoice2.Append(graphicFrame1); AlternateContentFallback alternateContentFallback1 = new AlternateContentFallback(); Xdr.Shape shape1 = new Xdr.Shape(){ Macro = "", TextLink = "" }; Xdr.NonVisualShapeProperties nonVisualShapeProperties1 = new Xdr.NonVisualShapeProperties(); Xdr.NonVisualDrawingProperties nonVisualDrawingProperties2 = new Xdr.NonVisualDrawingProperties(){ Id = (UInt32Value)0U, Name = "" }; Xdr.NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties1 = new Xdr.NonVisualShapeDrawingProperties(); A.ShapeLocks shapeLocks1 = new A.ShapeLocks(){ NoTextEdit = true }; nonVisualShapeDrawingProperties1.Append(shapeLocks1); nonVisualShapeProperties1.Append(nonVisualDrawingProperties2); nonVisualShapeProperties1.Append(nonVisualShapeDrawingProperties1); Xdr.ShapeProperties shapeProperties1 = new Xdr.ShapeProperties(); A.Transform2D transform2D1 = new A.Transform2D(); A.Offset offset2 = new A.Offset(){ X = 0L, Y = 1019175L }; A.Extents extents2 = new A.Extents(){ Cx = 1828800L, Cy = 2381250L }; transform2D1.Append(offset2); transform2D1.Append(extents2); A.PresetGeometry presetGeometry1 = new A.PresetGeometry(){ Preset = A.ShapeTypeValues.Rectangle }; A.AdjustValueList adjustValueList1 = new A.AdjustValueList(); presetGeometry1.Append(adjustValueList1); A.SolidFill solidFill1 = new A.SolidFill(); A.PresetColor presetColor1 = new A.PresetColor(){ Val = A.PresetColorValues.White }; solidFill1.Append(presetColor1); A.Outline outline1 = new A.Outline(){ Width = 1 }; A.SolidFill solidFill2 = new A.SolidFill(); A.PresetColor presetColor2 = new A.PresetColor(){ Val = A.PresetColorValues.Green }; solidFill2.Append(presetColor2); outline1.Append(solidFill2); shapeProperties1.Append(transform2D1); shapeProperties1.Append(presetGeometry1); shapeProperties1.Append(solidFill1); shapeProperties1.Append(outline1); Xdr.TextBody textBody1 = new Xdr.TextBody(); A.BodyProperties bodyProperties1 = new A.BodyProperties(){ VerticalOverflow = A.TextVerticalOverflowValues.Clip, HorizontalOverflow = A.TextHorizontalOverflowValues.Clip }; A.ListStyle listStyle1 = new A.ListStyle(); A.Paragraph paragraph1 = new A.Paragraph(); A.Run run1 = new A.Run(); A.RunProperties runProperties1 = new A.RunProperties(){ Language = "ja-JP", AlternativeLanguage = "en-US", FontSize = 1100 }; A.Text text16 = new A.Text(); text16.Text = "This shape represents a table slicer. Table slicers can be used in at least Excel 15.\n\nIf the shape was modified in an earlier version of Excel, or if the workbook was saved in Excel 2010 or earlier, the slicer cannot be used."; run1.Append(runProperties1); run1.Append(text16); paragraph1.Append(run1); textBody1.Append(bodyProperties1); textBody1.Append(listStyle1); textBody1.Append(paragraph1); shape1.Append(nonVisualShapeProperties1); shape1.Append(shapeProperties1); shape1.Append(textBody1); alternateContentFallback1.Append(shape1); alternateContent2.Append(alternateContentChoice2); alternateContent2.Append(alternateContentFallback1); Xdr.ClientData clientData1 = new Xdr.ClientData(); twoCellAnchor1.Append(fromMarker1); twoCellAnchor1.Append(toMarker1); twoCellAnchor1.Append(alternateContent2); twoCellAnchor1.Append(clientData1); Xdr.TwoCellAnchor twoCellAnchor2 = new Xdr.TwoCellAnchor(){ EditAs = Xdr.EditAsValues.Absolute }; Xdr.FromMarker fromMarker2 = new Xdr.FromMarker(); Xdr.ColumnId columnId3 = new Xdr.ColumnId(); columnId3.Text = "3"; Xdr.ColumnOffset columnOffset3 = new Xdr.ColumnOffset(); columnOffset3.Text = "0"; Xdr.RowId rowId3 = new Xdr.RowId(); rowId3.Text = "6"; Xdr.RowOffset rowOffset3 = new Xdr.RowOffset(); rowOffset3.Text = "0"; fromMarker2.Append(columnId3); fromMarker2.Append(columnOffset3); fromMarker2.Append(rowId3); fromMarker2.Append(rowOffset3); Xdr.ToMarker toMarker2 = new Xdr.ToMarker(); Xdr.ColumnId columnId4 = new Xdr.ColumnId(); columnId4.Text = "5"; Xdr.ColumnOffset columnOffset4 = new Xdr.ColumnOffset(); columnOffset4.Text = "333375"; Xdr.RowId rowId4 = new Xdr.RowId(); rowId4.Text = "19"; Xdr.RowOffset rowOffset4 = new Xdr.RowOffset(); rowOffset4.Text = "152400"; toMarker2.Append(columnId4); toMarker2.Append(columnOffset4); toMarker2.Append(rowId4); toMarker2.Append(rowOffset4); AlternateContent alternateContent3 = new AlternateContent(); alternateContent3.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); alternateContent3.AddNamespaceDeclaration("a15", "http://schemas.microsoft.com/office/drawing/2012/main"); AlternateContentChoice alternateContentChoice3 = new AlternateContentChoice(){ Requires = "a15" }; Xdr.GraphicFrame graphicFrame2 = new Xdr.GraphicFrame(){ Macro = "" }; Xdr.NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties2 = new Xdr.NonVisualGraphicFrameProperties(); Xdr.NonVisualDrawingProperties nonVisualDrawingProperties3 = new Xdr.NonVisualDrawingProperties(){ Id = (UInt32Value)3U, Name = "Slicer_2" }; Xdr.NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties2 = new Xdr.NonVisualGraphicFrameDrawingProperties(); nonVisualGraphicFrameProperties2.Append(nonVisualDrawingProperties3); nonVisualGraphicFrameProperties2.Append(nonVisualGraphicFrameDrawingProperties2); Xdr.Transform transform2 = new Xdr.Transform(); A.Offset offset3 = new A.Offset(){ X = 0L, Y = 0L }; A.Extents extents3 = new A.Extents(){ Cx = 0L, Cy = 0L }; transform2.Append(offset3); transform2.Append(extents3); A.Graphic graphic2 = new A.Graphic(); A.GraphicData graphicData2 = new A.GraphicData(){ Uri = "http://schemas.microsoft.com/office/drawing/2010/slicer" }; Sle.Slicer slicer2 = new Sle.Slicer(){ Name = "Slicer_2" }; slicer2.AddNamespaceDeclaration("sle", "http://schemas.microsoft.com/office/drawing/2010/slicer"); graphicData2.Append(slicer2); graphic2.Append(graphicData2); graphicFrame2.Append(nonVisualGraphicFrameProperties2); graphicFrame2.Append(transform2); graphicFrame2.Append(graphic2); alternateContentChoice3.Append(graphicFrame2); AlternateContentFallback alternateContentFallback2 = new AlternateContentFallback(); Xdr.Shape shape2 = new Xdr.Shape(){ Macro = "", TextLink = "" }; Xdr.NonVisualShapeProperties nonVisualShapeProperties2 = new Xdr.NonVisualShapeProperties(); Xdr.NonVisualDrawingProperties nonVisualDrawingProperties4 = new Xdr.NonVisualDrawingProperties(){ Id = (UInt32Value)0U, Name = "" }; Xdr.NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties2 = new Xdr.NonVisualShapeDrawingProperties(); A.ShapeLocks shapeLocks2 = new A.ShapeLocks(){ NoTextEdit = true }; nonVisualShapeDrawingProperties2.Append(shapeLocks2); nonVisualShapeProperties2.Append(nonVisualDrawingProperties4); nonVisualShapeProperties2.Append(nonVisualShapeDrawingProperties2); Xdr.ShapeProperties shapeProperties2 = new Xdr.ShapeProperties(); A.Transform2D transform2D2 = new A.Transform2D(); A.Offset offset4 = new A.Offset(){ X = 2428875L, Y = 1028700L }; A.Extents extents4 = new A.Extents(){ Cx = 1828800L, Cy = 2381250L }; transform2D2.Append(offset4); transform2D2.Append(extents4); A.PresetGeometry presetGeometry2 = new A.PresetGeometry(){ Preset = A.ShapeTypeValues.Rectangle }; A.AdjustValueList adjustValueList2 = new A.AdjustValueList(); presetGeometry2.Append(adjustValueList2); A.SolidFill solidFill3 = new A.SolidFill(); A.PresetColor presetColor3 = new A.PresetColor(){ Val = A.PresetColorValues.White }; solidFill3.Append(presetColor3); A.Outline outline2 = new A.Outline(){ Width = 1 }; A.SolidFill solidFill4 = new A.SolidFill(); A.PresetColor presetColor4 = new A.PresetColor(){ Val = A.PresetColorValues.Green }; solidFill4.Append(presetColor4); outline2.Append(solidFill4); shapeProperties2.Append(transform2D2); shapeProperties2.Append(presetGeometry2); shapeProperties2.Append(solidFill3); shapeProperties2.Append(outline2); Xdr.TextBody textBody2 = new Xdr.TextBody(); A.BodyProperties bodyProperties2 = new A.BodyProperties(){ VerticalOverflow = A.TextVerticalOverflowValues.Clip, HorizontalOverflow = A.TextHorizontalOverflowValues.Clip }; A.ListStyle listStyle2 = new A.ListStyle(); A.Paragraph paragraph2 = new A.Paragraph(); A.Run run2 = new A.Run(); A.RunProperties runProperties2 = new A.RunProperties(){ Language = "ja-JP", AlternativeLanguage = "en-US", FontSize = 1100 }; A.Text text17 = new A.Text(); text17.Text = "This shape represents a table slicer. Table slicers can be used in at least Excel 15.\n\nIf the shape was modified in an earlier version of Excel, or if the workbook was saved in Excel 2010 or earlier, the slicer cannot be used."; run2.Append(runProperties2); run2.Append(text17); paragraph2.Append(run2); textBody2.Append(bodyProperties2); textBody2.Append(listStyle2); textBody2.Append(paragraph2); shape2.Append(nonVisualShapeProperties2); shape2.Append(shapeProperties2); shape2.Append(textBody2); alternateContentFallback2.Append(shape2); alternateContent3.Append(alternateContentChoice3); alternateContent3.Append(alternateContentFallback2); Xdr.ClientData clientData2 = new Xdr.ClientData(); twoCellAnchor2.Append(fromMarker2); twoCellAnchor2.Append(toMarker2); twoCellAnchor2.Append(alternateContent3); twoCellAnchor2.Append(clientData2); Xdr.TwoCellAnchor twoCellAnchor3 = new Xdr.TwoCellAnchor(){ EditAs = Xdr.EditAsValues.Absolute }; Xdr.FromMarker fromMarker3 = new Xdr.FromMarker(); Xdr.ColumnId columnId5 = new Xdr.ColumnId(); columnId5.Text = "6"; Xdr.ColumnOffset columnOffset5 = new Xdr.ColumnOffset(); columnOffset5.Text = "0"; Xdr.RowId rowId5 = new Xdr.RowId(); rowId5.Text = "6"; Xdr.RowOffset rowOffset5 = new Xdr.RowOffset(); rowOffset5.Text = "9525"; fromMarker3.Append(columnId5); fromMarker3.Append(columnOffset5); fromMarker3.Append(rowId5); fromMarker3.Append(rowOffset5); Xdr.ToMarker toMarker3 = new Xdr.ToMarker(); Xdr.ColumnId columnId6 = new Xdr.ColumnId(); columnId6.Text = "8"; Xdr.ColumnOffset columnOffset6 = new Xdr.ColumnOffset(); columnOffset6.Text = "333375"; Xdr.RowId rowId6 = new Xdr.RowId(); rowId6.Text = "19"; Xdr.RowOffset rowOffset6 = new Xdr.RowOffset(); rowOffset6.Text = "161925"; toMarker3.Append(columnId6); toMarker3.Append(columnOffset6); toMarker3.Append(rowId6); toMarker3.Append(rowOffset6); AlternateContent alternateContent4 = new AlternateContent(); alternateContent4.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); alternateContent4.AddNamespaceDeclaration("a15", "http://schemas.microsoft.com/office/drawing/2012/main"); AlternateContentChoice alternateContentChoice4 = new AlternateContentChoice(){ Requires = "a15" }; Xdr.GraphicFrame graphicFrame3 = new Xdr.GraphicFrame(){ Macro = "" }; Xdr.NonVisualGraphicFrameProperties nonVisualGraphicFrameProperties3 = new Xdr.NonVisualGraphicFrameProperties(); Xdr.NonVisualDrawingProperties nonVisualDrawingProperties5 = new Xdr.NonVisualDrawingProperties(){ Id = (UInt32Value)4U, Name = "Slicer_3" }; Xdr.NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties3 = new Xdr.NonVisualGraphicFrameDrawingProperties(); nonVisualGraphicFrameProperties3.Append(nonVisualDrawingProperties5); nonVisualGraphicFrameProperties3.Append(nonVisualGraphicFrameDrawingProperties3); Xdr.Transform transform3 = new Xdr.Transform(); A.Offset offset5 = new A.Offset(){ X = 0L, Y = 0L }; A.Extents extents5 = new A.Extents(){ Cx = 0L, Cy = 0L }; transform3.Append(offset5); transform3.Append(extents5); A.Graphic graphic3 = new A.Graphic(); A.GraphicData graphicData3 = new A.GraphicData(){ Uri = "http://schemas.microsoft.com/office/drawing/2010/slicer" }; Sle.Slicer slicer3 = new Sle.Slicer(){ Name = "Slicer_3" }; slicer3.AddNamespaceDeclaration("sle", "http://schemas.microsoft.com/office/drawing/2010/slicer"); graphicData3.Append(slicer3); graphic3.Append(graphicData3); graphicFrame3.Append(nonVisualGraphicFrameProperties3); graphicFrame3.Append(transform3); graphicFrame3.Append(graphic3); alternateContentChoice4.Append(graphicFrame3); AlternateContentFallback alternateContentFallback3 = new AlternateContentFallback(); Xdr.Shape shape3 = new Xdr.Shape(){ Macro = "", TextLink = "" }; Xdr.NonVisualShapeProperties nonVisualShapeProperties3 = new Xdr.NonVisualShapeProperties(); Xdr.NonVisualDrawingProperties nonVisualDrawingProperties6 = new Xdr.NonVisualDrawingProperties(){ Id = (UInt32Value)0U, Name = "" }; Xdr.NonVisualShapeDrawingProperties nonVisualShapeDrawingProperties3 = new Xdr.NonVisualShapeDrawingProperties(); A.ShapeLocks shapeLocks3 = new A.ShapeLocks(){ NoTextEdit = true }; nonVisualShapeDrawingProperties3.Append(shapeLocks3); nonVisualShapeProperties3.Append(nonVisualDrawingProperties6); nonVisualShapeProperties3.Append(nonVisualShapeDrawingProperties3); Xdr.ShapeProperties shapeProperties3 = new Xdr.ShapeProperties(); A.Transform2D transform2D3 = new A.Transform2D(); A.Offset offset6 = new A.Offset(){ X = 4733925L, Y = 1038225L }; A.Extents extents6 = new A.Extents(){ Cx = 1828800L, Cy = 2381250L }; transform2D3.Append(offset6); transform2D3.Append(extents6); A.PresetGeometry presetGeometry3 = new A.PresetGeometry(){ Preset = A.ShapeTypeValues.Rectangle }; A.AdjustValueList adjustValueList3 = new A.AdjustValueList(); presetGeometry3.Append(adjustValueList3); A.SolidFill solidFill5 = new A.SolidFill(); A.PresetColor presetColor5 = new A.PresetColor(){ Val = A.PresetColorValues.White }; solidFill5.Append(presetColor5); A.Outline outline3 = new A.Outline(){ Width = 1 }; A.SolidFill solidFill6 = new A.SolidFill(); A.PresetColor presetColor6 = new A.PresetColor(){ Val = A.PresetColorValues.Green }; solidFill6.Append(presetColor6); outline3.Append(solidFill6); shapeProperties3.Append(transform2D3); shapeProperties3.Append(presetGeometry3); shapeProperties3.Append(solidFill5); shapeProperties3.Append(outline3); Xdr.TextBody textBody3 = new Xdr.TextBody(); A.BodyProperties bodyProperties3 = new A.BodyProperties(){ VerticalOverflow = A.TextVerticalOverflowValues.Clip, HorizontalOverflow = A.TextHorizontalOverflowValues.Clip }; A.ListStyle listStyle3 = new A.ListStyle(); A.Paragraph paragraph3 = new A.Paragraph(); A.Run run3 = new A.Run(); A.RunProperties runProperties3 = new A.RunProperties(){ Language = "ja-JP", AlternativeLanguage = "en-US", FontSize = 1100 }; A.Text text18 = new A.Text(); text18.Text = "This shape represents a table slicer. Table slicers can be used in at least Excel 15.\n\nIf the shape was modified in an earlier version of Excel, or if the workbook was saved in Excel 2010 or earlier, the slicer cannot be used."; run3.Append(runProperties3); run3.Append(text18); paragraph3.Append(run3); textBody3.Append(bodyProperties3); textBody3.Append(listStyle3); textBody3.Append(paragraph3); shape3.Append(nonVisualShapeProperties3); shape3.Append(shapeProperties3); shape3.Append(textBody3); alternateContentFallback3.Append(shape3); alternateContent4.Append(alternateContentChoice4); alternateContent4.Append(alternateContentFallback3); Xdr.ClientData clientData3 = new Xdr.ClientData(); twoCellAnchor3.Append(fromMarker3); twoCellAnchor3.Append(toMarker3); twoCellAnchor3.Append(alternateContent4); twoCellAnchor3.Append(clientData3); worksheetDrawing1.Append(twoCellAnchor1); worksheetDrawing1.Append(twoCellAnchor2); worksheetDrawing1.Append(twoCellAnchor3); drawingsPart1.WorksheetDrawing = worksheetDrawing1; } // Generates content of slicersPart1. private void GenerateSlicersPart1Content(SlicersPart slicersPart1) { X14.Slicers slicers1 = new X14.Slicers(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x" } }; slicers1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); slicers1.AddNamespaceDeclaration("x", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); X14.Slicer slicer4 = new X14.Slicer(){ Name = "Slicer_1", Cache = "Slicer_Column1", Caption = "Slicer_1", RowHeight = (UInt32Value)225425U }; X14.Slicer slicer5 = new X14.Slicer(){ Name = "Slicer_2", Cache = "Slicer_Column2", Caption = "Slicer_2", RowHeight = (UInt32Value)225425U }; X14.Slicer slicer6 = new X14.Slicer(){ Name = "Slicer_3", Cache = "Slicer_Column3", Caption = "Slicer_3", RowHeight = (UInt32Value)225425U }; slicers1.Append(slicer4); slicers1.Append(slicer5); slicers1.Append(slicer6); slicersPart1.Slicers = slicers1; } // Generates content of workbookStylesPart1. private void GenerateWorkbookStylesPart1Content(WorkbookStylesPart workbookStylesPart1) { Stylesheet stylesheet1 = new Stylesheet(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x14ac" } }; stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); Fonts fonts1 = new Fonts(){ Count = (UInt32Value)2U }; Font font1 = new Font(); FontSize fontSize1 = new FontSize(){ Val = 11D }; Color color1 = new Color(){ Theme = (UInt32Value)1U }; FontName fontName1 = new FontName(){ Val = "Calibri" }; FontFamilyNumbering fontFamilyNumbering1 = new FontFamilyNumbering(){ Val = 2 }; FontCharSet fontCharSet1 = new FontCharSet(){ Val = 128 }; FontScheme fontScheme1 = new FontScheme(){ Val = FontSchemeValues.Minor }; font1.Append(fontSize1); font1.Append(color1); font1.Append(fontName1); font1.Append(fontFamilyNumbering1); font1.Append(fontCharSet1); font1.Append(fontScheme1); Font font2 = new Font(); FontSize fontSize2 = new FontSize(){ Val = 6D }; FontName fontName2 = new FontName(){ Val = "Calibri" }; FontFamilyNumbering fontFamilyNumbering2 = new FontFamilyNumbering(){ Val = 2 }; FontCharSet fontCharSet2 = new FontCharSet(){ Val = 128 }; FontScheme fontScheme2 = new FontScheme(){ Val = FontSchemeValues.Minor }; font2.Append(fontSize2); font2.Append(fontName2); font2.Append(fontFamilyNumbering2); font2.Append(fontCharSet2); font2.Append(fontScheme2); fonts1.Append(font1); fonts1.Append(font2); Fills fills1 = new Fills(){ Count = (UInt32Value)2U }; Fill fill1 = new Fill(); PatternFill patternFill1 = new PatternFill(){ PatternType = PatternValues.None }; fill1.Append(patternFill1); Fill fill2 = new Fill(); PatternFill patternFill2 = new PatternFill(){ PatternType = PatternValues.Gray125 }; fill2.Append(patternFill2); fills1.Append(fill1); fills1.Append(fill2); Borders borders1 = new Borders(){ Count = (UInt32Value)1U }; Border border1 = new Border(); LeftBorder leftBorder1 = new LeftBorder(); RightBorder rightBorder1 = new RightBorder(); TopBorder topBorder1 = new TopBorder(); BottomBorder bottomBorder1 = new BottomBorder(); DiagonalBorder diagonalBorder1 = new DiagonalBorder(); border1.Append(leftBorder1); border1.Append(rightBorder1); border1.Append(topBorder1); border1.Append(bottomBorder1); border1.Append(diagonalBorder1); borders1.Append(border1); CellStyleFormats cellStyleFormats1 = new CellStyleFormats(){ Count = (UInt32Value)1U }; CellFormat cellFormat1 = new CellFormat(){ NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U }; Alignment alignment1 = new Alignment(){ Vertical = VerticalAlignmentValues.Center }; cellFormat1.Append(alignment1); cellStyleFormats1.Append(cellFormat1); CellFormats cellFormats1 = new CellFormats(){ Count = (UInt32Value)1U }; CellFormat cellFormat2 = new CellFormat(){ NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }; Alignment alignment2 = new Alignment(){ Vertical = VerticalAlignmentValues.Center }; cellFormat2.Append(alignment2); cellFormats1.Append(cellFormat2); CellStyles cellStyles1 = new CellStyles(){ Count = (UInt32Value)1U }; CellStyle cellStyle1 = new CellStyle(){ Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U }; cellStyles1.Append(cellStyle1); DifferentialFormats differentialFormats1 = new DifferentialFormats(){ Count = (UInt32Value)0U }; TableStyles tableStyles1 = new TableStyles(){ Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" }; StylesheetExtensionList stylesheetExtensionList1 = new StylesheetExtensionList(); StylesheetExtension stylesheetExtension1 = new StylesheetExtension(){ Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" }; stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); X14.SlicerStyles slicerStyles1 = new X14.SlicerStyles(){ DefaultSlicerStyle = "SlicerStyleLight1" }; stylesheetExtension1.Append(slicerStyles1); StylesheetExtension stylesheetExtension2 = new StylesheetExtension(){ Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" }; stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); X15.TimelineStyles timelineStyles1 = new X15.TimelineStyles(){ DefaultTimelineStyle = "TimeSlicerStyleLight1" }; stylesheetExtension2.Append(timelineStyles1); stylesheetExtensionList1.Append(stylesheetExtension1); stylesheetExtensionList1.Append(stylesheetExtension2); stylesheet1.Append(fonts1); stylesheet1.Append(fills1); stylesheet1.Append(borders1); stylesheet1.Append(cellStyleFormats1); stylesheet1.Append(cellFormats1); stylesheet1.Append(cellStyles1); stylesheet1.Append(differentialFormats1); stylesheet1.Append(tableStyles1); stylesheet1.Append(stylesheetExtensionList1); workbookStylesPart1.Stylesheet = stylesheet1; } // Generates content of themePart1. private void GenerateThemePart1Content(ThemePart themePart1) { A.Theme theme1 = new A.Theme(){ Name = "Office Theme" }; theme1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); A.ThemeElements themeElements1 = new A.ThemeElements(); A.ColorScheme colorScheme1 = new A.ColorScheme(){ Name = "Office" }; A.Dark1Color dark1Color1 = new A.Dark1Color(); A.SystemColor systemColor1 = new A.SystemColor(){ Val = A.SystemColorValues.WindowText, LastColor = "000000" }; dark1Color1.Append(systemColor1); A.Light1Color light1Color1 = new A.Light1Color(); A.SystemColor systemColor2 = new A.SystemColor(){ Val = A.SystemColorValues.Window, LastColor = "FFFFFF" }; light1Color1.Append(systemColor2); A.Dark2Color dark2Color1 = new A.Dark2Color(); A.RgbColorModelHex rgbColorModelHex1 = new A.RgbColorModelHex(){ Val = "44546A" }; dark2Color1.Append(rgbColorModelHex1); A.Light2Color light2Color1 = new A.Light2Color(); A.RgbColorModelHex rgbColorModelHex2 = new A.RgbColorModelHex(){ Val = "E7E6E6" }; light2Color1.Append(rgbColorModelHex2); A.Accent1Color accent1Color1 = new A.Accent1Color(); A.RgbColorModelHex rgbColorModelHex3 = new A.RgbColorModelHex(){ Val = "5B9BD5" }; accent1Color1.Append(rgbColorModelHex3); A.Accent2Color accent2Color1 = new A.Accent2Color(); A.RgbColorModelHex rgbColorModelHex4 = new A.RgbColorModelHex(){ Val = "ED7D31" }; accent2Color1.Append(rgbColorModelHex4); A.Accent3Color accent3Color1 = new A.Accent3Color(); A.RgbColorModelHex rgbColorModelHex5 = new A.RgbColorModelHex(){ Val = "A5A5A5" }; accent3Color1.Append(rgbColorModelHex5); A.Accent4Color accent4Color1 = new A.Accent4Color(); A.RgbColorModelHex rgbColorModelHex6 = new A.RgbColorModelHex(){ Val = "FFC000" }; accent4Color1.Append(rgbColorModelHex6); A.Accent5Color accent5Color1 = new A.Accent5Color(); A.RgbColorModelHex rgbColorModelHex7 = new A.RgbColorModelHex(){ Val = "4472C4" }; accent5Color1.Append(rgbColorModelHex7); A.Accent6Color accent6Color1 = new A.Accent6Color(); A.RgbColorModelHex rgbColorModelHex8 = new A.RgbColorModelHex(){ Val = "70AD47" }; accent6Color1.Append(rgbColorModelHex8); A.Hyperlink hyperlink1 = new A.Hyperlink(); A.RgbColorModelHex rgbColorModelHex9 = new A.RgbColorModelHex(){ Val = "0563C1" }; hyperlink1.Append(rgbColorModelHex9); A.FollowedHyperlinkColor followedHyperlinkColor1 = new A.FollowedHyperlinkColor(); A.RgbColorModelHex rgbColorModelHex10 = new A.RgbColorModelHex(){ Val = "954F72" }; followedHyperlinkColor1.Append(rgbColorModelHex10); colorScheme1.Append(dark1Color1); colorScheme1.Append(light1Color1); colorScheme1.Append(dark2Color1); colorScheme1.Append(light2Color1); colorScheme1.Append(accent1Color1); colorScheme1.Append(accent2Color1); colorScheme1.Append(accent3Color1); colorScheme1.Append(accent4Color1); colorScheme1.Append(accent5Color1); colorScheme1.Append(accent6Color1); colorScheme1.Append(hyperlink1); colorScheme1.Append(followedHyperlinkColor1); A.FontScheme fontScheme3 = new A.FontScheme(){ Name = "Office" }; A.MajorFont majorFont1 = new A.MajorFont(); A.LatinFont latinFont1 = new A.LatinFont(){ Typeface = "Calibri Light", Panose = "020F0302020204030204" }; A.EastAsianFont eastAsianFont1 = new A.EastAsianFont(){ Typeface = "" }; A.ComplexScriptFont complexScriptFont1 = new A.ComplexScriptFont(){ Typeface = "" }; A.SupplementalFont supplementalFont1 = new A.SupplementalFont(){ Script = "Jpan", Typeface = "MS Pゴシック" }; A.SupplementalFont supplementalFont2 = new A.SupplementalFont(){ Script = "Hang", Typeface = "맑은 고딕" }; A.SupplementalFont supplementalFont3 = new A.SupplementalFont(){ Script = "Hans", Typeface = "宋体" }; A.SupplementalFont supplementalFont4 = new A.SupplementalFont(){ Script = "Hant", Typeface = "新細明體" }; A.SupplementalFont supplementalFont5 = new A.SupplementalFont(){ Script = "Arab", Typeface = "Times New Roman" }; A.SupplementalFont supplementalFont6 = new A.SupplementalFont(){ Script = "Hebr", Typeface = "Times New Roman" }; A.SupplementalFont supplementalFont7 = new A.SupplementalFont(){ Script = "Thai", Typeface = "Tahoma" }; A.SupplementalFont supplementalFont8 = new A.SupplementalFont(){ Script = "Ethi", Typeface = "Nyala" }; A.SupplementalFont supplementalFont9 = new A.SupplementalFont(){ Script = "Beng", Typeface = "Vrinda" }; A.SupplementalFont supplementalFont10 = new A.SupplementalFont(){ Script = "Gujr", Typeface = "Shruti" }; A.SupplementalFont supplementalFont11 = new A.SupplementalFont(){ Script = "Khmr", Typeface = "MoolBoran" }; A.SupplementalFont supplementalFont12 = new A.SupplementalFont(){ Script = "Knda", Typeface = "Tunga" }; A.SupplementalFont supplementalFont13 = new A.SupplementalFont(){ Script = "Guru", Typeface = "Raavi" }; A.SupplementalFont supplementalFont14 = new A.SupplementalFont(){ Script = "Cans", Typeface = "Euphemia" }; A.SupplementalFont supplementalFont15 = new A.SupplementalFont(){ Script = "Cher", Typeface = "Plantagenet Cherokee" }; A.SupplementalFont supplementalFont16 = new A.SupplementalFont(){ Script = "Yiii", Typeface = "Microsoft Yi Baiti" }; A.SupplementalFont supplementalFont17 = new A.SupplementalFont(){ Script = "Tibt", Typeface = "Microsoft Himalaya" }; A.SupplementalFont supplementalFont18 = new A.SupplementalFont(){ Script = "Thaa", Typeface = "MV Boli" }; A.SupplementalFont supplementalFont19 = new A.SupplementalFont(){ Script = "Deva", Typeface = "Mangal" }; A.SupplementalFont supplementalFont20 = new A.SupplementalFont(){ Script = "Telu", Typeface = "Gautami" }; A.SupplementalFont supplementalFont21 = new A.SupplementalFont(){ Script = "Taml", Typeface = "Latha" }; A.SupplementalFont supplementalFont22 = new A.SupplementalFont(){ Script = "Syrc", Typeface = "Estrangelo Edessa" }; A.SupplementalFont supplementalFont23 = new A.SupplementalFont(){ Script = "Orya", Typeface = "Kalinga" }; A.SupplementalFont supplementalFont24 = new A.SupplementalFont(){ Script = "Mlym", Typeface = "Kartika" }; A.SupplementalFont supplementalFont25 = new A.SupplementalFont(){ Script = "Laoo", Typeface = "DokChampa" }; A.SupplementalFont supplementalFont26 = new A.SupplementalFont(){ Script = "Sinh", Typeface = "Iskoola Pota" }; A.SupplementalFont supplementalFont27 = new A.SupplementalFont(){ Script = "Mong", Typeface = "Mongolian Baiti" }; A.SupplementalFont supplementalFont28 = new A.SupplementalFont(){ Script = "Viet", Typeface = "Times New Roman" }; A.SupplementalFont supplementalFont29 = new A.SupplementalFont(){ Script = "Uigh", Typeface = "Microsoft Uighur" }; A.SupplementalFont supplementalFont30 = new A.SupplementalFont(){ Script = "Geor", Typeface = "Sylfaen" }; majorFont1.Append(latinFont1); majorFont1.Append(eastAsianFont1); majorFont1.Append(complexScriptFont1); majorFont1.Append(supplementalFont1); majorFont1.Append(supplementalFont2); majorFont1.Append(supplementalFont3); majorFont1.Append(supplementalFont4); majorFont1.Append(supplementalFont5); majorFont1.Append(supplementalFont6); majorFont1.Append(supplementalFont7); majorFont1.Append(supplementalFont8); majorFont1.Append(supplementalFont9); majorFont1.Append(supplementalFont10); majorFont1.Append(supplementalFont11); majorFont1.Append(supplementalFont12); majorFont1.Append(supplementalFont13); majorFont1.Append(supplementalFont14); majorFont1.Append(supplementalFont15); majorFont1.Append(supplementalFont16); majorFont1.Append(supplementalFont17); majorFont1.Append(supplementalFont18); majorFont1.Append(supplementalFont19); majorFont1.Append(supplementalFont20); majorFont1.Append(supplementalFont21); majorFont1.Append(supplementalFont22); majorFont1.Append(supplementalFont23); majorFont1.Append(supplementalFont24); majorFont1.Append(supplementalFont25); majorFont1.Append(supplementalFont26); majorFont1.Append(supplementalFont27); majorFont1.Append(supplementalFont28); majorFont1.Append(supplementalFont29); majorFont1.Append(supplementalFont30); A.MinorFont minorFont1 = new A.MinorFont(); A.LatinFont latinFont2 = new A.LatinFont(){ Typeface = "Calibri", Panose = "020F0502020204030204" }; A.EastAsianFont eastAsianFont2 = new A.EastAsianFont(){ Typeface = "" }; A.ComplexScriptFont complexScriptFont2 = new A.ComplexScriptFont(){ Typeface = "" }; A.SupplementalFont supplementalFont31 = new A.SupplementalFont(){ Script = "Jpan", Typeface = "MS Pゴシック" }; A.SupplementalFont supplementalFont32 = new A.SupplementalFont(){ Script = "Hang", Typeface = "맑은 고딕" }; A.SupplementalFont supplementalFont33 = new A.SupplementalFont(){ Script = "Hans", Typeface = "宋体" }; A.SupplementalFont supplementalFont34 = new A.SupplementalFont(){ Script = "Hant", Typeface = "新細明體" }; A.SupplementalFont supplementalFont35 = new A.SupplementalFont(){ Script = "Arab", Typeface = "Arial" }; A.SupplementalFont supplementalFont36 = new A.SupplementalFont(){ Script = "Hebr", Typeface = "Arial" }; A.SupplementalFont supplementalFont37 = new A.SupplementalFont(){ Script = "Thai", Typeface = "Tahoma" }; A.SupplementalFont supplementalFont38 = new A.SupplementalFont(){ Script = "Ethi", Typeface = "Nyala" }; A.SupplementalFont supplementalFont39 = new A.SupplementalFont(){ Script = "Beng", Typeface = "Vrinda" }; A.SupplementalFont supplementalFont40 = new A.SupplementalFont(){ Script = "Gujr", Typeface = "Shruti" }; A.SupplementalFont supplementalFont41 = new A.SupplementalFont(){ Script = "Khmr", Typeface = "DaunPenh" }; A.SupplementalFont supplementalFont42 = new A.SupplementalFont(){ Script = "Knda", Typeface = "Tunga" }; A.SupplementalFont supplementalFont43 = new A.SupplementalFont(){ Script = "Guru", Typeface = "Raavi" }; A.SupplementalFont supplementalFont44 = new A.SupplementalFont(){ Script = "Cans", Typeface = "Euphemia" }; A.SupplementalFont supplementalFont45 = new A.SupplementalFont(){ Script = "Cher", Typeface = "Plantagenet Cherokee" }; A.SupplementalFont supplementalFont46 = new A.SupplementalFont(){ Script = "Yiii", Typeface = "Microsoft Yi Baiti" }; A.SupplementalFont supplementalFont47 = new A.SupplementalFont(){ Script = "Tibt", Typeface = "Microsoft Himalaya" }; A.SupplementalFont supplementalFont48 = new A.SupplementalFont(){ Script = "Thaa", Typeface = "MV Boli" }; A.SupplementalFont supplementalFont49 = new A.SupplementalFont(){ Script = "Deva", Typeface = "Mangal" }; A.SupplementalFont supplementalFont50 = new A.SupplementalFont(){ Script = "Telu", Typeface = "Gautami" }; A.SupplementalFont supplementalFont51 = new A.SupplementalFont(){ Script = "Taml", Typeface = "Latha" }; A.SupplementalFont supplementalFont52 = new A.SupplementalFont(){ Script = "Syrc", Typeface = "Estrangelo Edessa" }; A.SupplementalFont supplementalFont53 = new A.SupplementalFont(){ Script = "Orya", Typeface = "Kalinga" }; A.SupplementalFont supplementalFont54 = new A.SupplementalFont(){ Script = "Mlym", Typeface = "Kartika" }; A.SupplementalFont supplementalFont55 = new A.SupplementalFont(){ Script = "Laoo", Typeface = "DokChampa" }; A.SupplementalFont supplementalFont56 = new A.SupplementalFont(){ Script = "Sinh", Typeface = "Iskoola Pota" }; A.SupplementalFont supplementalFont57 = new A.SupplementalFont(){ Script = "Mong", Typeface = "Mongolian Baiti" }; A.SupplementalFont supplementalFont58 = new A.SupplementalFont(){ Script = "Viet", Typeface = "Arial" }; A.SupplementalFont supplementalFont59 = new A.SupplementalFont(){ Script = "Uigh", Typeface = "Microsoft Uighur" }; A.SupplementalFont supplementalFont60 = new A.SupplementalFont(){ Script = "Geor", Typeface = "Sylfaen" }; minorFont1.Append(latinFont2); minorFont1.Append(eastAsianFont2); minorFont1.Append(complexScriptFont2); minorFont1.Append(supplementalFont31); minorFont1.Append(supplementalFont32); minorFont1.Append(supplementalFont33); minorFont1.Append(supplementalFont34); minorFont1.Append(supplementalFont35); minorFont1.Append(supplementalFont36); minorFont1.Append(supplementalFont37); minorFont1.Append(supplementalFont38); minorFont1.Append(supplementalFont39); minorFont1.Append(supplementalFont40); minorFont1.Append(supplementalFont41); minorFont1.Append(supplementalFont42); minorFont1.Append(supplementalFont43); minorFont1.Append(supplementalFont44); minorFont1.Append(supplementalFont45); minorFont1.Append(supplementalFont46); minorFont1.Append(supplementalFont47); minorFont1.Append(supplementalFont48); minorFont1.Append(supplementalFont49); minorFont1.Append(supplementalFont50); minorFont1.Append(supplementalFont51); minorFont1.Append(supplementalFont52); minorFont1.Append(supplementalFont53); minorFont1.Append(supplementalFont54); minorFont1.Append(supplementalFont55); minorFont1.Append(supplementalFont56); minorFont1.Append(supplementalFont57); minorFont1.Append(supplementalFont58); minorFont1.Append(supplementalFont59); minorFont1.Append(supplementalFont60); fontScheme3.Append(majorFont1); fontScheme3.Append(minorFont1); A.FormatScheme formatScheme1 = new A.FormatScheme(){ Name = "Office" }; A.FillStyleList fillStyleList1 = new A.FillStyleList(); A.SolidFill solidFill7 = new A.SolidFill(); A.SchemeColor schemeColor1 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; solidFill7.Append(schemeColor1); A.GradientFill gradientFill1 = new A.GradientFill(){ RotateWithShape = true }; A.GradientStopList gradientStopList1 = new A.GradientStopList(); A.GradientStop gradientStop1 = new A.GradientStop(){ Position = 0 }; A.SchemeColor schemeColor2 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.LuminanceModulation luminanceModulation1 = new A.LuminanceModulation(){ Val = 110000 }; A.SaturationModulation saturationModulation1 = new A.SaturationModulation(){ Val = 105000 }; A.Tint tint1 = new A.Tint(){ Val = 67000 }; schemeColor2.Append(luminanceModulation1); schemeColor2.Append(saturationModulation1); schemeColor2.Append(tint1); gradientStop1.Append(schemeColor2); A.GradientStop gradientStop2 = new A.GradientStop(){ Position = 50000 }; A.SchemeColor schemeColor3 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.LuminanceModulation luminanceModulation2 = new A.LuminanceModulation(){ Val = 105000 }; A.SaturationModulation saturationModulation2 = new A.SaturationModulation(){ Val = 103000 }; A.Tint tint2 = new A.Tint(){ Val = 73000 }; schemeColor3.Append(luminanceModulation2); schemeColor3.Append(saturationModulation2); schemeColor3.Append(tint2); gradientStop2.Append(schemeColor3); A.GradientStop gradientStop3 = new A.GradientStop(){ Position = 100000 }; A.SchemeColor schemeColor4 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.LuminanceModulation luminanceModulation3 = new A.LuminanceModulation(){ Val = 105000 }; A.SaturationModulation saturationModulation3 = new A.SaturationModulation(){ Val = 109000 }; A.Tint tint3 = new A.Tint(){ Val = 81000 }; schemeColor4.Append(luminanceModulation3); schemeColor4.Append(saturationModulation3); schemeColor4.Append(tint3); gradientStop3.Append(schemeColor4); gradientStopList1.Append(gradientStop1); gradientStopList1.Append(gradientStop2); gradientStopList1.Append(gradientStop3); A.LinearGradientFill linearGradientFill1 = new A.LinearGradientFill(){ Angle = 5400000, Scaled = false }; gradientFill1.Append(gradientStopList1); gradientFill1.Append(linearGradientFill1); A.GradientFill gradientFill2 = new A.GradientFill(){ RotateWithShape = true }; A.GradientStopList gradientStopList2 = new A.GradientStopList(); A.GradientStop gradientStop4 = new A.GradientStop(){ Position = 0 }; A.SchemeColor schemeColor5 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.SaturationModulation saturationModulation4 = new A.SaturationModulation(){ Val = 103000 }; A.LuminanceModulation luminanceModulation4 = new A.LuminanceModulation(){ Val = 102000 }; A.Tint tint4 = new A.Tint(){ Val = 94000 }; schemeColor5.Append(saturationModulation4); schemeColor5.Append(luminanceModulation4); schemeColor5.Append(tint4); gradientStop4.Append(schemeColor5); A.GradientStop gradientStop5 = new A.GradientStop(){ Position = 50000 }; A.SchemeColor schemeColor6 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.SaturationModulation saturationModulation5 = new A.SaturationModulation(){ Val = 110000 }; A.LuminanceModulation luminanceModulation5 = new A.LuminanceModulation(){ Val = 100000 }; A.Shade shade1 = new A.Shade(){ Val = 100000 }; schemeColor6.Append(saturationModulation5); schemeColor6.Append(luminanceModulation5); schemeColor6.Append(shade1); gradientStop5.Append(schemeColor6); A.GradientStop gradientStop6 = new A.GradientStop(){ Position = 100000 }; A.SchemeColor schemeColor7 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.LuminanceModulation luminanceModulation6 = new A.LuminanceModulation(){ Val = 99000 }; A.SaturationModulation saturationModulation6 = new A.SaturationModulation(){ Val = 120000 }; A.Shade shade2 = new A.Shade(){ Val = 78000 }; schemeColor7.Append(luminanceModulation6); schemeColor7.Append(saturationModulation6); schemeColor7.Append(shade2); gradientStop6.Append(schemeColor7); gradientStopList2.Append(gradientStop4); gradientStopList2.Append(gradientStop5); gradientStopList2.Append(gradientStop6); A.LinearGradientFill linearGradientFill2 = new A.LinearGradientFill(){ Angle = 5400000, Scaled = false }; gradientFill2.Append(gradientStopList2); gradientFill2.Append(linearGradientFill2); fillStyleList1.Append(solidFill7); fillStyleList1.Append(gradientFill1); fillStyleList1.Append(gradientFill2); A.LineStyleList lineStyleList1 = new A.LineStyleList(); A.Outline outline4 = new A.Outline(){ Width = 6350, CapType = A.LineCapValues.Flat, CompoundLineType = A.CompoundLineValues.Single, Alignment = A.PenAlignmentValues.Center }; A.SolidFill solidFill8 = new A.SolidFill(); A.SchemeColor schemeColor8 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; solidFill8.Append(schemeColor8); A.PresetDash presetDash1 = new A.PresetDash(){ Val = A.PresetLineDashValues.Solid }; A.Miter miter1 = new A.Miter(){ Limit = 800000 }; outline4.Append(solidFill8); outline4.Append(presetDash1); outline4.Append(miter1); A.Outline outline5 = new A.Outline(){ Width = 12700, CapType = A.LineCapValues.Flat, CompoundLineType = A.CompoundLineValues.Single, Alignment = A.PenAlignmentValues.Center }; A.SolidFill solidFill9 = new A.SolidFill(); A.SchemeColor schemeColor9 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; solidFill9.Append(schemeColor9); A.PresetDash presetDash2 = new A.PresetDash(){ Val = A.PresetLineDashValues.Solid }; A.Miter miter2 = new A.Miter(){ Limit = 800000 }; outline5.Append(solidFill9); outline5.Append(presetDash2); outline5.Append(miter2); A.Outline outline6 = new A.Outline(){ Width = 19050, CapType = A.LineCapValues.Flat, CompoundLineType = A.CompoundLineValues.Single, Alignment = A.PenAlignmentValues.Center }; A.SolidFill solidFill10 = new A.SolidFill(); A.SchemeColor schemeColor10 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; solidFill10.Append(schemeColor10); A.PresetDash presetDash3 = new A.PresetDash(){ Val = A.PresetLineDashValues.Solid }; A.Miter miter3 = new A.Miter(){ Limit = 800000 }; outline6.Append(solidFill10); outline6.Append(presetDash3); outline6.Append(miter3); lineStyleList1.Append(outline4); lineStyleList1.Append(outline5); lineStyleList1.Append(outline6); A.EffectStyleList effectStyleList1 = new A.EffectStyleList(); A.EffectStyle effectStyle1 = new A.EffectStyle(); A.EffectList effectList1 = new A.EffectList(); effectStyle1.Append(effectList1); A.EffectStyle effectStyle2 = new A.EffectStyle(); A.EffectList effectList2 = new A.EffectList(); effectStyle2.Append(effectList2); A.EffectStyle effectStyle3 = new A.EffectStyle(); A.EffectList effectList3 = new A.EffectList(); A.OuterShadow outerShadow1 = new A.OuterShadow(){ BlurRadius = 57150L, Distance = 19050L, Direction = 5400000, Alignment = A.RectangleAlignmentValues.Center, RotateWithShape = false }; A.RgbColorModelHex rgbColorModelHex11 = new A.RgbColorModelHex(){ Val = "000000" }; A.Alpha alpha1 = new A.Alpha(){ Val = 63000 }; rgbColorModelHex11.Append(alpha1); outerShadow1.Append(rgbColorModelHex11); effectList3.Append(outerShadow1); effectStyle3.Append(effectList3); effectStyleList1.Append(effectStyle1); effectStyleList1.Append(effectStyle2); effectStyleList1.Append(effectStyle3); A.BackgroundFillStyleList backgroundFillStyleList1 = new A.BackgroundFillStyleList(); A.SolidFill solidFill11 = new A.SolidFill(); A.SchemeColor schemeColor11 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; solidFill11.Append(schemeColor11); A.SolidFill solidFill12 = new A.SolidFill(); A.SchemeColor schemeColor12 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.Tint tint5 = new A.Tint(){ Val = 95000 }; A.SaturationModulation saturationModulation7 = new A.SaturationModulation(){ Val = 170000 }; schemeColor12.Append(tint5); schemeColor12.Append(saturationModulation7); solidFill12.Append(schemeColor12); A.GradientFill gradientFill3 = new A.GradientFill(){ RotateWithShape = true }; A.GradientStopList gradientStopList3 = new A.GradientStopList(); A.GradientStop gradientStop7 = new A.GradientStop(){ Position = 0 }; A.SchemeColor schemeColor13 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.Tint tint6 = new A.Tint(){ Val = 93000 }; A.SaturationModulation saturationModulation8 = new A.SaturationModulation(){ Val = 150000 }; A.Shade shade3 = new A.Shade(){ Val = 98000 }; A.LuminanceModulation luminanceModulation7 = new A.LuminanceModulation(){ Val = 102000 }; schemeColor13.Append(tint6); schemeColor13.Append(saturationModulation8); schemeColor13.Append(shade3); schemeColor13.Append(luminanceModulation7); gradientStop7.Append(schemeColor13); A.GradientStop gradientStop8 = new A.GradientStop(){ Position = 50000 }; A.SchemeColor schemeColor14 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.Tint tint7 = new A.Tint(){ Val = 98000 }; A.SaturationModulation saturationModulation9 = new A.SaturationModulation(){ Val = 130000 }; A.Shade shade4 = new A.Shade(){ Val = 90000 }; A.LuminanceModulation luminanceModulation8 = new A.LuminanceModulation(){ Val = 103000 }; schemeColor14.Append(tint7); schemeColor14.Append(saturationModulation9); schemeColor14.Append(shade4); schemeColor14.Append(luminanceModulation8); gradientStop8.Append(schemeColor14); A.GradientStop gradientStop9 = new A.GradientStop(){ Position = 100000 }; A.SchemeColor schemeColor15 = new A.SchemeColor(){ Val = A.SchemeColorValues.PhColor }; A.Shade shade5 = new A.Shade(){ Val = 63000 }; A.SaturationModulation saturationModulation10 = new A.SaturationModulation(){ Val = 120000 }; schemeColor15.Append(shade5); schemeColor15.Append(saturationModulation10); gradientStop9.Append(schemeColor15); gradientStopList3.Append(gradientStop7); gradientStopList3.Append(gradientStop8); gradientStopList3.Append(gradientStop9); A.LinearGradientFill linearGradientFill3 = new A.LinearGradientFill(){ Angle = 5400000, Scaled = false }; gradientFill3.Append(gradientStopList3); gradientFill3.Append(linearGradientFill3); backgroundFillStyleList1.Append(solidFill11); backgroundFillStyleList1.Append(solidFill12); backgroundFillStyleList1.Append(gradientFill3); formatScheme1.Append(fillStyleList1); formatScheme1.Append(lineStyleList1); formatScheme1.Append(effectStyleList1); formatScheme1.Append(backgroundFillStyleList1); themeElements1.Append(colorScheme1); themeElements1.Append(fontScheme3); themeElements1.Append(formatScheme1); A.ObjectDefaults objectDefaults1 = new A.ObjectDefaults(); A.ExtraColorSchemeList extraColorSchemeList1 = new A.ExtraColorSchemeList(); A.OfficeStyleSheetExtensionList officeStyleSheetExtensionList1 = new A.OfficeStyleSheetExtensionList(); A.OfficeStyleSheetExtension officeStyleSheetExtension1 = new A.OfficeStyleSheetExtension(){ Uri = "{05A4C25C-085E-4340-85A3-A5531E510DB2}" }; Thm15.ThemeFamily themeFamily1 = new Thm15.ThemeFamily(){ Name = "Office Theme", Id = "{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}", Vid = "{4A3C46E8-61CC-4603-A589-7422A47A8E4A}" }; themeFamily1.AddNamespaceDeclaration("thm15", "http://schemas.microsoft.com/office/thememl/2012/main"); officeStyleSheetExtension1.Append(themeFamily1); officeStyleSheetExtensionList1.Append(officeStyleSheetExtension1); theme1.Append(themeElements1); theme1.Append(objectDefaults1); theme1.Append(extraColorSchemeList1); theme1.Append(officeStyleSheetExtensionList1); themePart1.Theme = theme1; } // Generates content of slicerCachePart3. private void GenerateSlicerCachePart3Content(SlicerCachePart slicerCachePart3) { X14.SlicerCacheDefinition slicerCacheDefinition3 = new X14.SlicerCacheDefinition(){ Name = "Slicer_Column3", SourceName = "Column3", MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x" } }; slicerCacheDefinition3.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); slicerCacheDefinition3.AddNamespaceDeclaration("x", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); X14.SlicerCacheDefinitionExtensionList slicerCacheDefinitionExtensionList3 = new X14.SlicerCacheDefinitionExtensionList(); SlicerCacheDefinitionExtension slicerCacheDefinitionExtension3 = new SlicerCacheDefinitionExtension(){ Uri = "{2F2917AC-EB37-4324-AD4E-5DD8C200BD13}" }; slicerCacheDefinitionExtension3.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); X15.TableSlicerCache tableSlicerCache3 = new X15.TableSlicerCache(){ TableId = (UInt32Value)1U, Column = (UInt32Value)3U }; slicerCacheDefinitionExtension3.Append(tableSlicerCache3); slicerCacheDefinitionExtensionList3.Append(slicerCacheDefinitionExtension3); slicerCacheDefinition3.Append(slicerCacheDefinitionExtensionList3); slicerCachePart3.SlicerCacheDefinition = slicerCacheDefinition3; } private void SetPackageProperties(OpenXmlPackage document) { document.PackageProperties.Creator = "Masaki Tamura (Pasona Tech)"; document.PackageProperties.Created = System.Xml.XmlConvert.ToDateTime("2012-02-06T03:18:17Z", System.Xml.XmlDateTimeSerializationMode.RoundtripKind); document.PackageProperties.Modified = System.Xml.XmlConvert.ToDateTime("2012-10-03T08:44:58Z", System.Xml.XmlDateTimeSerializationMode.RoundtripKind); document.PackageProperties.LastModifiedBy = "Dan Ito"; } } }
50.249867
257
0.659702
[ "Apache-2.0" ]
Aliceljm1/openxml
DocumentFormat.OpenXml.Tests/ConformanceTest/Slicer/GeneratedDocument.cs
94,588
C#
// Copyright(c) Microsoft Corporation. // All rights reserved. // // Licensed under the MIT license. See LICENSE file in the solution root folder for full license information using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ApplicationCore; using ApplicationCore.Artifacts; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace WebReact.ViewModels { public class DocumentListViewModel : BaseListViewModel<DocumentViewModel> { public DocumentListViewModel() : base() { } } }
24.833333
108
0.755034
[ "MIT" ]
kulado/ProposalManager
WebReact/ViewModels/DocumentListViewModel.cs
598
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("07. Primes in Given Range")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07. Primes in Given Range")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4db667e7-2d3f-4871-90ab-6c46dd8f90dd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.459459
84
0.742797
[ "Apache-2.0" ]
genadi60/SoftUni
MethodsExercises/07. Primes in Given Range/Properties/AssemblyInfo.cs
1,426
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Xaml; using System.Windows.Markup; using System.Linq; namespace Eto.Serialization.Xaml { class EtoXamlSchemaContext : XamlSchemaContext { public const string EtoFormsNamespace = "http://schema.picoe.ca/eto.forms"; readonly Dictionary<string, XamlType> cache = new Dictionary<string, XamlType>(); readonly Dictionary<Type, XamlType> typeCache = new Dictionary<Type, XamlType>(); readonly object cache_sync = new object(); public EtoXamlSchemaContext(IEnumerable<Assembly> assemblies) : base(assemblies) { } const string clr_namespace = "clr-namespace:"; const string clr_assembly = "assembly="; const string eto_namespace = "clr-namespace:Eto.Forms;assembly=Eto"; protected override XamlType GetXamlType(string xamlNamespace, string name, params XamlType[] typeArguments) { var type = base.GetXamlType(xamlNamespace, name, typeArguments); if (type == null && xamlNamespace == EtoFormsNamespace) xamlNamespace = eto_namespace; if (type == null && xamlNamespace.StartsWith(clr_namespace, StringComparison.OrdinalIgnoreCase)) { lock (cache_sync) { if (!cache.TryGetValue(xamlNamespace + name, out type)) { var nsComponents = xamlNamespace.Split(';'); if (nsComponents.Length == 2 && nsComponents[1].StartsWith(clr_assembly, StringComparison.Ordinal)) { var assemblyName = nsComponents[1].Substring(clr_assembly.Length); var ns = nsComponents[0].Substring(clr_namespace.Length); var assembly = Assembly.Load(assemblyName); if (assembly != null) { var realType = assembly.GetType(ns + "." + name); type = xamlNamespace == eto_namespace ? new EtoXamlType(realType, this) : GetXamlType(realType); cache.Add(xamlNamespace + name, type); } } } } } return type; } public override XamlType GetXamlType(Type type) { if (type.Assembly == typeof(Platform).Assembly) { XamlType xamlType; if (!typeCache.TryGetValue(type, out xamlType)) { xamlType = new EtoXamlType(type, this); typeCache.Add(type, xamlType); } return xamlType; } return base.GetXamlType(type); } } }
30.986301
109
0.695402
[ "BSD-3-Clause" ]
DavidRutten/Eto
Source/Eto.Serialization.Xaml/EtoXamlSchemaContext.cs
2,262
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Demos.Web.Areas.Foo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Demos")] [assembly: AssemblyCompany("Nb")] [assembly: AssemblyCopyright("版权所有 Nb")] [assembly: AssemblyTrademark("Demos")] [assembly: AssemblyCulture("")] [assembly: Guid("99879ED4-058B-47B0-A3FC-A23A00877F79")] // 将 ComVisible 设置为 false 会使此程序集中的类型 // 对 COM 组件不可见。如果需要 // 从 COM 访问此程序集中的某个类型,请针对该类型将 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订版本 // // 可以指定所有值,也可以使用“修订号”和“内部版本号”的默认值, // 方法是按如下所示使用 "*": [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
27.892857
56
0.715749
[ "Apache-2.0" ]
congzw/MvcTemplate
src/Demos.Web/Areas/Foo/Properties/AssemblyInfo.cs
1,037
C#
namespace MaterialSkin.Controls { using MaterialSkin.Animations; using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Windows.Forms; public class MaterialCheckbox : CheckBox, IMaterialControl { [Browsable(false)] public int Depth { get; set; } [Browsable(false)] public MaterialSkinManager SkinManager => MaterialSkinManager.Instance; [Browsable(false)] public MouseState MouseState { get; set; } [Browsable(false)] public Point MouseLocation { get; set; } private bool _ripple; [Category("Appearance")] public bool Ripple { get { return _ripple; } set { _ripple = value; AutoSize = AutoSize; //Make AutoSize directly set the bounds. if (value) { Margin = new Padding(0); } Invalidate(); } } private readonly AnimationManager _checkAM; private readonly AnimationManager _rippleAM; private readonly AnimationManager _hoverAM; private const int HEIGHT_RIPPLE = 37; private const int HEIGHT_NO_RIPPLE = 20; private const int TEXT_OFFSET = 26; private const int CHECKBOX_SIZE = 18; private const int CHECKBOX_SIZE_HALF = CHECKBOX_SIZE / 2; private int _boxOffset; public MaterialCheckbox() { _checkAM = new AnimationManager { AnimationType = AnimationType.EaseInOut, Increment = 0.05 }; _hoverAM = new AnimationManager(true) { AnimationType = AnimationType.Linear, Increment = 0.10 }; _rippleAM = new AnimationManager(false) { AnimationType = AnimationType.Linear, Increment = 0.10, SecondaryIncrement = 0.08 }; CheckedChanged += (sender, args) => { if (Ripple) _checkAM.StartNewAnimation(Checked ? AnimationDirection.In : AnimationDirection.Out); }; _checkAM.OnAnimationProgress += sender => Invalidate(); _hoverAM.OnAnimationProgress += sender => Invalidate(); _rippleAM.OnAnimationProgress += sender => Invalidate(); Ripple = true; Height = HEIGHT_RIPPLE; MouseLocation = new Point(-1, -1); } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); _boxOffset = HEIGHT_RIPPLE / 2 - 9; } public override Size GetPreferredSize(Size proposedSize) { Size strSize; using (NativeTextRenderer NativeText = new NativeTextRenderer(CreateGraphics())) { strSize = NativeText.MeasureLogString(Text, SkinManager.getLogFontByType(MaterialSkinManager.fontType.Body1)); } int w = _boxOffset + TEXT_OFFSET + strSize.Width; return Ripple ? new Size(w, HEIGHT_RIPPLE) : new Size(w, HEIGHT_NO_RIPPLE); } private static readonly Point[] CheckmarkLine = { new Point(3, 8), new Point(7, 12), new Point(14, 5) }; protected override void OnPaint(PaintEventArgs pevent) { Graphics g = pevent.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; // clear the control g.Clear(Parent.BackColor); int CHECKBOX_CENTER = _boxOffset + CHECKBOX_SIZE_HALF - 1; Point animationSource = new Point(CHECKBOX_CENTER, CHECKBOX_CENTER); double animationProgress = _checkAM.GetProgress(); int colorAlpha = Enabled ? (int)(animationProgress * 255.0) : SkinManager.CheckBoxOffDisabledColor.A; int backgroundAlpha = Enabled ? (int)(SkinManager.CheckboxOffColor.A * (1.0 - animationProgress)) : SkinManager.CheckBoxOffDisabledColor.A; int rippleHeight = (HEIGHT_RIPPLE % 2 == 0) ? HEIGHT_RIPPLE - 3 : HEIGHT_RIPPLE - 2; SolidBrush brush = new SolidBrush(Color.FromArgb(colorAlpha, Enabled ? SkinManager.ColorScheme.AccentColor : SkinManager.CheckBoxOffDisabledColor)); Pen pen = new Pen(brush.Color, 2); // draw hover animation if (Ripple) { double animationValue = _hoverAM.IsAnimating() ? _hoverAM.GetProgress() : hovered ? 1 : 0; int rippleSize = (int)(rippleHeight * (0.7 + (0.3 * animationValue))); using (SolidBrush rippleBrush = new SolidBrush(Color.FromArgb((int)(40 * animationValue), !Checked ? SkinManager.Theme.SwitchRippleColor : brush.Color))) // no animation { g.FillEllipse(rippleBrush, new Rectangle(animationSource.X - rippleSize / 2, animationSource.Y - rippleSize / 2, rippleSize, rippleSize)); } } // draw ripple animation if (Ripple && _rippleAM.IsAnimating()) { for (int i = 0; i < _rippleAM.GetAnimationCount(); i++) { double animationValue = _rippleAM.GetProgress(i); int rippleSize = (_rippleAM.GetDirection(i) == AnimationDirection.InOutIn) ? (int)(rippleHeight * (0.7 + (0.3 * animationValue))) : rippleHeight; using (SolidBrush rippleBrush = new SolidBrush(Color.FromArgb((int)((animationValue * 40)), !Checked ? SkinManager.Theme.SwitchRippleColor : brush.Color))) { g.FillEllipse(rippleBrush, new Rectangle(animationSource.X - rippleSize / 2, animationSource.Y - rippleSize / 2, rippleSize, rippleSize)); } } } Rectangle checkMarkLineFill = new Rectangle(_boxOffset, _boxOffset, (int)(CHECKBOX_SIZE * animationProgress), CHECKBOX_SIZE); using (GraphicsPath checkmarkPath = DrawHelper.CreateRoundRect(_boxOffset - 0.5f, _boxOffset - 0.5f, CHECKBOX_SIZE, CHECKBOX_SIZE, 1)) { if (Enabled) { using (Pen pen2 = new Pen(DrawHelper.BlendColor(Parent.BackColor, Enabled ? SkinManager.CheckboxOffColor : SkinManager.CheckBoxOffDisabledColor, backgroundAlpha), 2)) { g.DrawPath(pen2, checkmarkPath); } g.DrawPath(pen, checkmarkPath); g.FillPath(brush, checkmarkPath); } else { if (Checked) g.FillPath(brush, checkmarkPath); else g.DrawPath(pen, checkmarkPath); } g.DrawImageUnscaledAndClipped(DrawCheckMarkBitmap(), checkMarkLineFill); } // draw checkbox text using (NativeTextRenderer NativeText = new NativeTextRenderer(g)) { Rectangle textLocation = new Rectangle(_boxOffset + TEXT_OFFSET, 0, Width - (_boxOffset + TEXT_OFFSET), HEIGHT_RIPPLE); NativeText.DrawTransparentText(Text, SkinManager.getLogFontByType(MaterialSkinManager.fontType.Body1), Enabled ? SkinManager.TextHighEmphasisColor : SkinManager.TextDisabledOrHintColor, textLocation.Location, textLocation.Size, NativeTextRenderer.TextAlignFlags.Left | NativeTextRenderer.TextAlignFlags.Middle); } // dispose used paint objects pen.Dispose(); brush.Dispose(); } private Bitmap DrawCheckMarkBitmap() { Bitmap checkMark = new Bitmap(CHECKBOX_SIZE, CHECKBOX_SIZE); Graphics g = Graphics.FromImage(checkMark); // clear everything, transparent g.Clear(Color.Transparent); // draw the checkmark lines using (Pen pen = new Pen(Parent.BackColor, 2)) { g.DrawLines(pen, CheckmarkLine); } return checkMark; } public override bool AutoSize { get { return base.AutoSize; } set { base.AutoSize = value; if (value) { Size = new Size(10, 10); } } } private bool IsMouseInCheckArea() { return ClientRectangle.Contains(MouseLocation); } private bool hovered = false; protected override void OnCreateControl() { base.OnCreateControl(); if (DesignMode) return; MouseState = MouseState.OUT; GotFocus += (sender, AddingNewEventArgs) => { if (Ripple && !hovered) { _hoverAM.StartNewAnimation(AnimationDirection.In, new object[] { Checked }); hovered = true; } }; LostFocus += (sender, args) => { if (Ripple && hovered) { _hoverAM.StartNewAnimation(AnimationDirection.Out, new object[] { Checked }); hovered = false; } }; MouseEnter += (sender, args) => { MouseState = MouseState.HOVER; //if (Ripple && !hovered) //{ // _hoverAM.StartNewAnimation(AnimationDirection.In, new object[] { Checked }); // hovered = true; //} }; MouseLeave += (sender, args) => { MouseLocation = new Point(-1, -1); MouseState = MouseState.OUT; //if (Ripple && hovered) //{ // _hoverAM.StartNewAnimation(AnimationDirection.Out, new object[] { Checked }); // hovered = false; //} }; MouseDown += (sender, args) => { MouseState = MouseState.DOWN; if (Ripple) { _rippleAM.SecondaryIncrement = 0; _rippleAM.StartNewAnimation(AnimationDirection.InOutIn, new object[] { Checked }); } }; KeyDown += (sender, args) => { if (Ripple && (args.KeyCode == Keys.Space) && _rippleAM.GetAnimationCount() == 0) { _rippleAM.SecondaryIncrement = 0; _rippleAM.StartNewAnimation(AnimationDirection.InOutIn, new object[] { Checked }); } }; MouseUp += (sender, args) => { if (Ripple) { MouseState = MouseState.HOVER; _rippleAM.SecondaryIncrement = 0.08; _hoverAM.StartNewAnimation(AnimationDirection.Out, new object[] { Checked }); hovered = false; } }; KeyUp += (sender, args) => { if (Ripple && (args.KeyCode == Keys.Space)) { MouseState = MouseState.HOVER; _rippleAM.SecondaryIncrement = 0.08; } }; MouseMove += (sender, args) => { MouseLocation = args.Location; Cursor = IsMouseInCheckArea() ? Cursors.Hand : Cursors.Default; }; } } }
36.571865
186
0.525295
[ "MIT" ]
lukaszmn/MaterialSkin
MaterialSkin/Controls/MaterialCheckBox.cs
11,961
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InspectRotation : MonoBehaviour { [SerializeField] float eulerAngX; [SerializeField] float eulerAngY; [SerializeField] float eulerAngZ; void Update() { eulerAngX = transform.localEulerAngles.x; eulerAngY = transform.localEulerAngles.y; eulerAngZ = transform.localEulerAngles.z; } }
19.173913
49
0.69161
[ "MIT" ]
DiarKarim/PrendoSim_2
PrendoSim/Assets/_Scripts/InspectRotation.cs
443
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("TinyImage")] [assembly: AssemblyDescription("Compresses images through www.tinify.com API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TinyImage")] [assembly: AssemblyCopyright("Copyright © 2022")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
43.462963
98
0.707712
[ "MIT" ]
bkarvelas/tiny-image
TinyImage/TinyImage/Properties/AssemblyInfo.cs
2,350
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.AzureNextGen.Batch.V20190801.Inputs { public sealed class AutoUserSpecificationArgs : Pulumi.ResourceArgs { /// <summary> /// The default value is nonAdmin. /// </summary> [Input("elevationLevel")] public Input<string>? ElevationLevel { get; set; } /// <summary> /// The default value is Pool. If the pool is running Windows a value of Task should be specified if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should be accessible by start tasks. /// </summary> [Input("scope")] public Input<string>? Scope { get; set; } public AutoUserSpecificationArgs() { } } }
37.125
380
0.680976
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Batch/V20190801/Inputs/AutoUserSpecificationArgs.cs
1,188
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DataSourceControlsHW { public partial class Continents : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void OnContextCreating(object sender, Microsoft.AspNet.EntityDataSource.EntityDataSourceContextCreatingEventArgs e) { } } }
21.909091
133
0.709544
[ "MIT" ]
shopOFF/Telerik-Academy-Courses
ASP.NET-Web-Forms/06. ASP.NET-DataSource-Controls/Homework/DataSourceControlsHW/DataSourceControlsHW/Continents.aspx.cs
484
C#
using System; namespace ResidualNet.Timeline { /// <summary> /// Represents the interface to a value interval that has the lower and upper contiguous interval boundaries. /// </summary> public interface IInterval<T> : IIntervalLower<T>, IIntervalUpper<T> where T : struct, IComparable<T> { /// <summary> /// Checks if the contiguous interval value lies within the contiguous interval. /// </summary> /// <param name="value">The contiguous interval value to check against.</param> /// <returns>True if contiguous value is within the contiguous interval; otherwise, false.</returns> bool IsWithin(T value); /// <summary> /// Checks if the contiguous interval value lies within the contiguous interval considering that null is a -infinity. /// </summary> /// <param name="value">The contiguous interval value to check against.</param> /// <returns>True if contiguous value is within the contiguous interval; otherwise, false.</returns> bool IsWithinLower(T? value); /// <summary> /// Checks if the contiguous interval value lies within the contiguous interval considering that null is a +infinity. /// </summary> /// <param name="value">The contiguous interval value to check against.</param> /// <returns>True if contiguous value is within the contiguous interval; otherwise, false.</returns> bool IsWithinUpper(T? value); } }
47
125
0.660239
[ "MIT" ]
daerhiel/Residual.Net
ResidualNet.Containers/ResidualNet.Containers/Timeline/Interfaces/IInterval.cs
1,506
C#
//------------------------------------------------------------------------------ // <copyright file="WmlImageAdapter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Security.Permissions; #if COMPILING_FOR_SHIPPED_SOURCE namespace System.Web.UI.MobileControls.ShippedAdapterSource #else namespace System.Web.UI.MobileControls.Adapters #endif { /* * WmlImageAdapter class. */ /// <include file='doc\WmlImageAdapter.uex' path='docs/doc[@for="WmlImageAdapter"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class WmlImageAdapter : WmlControlAdapter { /// <include file='doc\WmlImageAdapter.uex' path='docs/doc[@for="WmlImageAdapter.Control"]/*' /> protected new Image Control { get { return (Image)base.Control; } } /// <include file='doc\WmlImageAdapter.uex' path='docs/doc[@for="WmlImageAdapter.Render"]/*' /> public override void Render(WmlMobileTextWriter writer) { String source = Control.ImageUrl; String target = Control.NavigateUrl; String text = Control.AlternateText; bool breakAfterContents = Control.BreakAfter; String softkeyLabel = Control.SoftkeyLabel; bool implicitSoftkeyLabel = false; if (softkeyLabel.Length == 0) { implicitSoftkeyLabel = true; softkeyLabel = text; } writer.EnterLayout(Style); if (!String.IsNullOrEmpty(target)) { RenderBeginLink(writer, target, softkeyLabel, implicitSoftkeyLabel, true); breakAfterContents = false; } if (String.IsNullOrEmpty(source)) { // Just write the alternate as text writer.RenderText(text, breakAfterContents); } else { String localSource; if (source.StartsWith(Constants.SymbolProtocol, StringComparison.Ordinal)) { // src is required according to WML localSource = source.Substring(Constants.SymbolProtocol.Length); source = String.Empty; } else { localSource = null; // AUI 3652 source = Control.ResolveUrl(source); writer.AddResource(source); } writer.RenderImage(source, localSource, text, breakAfterContents); } if (!String.IsNullOrEmpty(target)) { RenderEndLink(writer, target, Control.BreakAfter); } writer.ExitLayout(Style); } } }
37.304348
219
0.543124
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/mit/System/Web/UI/MobileControls/Adapters/WmlImageAdapter.cs
3,432
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MishMash.Data; namespace MishMash.Data.Migrations { [DbContext(typeof(MishMashContext))] partial class MishMashContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("MishMash.Models.Channel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description"); b.Property<string>("Name"); b.Property<string>("Tags"); b.Property<int>("Type"); b.HasKey("Id"); b.ToTable("Channels"); }); modelBuilder.Entity("MishMash.Models.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Email"); b.Property<string>("Password"); b.Property<int>("Role"); b.Property<string>("Username"); b.HasKey("Id"); b.ToTable("Users"); }); modelBuilder.Entity("MishMash.Models.UserChannel", b => { b.Property<int>("ChannelId"); b.Property<int>("UserId"); b.HasKey("ChannelId", "UserId"); b.HasIndex("UserId"); b.ToTable("UsersChannels"); }); modelBuilder.Entity("MishMash.Models.UserChannel", b => { b.HasOne("MishMash.Models.Channel", "Channel") .WithMany("Followers") .HasForeignKey("ChannelId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("MishMash.Models.User", "User") .WithMany("FollowedChannels") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.340909
125
0.523517
[ "MIT" ]
kriss98/C-Projects
SIS/MishMash.Data/Migrations/MishMashContextModelSnapshot.cs
2,936
C#
namespace Gu.Reactive.Demo.Converters { using System; using System.Globalization; using System.Windows.Data; using System.Windows.Markup; using System.Windows.Media; [MarkupExtensionReturnType(typeof(BooleanToBrushConverter))] [ValueConversion(typeof(bool), typeof(Brush))] public class BooleanToBrushConverter : MarkupExtension, IValueConverter { public Brush? WhenTrue { get; set; } public Brush? WhenFalse { get; set; } public Brush? WhenNull { get; set; } public object? Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value switch { true => this.WhenTrue, false => this.WhenFalse, null => this.WhenNull, _ => throw new ArgumentException("Expected bool?", nameof(value)), }; } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } public override object ProvideValue(IServiceProvider serviceProvider) => this; } }
31.210526
112
0.629005
[ "MIT" ]
GuOrg/Gu.Reactive
Gu.Reactive.Demo/Converters/BooleanToBrushConverter.cs
1,188
C#
using UnityEngine; public class TransformInterface : MonoBehaviour { public Transform value; public Vector3 position => value.position; }
18.375
47
0.761905
[ "MIT" ]
Will9371/Character-Template
Assets/Playcraft/Quality of Life/Type Based/Transform/TransformInterface.cs
147
C#
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace org.camunda.bpm.engine.test.bpmn.parse { using BpmnParse = org.camunda.bpm.engine.impl.bpmn.parser.BpmnParse; using ProcessDefinitionEntity = org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity; using ProcessInstanceWithVariablesImpl = org.camunda.bpm.engine.impl.persistence.entity.ProcessInstanceWithVariablesImpl; using ActivityImpl = org.camunda.bpm.engine.impl.pvm.process.ActivityImpl; using PluggableProcessEngineTestCase = org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; using ProcessInstance = org.camunda.bpm.engine.runtime.ProcessInstance; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.camunda.bpm.engine.impl.bpmn.parser.DefaultFailedJobParseListener.FAILED_JOB_CONFIGURATION; public class FoxFailedJobParseListenerTest : PluggableProcessEngineTestCase { [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.testUserTask.bpmn20.xml" })] public virtual void testUserTaskParseFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("asyncUserTaskFailedJobRetryTimeCycle"); ActivityImpl userTask = findActivity(pi, "task"); checkFoxFailedJobConfig(userTask); } [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/CamundaFailedJobParseListenerTest.testUserTask.bpmn20.xml" })] public virtual void testUserTaskParseFailedJobRetryTimeCycleInActivitiNamespace() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("asyncUserTaskFailedJobRetryTimeCycle"); ActivityImpl userTask = findActivity(pi, "task"); checkFoxFailedJobConfig(userTask); } [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.testUserTask.bpmn20.xml" })] public virtual void testNotAsyncUserTaskParseFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("notAsyncUserTaskFailedJobRetryTimeCycle"); ActivityImpl userTask = findActivity(pi, "notAsyncTask"); checkNotContainingFoxFailedJobConfig(userTask); } [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.testUserTask.bpmn20.xml" })] public virtual void testAsyncUserTaskButWithoutParseFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("asyncUserTaskButWithoutFailedJobRetryTimeCycle"); ActivityImpl userTask = findActivity(pi, "asyncTaskWithoutFailedJobRetryTimeCycle"); checkNotContainingFoxFailedJobConfig(userTask); } [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.testTimer.bpmn20.xml" })] public virtual void testTimerBoundaryEventWithFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("boundaryEventWithFailedJobRetryTimeCycle"); ActivityImpl boundaryActivity = findActivity(pi, "boundaryTimerWithFailedJobRetryTimeCycle"); checkFoxFailedJobConfig(boundaryActivity); } [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.testTimer.bpmn20.xml" })] public virtual void testTimerBoundaryEventWithoutFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("boundaryEventWithoutFailedJobRetryTimeCycle"); ActivityImpl boundaryActivity = findActivity(pi, "boundaryTimerWithoutFailedJobRetryTimeCycle"); checkNotContainingFoxFailedJobConfig(boundaryActivity); } [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.testTimer.bpmn20.xml" })] public virtual void testTimerStartEventWithFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("startEventWithFailedJobRetryTimeCycle"); ActivityImpl startEvent = findActivity(pi, "startEventFailedJobRetryTimeCycle"); checkFoxFailedJobConfig(startEvent); } [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.testTimer.bpmn20.xml" })] public virtual void testIntermediateCatchTimerEventWithFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("intermediateTimerEventWithFailedJobRetryTimeCycle"); ActivityImpl timer = findActivity(pi, "timerEventWithFailedJobRetryTimeCycle"); checkFoxFailedJobConfig(timer); } [Deployment(resources : { "org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.testSignal.bpmn20.xml" })] public virtual void testSignalEventWithFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("signalEventWithFailedJobRetryTimeCycle"); ActivityImpl signal = findActivity(pi, "signalWithFailedJobRetryTimeCycle"); checkFoxFailedJobConfig(signal); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Deployment public void testMultiInstanceBodyWithFailedJobRetryTimeCycle() public virtual void testMultiInstanceBodyWithFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("process"); ActivityImpl miBody = findMultiInstanceBody(pi, "task"); checkFoxFailedJobConfig(miBody); ActivityImpl innerActivity = findActivity(pi, "task"); checkNotContainingFoxFailedJobConfig(innerActivity); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Deployment public void testInnerMultiInstanceActivityWithFailedJobRetryTimeCycle() public virtual void testInnerMultiInstanceActivityWithFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("process"); ActivityImpl miBody = findMultiInstanceBody(pi, "task"); checkNotContainingFoxFailedJobConfig(miBody); ActivityImpl innerActivity = findActivity(pi, "task"); checkFoxFailedJobConfig(innerActivity); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Deployment public void testMultiInstanceBodyAndInnerActivityWithFailedJobRetryTimeCycle() public virtual void testMultiInstanceBodyAndInnerActivityWithFailedJobRetryTimeCycle() { ProcessInstance pi = runtimeService.startProcessInstanceByKey("process"); ActivityImpl miBody = findMultiInstanceBody(pi, "task"); checkFoxFailedJobConfig(miBody); ActivityImpl innerActivity = findActivity(pi, "task"); checkFoxFailedJobConfig(innerActivity); } protected internal virtual ActivityImpl findActivity(ProcessInstance pi, string activityId) { ProcessInstanceWithVariablesImpl entity = (ProcessInstanceWithVariablesImpl) pi; ProcessDefinitionEntity processDefEntity = entity.ExecutionEntity.ProcessDefinition; assertNotNull(processDefEntity); ActivityImpl activity = processDefEntity.findActivity(activityId); assertNotNull(activity); return activity; } protected internal virtual ActivityImpl findMultiInstanceBody(ProcessInstance pi, string activityId) { return findActivity(pi, activityId + BpmnParse.MULTI_INSTANCE_BODY_ID_SUFFIX); } protected internal virtual void checkFoxFailedJobConfig(ActivityImpl activity) { assertNotNull(activity); assertTrue(activity.Properties.contains(FAILED_JOB_CONFIGURATION)); object value = activity.Properties.get(FAILED_JOB_CONFIGURATION).RetryIntervals.get(0); assertEquals("R5/PT5M", value); } protected internal virtual void checkNotContainingFoxFailedJobConfig(ActivityImpl activity) { assertFalse(activity.Properties.contains(FAILED_JOB_CONFIGURATION)); } } }
45.994624
131
0.812274
[ "Apache-2.0" ]
luizfbicalho/Camunda.NET
camunda-bpm-platform-net/engine/src/test/java/org/camunda/bpm/engine/test/bpmn/parse/FoxFailedJobParseListenerTest.cs
8,557
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NPoco; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Core.Configuration; using Umbraco.Core.Scoping; namespace Umbraco.Core.Sync { /// <summary> /// An <see cref="IServerMessenger"/> that works by storing messages in the database. /// </summary> // // this messenger writes ALL instructions to the database, // but only processes instructions coming from remote servers, // thus ensuring that instructions run only once // public class DatabaseServerMessenger : ServerMessengerBase { private readonly IRuntimeState _runtime; private readonly ManualResetEvent _syncIdle; private readonly object _locko = new object(); private readonly IProfilingLogger _profilingLogger; private readonly ISqlContext _sqlContext; private readonly Lazy<string> _distCacheFilePath; private int _lastId = -1; private DateTime _lastSync; private DateTime _lastPruned; private bool _initialized; private bool _syncing; private bool _released; public DatabaseServerMessengerOptions Options { get; } public DatabaseServerMessenger( IRuntimeState runtime, IScopeProvider scopeProvider, ISqlContext sqlContext, IProfilingLogger proflog, IGlobalSettings globalSettings, bool distributedEnabled, DatabaseServerMessengerOptions options) : base(distributedEnabled) { ScopeProvider = scopeProvider ?? throw new ArgumentNullException(nameof(scopeProvider)); _sqlContext = sqlContext; _runtime = runtime; _profilingLogger = proflog ?? throw new ArgumentNullException(nameof(proflog)); Logger = proflog; Options = options ?? throw new ArgumentNullException(nameof(options)); _lastPruned = _lastSync = DateTime.UtcNow; _syncIdle = new ManualResetEvent(true); _distCacheFilePath = new Lazy<string>(() => GetDistCacheFilePath(globalSettings)); } protected ILogger Logger { get; } protected IScopeProvider ScopeProvider { get; } protected Sql<ISqlContext> Sql() => _sqlContext.Sql(); private string DistCacheFilePath => _distCacheFilePath.Value; #region Messenger protected override bool RequiresDistributed(ICacheRefresher refresher, MessageType dispatchType) { // we don't care if there's servers listed or not, // if distributed call is enabled we will make the call return _initialized && DistributedEnabled; } protected override void DeliverRemote( ICacheRefresher refresher, MessageType messageType, IEnumerable<object> ids = null, string json = null) { var idsA = ids?.ToArray(); if (GetArrayType(idsA, out var idType) == false) throw new ArgumentException("All items must be of the same type, either int or Guid.", nameof(ids)); var instructions = RefreshInstruction.GetInstructions(refresher, messageType, idsA, idType, json); var dto = new CacheInstructionDto { UtcStamp = DateTime.UtcNow, Instructions = JsonConvert.SerializeObject(instructions, Formatting.None), OriginIdentity = LocalIdentity, InstructionCount = instructions.Sum(x => x.JsonIdCount) }; using (var scope = ScopeProvider.CreateScope()) { scope.Database.Insert(dto); scope.Complete(); } } #endregion #region Sync /// <summary> /// Boots the messenger. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// Callers MUST ensure thread-safety. /// </remarks> protected void Boot() { // weight:10, must release *before* the published snapshot service, because once released // the service will *not* be able to properly handle our notifications anymore const int weight = 10; if (!(_runtime is RuntimeState runtime)) throw new NotSupportedException($"Unsupported IRuntimeState implementation {_runtime.GetType().FullName}, expecting {typeof(RuntimeState).FullName}."); var registered = runtime.MainDom.Register( () => { lock (_locko) { _released = true; // no more syncs } // wait a max of 5 seconds and then return, so that we don't block // the entire MainDom callbacks chain and prevent the AppDomain from // properly releasing MainDom - a timeout here means that one refresher // is taking too much time processing, however when it's done we will // not update lastId and stop everything var idle =_syncIdle.WaitOne(5000); if (idle == false) { Logger.Warn<DatabaseServerMessenger>("The wait lock timed out, application is shutting down. The current instruction batch will be re-processed."); } }, weight); if (registered == false) return; ReadLastSynced(); // get _lastId using (var scope = ScopeProvider.CreateScope()) { EnsureInstructions(scope.Database); // reset _lastId if instructions are missing Initialize(scope.Database); // boot scope.Complete(); } } /// <summary> /// Initializes a server that has never synchronized before. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// Callers MUST ensure thread-safety. /// </remarks> private void Initialize(IUmbracoDatabase database) { lock (_locko) { if (_released) return; var coldboot = false; if (_lastId < 0) // never synced before { // we haven't synced - in this case we aren't going to sync the whole thing, we will assume this is a new // server and it will need to rebuild it's own caches, eg Lucene or the xml cache file. Logger.Warn<DatabaseServerMessenger>("No last synced Id found, this generally means this is a new server/install." + " The server will build its caches and indexes, and then adjust its last synced Id to the latest found in" + " the database and maintain cache updates based on that Id."); coldboot = true; } else { //check for how many instructions there are to process, each row contains a count of the number of instructions contained in each //row so we will sum these numbers to get the actual count. var count = database.ExecuteScalar<int>("SELECT SUM(instructionCount) FROM umbracoCacheInstruction WHERE id > @lastId", new {lastId = _lastId}); if (count > Options.MaxProcessingInstructionCount) { //too many instructions, proceed to cold boot Logger.Warn<DatabaseServerMessenger,int,int>( "The instruction count ({InstructionCount}) exceeds the specified MaxProcessingInstructionCount ({MaxProcessingInstructionCount})." + " The server will skip existing instructions, rebuild its caches and indexes entirely, adjust its last synced Id" + " to the latest found in the database and maintain cache updates based on that Id.", count, Options.MaxProcessingInstructionCount); coldboot = true; } } if (coldboot) { // go get the last id in the db and store it // note: do it BEFORE initializing otherwise some instructions might get lost // when doing it before, some instructions might run twice - not an issue var maxId = database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction"); //if there is a max currently, or if we've never synced if (maxId > 0 || _lastId < 0) SaveLastSynced(maxId); // execute initializing callbacks if (Options.InitializingCallbacks != null) foreach (var callback in Options.InitializingCallbacks) callback(); } _initialized = true; } } /// <summary> /// Synchronize the server (throttled). /// </summary> protected internal void Sync() { lock (_locko) { if (_syncing) return; //Don't continue if we are released if (_released) return; if ((DateTime.UtcNow - _lastSync).TotalSeconds <= Options.ThrottleSeconds) return; //Set our flag and the lock to be in it's original state (i.e. it can be awaited) _syncing = true; _syncIdle.Reset(); _lastSync = DateTime.UtcNow; } try { using (_profilingLogger.DebugDuration<DatabaseServerMessenger>("Syncing from database...")) using (var scope = ScopeProvider.CreateScope()) { ProcessDatabaseInstructions(scope.Database); //Check for pruning throttling if (_released || (DateTime.UtcNow - _lastPruned).TotalSeconds <= Options.PruneThrottleSeconds) { scope.Complete(); return; } _lastPruned = _lastSync; switch (Current.RuntimeState.ServerRole) { case ServerRole.Single: case ServerRole.Master: PruneOldInstructions(scope.Database); break; } scope.Complete(); } } finally { lock (_locko) { //We must reset our flag and signal any waiting locks _syncing = false; } _syncIdle.Set(); } } /// <summary> /// Process instructions from the database. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> /// <returns> /// Returns the number of processed instructions /// </returns> private void ProcessDatabaseInstructions(IUmbracoDatabase database) { // NOTE // we 'could' recurse to ensure that no remaining instructions are pending in the table before proceeding but I don't think that // would be a good idea since instructions could keep getting added and then all other threads will probably get stuck from serving requests // (depending on what the cache refreshers are doing). I think it's best we do the one time check, process them and continue, if there are // pending requests after being processed, they'll just be processed on the next poll. // // TODO: not true if we're running on a background thread, assuming we can? var sql = Sql().SelectAll() .From<CacheInstructionDto>() .Where<CacheInstructionDto>(dto => dto.Id > _lastId) .OrderBy<CacheInstructionDto>(dto => dto.Id); //only retrieve the top 100 (just in case there's tons) // even though MaxProcessingInstructionCount is by default 1000 we still don't want to process that many // rows in one request thread since each row can contain a ton of instructions (until 7.5.5 in which case // a row can only contain MaxProcessingInstructionCount) var topSql = sql.SelectTop(100); // only process instructions coming from a remote server, and ignore instructions coming from // the local server as they've already been processed. We should NOT assume that the sequence of // instructions in the database makes any sense whatsoever, because it's all async. var localIdentity = LocalIdentity; var lastId = 0; //tracks which ones have already been processed to avoid duplicates var processed = new HashSet<RefreshInstruction>(); //It would have been nice to do this in a Query instead of Fetch using a data reader to save // some memory however we cannot do that because inside of this loop the cache refreshers are also // performing some lookups which cannot be done with an active reader open foreach (var dto in database.Fetch<CacheInstructionDto>(topSql)) { //If this flag gets set it means we're shutting down! In this case, we need to exit asap and cannot // continue processing anything otherwise we'll hold up the app domain shutdown if (_released) { break; } if (dto.OriginIdentity == localIdentity) { // just skip that local one but update lastId nevertheless lastId = dto.Id; continue; } // deserialize remote instructions & skip if it fails JArray jsonA; try { jsonA = JsonConvert.DeserializeObject<JArray>(dto.Instructions); } catch (JsonException ex) { Logger.Error<DatabaseServerMessenger,int, string>(ex, "Failed to deserialize instructions ({DtoId}: '{DtoInstructions}').", dto.Id, dto.Instructions); lastId = dto.Id; // skip continue; } var instructionBatch = GetAllInstructions(jsonA); //process as per-normal var success = ProcessDatabaseInstructions(instructionBatch, dto, processed, ref lastId); //if they couldn't be all processed (i.e. we're shutting down) then exit if (success == false) { Logger.Info<DatabaseServerMessenger>("The current batch of instructions was not processed, app is shutting down"); break; } } if (lastId > 0) SaveLastSynced(lastId); } /// <summary> /// Processes the instruction batch and checks for errors /// </summary> /// <param name="instructionBatch"></param> /// <param name="dto"></param> /// <param name="processed"> /// Tracks which instructions have already been processed to avoid duplicates /// </param> /// <param name="lastId"></param> /// <returns> /// returns true if all instructions in the batch were processed, otherwise false if they could not be due to the app being shut down /// </returns> private bool ProcessDatabaseInstructions(IReadOnlyCollection<RefreshInstruction> instructionBatch, CacheInstructionDto dto, HashSet<RefreshInstruction> processed, ref int lastId) { // execute remote instructions & update lastId try { var result = NotifyRefreshers(instructionBatch, processed); if (result) { //if all instructions we're processed, set the last id lastId = dto.Id; } return result; } //catch (ThreadAbortException ex) //{ // //This will occur if the instructions processing is taking too long since this is occurring on a request thread. // // Or possibly if IIS terminates the appdomain. In any case, we should deal with this differently perhaps... //} catch (Exception ex) { Logger.Error<DatabaseServerMessenger,int, string> ( ex, "DISTRIBUTED CACHE IS NOT UPDATED. Failed to execute instructions ({DtoId}: '{DtoInstructions}'). Instruction is being skipped/ignored", dto.Id, dto.Instructions); //we cannot throw here because this invalid instruction will just keep getting processed over and over and errors // will be thrown over and over. The only thing we can do is ignore and move on. lastId = dto.Id; return false; } ////if this is returned it will not be saved //return -1; } /// <summary> /// Remove old instructions from the database /// </summary> /// <remarks> /// Always leave the last (most recent) record in the db table, this is so that not all instructions are removed which would cause /// the site to cold boot if there's been no instruction activity for more than DaysToRetainInstructions. /// See: http://issues.umbraco.org/issue/U4-7643#comment=67-25085 /// </remarks> private void PruneOldInstructions(IUmbracoDatabase database) { var pruneDate = DateTime.UtcNow.AddDays(-Options.DaysToRetainInstructions); // using 2 queries is faster than convoluted joins var maxId = database.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoCacheInstruction;"); var delete = new Sql().Append(@"DELETE FROM umbracoCacheInstruction WHERE utcStamp < @pruneDate AND id < @maxId", new { pruneDate, maxId }); database.Execute(delete); } /// <summary> /// Ensure that the last instruction that was processed is still in the database. /// </summary> /// <remarks> /// If the last instruction is not in the database anymore, then the messenger /// should not try to process any instructions, because some instructions might be lost, /// and it should instead cold-boot. /// However, if the last synced instruction id is '0' and there are '0' records, then this indicates /// that it's a fresh site and no user actions have taken place, in this circumstance we do not want to cold /// boot. See: http://issues.umbraco.org/issue/U4-8627 /// </remarks> private void EnsureInstructions(IUmbracoDatabase database) { if (_lastId == 0) { var sql = Sql().Select("COUNT(*)") .From<CacheInstructionDto>(); var count = database.ExecuteScalar<int>(sql); //if there are instructions but we haven't synced, then a cold boot is necessary if (count > 0) _lastId = -1; } else { var sql = Sql().SelectAll() .From<CacheInstructionDto>() .Where<CacheInstructionDto>(dto => dto.Id == _lastId); var dtos = database.Fetch<CacheInstructionDto>(sql); //if the last synced instruction is not found in the db, then a cold boot is necessary if (dtos.Count == 0) _lastId = -1; } } /// <summary> /// Reads the last-synced id from file into memory. /// </summary> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> private void ReadLastSynced() { if (File.Exists(DistCacheFilePath) == false) return; var content = File.ReadAllText(DistCacheFilePath); if (int.TryParse(content, out var last)) _lastId = last; } /// <summary> /// Updates the in-memory last-synced id and persists it to file. /// </summary> /// <param name="id">The id.</param> /// <remarks> /// Thread safety: this is NOT thread safe. Because it is NOT meant to run multi-threaded. /// </remarks> private void SaveLastSynced(int id) { File.WriteAllText(DistCacheFilePath, id.ToString(CultureInfo.InvariantCulture)); _lastId = id; } /// <summary> /// Gets the unique local identity of the executing AppDomain. /// </summary> /// <remarks> /// <para>It is not only about the "server" (machine name and appDomainappId), but also about /// an AppDomain, within a Process, on that server - because two AppDomains running at the same /// time on the same server (eg during a restart) are, practically, a LB setup.</para> /// <para>Practically, all we really need is the guid, the other infos are here for information /// and debugging purposes.</para> /// </remarks> protected static readonly string LocalIdentity = NetworkHelper.MachineName // eg DOMAIN\SERVER + "/" + HttpRuntime.AppDomainAppId // eg /LM/S3SVC/11/ROOT + " [P" + Process.GetCurrentProcess().Id // eg 1234 + "/D" + AppDomain.CurrentDomain.Id // eg 22 + "] " + Guid.NewGuid().ToString("N").ToUpper(); // make it truly unique private string GetDistCacheFilePath(IGlobalSettings globalSettings) { var fileName = HttpRuntime.AppDomainAppId.ReplaceNonAlphanumericChars(string.Empty) + "-lastsynced.txt"; var distCacheFilePath = Path.Combine(globalSettings.LocalTempPath, "DistCache", fileName); //ensure the folder exists var folder = Path.GetDirectoryName(distCacheFilePath); if (folder == null) throw new InvalidOperationException("The folder could not be determined for the file " + distCacheFilePath); if (Directory.Exists(folder) == false) Directory.CreateDirectory(folder); return distCacheFilePath; } #endregion #region Notify refreshers private static ICacheRefresher GetRefresher(Guid id) { var refresher = Current.CacheRefreshers[id]; if (refresher == null) throw new InvalidOperationException("Cache refresher with ID \"" + id + "\" does not exist."); return refresher; } private static IJsonCacheRefresher GetJsonRefresher(Guid id) { return GetJsonRefresher(GetRefresher(id)); } private static IJsonCacheRefresher GetJsonRefresher(ICacheRefresher refresher) { var jsonRefresher = refresher as IJsonCacheRefresher; if (jsonRefresher == null) throw new InvalidOperationException("Cache refresher with ID \"" + refresher.RefresherUniqueId + "\" does not implement " + typeof(IJsonCacheRefresher) + "."); return jsonRefresher; } /// <summary> /// Parses out the individual instructions to be processed /// </summary> /// <param name="jsonArray"></param> /// <returns></returns> private static List<RefreshInstruction> GetAllInstructions(IEnumerable<JToken> jsonArray) { var result = new List<RefreshInstruction>(); foreach (var jsonItem in jsonArray) { // could be a JObject in which case we can convert to a RefreshInstruction, // otherwise it could be another JArray - in which case we'll iterate that. var jsonObj = jsonItem as JObject; if (jsonObj != null) { var instruction = jsonObj.ToObject<RefreshInstruction>(); result.Add(instruction); } else { var jsonInnerArray = (JArray)jsonItem; result.AddRange(GetAllInstructions(jsonInnerArray)); // recurse } } return result; } /// <summary> /// executes the instructions against the cache refresher instances /// </summary> /// <param name="instructions"></param> /// <param name="processed"></param> /// <returns> /// Returns true if all instructions were processed, otherwise false if the processing was interrupted (i.e. app shutdown) /// </returns> private bool NotifyRefreshers(IEnumerable<RefreshInstruction> instructions, HashSet<RefreshInstruction> processed) { foreach (var instruction in instructions) { //Check if the app is shutting down, we need to exit if this happens. if (_released) { return false; } //this has already been processed if (processed.Contains(instruction)) continue; switch (instruction.RefreshType) { case RefreshMethodType.RefreshAll: RefreshAll(instruction.RefresherId); break; case RefreshMethodType.RefreshByGuid: RefreshByGuid(instruction.RefresherId, instruction.GuidId); break; case RefreshMethodType.RefreshById: RefreshById(instruction.RefresherId, instruction.IntId); break; case RefreshMethodType.RefreshByIds: RefreshByIds(instruction.RefresherId, instruction.JsonIds); break; case RefreshMethodType.RefreshByJson: RefreshByJson(instruction.RefresherId, instruction.JsonPayload); break; case RefreshMethodType.RemoveById: RemoveById(instruction.RefresherId, instruction.IntId); break; } processed.Add(instruction); } return true; } private static void RefreshAll(Guid uniqueIdentifier) { var refresher = GetRefresher(uniqueIdentifier); refresher.RefreshAll(); } private static void RefreshByGuid(Guid uniqueIdentifier, Guid id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Refresh(id); } private static void RefreshById(Guid uniqueIdentifier, int id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Refresh(id); } private static void RefreshByIds(Guid uniqueIdentifier, string jsonIds) { var refresher = GetRefresher(uniqueIdentifier); foreach (var id in JsonConvert.DeserializeObject<int[]>(jsonIds)) refresher.Refresh(id); } private static void RefreshByJson(Guid uniqueIdentifier, string jsonPayload) { var refresher = GetJsonRefresher(uniqueIdentifier); refresher.Refresh(jsonPayload); } private static void RemoveById(Guid uniqueIdentifier, int id) { var refresher = GetRefresher(uniqueIdentifier); refresher.Remove(id); } #endregion } }
42.101449
186
0.564682
[ "MIT" ]
AaronSadlerUK/Umbraco-CMS
src/Umbraco.Core/Sync/DatabaseServerMessenger.cs
29,050
C#
using System; namespace TMS.Nbrb.Core.Models { /// <summary> /// Currency rate properties. /// </summary> public class Rate { public int Cur_ID { get; set; } public DateTime Date { get; set; } public string Cur_Abbreviation { get; set; } public int Cur_Scale { get; set; } public string Cur_Name { get; set; } public float Cur_OfficialRate { get; set; } } }
24
52
0.578704
[ "MIT" ]
StephenRogonov/TMS-DotNet-Group-2-Rogonov
src/TMS.Nbrb.Core/Models/Rate.cs
434
C#
namespace App1.Models { public class NativeDevice { public string Id { get; set; } public string Name { get; set; } } }
16.555556
40
0.563758
[ "MIT" ]
nhoppasit/BluetoothLE-XF
src/App1/App1/App1/Models/NativeDevice.cs
151
C#
using UnityEngine; public class CookiesTileEvent : TileEvent { private int matchCount; private int requiredAmount; public CookiesTileEvent(int amount) { requiredAmount = amount; } public override void OnMatch() { matchCount++; Debug.Log("Cookies Matched"); } public override bool AchievementCompleted() { if(matchCount == requiredAmount) { return true; } else { return false; } } }
17.387097
47
0.543599
[ "Unlicense" ]
Larsspawn/dilo-chapter-7-matchtree
Assets/Scripts/TileEvent/CookiesTileEvent.cs
541
C#
using Starcounter; using Starcounter.Advanced; using System.Linq; using System; using System.Collections.Generic; namespace Colab.Public { [MenuItem_json] partial class MenuItem : Json { protected override void OnData() { } public Type PageType; public Boolean HasChildrenCB { get { return Children.Count() > 0; } } void Handle(Input.Morph input) { Master.SendCommand(ColabCommand.MORPH_URL, Url); } /// <summary> /// Level is internal to avoid programming bugs /// creating a infinity loopback /// </summary> private int _level = 0; public int Level { get { return _level; } set { _level = value; } } } }
19.116279
60
0.545012
[ "MIT" ]
colabers/Colab.Public.Tools
Colab.Public.Tools/Menu/MenuItem.json.cs
822
C#
using DomainEventsConsole.Interfaces; using DomainEventsConsole.Model; using System; namespace DomainEventsConsole.Events { public class AppointmentConfirmed : IDomainEvent { public Appointment Appointment { get; set; } public DateTime DateOccurred { get; private set; } public AppointmentConfirmed(Appointment appointment, DateTime dateConfirmed) { Appointment = appointment; DateOccurred = dateConfirmed; } public AppointmentConfirmed(Appointment appointment) : this(appointment, DateTime.Now) { } } }
28.809524
94
0.684298
[ "MIT" ]
ardalis/DomainEventsConsole
Events/AppointmentConfirmed.cs
605
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace BindingPathDemos.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23.238095
91
0.637295
[ "Apache-2.0" ]
NoleHealth/xamarin-forms-book-preview-2
Chapter16/BindingPathDemos/BindingPathDemos/BindingPathDemos.iOS/Main.cs
490
C#
using System; using System.Net.Mail; using System.Text.RegularExpressions; namespace YourShares.Domain.Util { public static class ValidateUtils { public static bool IsNullOrEmpty(string data) { return string.IsNullOrEmpty(data); } public static bool IsNullOrEmpty(Guid data) { return data == Guid.Empty; } public static bool IsNumber(string data) { long check = 0; var isNumber = long.TryParse(data, out check); return isNumber; } public static bool IsMail(string emailAddress) { try { var m = new MailAddress(emailAddress); return true; } catch (FormatException) { return false; } } public static bool IsPhone(string phone) { var regex = new Regex(@"^(\+)?[0-9]{8,12}$"); return regex.IsMatch(phone); } } }
22.826087
58
0.504762
[ "MIT" ]
fptu-prm391-group3/YourShares_ServerAPI
YourShares.Domain/Util/ValidateUtils.cs
1,052
C#
#if !NETSTANDARD13 /* * 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 groundstation-2019-05-23.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.GroundStation.Model { /// <summary> /// Base class for ListSatellites paginators. /// </summary> internal sealed partial class ListSatellitesPaginator : IPaginator<ListSatellitesResponse>, IListSatellitesPaginator { private readonly IAmazonGroundStation _client; private readonly ListSatellitesRequest _request; private int _isPaginatorInUse = 0; /// <summary> /// Enumerable containing all full responses for the operation /// </summary> public IPaginatedEnumerable<ListSatellitesResponse> Responses => new PaginatedResponse<ListSatellitesResponse>(this); /// <summary> /// Enumerable containing all of the Satellites /// </summary> public IPaginatedEnumerable<SatelliteListItem> Satellites => new PaginatedResultKeyResponse<ListSatellitesResponse, SatelliteListItem>(this, (i) => i.Satellites); internal ListSatellitesPaginator(IAmazonGroundStation client, ListSatellitesRequest request) { this._client = client; this._request = request; } #if BCL IEnumerable<ListSatellitesResponse> IPaginator<ListSatellitesResponse>.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."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; ListSatellitesResponse response; do { _request.NextToken = nextToken; response = _client.ListSatellites(_request); nextToken = response.NextToken; yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif #if AWS_ASYNC_ENUMERABLES_API async IAsyncEnumerable<ListSatellitesResponse> IPaginator<ListSatellitesResponse>.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."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; ListSatellitesResponse response; do { _request.NextToken = nextToken; response = await _client.ListSatellitesAsync(_request, cancellationToken).ConfigureAwait(false); nextToken = response.NextToken; cancellationToken.ThrowIfCancellationRequested(); yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif } } #endif
39.363636
150
0.666667
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/GroundStation/Generated/Model/_bcl45+netstandard/ListSatellitesPaginator.cs
3,897
C#
// MessageFormat for .NET // - IFormatter.cs // Author: Jeff Hansen <jeff@jeffijoe.com> // Copyright (C) Jeff Hansen 2014. All rights reserved. using System.Collections.Generic; namespace Jeffijoe.MessageFormat.Formatting { /// <summary> /// A Formatter is what transforms a pattern into a string, using the proper arguments. /// </summary> public interface IFormatter { #region Public Properties /// <summary> /// Each Formatter must declare whether or not an input variable is required to exist. /// Most of the time that is the case. /// </summary> bool VariableMustExist { get; } #endregion #region Public Methods and Operators /// <summary> /// Determines whether this instance can format a message based on the specified parameters. /// </summary> /// <param name="request"> /// The parameters. /// </param> /// <returns> /// The <see cref="bool" />. /// </returns> bool CanFormat(FormatterRequest request); /// <summary> /// Using the specified parameters and arguments, a formatted string shall be returned. /// The <see cref="IMessageFormatter" /> is being provided as well, to enable /// nested formatting. This is only called if <see cref="CanFormat" /> returns true. /// The args will always contain the <see cref="FormatterRequest.Variable" />. /// </summary> /// <param name="locale">The locale being used. It is up to the formatter what they do with this information.</param> /// <param name="request">The parameters.</param> /// <param name="args">The arguments.</param> /// <param name="value">The value of <see cref="FormatterRequest.Variable"/> from the given args dictionary. Can be null.</param> /// <param name="messageFormatter">The message formatter.</param> /// <returns> /// The <see cref="string" />. /// </returns> string Format( string locale, FormatterRequest request, IDictionary<string, object?> args, object? value, IMessageFormatter messageFormatter); #endregion } }
37.819672
137
0.594278
[ "MIT" ]
jeffijoe/messageformat.net
src/Jeffijoe.MessageFormat/Formatting/IFormatter.cs
2,309
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 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 ElasticGpus Object /// </summary> public class ElasticGpusUnmarshaller : IUnmarshaller<ElasticGpus, XmlUnmarshallerContext>, IUnmarshaller<ElasticGpus, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ElasticGpus Unmarshall(XmlUnmarshallerContext context) { ElasticGpus unmarshalledObject = new ElasticGpus(); 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("availabilityZone", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AvailabilityZone = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("elasticGpuHealth", targetDepth)) { var unmarshaller = ElasticGpuHealthUnmarshaller.Instance; unmarshalledObject.ElasticGpuHealth = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("elasticGpuId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ElasticGpuId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("elasticGpuState", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ElasticGpuState = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("elasticGpuType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ElasticGpuType = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("instanceId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.InstanceId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("tagSet/item", targetDepth)) { var unmarshaller = TagUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.Tags.Add(item); 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 ElasticGpus Unmarshall(JsonUnmarshallerContext context) { return null; } private static ElasticGpusUnmarshaller _instance = new ElasticGpusUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ElasticGpusUnmarshaller Instance { get { return _instance; } } } }
38.865672
146
0.559524
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/ElasticGpusUnmarshaller.cs
5,208
C#
///////////////////////////////////////////////////////////////////////////////////////////////// // // IL2C - A translator for ECMA-335 CIL/MSIL to C language. // Copyright (c) 2016-2019 Kouji Matsui (@kozy_kekyo, @kekyo2) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ///////////////////////////////////////////////////////////////////////////////////////////////// using System; using Mono.Cecil.Cil; using IL2C.Translators; using IL2C.Metadata; namespace IL2C.ILConverters { internal static class LdelemConverterUtilities { public static ExpressionEmitter Prepare( Func<ITypeInformation, bool> validateElementType, Func<ITypeInformation, ITypeInformation> extractElementType, bool isByReference, DecodeContext decodeContext) { // ECMA-335 III.4.8 ldelem.<type> - load an element of an array var siIndex = decodeContext.PopStack(); if (!(siIndex.TargetType.IsInt32StackFriendlyType || siIndex.TargetType.IsIntPtrStackFriendlyType)) { throw new InvalidProgramSequenceException( "Invalid index type: Location={0}, StackType={1}", decodeContext.CurrentCode.RawLocation, siIndex.TargetType.FriendlyName); } var siArray = decodeContext.PopStack(); if (!(siArray.TargetType.IsArray && validateElementType(siArray.TargetType.ElementType))) { throw new InvalidProgramSequenceException( "Invalid array element type: Location={0}, StackType={1}", decodeContext.CurrentCode.RawLocation, siArray.TargetType.FriendlyName); } var elementType = extractElementType(siArray.TargetType); var symbol = decodeContext.PushStack(elementType); return (extractContext, _) => { var expression = extractContext.GetRightExpression( elementType, siArray.TargetType.ElementType, string.Format("il2c_array_item{0}({1}, {2}, {3})", isByReference ? "ptr" : string.Empty, extractContext.GetSymbolName(siArray), siArray.TargetType.ElementType.CLanguageTypeName, extractContext.GetSymbolName(siIndex))); if (expression == null) { throw new InvalidProgramSequenceException( "Invalid target type: Location={0}, StackType={1}, TargetType={2}", decodeContext.CurrentCode.RawLocation, siArray.TargetType.FriendlyName, elementType.FriendlyName); } return new[] { string.Format( "{0} = {1}", extractContext.GetSymbolName(symbol), expression) }; }; } public static ExpressionEmitter Prepare( Func<ITypeInformation, bool> validateElementType, ITypeInformation elementType, bool isByReference, DecodeContext decodeContext) { return Prepare(validateElementType, _ => elementType, isByReference, decodeContext); } } internal sealed class Ldelem_i1Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_I1; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsInt32StackFriendlyType, decodeContext.PrepareContext.MetadataContext.SByteType, false, decodeContext); } } internal sealed class Ldelem_i2Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_I2; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsInt32StackFriendlyType, decodeContext.PrepareContext.MetadataContext.Int16Type, false, decodeContext); } } internal sealed class Ldelem_i4Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_I4; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsInt32StackFriendlyType, decodeContext.PrepareContext.MetadataContext.Int32Type, false, decodeContext); } } internal sealed class Ldelem_i8Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_I8; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsInt64StackFriendlyType, decodeContext.PrepareContext.MetadataContext.Int64Type, false, decodeContext); } } internal sealed class Ldelem_u1Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_U1; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsInt32StackFriendlyType, decodeContext.PrepareContext.MetadataContext.ByteType, false, decodeContext); } } internal sealed class Ldelem_u2Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_U2; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsInt32StackFriendlyType, decodeContext.PrepareContext.MetadataContext.UInt16Type, false, decodeContext); } } internal sealed class Ldelem_u4Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_U4; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsInt32StackFriendlyType, decodeContext.PrepareContext.MetadataContext.UInt32Type, false, decodeContext); } } internal sealed class Ldelem_r8Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_R8; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsFloatStackFriendlyType, decodeContext.PrepareContext.MetadataContext.DoubleType, false, decodeContext); } } internal sealed class Ldelem_r4Converter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_R4; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsFloatStackFriendlyType, decodeContext.PrepareContext.MetadataContext.SingleType, false, decodeContext); } } internal sealed class Ldelem_refConverter : InlineNoneConverter { public override OpCode OpCode => OpCodes.Ldelem_Ref; public override ExpressionEmitter Prepare(DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => elementType.IsReferenceType, arrayType => arrayType.ElementType, false, decodeContext); } } internal sealed class LdelemaConverter : InlineTypeConverter { public override OpCode OpCode => OpCodes.Ldelema; public override ExpressionEmitter Prepare(ITypeInformation operand, DecodeContext decodeContext) { return LdelemConverterUtilities.Prepare( elementType => operand.IsAssignableFrom(elementType), operand.MakeByReference(), true, decodeContext); } } }
36.89243
111
0.606587
[ "Apache-2.0" ]
am11/IL2C
IL2C.Core/ILConveters/LdelemConverters.cs
9,262
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; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.Win32; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Serializes options marked with <see cref="LocalUserProfileStorageLocation"/> to the local hive-specific registry. /// </summary> internal sealed class LocalUserRegistryOptionPersister : IOptionPersister { /// <summary> /// An object to gate access to <see cref="_registryKey"/>. /// </summary> private readonly object _gate = new(); private readonly RegistryKey _registryKey; public LocalUserRegistryOptionPersister(IThreadingContext threadingContext, IServiceProvider serviceProvider) { // Starting with Dev16, the ILocalRegistry service is expected to be free-threaded, and aquiring it from the // global service provider is expected to complete without any UI thread marshaling requirements. However, // since none of this is publicly documented, we keep this assertion for maximum compatibility assurance. // https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.vsregistry.registryroot // https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.ilocalregistry // https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.slocalregistry threadingContext.ThrowIfNotOnUIThread(); _registryKey = VSRegistry.RegistryRoot(serviceProvider, __VsLocalRegistryType.RegType_UserSettings, writable: true); } private static bool TryGetKeyPathAndName(IOption option, out string path, out string key) { var serialization = option.StorageLocations.OfType<LocalUserProfileStorageLocation>().SingleOrDefault(); if (serialization == null) { path = null; key = null; return false; } else { // We'll just use the filesystem APIs to decompose this path = Path.GetDirectoryName(serialization.KeyName); key = Path.GetFileName(serialization.KeyName); return true; } } bool IOptionPersister.TryFetch(OptionKey optionKey, out object value) { if (!TryGetKeyPathAndName(optionKey.Option, out var path, out var key)) { value = null; return false; } lock (_gate) { using var subKey = _registryKey.OpenSubKey(path); if (subKey == null) { value = null; return false; } // Options that are of type bool have to be serialized as integers if (optionKey.Option.Type == typeof(bool)) { value = subKey.GetValue(key, defaultValue: (bool)optionKey.Option.DefaultValue ? 1 : 0).Equals(1); return true; } else if (optionKey.Option.Type == typeof(long)) { var untypedValue = subKey.GetValue(key, defaultValue: optionKey.Option.DefaultValue); switch (untypedValue) { case string stringValue: { // Due to a previous bug we were accidentally serializing longs as strings. // Gracefully convert those back. var suceeded = long.TryParse(stringValue, out var longValue); value = longValue; return suceeded; } case long longValue: value = longValue; return true; } } else if (optionKey.Option.Type == typeof(int)) { var untypedValue = subKey.GetValue(key, defaultValue: optionKey.Option.DefaultValue); switch (untypedValue) { case string stringValue: { // Due to a previous bug we were accidentally serializing ints as strings. // Gracefully convert those back. var suceeded = int.TryParse(stringValue, out var intValue); value = intValue; return suceeded; } case int intValue: value = intValue; return true; } } else { // Otherwise we can just store normally value = subKey.GetValue(key, defaultValue: optionKey.Option.DefaultValue); return true; } } value = null; return false; } bool IOptionPersister.TryPersist(OptionKey optionKey, object value) { if (_registryKey == null) { throw new InvalidOperationException(); } if (!TryGetKeyPathAndName(optionKey.Option, out var path, out var key)) { return false; } lock (_gate) { using var subKey = _registryKey.CreateSubKey(path); // Options that are of type bool have to be serialized as integers if (optionKey.Option.Type == typeof(bool)) { subKey.SetValue(key, (bool)value ? 1 : 0, RegistryValueKind.DWord); return true; } else if (optionKey.Option.Type == typeof(long)) { subKey.SetValue(key, value, RegistryValueKind.QWord); return true; } else if (optionKey.Option.Type.IsEnum) { // If the enum is larger than an int, store as a QWord if (Marshal.SizeOf(Enum.GetUnderlyingType(optionKey.Option.Type)) > Marshal.SizeOf(typeof(int))) { subKey.SetValue(key, (long)value, RegistryValueKind.QWord); } else { subKey.SetValue(key, (int)value, RegistryValueKind.DWord); } return true; } else { subKey.SetValue(key, value); return true; } } } } }
40.362162
128
0.51828
[ "MIT" ]
333fred/roslyn
src/VisualStudio/Core/Def/Implementation/Options/LocalUserRegistryOptionPersister.cs
7,469
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 sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SageMaker.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SageMaker.Model.Internal.MarshallTransformations { /// <summary> /// EnableSagemakerServicecatalogPortfolio Request Marshaller /// </summary> public class EnableSagemakerServicecatalogPortfolioRequestMarshaller : IMarshaller<IRequest, EnableSagemakerServicecatalogPortfolioRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((EnableSagemakerServicecatalogPortfolioRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(EnableSagemakerServicecatalogPortfolioRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SageMaker"); string target = "SageMaker.EnableSagemakerServicecatalogPortfolio"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-07-24"; request.HttpMethod = "POST"; request.ResourcePath = "/"; var content = "{}"; request.Content = System.Text.Encoding.UTF8.GetBytes(content); return request; } private static EnableSagemakerServicecatalogPortfolioRequestMarshaller _instance = new EnableSagemakerServicecatalogPortfolioRequestMarshaller(); internal static EnableSagemakerServicecatalogPortfolioRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static EnableSagemakerServicecatalogPortfolioRequestMarshaller Instance { get { return _instance; } } } }
36.595506
191
0.671477
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/EnableSagemakerServicecatalogPortfolioRequestMarshaller.cs
3,257
C#
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.AmazonSqsTransport.Contexts { using System; using System.Threading; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SQS; using GreenPipes; using Topology; using Transport; public class SharedConnectionContext : ConnectionContext { readonly CancellationToken _cancellationToken; readonly ConnectionContext _context; public SharedConnectionContext(ConnectionContext context, CancellationToken cancellationToken) { _context = context; _cancellationToken = cancellationToken; } CancellationToken PipeContext.CancellationToken => _cancellationToken; bool PipeContext.HasPayloadType(Type contextType) { return _context.HasPayloadType(contextType); } bool PipeContext.TryGetPayload<TPayload>(out TPayload payload) { return _context.TryGetPayload(out payload); } TPayload PipeContext.GetOrAddPayload<TPayload>(PayloadFactory<TPayload> payloadFactory) { return _context.GetOrAddPayload(payloadFactory); } T PipeContext.AddOrUpdatePayload<T>(PayloadFactory<T> addFactory, UpdatePayloadFactory<T> updateFactory) { return _context.AddOrUpdatePayload(addFactory, updateFactory); } IConnection ConnectionContext.Connection => _context.Connection; public Uri HostAddress => _context.HostAddress; public IAmazonSqsHostTopology Topology => _context.Topology; Task<IAmazonSQS> ConnectionContext.CreateAmazonSqs() { return _context.CreateAmazonSqs(); } Task<IAmazonSimpleNotificationService> ConnectionContext.CreateAmazonSns() { return _context.CreateAmazonSns(); } Task<ClientContext> ConnectionContext.CreateClientContext() { return _context.CreateClientContext(); } } }
34.64557
113
0.671538
[ "ECL-2.0", "Apache-2.0" ]
codigoespagueti/MassTransit
src/MassTransit.AmazonSqsTransport/Contexts/SharedConnectionContext.cs
2,739
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Webscraper.Core.DataTypes; using Excel = Microsoft.Office.Interop.Excel; namespace Webscraper.Core.JobOutput { class ItemExcelFileOutput : IJobOutput<ItemProps> { public string OutputFileDir { get; set; } = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); public string OutputFileName { get; set; } = "ItemExcelFileOutput"; public bool Append { get; set; } = true; public void Write(ItemProps output) { Write(new ItemProps[] {output}); } public void Write(IEnumerable<ItemProps> output) { string filePath = OutputFileDir + "\\" + OutputFileName + ".xls"; Excel.Application app = new Excel.Application(); if (app == null) return; app.DisplayAlerts = false; Excel.Workbook wb; if (Append && File.Exists(filePath)) wb = app.Workbooks.Open(filePath); else wb = app.Workbooks.Add(); try { Excel.Worksheet sheet = (Excel.Worksheet)wb.Sheets.Add(); sheet.Name = "Scraping " + DateTime.Now.ToString("HH-mm-ss dd_mm_yyyy"); List<string> keyList = new List<string>(); foreach (var props in output) keyList.AddRange(props.Keys.ToList().Where(key => !keyList.Contains(key))); for (int i = 1; i <= keyList.Count; i++) sheet.Cells[1, i] = keyList[i - 1]; int row = 2; foreach (var props in output) { foreach (var prop in props) sheet.Cells[row, keyList.IndexOf(prop.Key) + 1] = prop.Value; row++; } app.ActiveWorkbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookNormal); } catch (Exception) { throw; } finally { wb.Close(); app.Quit(); } } } }
23.75
107
0.65731
[ "MIT" ]
denisd3219/webscraper
Webscraper/Core/JobOutput/ItemExcelFileOutput.cs
1,712
C#
using System.Threading.Tasks; using Ansibility.Web.ApiModels; using Ansibility.Web.ApiModels.Enums; using Ansibility.Web.Exceptions; namespace Ansibility.Web.Services { public interface ITaskCenter { /// <summary> /// add task /// </summary> /// <param name="ansibilityTask"></param> /// <returns>taskid</returns> Task<string> AddTaskAsync(AnsibilityTask ansibilityTask); /// <summary> /// /// </summary> /// <param name="taskId"></param> /// <returns></returns> /// <exception cref="TaskNotFoundException"></exception> Task<PlaybookResult> GetResultAsync(string taskId); /// <summary> /// /// </summary> /// <param name="taskId"></param> /// <returns></returns> /// <exception cref="TaskNotFoundException"></exception> Task<TaskState> GetStateAsync(string taskId); } }
28.69697
65
0.581837
[ "MIT" ]
newbe36524/Ansibility
src/Ansibility.Web/Services/ITaskCenter.cs
949
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace FlatFile.Core.Attributes.Extensions { internal static class AttributeUtil { public static T GetAttribute<T>(this FieldInfo field, bool inherited = true) where T : Attribute { return field.GetAttributes<T>(inherited).FirstOrDefault(); } public static T GetAttribute<T>(this MemberInfo member, bool inherited = true) where T : Attribute { return member.GetAttributes<T>(inherited).FirstOrDefault(); } public static T GetAttribute<T>(this PropertyInfo property, bool inherited = true) where T : Attribute { return property.GetAttributes<T>(inherited).FirstOrDefault(); } public static T GetAttribute<T>(this MethodInfo method, bool inherited = true) where T : Attribute { return method.GetAttributes<T>(inherited).FirstOrDefault(); } public static T GetAttribute<T>(this ParameterInfo param, bool inherited = true) where T : Attribute { return param.GetAttributes<T>(inherited).FirstOrDefault(); } public static T GetAttribute<T>(this Type type, bool inherited = true) where T : Attribute { return type.GetAttributes<T>(inherited).FirstOrDefault(); } public static IEnumerable<T> GetAttributes<T>(this MemberInfo member, bool inherited = true) where T : Attribute { return (T[]) member.GetCustomAttributes(typeof (T), inherited); } public static IEnumerable<T> GetAttributes<T>(this PropertyInfo property, bool inherited = true) where T : Attribute { return (T[]) property.GetCustomAttributes(typeof (T), inherited); } public static IEnumerable<T> GetAttributes<T>(this FieldInfo field, bool inherited = true) where T : Attribute { return field.GetCustomAttributes(typeof (T), inherited).Cast<T>(); } public static IEnumerable<T> GetAttributes<T>(this MethodInfo method, bool inherited = true) where T : Attribute { return method.GetCustomAttributes(typeof (T), inherited).Cast<T>(); } public static IEnumerable<T> GetAttributes<T>(this ParameterInfo param, bool inherited = true) where T : Attribute { return param.GetCustomAttributes(typeof (T), inherited).Cast<T>(); } public static IEnumerable<T> GetAttributes<T>(this Type type, bool inherited = true) where T : Attribute { return type.GetTypeInfo().GetCustomAttributes(typeof (T), inherited).Cast<T>(); } } }
32.809524
120
0.63643
[ "MIT" ]
juhntao/FlatFile
src/FlatFile.Core.Attributes/Extensions/AttributeUtil.cs
2,758
C#
using CrashNSaneLoadDetector; using LiveSplit.Model; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Windows.Forms; using System.Xml; namespace LiveSplit.UI.Components { public partial class CTRNitroFueledLoadRemoverSettings : UserControl { #region Public Fields public bool AutoSplitterEnabled = false; public bool AutoSplitterDisableOnSkipUntilSplit = false; public bool RemoveFadeouts = false; public bool RemoveFadeins = false; public bool SaveDetectionLog = false; public bool RecordImages = false; public int AverageBlackLevel = -1; public string DetectionLogFolderName = "CTRNitroFueledLoadRemoverLog"; //Number of frames to wait for a change from load -> running and vice versa. public int AutoSplitterJitterToleranceFrames = 8; //If you split manually during "AutoSplitter" mode, I ignore AutoSplitter-splits for 50 frames. (A little less than 2 seconds) //This means that if a split would happen during these frames, it is ignored. public int AutoSplitterManualSplitDelayFrames = 50; #endregion Public Fields #region Private Fields private AutoSplitData autoSplitData = null; private float captureAspectRatioX = 16.0f; private float captureAspectRatioY = 9.0f; private List<string> captureIDs = null; private Size captureSize = new Size(300, 100); private float cropOffsetX = 590.0f; private float cropOffsetY = 434.0f; private bool drawingPreview = false; private List<Control> dynamicAutoSplitterControls; private float featureVectorResolutionX = 1920.0f; private float featureVectorResolutionY = 1080.0f; private ImageCaptureInfo imageCaptureInfo; private Bitmap lastDiagnosticCapture = null; private List<int> lastFeatures = null; private Bitmap lastFullCapture = null; private Bitmap lastFullCroppedCapture = null; private int lastMatchingBins = 0; private LiveSplitState liveSplitState = null; //private string DiagnosticsFolderName = "CrashNSTDiagnostics/"; private int numCaptures = 0; private int numScreens = 1; private Dictionary<string, XmlElement> AllGameAutoSplitSettings; private Bitmap previewImage = null; //-1 -> full screen, otherwise index process list private int processCaptureIndex = -1; private Process[] processList; private int scalingValue = 100; private float scalingValueFloat = 1.0f; private string selectedCaptureID = ""; private Point selectionBottomRight = new Point(0, 0); private Rectangle selectionRectanglePreviewBox; private Point selectionTopLeft = new Point(0, 0); #endregion Private Fields #region Public Constructors private string LoadRemoverDataName = ""; public class Binder : System.Runtime.Serialization.SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { Assembly ass = Assembly.Load(assemblyName); return ass.GetType(typeName); } } private void cmbDatabase_SelectedIndexChanged(object sender, EventArgs e) { LoadRemoverDataName = cmbDatabase.SelectedItem.ToString(); DeserializeAndUpdateDetectorData(); } private void SetComboBoxToStoredDatabase(string database) { for(int item_index = 0; item_index < cmbDatabase.Items.Count; item_index++) { var item = cmbDatabase.Items[item_index]; if (item.ToString() == database) { cmbDatabase.SelectedIndex = item_index; return; } } } private string[] getDatabaseFiles() { return Directory.GetFiles("Components/", "*.ctrnfdata"); } private void DeserializeAndUpdateDetectorData() { DetectorData data = DeserializeDetectorData(LoadRemoverDataName); captureSize = new Size(data.sizeX, data.sizeY); FeatureDetector.numberOfBins = data.numberOfHistogramBins; FeatureDetector.patchSizeX = captureSize.Width / data.numPatchesX; FeatureDetector.patchSizeY = captureSize.Height / data.numPatchesY; int[][] features_temp = data.features.ToArray(); int len_x = features_temp.Length; int len_y = features_temp[0].Length; FeatureDetector.listOfFeatureVectorsEng = new int[len_x, len_y]; for(int x = 0; x < len_x; x++) { for (int y = 0; y < len_y; y++) { FeatureDetector.listOfFeatureVectorsEng[x, y] = features_temp[x][y]; } } } public CTRNitroFueledLoadRemoverSettings(LiveSplitState state) { InitializeComponent(); string[] database_files = getDatabaseFiles(); if(database_files.Length == 0) { MessageBox.Show("Error: Please make sure that at least one .ctrnfdata file exists in the Components directory!", "CTRNF Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } cmbDatabase.Items.Clear(); foreach (string database_file in database_files) { cmbDatabase.Items.Add(database_file); } cmbDatabase.SelectedIndex = 0; //RemoveFadeins = chkRemoveFadeIns.Checked; DeserializeAndUpdateDetectorData(); RemoveFadeouts = chkRemoveTransitions.Checked; RemoveFadeins = chkRemoveTransitions.Checked; SaveDetectionLog = chkSaveDetectionLog.Checked; AllGameAutoSplitSettings = new Dictionary<string, XmlElement>(); dynamicAutoSplitterControls = new List<Control>(); CreateAutoSplitControls(state); liveSplitState = state; initImageCaptureInfo(); //processListComboBox.SelectedIndex = 0; lblVersion.Text = "v" + Assembly.GetExecutingAssembly().GetName().Version.ToString(3); RefreshCaptureWindowList(); //processListComboBox.SelectedIndex = 0; DrawPreview(); } #endregion Public Constructors #region Public Methods public void StoreCaptureImage(string gameName, string category) { System.IO.Directory.CreateDirectory(Path.Combine(DetectionLogFolderName, devToolsCaptureImageText.Text)); string capture_time = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff"); for (int offset_x = -4; offset_x <= 4; offset_x += 2) { for (int offset_y = -4; offset_y <= 4; offset_y += 2) { imageCaptureInfo.cropOffsetY = cropOffsetY + offset_y; imageCaptureInfo.cropOffsetX = cropOffsetX + offset_x; CaptureImageFullPreview(ref imageCaptureInfo, true); string fileName = Path.Combine(DetectionLogFolderName, devToolsCaptureImageText.Text, "CTRNitroFueledLoadRemover_Log_" + capture_time + removeInvalidXMLCharacters(gameName) + "_" + removeInvalidXMLCharacters(category) + "_" + offset_x + "_" + offset_y + ".png"); using (MemoryStream memory = new MemoryStream()) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) { Bitmap capture = CaptureImage(); capture.Save(memory, ImageFormat.Png); byte[] bytes = memory.ToArray(); fs.Write(bytes, 0, bytes.Length); } } } } imageCaptureInfo.cropOffsetY = cropOffsetY; imageCaptureInfo.cropOffsetX = cropOffsetX; CaptureImageFullPreview(ref imageCaptureInfo, true); devToolsCroppedPictureBox.Image = CaptureImage(); } public void SetBlackLevel(int black_level) { AverageBlackLevel = black_level; lblBlackLevel.Text = "Black-Level: " + AverageBlackLevel; } public Bitmap CaptureImage() { Bitmap b = new Bitmap(1, 1); //Full screen capture if (processCaptureIndex < 0) { Screen selected_screen = Screen.AllScreens[-processCaptureIndex - 1]; Rectangle screenRect = selected_screen.Bounds; screenRect.Width = (int)(screenRect.Width * scalingValueFloat); screenRect.Height = (int)(screenRect.Height * scalingValueFloat); Point screenCenter = new Point(screenRect.Width / 2, screenRect.Height / 2); //Change size according to selected crop screenRect.Width = (int)(imageCaptureInfo.crop_coordinate_right - imageCaptureInfo.crop_coordinate_left); screenRect.Height = (int)(imageCaptureInfo.crop_coordinate_bottom - imageCaptureInfo.crop_coordinate_top); //Compute crop coordinates and width/ height based on resoution ImageCapture.SizeAdjustedCropAndOffset(screenRect.Width, screenRect.Height, ref imageCaptureInfo); //Adjust for crop offset imageCaptureInfo.center_of_frame_x += imageCaptureInfo.crop_coordinate_left; imageCaptureInfo.center_of_frame_y += imageCaptureInfo.crop_coordinate_top; //Adjust for selected screen offset imageCaptureInfo.center_of_frame_x += selected_screen.Bounds.X; imageCaptureInfo.center_of_frame_y += selected_screen.Bounds.Y; b = ImageCapture.CaptureFromDisplay(ref imageCaptureInfo); } else { IntPtr handle = new IntPtr(0); if (processCaptureIndex >= processList.Length) return b; if (processCaptureIndex != -1) { handle = processList[processCaptureIndex].MainWindowHandle; } //Capture from specific process processList[processCaptureIndex].Refresh(); if ((int)handle == 0) return b; b = ImageCapture.PrintWindow(handle, ref imageCaptureInfo, useCrop: true); } return b; } public Bitmap CaptureImageFullPreview(ref ImageCaptureInfo imageCaptureInfo, bool useCrop = false) { Bitmap b = new Bitmap(1, 1); //Full screen capture if (processCaptureIndex < 0) { Screen selected_screen = Screen.AllScreens[-processCaptureIndex - 1]; Rectangle screenRect = selected_screen.Bounds; screenRect.Width = (int)(screenRect.Width * scalingValueFloat); screenRect.Height = (int)(screenRect.Height * scalingValueFloat); Point screenCenter = new Point((int)(screenRect.Width / 2.0f), (int)(screenRect.Height / 2.0f)); if (useCrop) { //Change size according to selected crop screenRect.Width = (int)(imageCaptureInfo.crop_coordinate_right - imageCaptureInfo.crop_coordinate_left); screenRect.Height = (int)(imageCaptureInfo.crop_coordinate_bottom - imageCaptureInfo.crop_coordinate_top); } //Compute crop coordinates and width/ height based on resoution ImageCapture.SizeAdjustedCropAndOffset(screenRect.Width, screenRect.Height, ref imageCaptureInfo); imageCaptureInfo.actual_crop_size_x = 2 * imageCaptureInfo.center_of_frame_x; imageCaptureInfo.actual_crop_size_y = 2 * imageCaptureInfo.center_of_frame_y; if (useCrop) { //Adjust for crop offset imageCaptureInfo.center_of_frame_x += imageCaptureInfo.crop_coordinate_left; imageCaptureInfo.center_of_frame_y += imageCaptureInfo.crop_coordinate_top; } //Adjust for selected screen offset imageCaptureInfo.center_of_frame_x += selected_screen.Bounds.X; imageCaptureInfo.center_of_frame_y += selected_screen.Bounds.Y; imageCaptureInfo.actual_offset_x = 0; imageCaptureInfo.actual_offset_y = 0; b = ImageCapture.CaptureFromDisplay(ref imageCaptureInfo); imageCaptureInfo.actual_offset_x = cropOffsetX; imageCaptureInfo.actual_offset_y = cropOffsetY; } else { IntPtr handle = new IntPtr(0); if (processCaptureIndex >= processList.Length) return b; if (processCaptureIndex != -1) { handle = processList[processCaptureIndex].MainWindowHandle; } //Capture from specific process processList[processCaptureIndex].Refresh(); if ((int)handle == 0) return b; b = ImageCapture.PrintWindow(handle, ref imageCaptureInfo, full: true, useCrop: useCrop, scalingValueFloat: scalingValueFloat); } return b; } public void ChangeAutoSplitSettingsToGameName(string gameName, string category) { gameName = removeInvalidXMLCharacters(gameName); category = removeInvalidXMLCharacters(category); //TODO: go through gameSettings to see if the game matches, enter info based on that. foreach (var control in dynamicAutoSplitterControls) { tabPage2.Controls.Remove(control); } dynamicAutoSplitterControls.Clear(); //Add current game to gameSettings XmlDocument document = new XmlDocument(); var gameNode = document.CreateElement(autoSplitData.GameName + autoSplitData.Category); //var categoryNode = document.CreateElement(autoSplitData.Category); foreach (AutoSplitEntry splitEntry in autoSplitData.SplitData) { gameNode.AppendChild(ToElement(document, splitEntry.SplitName, splitEntry.NumberOfLoads)); } AllGameAutoSplitSettings[autoSplitData.GameName + autoSplitData.Category] = gameNode; //otherGameSettings[] CreateAutoSplitControls(liveSplitState); //Change controls if we find the chosen game foreach (var gameSettings in AllGameAutoSplitSettings) { if (gameSettings.Key == gameName + category) { var game_element = gameSettings.Value; //var splits_element = game_element[autoSplitData.Category]; Dictionary<string, int> usedSplitNames = new Dictionary<string, int>(); foreach (XmlElement number_of_loads in game_element) { var up_down_controls = tabPage2.Controls.Find(number_of_loads.LocalName, true); if (usedSplitNames.ContainsKey(number_of_loads.LocalName) == false) { usedSplitNames[number_of_loads.LocalName] = 0; } else { usedSplitNames[number_of_loads.LocalName]++; } //var up_down = tabPage2.Controls.Find(number_of_loads.LocalName, true).FirstOrDefault() as NumericUpDown; NumericUpDown up_down = (NumericUpDown)up_down_controls[usedSplitNames[number_of_loads.LocalName]]; if (up_down != null) { up_down.Value = Convert.ToInt32(number_of_loads.InnerText); } } } } } public int GetCumulativeNumberOfLoadsForSplit(string splitName) { int numberOfLoads = 0; splitName = removeInvalidXMLCharacters(splitName); foreach (AutoSplitEntry entry in autoSplitData.SplitData) { numberOfLoads += entry.NumberOfLoads; if (entry.SplitName == splitName) { return numberOfLoads; } } return numberOfLoads; } public int GetAutoSplitNumberOfLoadsForSplit(string splitName) { splitName = removeInvalidXMLCharacters(splitName); foreach (AutoSplitEntry entry in autoSplitData.SplitData) { if (entry.SplitName == splitName) { return entry.NumberOfLoads; } } //This should never happen, but might if the splits are changed without reloading the component... return 2; } public XmlNode GetSettings(XmlDocument document) { //RefreshCaptureWindowList(); var settingsNode = document.CreateElement("Settings"); settingsNode.AppendChild(ToElement(document, "Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(3))); settingsNode.AppendChild(ToElement(document, "RequiredMatches", FeatureDetector.numberOfBinsCorrect)); if (captureIDs != null) { if (processListComboBox.SelectedIndex < captureIDs.Count && processListComboBox.SelectedIndex >= 0) { var selectedCaptureTitle = captureIDs[processListComboBox.SelectedIndex]; settingsNode.AppendChild(ToElement(document, "SelectedCaptureTitle", selectedCaptureTitle)); } } settingsNode.AppendChild(ToElement(document, "ScalingPercent", trackBar1.Value)); var captureRegionNode = document.CreateElement("CaptureRegion"); captureRegionNode.AppendChild(ToElement(document, "X", selectionRectanglePreviewBox.X)); captureRegionNode.AppendChild(ToElement(document, "Y", selectionRectanglePreviewBox.Y)); captureRegionNode.AppendChild(ToElement(document, "Width", selectionRectanglePreviewBox.Width)); captureRegionNode.AppendChild(ToElement(document, "Height", selectionRectanglePreviewBox.Height)); settingsNode.AppendChild(captureRegionNode); settingsNode.AppendChild(ToElement(document, "AutoSplitEnabled", enableAutoSplitterChk.Checked)); settingsNode.AppendChild(ToElement(document, "AutoSplitDisableOnSkipUntilSplit", chkAutoSplitterDisableOnSkip.Checked)); settingsNode.AppendChild(ToElement(document, "RemoveFadeouts", chkRemoveTransitions.Checked)); //settingsNode.AppendChild(ToElement(document, "RemoveFadeins", chkRemoveFadeIns.Checked)); settingsNode.AppendChild(ToElement(document, "SaveDetectionLog", chkSaveDetectionLog.Checked)); settingsNode.AppendChild(ToElement(document, "DatabaseFile", cmbDatabase.SelectedItem.ToString())); var splitsNode = document.CreateElement("AutoSplitGames"); //Re-Add all other games/categories to the xml file foreach (var gameSettings in AllGameAutoSplitSettings) { if (gameSettings.Key != autoSplitData.GameName + autoSplitData.Category) { XmlNode node = document.ImportNode(gameSettings.Value, true); splitsNode.AppendChild(node); } } var gameNode = document.CreateElement(autoSplitData.GameName + autoSplitData.Category); //var categoryNode = document.CreateElement(autoSplitData.Category); foreach (AutoSplitEntry splitEntry in autoSplitData.SplitData) { gameNode.AppendChild(ToElement(document, splitEntry.SplitName, splitEntry.NumberOfLoads)); } AllGameAutoSplitSettings[autoSplitData.GameName + autoSplitData.Category] = gameNode; //gameNode.AppendChild(categoryNode); splitsNode.AppendChild(gameNode); settingsNode.AppendChild(splitsNode); //settingsNode.AppendChild(ToElement(document, "AutoReset", AutoReset.ToString())); //settingsNode.AppendChild(ToElement(document, "Category", category.ToString())); /*if (checkedListBox1.Items.Count == SplitsByCategory[category].Length) { for (int i = 0; i < checkedListBox1.Items.Count; i++) { SplitsByCategory[category][i].enabled = (checkedListBox1.GetItemCheckState(i) == CheckState.Checked); } } foreach (Split[] category in SplitsByCategory) { foreach (Split split in category) { settingsNode.AppendChild(ToElement(document, "split_" + split.splitID, split.enabled.ToString())); } }*/ return settingsNode; } public void SetSettings(XmlNode settings) { var element = (XmlElement)settings; if (!element.IsEmpty) { Version version; if (element["Version"] != null) { version = Version.Parse(element["Version"].InnerText); } else { version = new Version(1, 0, 0); } if (element["RequiredMatches"] != null) { FeatureDetector.numberOfBinsCorrect = Convert.ToInt32(element["RequiredMatches"].InnerText); requiredMatchesUpDown.Value = Convert.ToDecimal(FeatureDetector.numberOfBinsCorrect / (float)FeatureDetector.listOfFeatureVectorsEng.GetLength(1)); } if (element["SelectedCaptureTitle"] != null) { String selectedCaptureTitle = element["SelectedCaptureTitle"].InnerText; selectedCaptureID = selectedCaptureTitle; UpdateIndexToCaptureID(); RefreshCaptureWindowList(); } if (element["ScalingPercent"] != null) { trackBar1.Value = Convert.ToInt32(element["ScalingPercent"].InnerText); } if (element["CaptureRegion"] != null) { var element_region = element["CaptureRegion"]; if (element_region["X"] != null && element_region["Y"] != null && element_region["Width"] != null && element_region["Height"] != null) { int captureRegionX = Convert.ToInt32(element_region["X"].InnerText); int captureRegionY = Convert.ToInt32(element_region["Y"].InnerText); int captureRegionWidth = Convert.ToInt32(element_region["Width"].InnerText); int captureRegionHeight = Convert.ToInt32(element_region["Height"].InnerText); selectionRectanglePreviewBox = new Rectangle(captureRegionX, captureRegionY, captureRegionWidth, captureRegionHeight); selectionTopLeft = new Point(captureRegionX, captureRegionY); selectionBottomRight = new Point(captureRegionX + captureRegionWidth, captureRegionY + captureRegionHeight); //RefreshCaptureWindowList(); } } /*foreach (Split[] category in SplitsByCategory) { foreach (Split split in category) { if (element["split_" + split.splitID] != null) { split.enabled = Convert.ToBoolean(element["split_" + split.splitID].InnerText); } } }*/ if (element["AutoSplitEnabled"] != null) { enableAutoSplitterChk.Checked = Convert.ToBoolean(element["AutoSplitEnabled"].InnerText); } if (element["AutoSplitDisableOnSkipUntilSplit"] != null) { chkAutoSplitterDisableOnSkip.Checked = Convert.ToBoolean(element["AutoSplitDisableOnSkipUntilSplit"].InnerText); } if (element["RemoveFadeouts"] != null) { chkRemoveTransitions.Checked = Convert.ToBoolean(element["RemoveFadeouts"].InnerText); } //if (element["RemoveFadeins"] != null) //{ // chkRemoveFadeIns.Checked = Convert.ToBoolean(element["RemoveFadeins"].InnerText); //} chkRemoveFadeIns.Checked = chkRemoveTransitions.Checked; if (element["SaveDetectionLog"] != null) { chkSaveDetectionLog.Checked = Convert.ToBoolean(element["SaveDetectionLog"].InnerText); } if (element["DatabaseFile"] != null) { SetComboBoxToStoredDatabase(element["DatabaseFile"].InnerText); } if (element["AutoSplitGames"] != null) { var auto_split_element = element["AutoSplitGames"]; foreach (XmlElement game in auto_split_element) { if (game.LocalName != autoSplitData.GameName) { AllGameAutoSplitSettings[game.LocalName] = game; } } if (auto_split_element[autoSplitData.GameName + autoSplitData.Category] != null) { var game_element = auto_split_element[autoSplitData.GameName + autoSplitData.Category]; AllGameAutoSplitSettings[autoSplitData.GameName + autoSplitData.Category] = game_element; //var splits_element = game_element[autoSplitData.Category]; Dictionary<string, int> usedSplitNames = new Dictionary<string, int>(); foreach (XmlElement number_of_loads in game_element) { var up_down_controls = tabPage2.Controls.Find(number_of_loads.LocalName, true); //This can happen if the layout was not saved and contains old splits. if(up_down_controls == null || up_down_controls.Length == 0) { continue; } if (usedSplitNames.ContainsKey(number_of_loads.LocalName) == false) { usedSplitNames[number_of_loads.LocalName] = 0; } else { usedSplitNames[number_of_loads.LocalName]++; } //var up_down = tabPage2.Controls.Find(number_of_loads.LocalName, true).FirstOrDefault() as NumericUpDown; NumericUpDown up_down = (NumericUpDown)up_down_controls[usedSplitNames[number_of_loads.LocalName]]; if (up_down != null) { up_down.Value = Convert.ToInt32(number_of_loads.InnerText); } } } } DrawPreview(); CaptureImageFullPreview(ref imageCaptureInfo, true); devToolsCroppedPictureBox.Image = CaptureImage(); } } #endregion Public Methods #region Private Methods private void AutoSplitUpDown_ValueChanged(object sender, EventArgs e, string splitName) { foreach (AutoSplitEntry entry in autoSplitData.SplitData) { if (entry.SplitName == splitName) { entry.NumberOfLoads = (int)((NumericUpDown)sender).Value; return; } } } private void checkAutoReset_CheckedChanged(object sender, EventArgs e) { } private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (processListComboBox.SelectedIndex < numScreens) { processCaptureIndex = -processListComboBox.SelectedIndex - 1; } else { processCaptureIndex = processListComboBox.SelectedIndex - numScreens; } //selectionTopLeft = new Point(0, 0); //selectionBottomRight = new Point(previewPictureBox.Width, previewPictureBox.Height); selectionRectanglePreviewBox = new Rectangle(selectionTopLeft.X, selectionTopLeft.Y, selectionBottomRight.X - selectionTopLeft.X, selectionBottomRight.Y - selectionTopLeft.Y); //Console.WriteLine("SELECTED ITEM: {0}", processListComboBox.SelectedItem.ToString()); DrawPreview(); } private void CreateAutoSplitControls(LiveSplitState state) { autoSplitCategoryLbl.Text = "Category: " + state.Run.CategoryName; autoSplitNameLbl.Text = "Game: " + state.Run.GameName; int splitOffsetY = 95; int splitSpacing = 50; int splitCounter = 0; autoSplitData = new AutoSplitData(removeInvalidXMLCharacters(state.Run.GameName), removeInvalidXMLCharacters(state.Run.CategoryName)); foreach (var split in state.Run) { //Setup controls for changing AutoSplit settings var autoSplitPanel = new System.Windows.Forms.Panel(); var autoSplitLbl = new System.Windows.Forms.Label(); var autoSplitUpDown = new System.Windows.Forms.NumericUpDown(); autoSplitUpDown.Value = 2; autoSplitPanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; autoSplitPanel.Controls.Add(autoSplitUpDown); autoSplitPanel.Controls.Add(autoSplitLbl); autoSplitPanel.Location = new System.Drawing.Point(28, splitOffsetY + splitSpacing * splitCounter); autoSplitPanel.Size = new System.Drawing.Size(409, 39); autoSplitLbl.AutoSize = true; autoSplitLbl.Location = new System.Drawing.Point(3, 10); autoSplitLbl.Size = new System.Drawing.Size(199, 13); autoSplitLbl.TabIndex = 0; autoSplitLbl.Text = split.Name; autoSplitUpDown.Location = new System.Drawing.Point(367, 8); autoSplitUpDown.Size = new System.Drawing.Size(35, 20); autoSplitUpDown.TabIndex = 1; //Remove all whitespace to name the control, we can then access it in SetSettings. autoSplitUpDown.Name = removeInvalidXMLCharacters(split.Name); autoSplitUpDown.ValueChanged += (s, e) => AutoSplitUpDown_ValueChanged(autoSplitUpDown, e, removeInvalidXMLCharacters(split.Name)); tabPage2.Controls.Add(autoSplitPanel); //tabPage2.Controls.Add(autoSplitLbl); //tabPage2.Controls.Add(autoSplitUpDown); autoSplitData.SplitData.Add(new AutoSplitEntry(removeInvalidXMLCharacters(split.Name), 2)); dynamicAutoSplitterControls.Add(autoSplitPanel); splitCounter++; } } private void DrawCaptureRectangleBitmap() { Bitmap capture_image = (Bitmap)previewImage.Clone(); //Draw selection rectangle using (Graphics g = Graphics.FromImage(capture_image)) { Pen drawing_pen = new Pen(Color.Magenta, 8.0f); drawing_pen.Alignment = PenAlignment.Inset; g.DrawRectangle(drawing_pen, selectionRectanglePreviewBox); } previewPictureBox.Image = capture_image; } private void DrawPreview() { try { ImageCaptureInfo copy = imageCaptureInfo; copy.captureSizeX = previewPictureBox.Width; copy.captureSizeY = previewPictureBox.Height; //Show something in the preview previewImage = CaptureImageFullPreview(ref copy); float crop_size_x = copy.actual_crop_size_x; float crop_size_y = copy.actual_crop_size_y; lastFullCapture = previewImage; //Draw selection rectangle DrawCaptureRectangleBitmap(); //Compute image crop coordinates according to selection rectangle //Get raw image size from imageCaptureInfo.actual_crop_size to compute scaling between raw and rectangle coordinates //Console.WriteLine("SIZE X: {0}, SIZE Y: {1}", imageCaptureInfo.actual_crop_size_x, imageCaptureInfo.actual_crop_size_y); imageCaptureInfo.crop_coordinate_left = selectionRectanglePreviewBox.Left * (crop_size_x / previewPictureBox.Width); imageCaptureInfo.crop_coordinate_right = selectionRectanglePreviewBox.Right * (crop_size_x / previewPictureBox.Width); imageCaptureInfo.crop_coordinate_top = selectionRectanglePreviewBox.Top * (crop_size_y / previewPictureBox.Height); imageCaptureInfo.crop_coordinate_bottom = selectionRectanglePreviewBox.Bottom * (crop_size_y / previewPictureBox.Height); copy.crop_coordinate_left = selectionRectanglePreviewBox.Left * (crop_size_x / previewPictureBox.Width); copy.crop_coordinate_right = selectionRectanglePreviewBox.Right * (crop_size_x / previewPictureBox.Width); copy.crop_coordinate_top = selectionRectanglePreviewBox.Top * (crop_size_y / previewPictureBox.Height); copy.crop_coordinate_bottom = selectionRectanglePreviewBox.Bottom * (crop_size_y / previewPictureBox.Height); Bitmap full_cropped_capture = CaptureImageFullPreview(ref copy, useCrop: true); croppedPreviewPictureBox.Image = full_cropped_capture; lastFullCroppedCapture = full_cropped_capture; copy.captureSizeX = captureSize.Width; copy.captureSizeY = captureSize.Height; //Show matching bins for preview var capture = CaptureImage(); List<int> dummy; List<int> dummy2; int black_level = 0; var features = FeatureDetector.featuresFromBitmap(capture, out dummy, out black_level, out dummy2); int tempMatchingBins = 0; var isLoading = FeatureDetector.compareFeatureVector(features.ToArray(), FeatureDetector.listOfFeatureVectorsEng, out tempMatchingBins, -1.0f, false); lastFeatures = features; lastDiagnosticCapture = capture; lastMatchingBins = tempMatchingBins; matchDisplayLabel.Text = Math.Round((Convert.ToSingle(tempMatchingBins) / Convert.ToSingle(FeatureDetector.listOfFeatureVectorsEng.GetLength(1))), 4).ToString(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.ToString()); } } private void enableAutoSplitterChk_CheckedChanged(object sender, EventArgs e) { AutoSplitterEnabled = enableAutoSplitterChk.Checked; } private void initImageCaptureInfo() { imageCaptureInfo = new ImageCaptureInfo(); selectionTopLeft = new Point(0, 0); selectionBottomRight = new Point(previewPictureBox.Width, previewPictureBox.Height); selectionRectanglePreviewBox = new Rectangle(selectionTopLeft.X, selectionTopLeft.Y, selectionBottomRight.X - selectionTopLeft.X, selectionBottomRight.Y - selectionTopLeft.Y); requiredMatchesUpDown.Value = Convert.ToDecimal(FeatureDetector.numberOfBinsCorrect / (float)FeatureDetector.listOfFeatureVectorsEng.GetLength(1)); imageCaptureInfo.featureVectorResolutionX = featureVectorResolutionX; imageCaptureInfo.featureVectorResolutionY = featureVectorResolutionY; imageCaptureInfo.captureSizeX = captureSize.Width; imageCaptureInfo.captureSizeY = captureSize.Height; imageCaptureInfo.cropOffsetX = cropOffsetX; imageCaptureInfo.cropOffsetY = cropOffsetY; imageCaptureInfo.captureAspectRatio = captureAspectRatioX / captureAspectRatioY; } private void previewPictureBox_MouseClick(object sender, MouseEventArgs e) { } private void previewPictureBox_MouseDown(object sender, MouseEventArgs e) { SetRectangleFromMouse(e); DrawPreview(); } private void previewPictureBox_MouseMove(object sender, MouseEventArgs e) { SetRectangleFromMouse(e); if (drawingPreview == false) { drawingPreview = true; //Draw selection rectangle DrawCaptureRectangleBitmap(); drawingPreview = false; } } private void previewPictureBox_MouseUp(object sender, MouseEventArgs e) { SetRectangleFromMouse(e); DrawPreview(); } private void processListComboBox_DropDown(object sender, EventArgs e) { RefreshCaptureWindowList(); //processListComboBox.SelectedIndex = 0; } private void RefreshCaptureWindowList() { try { Process[] processListtmp = Process.GetProcesses(); List<Process> processes_with_name = new List<Process>(); if (captureIDs != null) { if (processListComboBox.SelectedIndex < captureIDs.Count && processListComboBox.SelectedIndex >= 0) { selectedCaptureID = processListComboBox.SelectedItem.ToString(); } } captureIDs = new List<string>(); processListComboBox.Items.Clear(); numScreens = 0; foreach (var screen in Screen.AllScreens) { // For each screen, add the screen properties to a list box. processListComboBox.Items.Add("Screen: " + screen.DeviceName + ", " + screen.Bounds.ToString()); captureIDs.Add("Screen: " + screen.DeviceName); numScreens++; } foreach (Process process in processListtmp) { if (!String.IsNullOrEmpty(process.MainWindowTitle)) { //Console.WriteLine("Process: {0} ID: {1} Window title: {2} HWND PTR {3}", process.ProcessName, process.Id, process.MainWindowTitle, process.MainWindowHandle); processListComboBox.Items.Add(process.ProcessName + ": " + process.MainWindowTitle); captureIDs.Add(process.ProcessName); processes_with_name.Add(process); } } UpdateIndexToCaptureID(); //processListComboBox.SelectedIndex = 0; processList = processes_with_name.ToArray(); } catch(Exception ex) { Console.WriteLine("Error: " + ex.ToString()); } } public string removeInvalidXMLCharacters(string in_string) { if (in_string == null) return null; StringBuilder sbOutput = new StringBuilder(); char ch; bool was_other_char = false; for (int i = 0; i < in_string.Length; i++) { ch = in_string[i]; if ((ch >= 0x0 && ch <= 0x2F) || (ch >= 0x3A && ch <= 0x40) || (ch >= 0x5B && ch <= 0x60) || (ch >= 0x7B) ) { continue; } //Can't start with a number. if (was_other_char == false && ch >= '0' && ch <= '9') { continue; } /*if ((ch >= 0x0020 && ch <= 0xD7FF) || (ch >= 0xE000 && ch <= 0xFFFD) || ch == 0x0009 || ch == 0x000A || ch == 0x000D) {*/ sbOutput.Append(ch); was_other_char = true; //} } if (sbOutput.Length == 0) { sbOutput.Append("NULL"); } return sbOutput.ToString(); } private void requiredMatchesUpDown_ValueChanged(object sender, EventArgs e) { FeatureDetector.numberOfBinsCorrect = (int)(requiredMatchesUpDown.Value * FeatureDetector.listOfFeatureVectorsEng.GetLength(1)); } private void saveDiagnosticsButton_Click(object sender, EventArgs e) { try { FolderBrowserDialog fbd = new FolderBrowserDialog(); var result = fbd.ShowDialog(); if (result != DialogResult.OK) { return; } //System.IO.Directory.CreateDirectory(fbd.SelectedPath); numCaptures++; lastFullCapture.Save(fbd.SelectedPath + "/" + numCaptures.ToString() + "_FULL_" + lastMatchingBins + ".jpg", ImageFormat.Jpeg); lastFullCroppedCapture.Save(fbd.SelectedPath + "/" + numCaptures.ToString() + "_FULL_CROPPED_" + lastMatchingBins + ".jpg", ImageFormat.Jpeg); lastDiagnosticCapture.Save(fbd.SelectedPath + "/" + numCaptures.ToString() + "_DIAGNOSTIC_" + lastMatchingBins + ".jpg", ImageFormat.Jpeg); saveFeatureVectorToTxt(lastFeatures, numCaptures.ToString() + "_FEATURES_" + lastMatchingBins + ".txt", fbd.SelectedPath); } catch(Exception ex) { Console.WriteLine("Error: " + ex.ToString()); } } private void saveFeatureVectorToTxt(List<int> featureVector, string filename, string directoryName) { System.IO.Directory.CreateDirectory(directoryName); try { using (var file = File.CreateText(directoryName + "/" + filename)) { file.Write("{"); file.Write(string.Join(",", featureVector)); file.Write("},\n"); } } catch { //yeah, silent catch is bad, I don't care } } private void SetRectangleFromMouse(MouseEventArgs e) { //Clamp values to pictureBox range int x = Math.Min(Math.Max(0, e.Location.X), previewPictureBox.Width); int y = Math.Min(Math.Max(0, e.Location.Y), previewPictureBox.Height); if (e.Button == MouseButtons.Left && (selectionRectanglePreviewBox.Left + selectionRectanglePreviewBox.Width) - x > 0 && (selectionRectanglePreviewBox.Top + selectionRectanglePreviewBox.Height) - y > 0) { selectionTopLeft = new Point(x, y); } else if (e.Button == MouseButtons.Right && x - selectionRectanglePreviewBox.Left > 0 && y - selectionRectanglePreviewBox.Top > 0) { selectionBottomRight = new Point(x, y); } do_not_trigger_value_changed = true; numTopLeftRectY.Value = selectionTopLeft.Y; do_not_trigger_value_changed = true; numTopLeftRectX.Value = selectionTopLeft.X; do_not_trigger_value_changed = true; numBottomRightRectY.Value = selectionBottomRight.Y; do_not_trigger_value_changed = true; numBottomRightRectX.Value = selectionBottomRight.X; selectionRectanglePreviewBox = new Rectangle(selectionTopLeft.X, selectionTopLeft.Y, selectionBottomRight.X - selectionTopLeft.X, selectionBottomRight.Y - selectionTopLeft.Y); } private XmlElement ToElement<T>(XmlDocument document, String name, T value) { var element = document.CreateElement(name); element.InnerText = value.ToString(); return element; } private void trackBar1_ValueChanged(object sender, EventArgs e) { scalingValue = trackBar1.Value; if (scalingValue % trackBar1.SmallChange != 0) { scalingValue = (scalingValue / trackBar1.SmallChange) * trackBar1.SmallChange; trackBar1.Value = scalingValue; } scalingValueFloat = ((float)scalingValue) / 100.0f; scalingLabel.Text = "Scaling: " + trackBar1.Value.ToString() + "%"; DrawPreview(); } private void UpdateIndexToCaptureID() { //Find matching window, set selected index to index in dropdown items int item_index = 0; for (item_index = 0; item_index < processListComboBox.Items.Count; item_index++) { String item = processListComboBox.Items[item_index].ToString(); if (item.Contains(selectedCaptureID)) { processListComboBox.SelectedIndex = item_index; //processListComboBox.Text = processListComboBox.SelectedItem.ToString(); break; } } } private void updatePreviewButton_Click(object sender, EventArgs e) { DrawPreview(); } #endregion Private Methods private void chkAutoSplitterDisableOnSkip_CheckedChanged(object sender, EventArgs e) { AutoSplitterDisableOnSkipUntilSplit = chkAutoSplitterDisableOnSkip.Checked; } private void chkRemoveTransitions_CheckedChanged(object sender, EventArgs e) { RemoveFadeouts = chkRemoveTransitions.Checked; RemoveFadeins = chkRemoveTransitions.Checked; } private void chkSaveDetectionLog_CheckedChanged(object sender, EventArgs e) { SaveDetectionLog = chkSaveDetectionLog.Checked; } private void chkRemoveFadeIns_CheckedChanged(object sender, EventArgs e) { //RemoveFadeins = chkRemoveFadeIns.Checked; RemoveFadeins = chkRemoveTransitions.Checked; } private void devToolsCropX_ValueChanged(object sender, EventArgs e) { cropOffsetX = Convert.ToSingle(devToolsCropX.Value); imageCaptureInfo.cropOffsetX = cropOffsetX; CaptureImageFullPreview(ref imageCaptureInfo, true); devToolsCroppedPictureBox.Image = CaptureImage(); } private void devToolsCropY_ValueChanged(object sender, EventArgs e) { cropOffsetY = Convert.ToSingle(devToolsCropY.Value); imageCaptureInfo.cropOffsetY = cropOffsetY; CaptureImageFullPreview(ref imageCaptureInfo, true); devToolsCroppedPictureBox.Image = CaptureImage(); } private void devToolsRecord_CheckedChanged(object sender, EventArgs e) { RecordImages = devToolsRecord.Checked; } private bool IsFeatureUnique(DetectorData data, int[] feature) { int tempMatchingBins; return !FeatureDetector.compareFeatureVector(feature, data.features, out tempMatchingBins, -1.0f, false); } private void ComputeDatabaseFromPath(string path) { DetectorData data = new DetectorData(); data.sizeX = captureSize.Width; data.sizeY = captureSize.Height; data.numberOfHistogramBins = 16; data.numPatchesX = 6; data.numPatchesY = 2; data.offsetX = Convert.ToInt32(cropOffsetX); data.offsetY = Convert.ToInt32(cropOffsetY); data.features = new List<int[]>(); var files = System.IO.Directory.GetFiles(path); float[] downsampling_factors = { 1, 2, 3}; float[] brightness_values = { 1.0f, 0.97f, 1.03f }; float[] contrast_values = { 1.0f, 0.97f, 1.03f }; InterpolationMode[] interpolation_modes = { InterpolationMode.NearestNeighbor, InterpolationMode.Bicubic }; int previous_matching_bins = FeatureDetector.numberOfBinsCorrect; FeatureDetector.numberOfBinsCorrect = 420; foreach (string filename in files) { foreach (float downsampling_factor in downsampling_factors) { foreach (float brightness in brightness_values) { foreach (float contrast in contrast_values) { foreach (InterpolationMode interpolation_mode in interpolation_modes) { float gamma = 1.0f; // no change in gamma float adjustedBrightness = brightness - 1.0f; // create matrix that will brighten and contrast the image // https://stackoverflow.com/a/15408608 float[][] ptsArray = { new float[] {contrast, 0, 0, 0, 0}, // scale red new float[] {0, contrast, 0, 0, 0}, // scale green new float[] {0, 0, contrast, 0, 0}, // scale blue new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}}; Bitmap bmp = new Bitmap(filename); //Make 32 bit ARGB bitmap Bitmap clone = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //Make 32 bit ARGB bitmap Bitmap sample_factor_clone = new Bitmap(Convert.ToInt32(bmp.Width / downsampling_factor), Convert.ToInt32(bmp.Height / downsampling_factor), System.Drawing.Imaging.PixelFormat.Format32bppArgb); var attributes = new ImageAttributes(); attributes.SetWrapMode(WrapMode.TileFlipXY); using (Graphics gr = Graphics.FromImage(sample_factor_clone)) { gr.InterpolationMode = interpolation_mode; gr.DrawImage(bmp, new Rectangle(0, 0, sample_factor_clone.Width, sample_factor_clone.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, attributes); } attributes.ClearColorMatrix(); attributes.SetColorMatrix(new ColorMatrix(ptsArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap); attributes.SetGamma(gamma, ColorAdjustType.Bitmap); using (Graphics gr = Graphics.FromImage(clone)) { gr.InterpolationMode = interpolation_mode; gr.DrawImage(sample_factor_clone, new Rectangle(0, 0, clone.Width, clone.Height), 0, 0, sample_factor_clone.Width, sample_factor_clone.Height, GraphicsUnit.Pixel, attributes); } int black_level = 0; List<int> max_per_patch = new List<int>(); List<int> min_per_patch = new List<int>(); int[] feature = FeatureDetector.featuresFromBitmap(clone, out max_per_patch, out black_level, out min_per_patch).ToArray(); if (IsFeatureUnique(data, feature)) { data.features.Add(feature); } bmp.Dispose(); clone.Dispose(); sample_factor_clone.Dispose(); } } } } } SerializeDetectorData(data, new DirectoryInfo(path).Name); FeatureDetector.numberOfBinsCorrect = previous_matching_bins; } private void devToolsDatabaseButton_Click(object sender, EventArgs e) { using (var fbd = new System.Windows.Forms.FolderBrowserDialog()) { DialogResult result = fbd.ShowDialog(); if (result != DialogResult.OK) { return; } ComputeDatabaseFromPath(fbd.SelectedPath); } } void SerializeDetectorData(DetectorData data, string path_suffix = "") { IFormatter formatter = new BinaryFormatter(); System.IO.Directory.CreateDirectory(Path.Combine(DetectionLogFolderName, "SerializedData")); Stream stream = new FileStream(Path.Combine(DetectionLogFolderName, "SerializedData", "LiveSplit.CTRNitroFueledLoadRemover_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff") + "_" + path_suffix + ".ctrnfdata"), FileMode.Create, FileAccess.Write); formatter.Serialize(stream, data); stream.Close(); } DetectorData DeserializeDetectorData(string path) { IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read); formatter.Binder = new Binder(); DetectorData data = (DetectorData)formatter.Deserialize(stream); stream.Close(); return data; } private void devToolsDataBaseFromCaptureImages_Click(object sender, EventArgs e) { ComputeDatabaseFromPath(Path.Combine(DetectionLogFolderName, devToolsCaptureImageText.Text)); } private void trackBar1_Scroll(object sender, EventArgs e) { } bool do_not_trigger_value_changed = false; private void numericUpDown4_ValueChanged(object sender, EventArgs e) { if (do_not_trigger_value_changed == false) { SetRectangleFromMouse(new MouseEventArgs(MouseButtons.Left, 1, Convert.ToInt32(numTopLeftRectX.Value), Convert.ToInt32(numTopLeftRectY.Value), 0)); DrawPreview(); } do_not_trigger_value_changed = false; } private void numericUpDown3_ValueChanged(object sender, EventArgs e) { if (do_not_trigger_value_changed == false) { SetRectangleFromMouse(new MouseEventArgs(MouseButtons.Left, 1, Convert.ToInt32(numTopLeftRectX.Value), Convert.ToInt32(numTopLeftRectY.Value), 0)); DrawPreview(); } do_not_trigger_value_changed = false; } private void numericUpDown2_ValueChanged(object sender, EventArgs e) { if (do_not_trigger_value_changed == false) { SetRectangleFromMouse(new MouseEventArgs(MouseButtons.Right, 1, Convert.ToInt32(numBottomRightRectX.Value), Convert.ToInt32(numBottomRightRectY.Value), 0)); DrawPreview(); } do_not_trigger_value_changed = false; } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { if (do_not_trigger_value_changed == false) { SetRectangleFromMouse(new MouseEventArgs(MouseButtons.Right, 1, Convert.ToInt32(numBottomRightRectX.Value), Convert.ToInt32(numBottomRightRectY.Value), 0)); DrawPreview(); } do_not_trigger_value_changed = false; } } [Serializable] public class DetectorData { public int offsetX; public int offsetY; public int sizeX; public int sizeY; public int numPatchesX; public int numPatchesY; public int numberOfHistogramBins; public List<int[]> features; } public class AutoSplitData { #region Public Fields public string Category; public string GameName; public List<AutoSplitEntry> SplitData; #endregion Public Fields #region Public Constructors public AutoSplitData(string gameName, string category) { SplitData = new List<AutoSplitEntry>(); GameName = gameName; Category = category; } #endregion Public Constructors } public class AutoSplitEntry { #region Public Fields public int NumberOfLoads = 2; public string SplitName = ""; #endregion Public Fields #region Public Constructors public AutoSplitEntry(string splitName, int numberOfLoads) { SplitName = splitName; NumberOfLoads = numberOfLoads; } #endregion Public Constructors } }
32.967347
272
0.705666
[ "MIT" ]
thomasneff/LiveSplit.CTRNitroFueledLoadRemover
ComponentSettings.cs
48,464
C#
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Quix.Snowflake.Writer.Configuration { [ExcludeFromCodeCoverage] public class BrokerConfiguration { /// <summary> /// The topic name used for display purposes /// </summary> public string TopicName { get; set; } /// <summary> /// When data is read from the broker, commit should occur after reading this amount of messages. (Or another condition occurs) /// </summary> public int? CommitAfterEveryCount { get; set; } /// <summary> /// When data is first read from broker (either from start or after last commit), wait this amount of milliseconds then do a commit. (or another condition occurs) /// </summary> public int? CommitAfterMs { get; set; } /// <summary> /// Extra properties for Kafka broker configuration /// </summary> public Dictionary<string, string> Properties { get; set; } } }
33.354839
171
0.628627
[ "Apache-2.0" ]
quixai/quix-library
csharp/destinations/snowflake/Quix.Snowflake.Writer/Configuration/BrokerConfiguration.cs
1,036
C#
using System; namespace FruitProject { class Program { static void Main(string[] args) { Fruit fruta = new Fruit("green","medium"); fruta.grow("bigger"); Avocado palta = new Avocado("Medium","Green", true); palta.ripe("turn black"); } } }
18.2
65
0.458791
[ "MIT" ]
vinostroza/HW5.31
FruitProject/FruitProject/Program.cs
366
C#
using SamuraiApp.Data; using System.Linq; using Microsoft.EntityFrameworkCore; namespace SamuraiApp.UI { internal class RawSqlInteractions { private static SamuraiContext _context = new SamuraiContext(); public static void Interact() { //QuerySamuraiBattleStats(); //QueryUsingRawSql(); //QueryRelatedUsingRawSql(); //QueryUsingRawSqlWithInterpolation(); //DANGERQueryUsingRawSqlWithInterpolation(); //QueryUsingFromSqlRawStoredProc(); //QueryUsingFromSqlIntStoredProc(); //ExecuteSomeRawSql(); } private static void QuerySamuraiBattleStats() { // call DB View //_context.SamuraiBattleStats.ToList(); //Executed DbCommand(102ms) [Parameters=[], CommandType = 'Text', CommandTimeout = '30'] //SELECT[s].[EarliestBattle], [s].[Name], [s].[NumberOfBattles] //FROM[SamuraiBattleStats] AS[s] //_context.SamuraiBattleStats.FirstOrDefault(); //Executed DbCommand(13ms) [Parameters=[], CommandType = 'Text', CommandTimeout = '30'] //SELECT TOP(1) [s].[EarliestBattle], [s].[Name], [s].[NumberOfBattles] //FROM[SamuraiBattleStats] AS[s] //_context.SamuraiBattleStats.FirstOrDefault(b => b.Name == "SampsonSan"); //Executed DbCommand(30ms) [Parameters=[], CommandType = 'Text', CommandTimeout = '30'] //SELECT TOP(1) [s].[EarliestBattle], [s].[Name], [s].[NumberOfBattles] //FROM[SamuraiBattleStats] AS[s] //WHERE[s].[Name] = N'SampsonSan' _context.SamuraiBattleStats.Find(2); //Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. } private static void QueryUsingRawSql() { _context.Samurais.FromSqlRaw("Select * from samurais").ToList(); //Executed DbCommand(36ms) [Parameters=[], CommandType = 'Text', CommandTimeout = '30'] //Select* from samurais _context.Samurais.FromSqlRaw("Select Id, Name, Quotes, Battles, Horse from Samurais").ToList(); //Unhandled exception. Microsoft.Data.SqlClient.SqlException(0x80131904): Invalid column name 'Quotes'. // Invalid column name 'Battles'. // Invalid column name 'Horse'. } private static void QueryRelatedUsingRawSql() { _context.Samurais.FromSqlRaw("Select Id, Name from Samurais").Include(s => s.Quotes).ToList(); //Executed DbCommand(51ms) [Parameters=[], CommandType = 'Text', CommandTimeout = '30'] //SELECT[s].[Id], [s].[Name], [q].[Id], [q].[SamuraiId], [q].[Text] //FROM( // Select Id, Name from Samurais //) AS[s] //LEFT JOIN[Quotes] AS[q] ON[s].[Id] = [q].[SamuraiId] //ORDER BY[s].[Id], [q].[Id] } private static void QueryUsingRawSqlWithInterpolation() { // FromSqlInterpolated prevents Sql injection string name = "Kikuchyo"; _context.Samurais.FromSqlInterpolated($"Select * from Samurais Where Name= {name}").ToList(); //Executed DbCommand(36ms) [Parameters=[p0 = 'Kikuchyo'(Size = 4000)], CommandType = 'Text', CommandTimeout = '30'] //Select* from Samurais Where Name = @p0 } private static void DANGERQueryUsingRawSqlWithInterpolation() { string name = "Kikuchyo"; _context.Samurais.FromSqlRaw($"Select * from Samurais Where Name= '{name}'").ToList(); //Executed DbCommand(27ms) [Parameters=[], CommandType = 'Text', CommandTimeout = '30'] //Select* from Samurais Where Name = 'Kikuchyo' } private static void QueryUsingFromSqlRawStoredProc() { var text = "Happy"; _context.Samurais.FromSqlRaw("EXEC dbo.SamuraisWhoSaidAWord {0}", text).ToList(); //Executed DbCommand(95ms) [Parameters=[p0 = 'Happy'(Size = 4000)], CommandType = 'Text', CommandTimeout = '30'] //EXEC dbo.SamuraisWhoSaidAWord @p0 } private static void QueryUsingFromSqlIntStoredProc() { var text = "Happy"; _context.Samurais.FromSqlInterpolated($"EXEC dbo.SamuraisWhoSaidAWord {text}").ToList(); //Executed DbCommand(48ms) [Parameters=[p0 = 'Happy'(Size = 4000)], CommandType = 'Text', CommandTimeout = '30'] //EXEC dbo.SamuraisWhoSaidAWord @p0 } private static void ExecuteSomeRawSql() { //var samuraiId = 2; //_context.Database.ExecuteSqlRaw("EXEC DeleteQuotesForSamurai {0}", samuraiId); //Executed DbCommand(100ms) [Parameters=[@p0 = '2'], CommandType = 'Text', CommandTimeout = '30'] //EXEC DeleteQuotesForSamurai @p0 var samuraiId = 2; _context.Database.ExecuteSqlInterpolated($"EXEC DeleteQuotesForSamurai {samuraiId}"); //Executed DbCommand(46ms) [Parameters=[@p0 = '2'], CommandType = 'Text', CommandTimeout = '30'] //EXEC DeleteQuotesForSamurai @p0 } } }
40.312977
127
0.595152
[ "MIT" ]
chunk1ty/FrameworkPlayground
src/EntityFrameworkCore/SamuraiApp/SamuraiApp.UI/RawSqlInteractions.cs
5,283
C#
namespace UglyToad.MakeMe.Makers.PostalCode { using System; using System.Collections.Generic; using Data; using Specification.PostalCode; internal class PostalCodeMaker : Maker<string> { private readonly PostalCodeSpecification specification; private static readonly Dictionary<IsoAlpha2Code, Func<PostalCodeSpecification, Random, string>> Makers = new Dictionary<IsoAlpha2Code, Func<PostalCodeSpecification, Random, string>> { { IsoAlpha2Code.UnitedKingdom, (s, r) => new UnitedKingdomPostcodeMaker(s, r).Make() }, { IsoAlpha2Code.India, (s, r) => new DigitPostcodeMaker(s, r, 6).Make() } }; public PostalCodeMaker(PostalCodeSpecification specification, Random random) : base(specification, random) { this.specification = specification; } public override string Make() { var country = specification.Country.GetValueOrDefault(IsoAlpha2Code.Unknown); Func<PostalCodeSpecification, Random, string> makerFunc; if (Makers.TryGetValue(country, out makerFunc)) { return makerFunc(specification, Random); } return new DigitPostcodeMaker(specification, Random, 5).Make(); } } }
35.342105
112
0.636634
[ "MIT" ]
UglyToad/MakeMe
UglyToad.MakeMe/Makers/PostalCode/PostalCodeMaker.cs
1,345
C#
namespace TeamCity.CSharpInteractive.Tests.UsageScenarios { using System.Collections; using System.Collections.Generic; using Contracts; public class Scenario: IHost { public IHost Host => this; public IReadOnlyList<string> Args { get; } = new List<string> { "Arg1", "Arg2" }; public IProperties Props { get; } = new Properties(); public T GetService<T>() => Composer.Resolve<T>(); public void WriteLine() => Composer.Resolve<IHost>().WriteLine(); public void WriteLine<T>(T line, Color color = Color.Default) => Composer.Resolve<IHost>().WriteLine(line, color); public void Error(string error, string errorId = "Unknown") => Composer.Resolve<IHost>().Error(error, errorId); public void Warning(string warning) => Composer.Resolve<IHost>().Warning(warning); public void Info(string text) => Composer.Resolve<IHost>().Info(text); public void Trace(string trace, string origin = "") => Composer.Resolve<IHost>().Trace(trace, origin); private class Properties: IProperties { private readonly Dictionary<string, string> _dict = new() { {"TEAMCITY_VERSION", "2021.2"}, {"TEAMCITY_PROJECT_NAME", "Samples"} }; public int Count => _dict.Count; public string this[string key] { get => _dict[key]; set => _dict[key] = value; } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => _dict.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public bool TryGetValue(string key, out string value) => _dict.TryGetValue(key, out value!); } } }
32.910714
122
0.589257
[ "MIT" ]
JetBrains/teamcity-csharp-interactive
TeamCity.CSharpInteractive.Tests/UsageScenarios/Scenario.cs
1,843
C#
namespace Seal { partial class ReportDesigner { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ReportDesigner)); this.mainMenuStrip = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reloadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.executeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.renderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.executeViewOutputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.renderViewOutputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.MRUToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.showScriptErrorsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.schedulesWithCurrentUserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.treeContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.removeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.addFromToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.removeRootToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sortColumnAlphaOrderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sortColumnSQLOrderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mainToolStrip = new System.Windows.Forms.ToolStrip(); this.newToolStripButton = new System.Windows.Forms.ToolStripButton(); this.openToolStripButton = new System.Windows.Forms.ToolStripButton(); this.saveToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.executeToolStripButton = new System.Windows.Forms.ToolStripButton(); this.renderToolStripButton = new System.Windows.Forms.ToolStripButton(); this.executeViewOutputToolStripButton = new System.Windows.Forms.ToolStripButton(); this.renderViewOutputToolStripButton = new System.Windows.Forms.ToolStripButton(); this.mainPanel = new System.Windows.Forms.Panel(); this.mainSplitContainer = new System.Windows.Forms.SplitContainer(); this.mainTreeView = new System.Windows.Forms.TreeView(); this.mainImageList = new System.Windows.Forms.ImageList(this.components); this.mainPropertyGrid = new System.Windows.Forms.PropertyGrid(); this.mainTimer = new System.Windows.Forms.Timer(this.components); this.mainMenuStrip.SuspendLayout(); this.treeContextMenuStrip.SuspendLayout(); this.mainToolStrip.SuspendLayout(); this.mainPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.mainSplitContainer)).BeginInit(); this.mainSplitContainer.Panel1.SuspendLayout(); this.mainSplitContainer.Panel2.SuspendLayout(); this.mainSplitContainer.SuspendLayout(); this.SuspendLayout(); // // mainMenuStrip // this.mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.optionsToolStripMenuItem, this.toolsToolStripMenuItem, this.helpToolStripMenuItem}); this.mainMenuStrip.Location = new System.Drawing.Point(0, 0); this.mainMenuStrip.Name = "mainMenuStrip"; this.mainMenuStrip.Size = new System.Drawing.Size(1220, 24); this.mainMenuStrip.TabIndex = 0; this.mainMenuStrip.Text = "mainMenuStrip"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem, this.openToolStripMenuItem, this.reloadToolStripMenuItem, this.saveToolStripMenuItem, this.saveAsToolStripMenuItem, this.closeToolStripMenuItem, this.toolStripSeparator2, this.executeToolStripMenuItem, this.renderToolStripMenuItem, this.executeViewOutputToolStripMenuItem, this.renderViewOutputToolStripMenuItem, this.toolStripSeparator3, this.MRUToolStripMenuItem, this.toolStripSeparator1, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.White; this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // newToolStripMenuItem // this.newToolStripMenuItem.Image = global::Seal.Properties.Resources._new; this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.newToolStripMenuItem.Text = "New"; this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click); // // openToolStripMenuItem // this.openToolStripMenuItem.Image = global::Seal.Properties.Resources.open; this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.openToolStripMenuItem.Text = "Open"; this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // reloadToolStripMenuItem // this.reloadToolStripMenuItem.Name = "reloadToolStripMenuItem"; this.reloadToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R))); this.reloadToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.reloadToolStripMenuItem.Text = "Reload"; this.reloadToolStripMenuItem.Click += new System.EventHandler(this.reloadToolStripMenuItem_Click); // // saveToolStripMenuItem // this.saveToolStripMenuItem.Image = global::Seal.Properties.Resources.save; this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.saveToolStripMenuItem.Text = "Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.ShortcutKeyDisplayString = ""; this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.saveAsToolStripMenuItem.Text = "Save As..."; this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // closeToolStripMenuItem // this.closeToolStripMenuItem.Name = "closeToolStripMenuItem"; this.closeToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.closeToolStripMenuItem.Text = "Close"; this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(164, 6); // // executeToolStripMenuItem // this.executeToolStripMenuItem.Image = global::Seal.Properties.Resources.execute; this.executeToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.White; this.executeToolStripMenuItem.Name = "executeToolStripMenuItem"; this.executeToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5; this.executeToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.executeToolStripMenuItem.Text = "Execute"; this.executeToolStripMenuItem.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // renderToolStripMenuItem // this.renderToolStripMenuItem.Image = global::Seal.Properties.Resources.render; this.renderToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.White; this.renderToolStripMenuItem.Name = "renderToolStripMenuItem"; this.renderToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F6; this.renderToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.renderToolStripMenuItem.Text = "Render"; this.renderToolStripMenuItem.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // executeViewOutputToolStripMenuItem // this.executeViewOutputToolStripMenuItem.Image = global::Seal.Properties.Resources.execute; this.executeViewOutputToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.White; this.executeViewOutputToolStripMenuItem.Name = "executeViewOutputToolStripMenuItem"; this.executeViewOutputToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F10; this.executeViewOutputToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.executeViewOutputToolStripMenuItem.Text = "Execute View"; this.executeViewOutputToolStripMenuItem.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // renderViewOutputToolStripMenuItem // this.renderViewOutputToolStripMenuItem.Image = global::Seal.Properties.Resources.render; this.renderViewOutputToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.White; this.renderViewOutputToolStripMenuItem.Name = "renderViewOutputToolStripMenuItem"; this.renderViewOutputToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F11; this.renderViewOutputToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.renderViewOutputToolStripMenuItem.Text = "Render View"; this.renderViewOutputToolStripMenuItem.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(164, 6); // // MRUToolStripMenuItem // this.MRUToolStripMenuItem.Name = "MRUToolStripMenuItem"; this.MRUToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.MRUToolStripMenuItem.Text = "Recent Reports"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(164, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Image = global::Seal.Properties.Resources.exit; this.exitToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.showScriptErrorsToolStripMenuItem, this.schedulesWithCurrentUserToolStripMenuItem}); this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(61, 20); this.optionsToolStripMenuItem.Text = "Options"; // // showScriptErrorsToolStripMenuItem // this.showScriptErrorsToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.showScriptErrorsToolStripMenuItem.Name = "showScriptErrorsToolStripMenuItem"; this.showScriptErrorsToolStripMenuItem.Size = new System.Drawing.Size(260, 22); this.showScriptErrorsToolStripMenuItem.Text = "Show script errors"; this.showScriptErrorsToolStripMenuItem.ToolTipText = "If checked, JavaScript errors are displayed in the report viewer."; this.showScriptErrorsToolStripMenuItem.Click += new System.EventHandler(this.showScriptErrorsToolStripMenuItem_Click); // // schedulesWithCurrentUserToolStripMenuItem // this.schedulesWithCurrentUserToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.schedulesWithCurrentUserToolStripMenuItem.Name = "schedulesWithCurrentUserToolStripMenuItem"; this.schedulesWithCurrentUserToolStripMenuItem.Size = new System.Drawing.Size(260, 22); this.schedulesWithCurrentUserToolStripMenuItem.Text = "Schedule reports using current user"; this.schedulesWithCurrentUserToolStripMenuItem.ToolTipText = "If checked, the schedules are created with the current logged user.\r\nNo administr" + "ators rights are required in this case."; this.schedulesWithCurrentUserToolStripMenuItem.Click += new System.EventHandler(this.schedulesWithCurrentUserToolStripMenuItem_Click); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(47, 20); this.toolsToolStripMenuItem.Text = "Tools"; // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "Help"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(116, 22); this.aboutToolStripMenuItem.Text = "About..."; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // treeContextMenuStrip // this.treeContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addToolStripMenuItem, this.removeToolStripMenuItem, this.addFromToolStripMenuItem, this.copyToolStripMenuItem, this.removeRootToolStripMenuItem, this.sortColumnAlphaOrderToolStripMenuItem, this.sortColumnSQLOrderToolStripMenuItem}); this.treeContextMenuStrip.Name = "treeContextMenuStrip"; this.treeContextMenuStrip.Size = new System.Drawing.Size(233, 158); this.treeContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.treeContextMenuStrip_Opening); // // addToolStripMenuItem // this.addToolStripMenuItem.Name = "addToolStripMenuItem"; this.addToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.addToolStripMenuItem.Text = "Add"; this.addToolStripMenuItem.Click += new System.EventHandler(this.addToolStripMenuItem_Click); // // removeToolStripMenuItem // this.removeToolStripMenuItem.Name = "removeToolStripMenuItem"; this.removeToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.removeToolStripMenuItem.Text = "Remove"; this.removeToolStripMenuItem.Click += new System.EventHandler(this.removeToolStripMenuItem_Click); // // addFromToolStripMenuItem // this.addFromToolStripMenuItem.Name = "addFromToolStripMenuItem"; this.addFromToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.addFromToolStripMenuItem.Text = "Add from Catalog..."; this.addFromToolStripMenuItem.Click += new System.EventHandler(this.addFromToolStripMenuItem_Click); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.copyToolStripMenuItem.Text = "Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click); // // removeRootToolStripMenuItem // this.removeRootToolStripMenuItem.Name = "removeRootToolStripMenuItem"; this.removeRootToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.removeRootToolStripMenuItem.Text = "Remove Root"; this.removeRootToolStripMenuItem.Click += new System.EventHandler(this.removeRootToolStripMenuItem_Click); // // sortColumnAlphaOrderToolStripMenuItem // this.sortColumnAlphaOrderToolStripMenuItem.Name = "sortColumnAlphaOrderToolStripMenuItem"; this.sortColumnAlphaOrderToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.sortColumnAlphaOrderToolStripMenuItem.Text = "Sort Columns by Name "; this.sortColumnAlphaOrderToolStripMenuItem.Click += new System.EventHandler(this.sortColumnsToolStripMenuItem_Click); // // sortColumnSQLOrderToolStripMenuItem // this.sortColumnSQLOrderToolStripMenuItem.Name = "sortColumnSQLOrderToolStripMenuItem"; this.sortColumnSQLOrderToolStripMenuItem.Size = new System.Drawing.Size(232, 22); this.sortColumnSQLOrderToolStripMenuItem.Text = "Sort Columns by SQL position"; this.sortColumnSQLOrderToolStripMenuItem.Click += new System.EventHandler(this.sortColumnsToolStripMenuItem_Click); // // mainToolStrip // this.mainToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripButton, this.openToolStripButton, this.saveToolStripButton, this.toolStripSeparator8, this.executeToolStripButton, this.renderToolStripButton, this.executeViewOutputToolStripButton, this.renderViewOutputToolStripButton}); this.mainToolStrip.Location = new System.Drawing.Point(0, 24); this.mainToolStrip.Name = "mainToolStrip"; this.mainToolStrip.Size = new System.Drawing.Size(1220, 25); this.mainToolStrip.TabIndex = 31; // // newToolStripButton // this.newToolStripButton.Image = global::Seal.Properties.Resources._new; this.newToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.newToolStripButton.Name = "newToolStripButton"; this.newToolStripButton.Size = new System.Drawing.Size(51, 22); this.newToolStripButton.Text = "New"; this.newToolStripButton.Click += new System.EventHandler(this.newToolStripMenuItem_Click); // // openToolStripButton // this.openToolStripButton.Image = global::Seal.Properties.Resources.open; this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.openToolStripButton.Name = "openToolStripButton"; this.openToolStripButton.Size = new System.Drawing.Size(56, 22); this.openToolStripButton.Text = "Open"; this.openToolStripButton.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // saveToolStripButton // this.saveToolStripButton.Image = global::Seal.Properties.Resources.save; this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Black; this.saveToolStripButton.Name = "saveToolStripButton"; this.saveToolStripButton.Size = new System.Drawing.Size(51, 22); this.saveToolStripButton.Text = "Save"; this.saveToolStripButton.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25); // // executeToolStripButton // this.executeToolStripButton.Image = global::Seal.Properties.Resources.execute; this.executeToolStripButton.ImageTransparentColor = System.Drawing.Color.White; this.executeToolStripButton.Name = "executeToolStripButton"; this.executeToolStripButton.Size = new System.Drawing.Size(67, 22); this.executeToolStripButton.Text = "Execute"; this.executeToolStripButton.ToolTipText = "F5 Execute the report"; this.executeToolStripButton.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // renderToolStripButton // this.renderToolStripButton.Image = global::Seal.Properties.Resources.render; this.renderToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.renderToolStripButton.Name = "renderToolStripButton"; this.renderToolStripButton.Size = new System.Drawing.Size(64, 22); this.renderToolStripButton.Text = "Render"; this.renderToolStripButton.ToolTipText = "F6 Execute the report using the models of the previous execution"; this.renderToolStripButton.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // executeViewOutputToolStripButton // this.executeViewOutputToolStripButton.Image = global::Seal.Properties.Resources.execute; this.executeViewOutputToolStripButton.ImageTransparentColor = System.Drawing.Color.White; this.executeViewOutputToolStripButton.Name = "executeViewOutputToolStripButton"; this.executeViewOutputToolStripButton.Size = new System.Drawing.Size(95, 22); this.executeViewOutputToolStripButton.Text = "Execute View"; this.executeViewOutputToolStripButton.ToolTipText = "Execute the report using the selected view"; this.executeViewOutputToolStripButton.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // renderViewOutputToolStripButton // this.renderViewOutputToolStripButton.Image = global::Seal.Properties.Resources.render; this.renderViewOutputToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.renderViewOutputToolStripButton.Name = "renderViewOutputToolStripButton"; this.renderViewOutputToolStripButton.Size = new System.Drawing.Size(92, 22); this.renderViewOutputToolStripButton.Text = "Render View"; this.renderViewOutputToolStripButton.ToolTipText = "Execute the report using the models of the previous execution and the selected vi" + "ew"; this.renderViewOutputToolStripButton.Click += new System.EventHandler(this.executeToolStripMenuItem_Click); // // mainPanel // this.mainPanel.Controls.Add(this.mainSplitContainer); this.mainPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.mainPanel.Location = new System.Drawing.Point(0, 49); this.mainPanel.Name = "mainPanel"; this.mainPanel.Size = new System.Drawing.Size(1220, 628); this.mainPanel.TabIndex = 32; // // mainSplitContainer // this.mainSplitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.mainSplitContainer.Location = new System.Drawing.Point(0, 0); this.mainSplitContainer.Name = "mainSplitContainer"; // // mainSplitContainer.Panel1 // this.mainSplitContainer.Panel1.Controls.Add(this.mainTreeView); // // mainSplitContainer.Panel2 // this.mainSplitContainer.Panel2.Controls.Add(this.mainPropertyGrid); this.mainSplitContainer.Size = new System.Drawing.Size(1220, 628); this.mainSplitContainer.SplitterDistance = 206; this.mainSplitContainer.TabIndex = 4; // // mainTreeView // this.mainTreeView.AllowDrop = true; this.mainTreeView.ContextMenuStrip = this.treeContextMenuStrip; this.mainTreeView.Dock = System.Windows.Forms.DockStyle.Fill; this.mainTreeView.HideSelection = false; this.mainTreeView.ImageIndex = 0; this.mainTreeView.ImageList = this.mainImageList; this.mainTreeView.LabelEdit = true; this.mainTreeView.Location = new System.Drawing.Point(0, 0); this.mainTreeView.Name = "mainTreeView"; this.mainTreeView.SelectedImageIndex = 0; this.mainTreeView.Size = new System.Drawing.Size(206, 628); this.mainTreeView.TabIndex = 1; this.mainTreeView.BeforeLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.mainTreeView_BeforeLabelEdit); this.mainTreeView.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.mainTreeView_AfterLabelEdit); this.mainTreeView.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.mainTreeView_ItemDrag); this.mainTreeView.BeforeSelect += new System.Windows.Forms.TreeViewCancelEventHandler(this.mainTreeView_BeforeSelect); this.mainTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.mainTreeView_AfterSelect); this.mainTreeView.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.mainTreeView_NodeMouseClick); this.mainTreeView.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.mainTreeView_NodeMouseDoubleClick); this.mainTreeView.DragDrop += new System.Windows.Forms.DragEventHandler(this.mainTreeView_DragDrop); this.mainTreeView.DragEnter += new System.Windows.Forms.DragEventHandler(this.mainTreeView_DragEnter); this.mainTreeView.DragOver += new System.Windows.Forms.DragEventHandler(this.mainTreeView_DragOver); this.mainTreeView.MouseUp += new System.Windows.Forms.MouseEventHandler(this.mainTreeView_MouseUp); // // mainImageList // this.mainImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("mainImageList.ImageStream"))); this.mainImageList.TransparentColor = System.Drawing.Color.Transparent; this.mainImageList.Images.SetKeyName(0, "database.png"); this.mainImageList.Images.SetKeyName(1, "connection.png"); this.mainImageList.Images.SetKeyName(2, "folder.png"); this.mainImageList.Images.SetKeyName(3, "label.png"); this.mainImageList.Images.SetKeyName(4, "table.png"); this.mainImageList.Images.SetKeyName(5, "join.png"); this.mainImageList.Images.SetKeyName(6, "enum.png"); this.mainImageList.Images.SetKeyName(7, "element.png"); this.mainImageList.Images.SetKeyName(8, "view.png"); this.mainImageList.Images.SetKeyName(9, "device.png"); this.mainImageList.Images.SetKeyName(10, "model.png"); this.mainImageList.Images.SetKeyName(11, "schedule.png"); this.mainImageList.Images.SetKeyName(12, "task.png"); this.mainImageList.Images.SetKeyName(13, "nosql.png"); this.mainImageList.Images.SetKeyName(14, "task2.png"); // // mainPropertyGrid // this.mainPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.mainPropertyGrid.Location = new System.Drawing.Point(0, 0); this.mainPropertyGrid.Name = "mainPropertyGrid"; this.mainPropertyGrid.Size = new System.Drawing.Size(1010, 628); this.mainPropertyGrid.TabIndex = 1; this.mainPropertyGrid.ToolbarVisible = false; this.mainPropertyGrid.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.mainPropertyGrid_PropertyValueChanged); // // mainTimer // this.mainTimer.Enabled = true; this.mainTimer.Interval = 500; this.mainTimer.Tick += new System.EventHandler(this.mainTimer_Tick); // // ReportDesigner // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1220, 677); this.Controls.Add(this.mainPanel); this.Controls.Add(this.mainToolStrip); this.Controls.Add(this.mainMenuStrip); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.mainMenuStrip; this.Name = "ReportDesigner"; this.Text = "Seal Report Designer"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ReportDesigner_FormClosing); this.Load += new System.EventHandler(this.ReportDesigner_Load); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ReportDesigner_KeyDown); this.mainMenuStrip.ResumeLayout(false); this.mainMenuStrip.PerformLayout(); this.treeContextMenuStrip.ResumeLayout(false); this.mainToolStrip.ResumeLayout(false); this.mainToolStrip.PerformLayout(); this.mainPanel.ResumeLayout(false); this.mainSplitContainer.Panel1.ResumeLayout(false); this.mainSplitContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.mainSplitContainer)).EndInit(); this.mainSplitContainer.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip mainMenuStrip; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem executeToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ContextMenuStrip treeContextMenuStrip; private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem removeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; private System.Windows.Forms.ToolStrip mainToolStrip; private System.Windows.Forms.ToolStripButton newToolStripButton; private System.Windows.Forms.ToolStripButton openToolStripButton; private System.Windows.Forms.ToolStripButton renderToolStripButton; private System.Windows.Forms.ToolStripButton saveToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem MRUToolStripMenuItem; private System.Windows.Forms.ToolStripButton executeToolStripButton; private System.Windows.Forms.Panel mainPanel; private System.Windows.Forms.SplitContainer mainSplitContainer; private System.Windows.Forms.TreeView mainTreeView; private System.Windows.Forms.ToolStripMenuItem addFromToolStripMenuItem; private System.Windows.Forms.PropertyGrid mainPropertyGrid; private System.Windows.Forms.ImageList mainImageList; private System.Windows.Forms.Timer mainTimer; private System.Windows.Forms.ToolStripMenuItem renderToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripButton executeViewOutputToolStripButton; private System.Windows.Forms.ToolStripButton renderViewOutputToolStripButton; private System.Windows.Forms.ToolStripMenuItem executeViewOutputToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem renderViewOutputToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem removeRootToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reloadToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem showScriptErrorsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem schedulesWithCurrentUserToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sortColumnAlphaOrderToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sortColumnSQLOrderToolStripMenuItem; } }
62.141005
160
0.681438
[ "Apache-2.0" ]
andr3i4o/Seal-Report
Projects/SealReportDesigner/ReportDesigner.Designer.cs
38,343
C#
using GameDev.tv_Assets.Scripts.Inventories; namespace GameDev.tv_Assets.Scripts.UI.Inventories { /// <summary> /// Allows the `ItemTooltipSpawner` to display the right information. /// </summary> public interface IItemHolder { InventoryItem GetItem(); } }
22.384615
73
0.683849
[ "MIT" ]
brinleyzhao1/Whimel-A-Magic-Academy
Assets/Asset Packs/GameDev.tv Assets/Scripts/UI/Inventories/IItemHolder.cs
293
C#
using System; using System.Windows; using System.Windows.Input; using Magellan; using Magellan.Events; using Magellan.Progress; using Magellan.Transitionals; namespace iPhone { public partial class MainWindow : Window, INavigationProgressListener { public MainWindow() { InitializeComponent(); Loaded += (x, y) => Navigator.NavigateWithTransition("Home", "Home", "ZoomIn"); } public INavigator Navigator { get; set; } private void HomeButtonClicked(object sender, RoutedEventArgs e) { Navigator.NavigateWithTransition("Home", "Home", "ZoomOut"); } private void BeginMove(object sender, MouseButtonEventArgs e) { DragMove(); } private void CloseWindow(object sender, RoutedEventArgs e) { Close(); } public void UpdateProgress(NavigationEvent navigationEvent) { Dispatcher.Invoke( new Action(delegate { if (navigationEvent is BeginRequestNavigationEvent) BusyIndicator.IsBusy = true; if (navigationEvent is CompleteNavigationEvent) BusyIndicator.IsBusy = false; })); } } }
27.191489
100
0.599374
[ "MIT" ]
rog1039/magellan-framework
src/Samples/iPhone/MainWindow.xaml.cs
1,280
C#
using Application.Common.Mappings; using AutoMapper; using Domain.Entities.Insurance; namespace Application.Stammdaten.Queries.GetTitel { public class TitelDto : IMapFrom<Titel> { public int Id { get; set; } public string BezeichnungKurz { get; set; } public string Beschreibung { get; set; } public void Mapping(Profile profile) { profile.CreateMap<Titel, TitelDto>(); } } }
25.444444
51
0.633188
[ "MIT" ]
RotterAxel/NettoAPI-Github
Application/Stammdaten/Queries/GetTitel/TitelDto.cs
460
C#
using System.Collections.Generic; using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Response { /// <summary> /// AlipayEcoMycarMaintainShopQueryResponse. /// </summary> public class AlipayEcoMycarMaintainShopQueryResponse : AlipayResponse { /// <summary> /// 门店详细地址,地址字符长度在4-50个字符,注:不含省市区。门店详细地址按规范格式填写地址,以免影响门店搜索及活动报名:例1:道路+门牌号,“人民东路18号”;例2:道路+门牌号+标志性建筑+楼层,“四川北路1552号欢乐广场1楼” /// </summary> [JsonPropertyName("address")] public string Address { get; set; } /// <summary> /// 支付宝帐号 /// </summary> [JsonPropertyName("alipay_account")] public string AlipayAccount { get; set; } /// <summary> /// 门店支持的车型品牌,支付宝车型库品牌编号(系统唯一),品牌编号可以通过调用【查询车型信息接口】alipay.eco.mycar.carmodel.query 获取。 /// </summary> [JsonPropertyName("brand_ids")] public List<string> BrandIds { get; set; } /// <summary> /// 城市编号(国标码,详见国家统计局数据 <a href="http://aopsdkdownload.cn-hangzhou.alipay-pub.aliyun-inc.com/doc/AreaCodeList.zip">点此下载</a>) /// </summary> [JsonPropertyName("city_code")] public string CityCode { get; set; } /// <summary> /// 门店营业结束时间(HH:mm) /// </summary> [JsonPropertyName("close_time")] public string CloseTime { get; set; } /// <summary> /// 门店店长邮箱 /// </summary> [JsonPropertyName("contact_email")] public string ContactEmail { get; set; } /// <summary> /// 门店店长移动电话号码;不在客户端展示 /// </summary> [JsonPropertyName("contact_mobile_phone")] public string ContactMobilePhone { get; set; } /// <summary> /// 门店店长姓名 /// </summary> [JsonPropertyName("contact_name")] public string ContactName { get; set; } /// <summary> /// 区编号(国标码,详见国家统计局数据 <a href="http://aopsdkdownload.cn-hangzhou.alipay-pub.aliyun-inc.com/doc/AreaCodeList.zip">点此下载</a>) /// </summary> [JsonPropertyName("district_code")] public string DistrictCode { get; set; } /// <summary> /// 扩展参数,json格式,可以存放营销信息,以及主营描述等扩展信息 /// </summary> [JsonPropertyName("ext_param")] public string ExtParam { get; set; } /// <summary> /// 行业应用类目编号 15:洗车 16:保养 17:停车 20:4S /// </summary> [JsonPropertyName("industry_app_category_id")] public List<long> IndustryAppCategoryId { get; set; } /// <summary> /// 行业类目编号(<a href="https://doc.open.alipay.com/doc2/detail.htm?treeId=205&articleId=104497&docType=1">点此查看</a> 非口碑类目 – 爱车) /// </summary> [JsonPropertyName("industry_category_id")] public List<long> IndustryCategoryId { get; set; } /// <summary> /// 高德地图纬度(经纬度是门店搜索和活动推荐的重要参数,录入时请确保经纬度参数准确) /// </summary> [JsonPropertyName("lat")] public string Lat { get; set; } /// <summary> /// 高德地图经度(经纬度是门店搜索和活动推荐的重要参数,录入时请确保经纬度参数准确) /// </summary> [JsonPropertyName("lon")] public string Lon { get; set; } /// <summary> /// 车主平台接口上传主图片地址,通过alipay.eco.mycar.image.upload接口上传。 /// </summary> [JsonPropertyName("main_image")] public string MainImage { get; set; } /// <summary> /// 分支机构编号,商户在车主平台自己创建的分支机构编码 /// </summary> [JsonPropertyName("merchant_branch_id")] public long MerchantBranchId { get; set; } /// <summary> /// 门店营业开始时间(HH:mm) /// </summary> [JsonPropertyName("open_time")] public string OpenTime { get; set; } /// <summary> /// 车主平台接口上传副图片地址,通过alipay.eco.mycar.image.upload接口上传。 /// </summary> [JsonPropertyName("other_images")] public List<string> OtherImages { get; set; } /// <summary> /// 外部门店编号,门店创建时上传的ISV门店唯一标示 /// </summary> [JsonPropertyName("out_shop_id")] public string OutShopId { get; set; } /// <summary> /// 省编号(国标码,详见国家统计局数据 <a href="http://aopsdkdownload.cn-hangzhou.alipay-pub.aliyun-inc.com/doc/AreaCodeList.zip">点此下载</a>) /// </summary> [JsonPropertyName("province_code")] public string ProvinceCode { get; set; } /// <summary> /// 分店名称,比如:万塘路店,与主门店名合并在客户端显示为:爱特堡(益乐路店) /// </summary> [JsonPropertyName("shop_branch_name")] public string ShopBranchName { get; set; } /// <summary> /// 车主平台门店编号 /// </summary> [JsonPropertyName("shop_id")] public long ShopId { get; set; } /// <summary> /// 主门店名,比如:爱特堡;主店名里不要包含分店名,如“益乐路店”。主店名长度不能超过20个字符 /// </summary> [JsonPropertyName("shop_name")] public string ShopName { get; set; } /// <summary> /// 门店电话号码;支持座机和手机,只支持数字和+-号,在客户端对用户展现。 /// </summary> [JsonPropertyName("shop_tel")] public string ShopTel { get; set; } /// <summary> /// 该字段已废弃。 /// </summary> [JsonPropertyName("shop_type")] public string ShopType { get; set; } /// <summary> /// 门店状态(0:下线;1:上线) /// </summary> [JsonPropertyName("status")] public string Status { get; set; } } }
31.922619
131
0.562558
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Response/AlipayEcoMycarMaintainShopQueryResponse.cs
6,655
C#
using System; using com.spacepuppy.Collections; namespace com.spacepuppy.Utils { /// <summary> /// Waits a duration of time and then calls a System.Action. /// /// This can accept a System.Collections.IEnumerator just like a Coroutine, but it does not respect any yield instructions. All yielded objects wait a single frame. /// </summary> public sealed class InvokeHandle : IUpdateable, IRadicalWaitHandle, IRadicalEnumerator, ISPDisposable { #region Fields private UpdatePump _pump; private System.Action _callback; private System.Collections.IEnumerator _handle; #endregion #region CONSTRUCTOR private InvokeHandle() { } #endregion #region IUpdateable Interface void IUpdateable.Update() { if (_handle == null || !_handle.MoveNext()) { var d = _callback; this.Dispose(); if (d != null) d(); } } #endregion #region IRadicalWaitHandle Interface bool IRadicalWaitHandle.Cancelled { get { return false; } } public bool IsComplete { get { return _handle == null; } } void IRadicalWaitHandle.OnComplete(System.Action<IRadicalWaitHandle> callback) { if (_handle == null || callback == null) return; _callback += () => callback(this); } bool IRadicalYieldInstruction.Tick(out object yieldObject) { yieldObject = null; return _handle != null; } #endregion #region IEnumerator Interface object System.Collections.IEnumerator.Current => null; bool System.Collections.IEnumerator.MoveNext() { return _handle != null; } void System.Collections.IEnumerator.Reset() { //do nothing } #endregion #region ISPDisposable Interface bool ISPDisposable.IsDisposed => _pump == null; public void Dispose() { if (_pump != null) _pump.Remove(this); _pump = null; _callback = null; _handle = null; _pool.Release(this); } #endregion #region Static Factory private static ObjectCachePool<InvokeHandle> _pool = new ObjectCachePool<InvokeHandle>(-1, () => new InvokeHandle()); public static InvokeHandle Begin(UpdatePump pump, System.Action callback, float duration, ITimeSupplier time) { if (pump == null) throw new System.ArgumentNullException("pump"); var handle = _pool.GetInstance(); handle._callback = callback; handle._handle = WaitForDuration.Seconds(duration, time); handle._pump = pump; pump.Add(handle); return handle; } public static InvokeHandle Begin(UpdatePump pump, System.Action callback, System.Collections.IEnumerator e) { if (pump == null) throw new System.ArgumentNullException("pump"); var handle = _pool.GetInstance(); handle._callback = callback; handle._handle = e; handle._pump = pump; pump.Add(handle); return handle; } #endregion } }
24.397163
168
0.564244
[ "MIT" ]
lordofduct/spacepuppy-unity-framework-4.0
Framework/com.spacepuppy.radicalcoroutine/Runtime/src/Utils/InvokeHandle.cs
3,442
C#
// <copyright file="ParticipantDataEntity.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace WaterCoolerAPI.Repositories.ParticipantData { using System; using Microsoft.Azure.Cosmos.Table; /// <summary> /// Participant data entity class. /// This entity holds the information about a participant. /// </summary> public class ParticipantDataEntity : TableEntity { /// <summary> /// Gets or sets the object id. /// </summary> public string CallId { get; set; } /// <summary> /// Gets or sets the object id. /// </summary> public string ObjectId { get; set; } /// <summary> /// Gets or sets the log time. /// </summary> public DateTime? LogTime { get; set; } /// <summary> /// Gets or sets the Start Time Of Meeting for a User . /// </summary> public DateTime StartTime { get; set; } /// <summary> /// Gets or sets the End time for a User. /// </summary> public DateTime? EndTime { get; set; } } }
27.309524
67
0.565824
[ "MIT" ]
7w8mds/teek-che
WaterCoolerAPI/WaterCoolerAPI/Repositories/ParticipantData/ParticipantDataEntity.cs
1,149
C#
namespace ModularityPro.ViewModels { public class LoginViewModel { public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } } }
21.777778
40
0.673469
[ "Apache-2.0" ]
djzevenbergen/test-mdp
ModularityPro/ViewModels/LoginViewModel.cs
196
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TextHelper { public class Ciphre { private string pomPasswd = ""; public string helpflPasswd = ""; private string hexalPattern = "0123456789ABCDEF"; public string securePasswd(string passwd) { if (passwd.Length > helpflPasswd.Length) { string newHelpflPasswd = ""; for (int i = 0; i < passwd.Length; i++) { newHelpflPasswd += helpflPasswd[i % helpflPasswd.Length]; } helpflPasswd = newHelpflPasswd; } else if (passwd.Length < helpflPasswd.Length) { string newHelpflPasswd = ""; newHelpflPasswd = helpflPasswd.Substring(0, passwd.Length); helpflPasswd = newHelpflPasswd; } for (int i = 0; i < passwd.Length; i++) { if ((((int)(passwd[i]) + (int)(helpflPasswd[i])) - 96) > 122) pomPasswd += (char)(((int)(passwd[i]) + (int)(helpflPasswd[i]) - 96) - 26); else pomPasswd += (char)(((int)(passwd[i]) + (int)(helpflPasswd[i]) - 96)); } return pomPasswd; } public string toHexal(string prepPasswd) { string resPasswd = "0x"; foreach (char letter in pomPasswd) { for (int i = 1; i < 16; i++) { if (((int)letter == 0) || ((((int)(letter)) % i) == 0)) resPasswd += hexalPattern[i]; if (i % 6 == 0) resPasswd += "0x"; } } return resPasswd; } } }
30.934426
95
0.45628
[ "MIT" ]
MichalKyjovsky/CourseWorkNPRG030
TextHelper/Ciphre.cs
1,889
C#
///----------------------------------------------------------------- /// Author: Messaia /// AuthorUrl: http://messaia.com /// Date: 27.01.2018 18:17:18 /// Copyright (©) 2018, MESSAIA.NET, all Rights Reserved. /// Licensed under the Apache License, Version 2.0. /// See License.txt in the project root for license information. ///----------------------------------------------------------------- namespace Messaia.Net.Shop.Impl { using Messaia.Net.Model; /// <summary> /// CartItem class. /// </summary> public class CartItem : AuditEntity, ICartItem { /// <summary> /// Gets or sets the Quantity /// </summary> public int Quantity { get; set; } /// <summary> /// Gets or sets the SubTotal /// </summary> public float SubTotal { get; set; } /// <summary> /// Gets or sets the SubTotalNet /// </summary> public float SubTotalNet { get; set; } /// <summary> /// Gets or sets the SubTotalPopublic ints /// </summary> public int SubTotalPoints { get; set; } /// <summary> /// Gets or sets the ProductId /// </summary> public int? ProductId { get; set; } /// <summary> /// Gets or sets the Product /// </summary> public IProduct Product { get; set; } /// <summary> /// Gets or sets the ProductId /// </summary> public int? CartId { get; set; } /// <summary> /// Gets or sets the Cart /// </summary> public ICart Cart { get; set; } } }
29.206897
82
0.4634
[ "Apache-2.0" ]
fouadmess/NetCore
Messaia.Net.Shop.Impl/Models/Cart/CartItem.cs
1,697
C#
using FpML.V5r10.Reporting.ModelFramework; using Microsoft.VisualStudio.TestTools.UnitTesting; using Orion.Analytics.DayCounters; namespace Orion.Analytics.Tests.Dates { [TestClass] public class DayCounterHelperTest { [TestMethod] public void ParseTest() { IDayCounter dayCounter = DayCounterHelper.Parse("Act/360"); Assert.IsNotNull(dayCounter); } } }
23.722222
71
0.674473
[ "BSD-3-Clause" ]
mmrath/Highlander.Net
FpML.V5r10.Tests/FpML.V5r10.Analytics.Tests/Dates/DayCounterHelperTest.cs
429
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Runtime.Serialization; using Vts.Common; using Vts.IO; using Vts.MonteCarlo.Helpers; using Vts.MonteCarlo.PhotonData; namespace Vts.MonteCarlo.Detectors { /// <summary> /// Tally for pMC estimation of reflectance as a function of Fx. /// </summary> public class pMCROfFxAndTimeDetectorInput : DetectorInput, IDetectorInput { /// <summary> /// constructor for pMC reflectance as a function of Fx detector input /// </summary> public pMCROfFxAndTimeDetectorInput() { TallyType = "pMCROfFxAndTime"; Name = "pMCROfFxAndTime"; Fx = new DoubleRange(0.0, 10, 101); // modify base class TallyDetails to take advantage of built-in validation capabilities (error-checking) TallyDetails.IspMCReflectanceTally = true; } /// <summary> /// detector Fx binning /// </summary> public DoubleRange Fx { get; set; } /// <summary> /// time binning /// </summary> public DoubleRange Time { get; set; } /// <summary> /// list of perturbed OPs listed in order of tissue regions /// </summary> public IList<OpticalProperties> PerturbedOps { get; set; } /// <summary> /// list of perturbed regions indices /// </summary> public IList<int> PerturbedRegionsIndices { get; set; } public IDetector CreateDetector() { return new pMCROfFxAndTimeDetector { // required properties (part of DetectorInput/Detector base classes) TallyType = this.TallyType, Name = this.Name, TallySecondMoment = this.TallySecondMoment, TallyDetails = this.TallyDetails, // optional/custom detector-specific properties Fx = this.Fx, Time = this.Time, PerturbedOps = this.PerturbedOps, PerturbedRegionsIndices = this.PerturbedRegionsIndices, }; } } /// <summary> /// Implements IDetector. Tally for pMC reflectance as a function of Fx. /// This implementation works for DAW and CAW processing. /// </summary> public class pMCROfFxAndTimeDetector : Detector, IDetector { private double[] _fxArray; private IList<OpticalProperties> _referenceOps; private IList<OpticalProperties> _perturbedOps; private IList<int> _perturbedRegionsIndices; private Func<IList<long>, IList<double>, IList<OpticalProperties>, IList<OpticalProperties>, IList<int>, double> _absorbAction; /* ==== Place optional/user-defined input properties here. They will be saved in text (JSON) format ==== */ /* ==== Note: make sure to copy over all optional/user-defined inputs from corresponding input class ==== */ /// <summary> /// Fx binning /// </summary> public DoubleRange Fx { get; set; } /// <summary> /// time binning /// </summary> public DoubleRange Time { get; set; } /// <summary> /// list of perturbed OPs listed in order of tissue regions /// </summary> public IList<OpticalProperties> PerturbedOps { get; set; } /// <summary> /// list of perturbed regions indices /// </summary> public IList<int> PerturbedRegionsIndices { get; set; } /* ==== Place user-defined output arrays here. They should be prepended with "[IgnoreDataMember]" attribute ==== */ /* ==== Then, GetBinaryArrays() should be implemented to save them separately in binary format ==== */ /// <summary> /// detector mean /// </summary> [IgnoreDataMember] public Complex[,] Mean { get; set; } /// <summary> /// detector second moment /// </summary> [IgnoreDataMember] public Complex[,] SecondMoment { get; set; } /* ==== Place optional/user-defined output properties here. They will be saved in text (JSON) format ==== */ /// <summary> /// number of times detector gets tallied to /// </summary> public long TallyCount { get; set; } public void Initialize(ITissue tissue, Random rng) { // assign any user-defined outputs (except arrays...we'll make those on-demand) TallyCount = 0; // if the data arrays are null, create them (only create second moment if TallySecondMoment is true) Mean = Mean ?? new Complex[Fx.Count, Time.Count - 1]; SecondMoment = SecondMoment ?? (TallySecondMoment ? new Complex[Fx.Count, Time.Count - 1] : null); // intialize any other necessary class fields here _perturbedOps = PerturbedOps; _perturbedRegionsIndices = PerturbedRegionsIndices; _referenceOps = tissue.Regions.Select(r => r.RegionOP).ToArray(); _absorbAction = AbsorptionWeightingMethods.GetpMCTerminationAbsorptionWeightingMethod(tissue, this); _fxArray = Fx.AsEnumerable().ToArray(); } /// <summary> /// method to tally to detector /// </summary> /// <param name="photon">photon data needed to tally</param> public void Tally(Photon photon) { var dp = photon.DP; var x = dp.Position.X; var it = DetectorBinning.WhichBin(dp.TotalTime, Time.Count - 1, Time.Delta, Time.Start); if (it != -1) { double weightFactor = _absorbAction( photon.History.SubRegionInfoList.Select(c => c.NumberOfCollisions).ToArray(), photon.History.SubRegionInfoList.Select(p => p.PathLength).ToArray(), _perturbedOps, _referenceOps, _perturbedRegionsIndices); for (int ifx = 0; ifx < _fxArray.Length; ++ifx) { double freq = _fxArray[ifx]; var sinNegativeTwoPiFX = Math.Sin(-2*Math.PI*freq*x); var cosNegativeTwoPiFX = Math.Cos(-2*Math.PI*freq*x); /* convert to Hz-sec from MHz-ns 1e-6*1e9=1e-3 */ // convert to Hz-sec from GHz-ns 1e-9*1e9=1 var deltaWeight = dp.Weight * weightFactor * (cosNegativeTwoPiFX + Complex.ImaginaryOne*sinNegativeTwoPiFX); Mean[ifx, it] += deltaWeight; if (TallySecondMoment) // 2nd moment is E[xx*]=E[xreal^2]+E[ximag^2] { var deltaWeight2 = dp.Weight*dp.Weight*weightFactor*weightFactor*cosNegativeTwoPiFX*cosNegativeTwoPiFX + dp.Weight*dp.Weight*weightFactor*weightFactor*sinNegativeTwoPiFX*sinNegativeTwoPiFX; // second moment of complex tally is square of real and imag separately SecondMoment[ifx, it] += deltaWeight2; } } TallyCount++; } } /// <summary> /// method to normalize detector results after numPhotons launched /// </summary> /// <param name="numPhotons">number of photons launched</param> public void Normalize(long numPhotons) { for (int ifx = 0; ifx < Fx.Count; ifx++) { for (int it = 0; it < Time.Count - 1; it++) { Mean[ifx, it] /= Time.Delta * numPhotons; if (TallySecondMoment) { SecondMoment[ifx, it] /= Time.Delta * Time.Delta * numPhotons; } } } } // this is to allow saving of large arrays separately as a binary file public BinaryArraySerializer[] GetBinarySerializers() // NEED TO ASK DC: about complex array implementation { return new[] { new BinaryArraySerializer { DataArray = Mean, Name = "Mean", FileTag = "", WriteData = binaryWriter => { for (int i = 0; i < Fx.Count; i++) { for (int j = 0; j < Time.Count - 1; j++) { binaryWriter.Write(Mean[i, j].Real); binaryWriter.Write(Mean[i, j].Imaginary); } } }, ReadData = binaryReader => { Mean = Mean ?? new Complex[ Fx.Count, Time.Count - 1]; for (int i = 0; i < Fx.Count - 1; i++) { for (int j = 0; j < Time.Count - 1; j++) { var real = binaryReader.ReadDouble(); var imag = binaryReader.ReadDouble(); Mean[i, j] = new Complex(real, imag); } } } }, // return a null serializer, if we're not serializing the second moment !TallySecondMoment ? null : new BinaryArraySerializer { DataArray = SecondMoment, Name = "SecondMoment", FileTag = "_2", WriteData = binaryWriter => { if (!TallySecondMoment || SecondMoment == null) return; for (int i = 0; i < Fx.Count; i++) { for (int j = 0; j < Time.Count - 1; j++) { binaryWriter.Write(SecondMoment[i, j].Real); binaryWriter.Write(SecondMoment[i, j].Imaginary); } } }, ReadData = binaryReader => { if (!TallySecondMoment || SecondMoment == null) return; SecondMoment = new Complex[ Fx.Count, Time.Count - 1]; for (int i = 0; i < Fx.Count - 1; i++) { for (int j = 0; j < Time.Count - 1; j++) { var real = binaryReader.ReadDouble(); var imag = binaryReader.ReadDouble(); SecondMoment[i, j] = new Complex(real, imag); } } }, }, }; } /// <summary> /// Method to determine if photon is within detector /// </summary> /// <param name="dp">photon data point</param> /// <returns>method always returns true</returns> public bool ContainsPoint(PhotonDataPoint dp) { return true; // or, possibly test for NA or confined position, etc // return (dp.StateFlag.Has(PhotonStateType.PseudoTransmissionDomainTopBoundary)); } } }
42.864662
135
0.509472
[ "MIT" ]
VirtualPhotonics/Vts.Silverlight
src/Vts/MonteCarlo/Detectors/pMCROfFxAndTimeDetector.cs
11,404
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* DirectAccess64.cs -- direct reading IRBIS64 databases * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.Collections.Generic; using System.IO; using AM.Logging; using CodeJam; using JetBrains.Annotations; using ManagedIrbis.Search; using MoonSharp.Interpreter; #endregion namespace ManagedIrbis.Direct { // // Начиная с 2014.1 // // Добавлена возможность фрагментации словаря БД. // // При значительных объемах БД (более 1 млн. записей) // фрагментация словаря БД существенно ускоряет актуализацию записей. // // В связи с этим в INI-файл (irbisa.ini) добавлен новый параметр // // CREATE_OLD_INVERTION_FILES=1 // // который принимает значения: 1 (по умолчанию) - нет фрагментации // 0 - есть фрагментация. // // Использовать фрагментацию словаря (т.е. устанавливать значение 0) // имеет смысл при работе с БД, содержащими более 1 млн. записей. // // При включении фрагментации (CREATE_OLD_INVERTION_FILES=0) // для непустой БД (MFN>0) необходимо выполнить режим // СОЗДАТЬ СЛОВАРЬ ЗАНОВО. // // В таблицу описания БД в интерфейсе АРМа Администратор добавлена // строка, отражающая состояние БД в части фрагментации словаря: // ФРАГМЕНТАЦИЯ СЛОВАРЯ - Да/Нет. // // // Начиная с 2015.1 // // Обеспечена возможность фрагментации файла документов // (по умолчанию отсутствует), что позволяет распараллелить // (а следовательно и ускорить) процессы одновременного редактирования // записей из разных диапазонов MFN. Данный режим рекомендуется // применять при активной книговыдаче для баз данных читателей // RDR и электронного каталога. // // Чтобы включить режим фрагментации файла документов, надо установить // в ини файле АРМ Администратор параметр // MST_NUM_FRAGMENTS=N // (где N принимает значения от 2 до 32 и определяет количество // фрагментов, на которые разбивается файл документов) // после чего сделать РЕОРГАНИЗАЦИЮ ФАЙЛА ДОКУМЕНТОВ. // Параметр фрагментации сохраняется непосредственно в базе данных, // так что все дальнейшие операции (на сервере или в АРМ Администратор), // кроме РЕОРГАНИЗАЦИИ ФАЙЛА ДОКУМЕНТОВ, параметр MST_NUM_FRAGMENTS // не используют. // В результате фрагментации образуется N пар файлов MST и XRF. // Нумерация начинается с индекса 0 и сохраняется в расширении этих файлов, // например, IBIS.MST1 IBIS.XRF1, причем индекс 0 не используется, // т.е. IBIS.MST0 пишется как IBIS.MST. Новые записи сохраняются // в последнем фрагменте файла документов (с индексом N–1), // поэтому при существенном изменении общего объема БД необходимо // проводить РЕОРГАНИЗАЦИЮ ФАЙЛА ДОКУМЕНТОВ (в результате чего фрагментация, // т.е. распределение записей по фрагментам будет выполнена заново.) // // Фактически не работает // /// <summary> /// Direct reading IRBIS64 databases. /// </summary> [PublicAPI] [MoonSharpUserData] public sealed class DirectAccess64 : IDisposable { #region Properties /// <summary> /// Master file. /// </summary> [NotNull] public MstFile64 Mst { get; private set; } /// <summary> /// Cross-references file. /// </summary> [NotNull] public XrfFile64 Xrf { get; private set; } /// <summary> /// Inverted (index) file. /// </summary> [NotNull] public InvertedFile64 InvertedFile { get; private set; } /// <summary> /// Database path. /// </summary> [NotNull] public string Database { get; private set; } #endregion #region Construction /// <summary> /// Constructor. /// </summary> public DirectAccess64 ( [NotNull] string masterFile ) : this(masterFile, DirectAccessMode.Exclusive) { } /// <summary> /// Constructor. /// </summary> public DirectAccess64 ( [NotNull] string masterFile, DirectAccessMode mode ) { Code.NotNullNorEmpty(masterFile, "masterFile"); Database = Path.GetFileNameWithoutExtension(masterFile); Mst = new MstFile64(Path.ChangeExtension(masterFile, ".mst"), mode); Xrf = new XrfFile64(Path.ChangeExtension(masterFile, ".xrf"), mode); InvertedFile = new InvertedFile64(Path.ChangeExtension(masterFile, ".ifp"), mode); } #endregion #region Public methods /// <summary> /// Get database info. /// </summary> [NotNull] public DatabaseInfo GetDatabaseInfo() { int maxMfn = GetMaxMfn(); List<int> logicallyDeleted = new List<int>(); List<int> physicallyDeleted = new List<int>(); List<int> nonActualized = new List<int>(); List<int> lockedRecords = new List<int>(); for (int mfn = 1; mfn <= maxMfn; mfn++) { XrfRecord64 record = Xrf.ReadRecord(mfn); if ((record.Status & RecordStatus.LogicallyDeleted) != 0) { logicallyDeleted.Add(mfn); } if ((record.Status & RecordStatus.PhysicallyDeleted) != 0) { physicallyDeleted.Add(mfn); } if ((record.Status & RecordStatus.NonActualized) != 0) { nonActualized.Add(mfn); } if ((record.Status & RecordStatus.Locked) != 0) { lockedRecords.Add(mfn); } } DatabaseInfo result = new DatabaseInfo { MaxMfn = maxMfn, DatabaseLocked = Mst.ReadDatabaseLockedFlag(), LogicallyDeletedRecords = logicallyDeleted.ToArray(), PhysicallyDeletedRecords = physicallyDeleted.ToArray(), NonActualizedRecords = nonActualized.ToArray(), LockedRecords = lockedRecords.ToArray() }; return result; } /// <summary> /// Get max MFN for database. Not next MFN! /// </summary> public int GetMaxMfn() { return Mst.ControlRecord.NextMfn - 1; } /// <summary> /// Read raw record. /// </summary> [CanBeNull] public MstRecord64 ReadRawRecord ( int mfn ) { Code.Positive(mfn, "mfn"); XrfRecord64 xrfRecord = Xrf.ReadRecord(mfn); if (xrfRecord.Offset == 0) { return null; } MstRecord64 result = Mst.ReadRecord(xrfRecord.Offset); return result; } /// <summary> /// Read record with given MFN. /// </summary> [CanBeNull] public MarcRecord ReadRecord ( int mfn ) { Code.Positive(mfn, "mfn"); XrfRecord64 xrfRecord = Xrf.ReadRecord(mfn); if (xrfRecord.Offset == 0 || (xrfRecord.Status & RecordStatus.PhysicallyDeleted) != 0) { return null; } MstRecord64 mstRecord = Mst.ReadRecord(xrfRecord.Offset); MarcRecord result = mstRecord.DecodeRecord(); result.Database = Database; return result; } /// <summary> /// Read all versions of the record. /// </summary> [NotNull] public MarcRecord[] ReadAllRecordVersions ( int mfn ) { Code.Positive(mfn, "mfn"); List<MarcRecord> result = new List<MarcRecord>(); MarcRecord lastVersion = ReadRecord(mfn); if (lastVersion != null) { result.Add(lastVersion); while (true) { long offset = lastVersion.PreviousOffset; if (offset == 0) { break; } MstRecord64 mstRecord = Mst.ReadRecord(offset); MarcRecord previousVersion = mstRecord.DecodeRecord(); previousVersion.Database = lastVersion.Database; previousVersion.Mfn = lastVersion.Mfn; result.Add(previousVersion); lastVersion = previousVersion; } } return result.ToArray(); } /// <summary> /// Read links for the term. /// </summary> [NotNull] [ItemNotNull] public TermLink[] ReadLinks ( [NotNull] string key ) { Code.NotNull(key, "key"); return InvertedFile.SearchExact(key); } /// <summary> /// Read terms. /// </summary> [NotNull] [ItemNotNull] public TermInfo[] ReadTerms ( [NotNull] TermParameters parameters ) { Code.NotNull(parameters, "parameters"); TermInfo[] result = InvertedFile.ReadTerms(parameters); return result; } /// <summary> /// Reopen files. /// </summary> public void ReopenFiles ( DirectAccessMode newMode ) { Mst.ReopenFile(newMode); Xrf.ReopenFile(newMode); InvertedFile.ReopenFiles(newMode); } /// <summary> /// Simple search. /// </summary> [NotNull] public int[] SearchSimple ( [NotNull] string key ) { Code.NotNullNorEmpty(key, "key"); int[] found = InvertedFile.SearchSimple(key); List<int> result = new List<int>(); foreach (int mfn in found) { if (!Xrf.ReadRecord(mfn).Deleted) { result.Add(mfn); } } return result.ToArray(); } /// <summary> /// Simple search and read records. /// </summary> [NotNull] public MarcRecord[] SearchReadSimple ( [NotNull] string key ) { Code.NotNullNorEmpty(key, "key"); int[] mfns = InvertedFile.SearchSimple(key); List<MarcRecord> result = new List<MarcRecord>(); foreach (int mfn in mfns) { try { XrfRecord64 xrfRecord = Xrf.ReadRecord(mfn); if (!xrfRecord.Deleted) { MstRecord64 mstRecord = Mst.ReadRecord(xrfRecord.Offset); if (!mstRecord.Deleted) { MarcRecord irbisRecord = mstRecord.DecodeRecord(); irbisRecord.Database = Database; result.Add(irbisRecord); } } } catch (Exception exception) { Log.TraceException ( "DirectReader64::SearchReadSimple", exception ); } } return result.ToArray(); } /// <summary> /// Write the record. /// </summary> public void WriteRawRecord ( [NotNull] MstRecord64 mstRecord ) { Code.NotNull(mstRecord, "mstRecord"); MstRecordLeader64 leader = mstRecord.Leader; int mfn = leader.Mfn; XrfRecord64 xrfRecord; if (mfn == 0) { mfn = Mst.ControlRecord.NextMfn; leader.Mfn = mfn; MstControlRecord64 control = Mst.ControlRecord; control.NextMfn = mfn + 1; Mst.ControlRecord = control; xrfRecord = new XrfRecord64 { Mfn = mfn, Offset = Mst.WriteRecord(mstRecord), Status = (RecordStatus)leader.Status }; } else { xrfRecord = Xrf.ReadRecord(mfn); long previousOffset = xrfRecord.Offset; leader.Previous = previousOffset; MstRecordLeader64 previousLeader = Mst.ReadLeader(previousOffset); previousLeader.Status = (int)RecordStatus.NonActualized; Mst.UpdateLeader(previousLeader, previousOffset); xrfRecord.Offset = Mst.WriteRecord(mstRecord); } Xrf.WriteRecord(xrfRecord); Mst.UpdateControlRecord(false); } /// <summary> /// Write the record. /// </summary> public void WriteRecord ( [NotNull] MarcRecord record ) { Code.NotNull(record, "record"); if (record.Version < 0) { record.Version = 0; } record.Version++; record.Status |= RecordStatus.Last | RecordStatus.NonActualized; MstRecord64 mstRecord64 = MstRecord64.EncodeRecord(record); WriteRawRecord(mstRecord64); record.Database = Database; record.Mfn = mstRecord64.Leader.Mfn; record.PreviousOffset = mstRecord64.Leader.Previous; } #endregion #region IDisposable members /// <inheritdoc cref="IDisposable.Dispose" /> public void Dispose() { Mst.Dispose(); Xrf.Dispose(); InvertedFile.Dispose(); } #endregion } }
29.963115
94
0.510874
[ "MIT" ]
fossabot/ManagedIrbis
Source/Classic/Libs/ManagedIrbis/Source/Direct/DirectAccess64.cs
16,273
C#