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) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime
{
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using static Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Extensions;
public class RestException : Exception, IDisposable
{
public System.Net.HttpStatusCode StatusCode { get; set; }
public string Code { get; protected set; }
protected string message;
public HttpRequestMessage RequestMessage { get; protected set; }
public HttpResponseHeaders ResponseHeaders { get; protected set; }
public string ResponseBody { get; protected set; }
public string ClientRequestId { get; protected set; }
public string RequestId { get; protected set; }
public override string Message => message;
public string Action { get; protected set; }
public RestException(System.Net.Http.HttpResponseMessage response)
{
StatusCode = response.StatusCode;
//CloneWithContent will not work here since the content is disposed after sendAsync
//Besides, it seems there is no need for the request content cloned here.
RequestMessage = response.RequestMessage.Clone();
ResponseBody = response.Content.ReadAsStringAsync().Result;
ResponseHeaders = response.Headers;
RequestId = response.GetFirstHeader("x-ms-request-id");
ClientRequestId = response.GetFirstHeader("x-ms-client-request-id");
try
{
// try to parse the body as JSON, and see if a code and message are in there.
var json = Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Json.JsonObject;
// error message could be in properties.statusMessage
{ message = If(json?.Property("properties"), out var p)
&& If(p?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Json.JsonString>("statusMessage"), out var sm)
? (string)sm : (string)Message; }
// see if there is an error block in the body
json = json?.Property("error") ?? json;
{ Code = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Json.JsonString>("code"), out var c) ? (string)c : (string)StatusCode.ToString(); }
{ message = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Json.JsonString>("message"), out var m) ? (string)m : (string)Message; }
{ Action = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime.Json.JsonString>("action"), out var a) ? (string)a : (string)Action; }
}
#if DEBUG
catch (System.Exception E)
{
System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}");
}
#else
catch
{
// couldn't get the code/message from the body response.
// we'll create one below.
}
#endif
if (string.IsNullOrEmpty(message))
{
if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError)
{
message = $"The server responded with a Request Error, Status: {StatusCode}";
}
else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError)
{
message = $"The server responded with a Server Error, Status: {StatusCode}";
}
else
{
message = $"The server responded with an unrecognized response, Status: {StatusCode}";
}
}
}
public void Dispose()
{
((IDisposable)RequestMessage).Dispose();
}
}
public class RestException<T> : RestException
{
public T Error { get; protected set; }
public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response)
{
Error = error;
}
}
public class UndeclaredResponseException : RestException
{
public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response)
{
}
}
} | 45.211009 | 183 | 0.574675 | [
"MIT"
] | Agazoth/azure-powershell | src/Elastic/generated/runtime/UndeclaredResponseException.cs | 4,820 | C# |
using System;
using Xunit;
namespace Automation.TestFramework.Tests
{
[TestCase("WithErrors-1")]
public class TestCaseWithErrors1 : IDisposable
{
private bool _isExpectedCalled;
private bool _isSummaryCalled;
[Summary("Summary - fails")]
public void Summary()
{
_isSummaryCalled = true;
}
[Precondition(1, "Precondition")]
public void Precondition1()
{
}
[Input(1, "Input - fails")]
public void Input1()
{
throw new Exception("Error thrown");
}
[ExpectedResult(1, "Expected result - skip")]
public void Expected1()
{
_isExpectedCalled = true;
}
public void Dispose()
{
Assert.False(_isExpectedCalled);
Assert.False(_isSummaryCalled);
}
}
[TestCase("WithErrors-2")]
public class TestCaseWithErrors2 : IDisposable
{
private bool _isExpectedCalled;
private bool _isSummaryCalled;
private bool _isInputCalled;
[Summary("Summary - fails")]
public void Summary()
{
_isSummaryCalled = true;
}
[Precondition(1, "Precondition - fails")]
public void Precondition1()
{
throw new Exception("Error thrown");
}
[Input(1, "Input - skip")]
public void Input1()
{
_isInputCalled = true;
}
[ExpectedResult(1, "Expected result - skip")]
public void Expected1()
{
_isExpectedCalled = true;
}
public void Dispose()
{
Assert.False(_isExpectedCalled);
Assert.False(_isInputCalled);
Assert.False(_isSummaryCalled);
}
}
} | 23.85 | 54 | 0.512579 | [
"Apache-2.0"
] | D0tNet4Fun/Automation.TestFramework | Automation.TestFramework.Tests/TestCasesWithErrors.cs | 1,910 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Reposed.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Reposed.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.486111 | 173 | 0.601949 | [
"MIT"
] | JoshLmao/Reposed | Reposed/Reposed/Properties/Resources.Designer.cs | 2,773 | C# |
namespace System.Activities.Presentation.Documents
{
using System.Activities.Presentation;
using System.Activities.Presentation.Internal.Properties;
using System;
using System.Globalization;
/// <summary>
/// This attribute can be placed on the root of a model
/// object graph to specify what view manager should be
/// used to present the view.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
sealed class ViewManagerAttribute : Attribute
{
private Type _viewManagerType;
/// <summary>
/// An empty ViewManagerAttribute allows you to "unset" the view manager from a base class.
/// </summary>
public ViewManagerAttribute()
{
}
/// <summary>
/// Creates a new ViewManager attribute.
/// </summary>
/// <param name="viewManagerType">The type of view manager to use. The type specified must derive from ViewManager.</param>
/// <exception cref="ArgumentNullException">If viewManagerType is null.</exception>
/// <exception cref="ArgumentException">If viewManagerType does not specify a type that derives from ViewManager.</exception>
public ViewManagerAttribute(Type viewManagerType)
{
if (viewManagerType == null) throw FxTrace.Exception.ArgumentNull("viewManagerType");
if (!typeof(ViewManager).IsAssignableFrom(viewManagerType))
{
throw FxTrace.Exception.AsError(new ArgumentException(string.Format(CultureInfo.CurrentCulture,
Resources.Error_InvalidArgumentType,
"viewManagerType",
typeof(ViewManager).FullName)));
}
_viewManagerType = viewManagerType;
}
/// <summary>
/// The type of view manager to create for the model.
/// </summary>
public Type ViewManagerType
{
get { return _viewManagerType; }
}
}
}
| 36.482143 | 133 | 0.631914 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/cdf/src/NetFx40/Tools/System.Activities.Presentation/System/Activities/Presentation/Base/Documents/ViewManagerAttribute.cs | 2,043 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 20.11.2020.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.ExclusiveOr.Complete.NullableInt64.Int64{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1=System.Nullable<System.Int64>;
using T_DATA2=System.Int64;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields
public static class TestSet_001__fields
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_BIGINT";
private const string c_NameOf__COL_DATA2 ="COL2_BIGINT";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2)]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_00a01()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 c_value1=3;
const T_DATA2 c_value2=1;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(2,
c_value1^c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1^r.COL_DATA2)==2 && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (BIN_XOR(").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).T(") = 2) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_00a01
//-----------------------------------------------------------------------
[Test]
public static void Test_00x01()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 c_value1=3;
const T_DATA2 c_value2=1;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(3,
c_value1^c_value2^c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1^r.COL_DATA2^r.COL_DATA2)==3 && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (BIN_XOR(BIN_XOR(").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).T("), ").N("t",c_NameOf__COL_DATA2).T(") = 3) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_00x01
//-----------------------------------------------------------------------
[Test]
public static void Test_00x02()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 c_value1=3;
const T_DATA2 c_value2=1;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(1,
c_value1^(c_value2+c_value2));
var recs=db.testTable.Where(r => (r.COL_DATA1^(r.COL_DATA2+r.COL_DATA2))==1 && r.TEST_ID==testID);
try
{
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}
TestServices.ThrowWeWaitError();
}
catch(lcpi.lib.structure.exceptions.t_invalid_operation_exception e)
{
CheckErrors.PrintException_OK(e);
Assert.AreEqual
(1,
TestUtils.GetRecordCount(e));
CheckErrors.CheckErrorRecord__sql_translator_err__unsupported_binary_operator_type_3
(TestUtils.GetRecord(e,0),
CheckErrors.c_src__EFCoreDataProvider__FB_Common__BinaryOperatorTranslatorProvider,
Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.LcpiOleDb__ExpressionType.ExclusiveOr,
typeof(System.Int64),
typeof(System.Double));
}//catch
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_00x02
//-----------------------------------------------------------------------
[Test]
public static void Test_10a01__nullV1()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA2 c_value2=1;
System.Int64? testID=Helper__InsertRow(db,null,c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1^r.COL_DATA2)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N("t",c_NameOf__COL_DATA1).IS_NULL().T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_10a01__nullV1
//-----------------------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.ExclusiveOr.Complete.NullableInt64.Int64
| 26.093567 | 205 | 0.562528 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/ExclusiveOr/Complete/NullableInt64/Int64/TestSet_001__fields.cs | 8,926 | C# |
/*
===============================================================================
EntitySpaces 2010 by EntitySpaces, LLC
Persistence Layer and Business Objects for Microsoft .NET
EntitySpaces(TM) is a legal trademark of EntitySpaces, LLC
http://www.entityspaces.net
===============================================================================
EntitySpaces Version : 2011.0.0321.0
EntitySpaces Driver : SQL
Date Generated : 3/19/2011 6:00:28 PM
===============================================================================
*/
using System;
using EntitySpaces.Core;
using EntitySpaces.Interfaces;
using EntitySpaces.DynamicQuery;
namespace BusinessObjects
{
public partial class OrderDetails : esOrderDetails
{
public OrderDetails()
{
}
}
}
| 27.966667 | 79 | 0.480334 | [
"Unlicense"
] | EntitySpaces/EntitySpaces-CompleteSource | Samples/Silverlight_C#/EntitySpaces.SilverlightApplication.Web/Custom/OrderDetails.cs | 839 | C# |
using System;
using CMS.FormEngine.Web.UI;
using CMS.Helpers;
using CMS.UIControls;
public partial class CMSAdminControls_UI_Selectors_FaviconSelector : FormEngineUserControl
{
private bool mEnabled = true;
/// <summary>
/// Gets or sets if value can be changed.
/// </summary>
public override bool Enabled
{
get
{
return mEnabled;
}
set
{
mEnabled = value;
// Sets all FaviconSelector components as Enabled or Disabled depending on value
pnlSingleFileSelector.Enabled = value;
pnlMultipleFileSelector.Enabled = value;
radSingleFavicon.Enabled = value;
radMultipleFavicons.Enabled = value;
}
}
/// <summary>
/// Path to selected favicon.
/// </summary>
public override object Value
{
get
{
return radSingleFavicon.Checked ? fsSingleFavicon.Value : fsMultipleFavicon.Value;
}
set
{
var path = value as string;
// Set setting controls accordingly to the selected path
fsSingleFavicon.Value = path;
fsMultipleFavicon.Value = path;
// Sets radio buttons accordingly to the type of selected path
var isDirectory = !String.IsNullOrWhiteSpace(path) && FileHelper.DirectoryExists(path);
radMultipleFavicons.Checked = isDirectory;
radSingleFavicon.Checked = !isDirectory;
}
}
public override bool IsValid()
{
return radSingleFavicon.Checked ? fsSingleFavicon.IsValid() : fsMultipleFavicon.IsValid();
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
fsSingleFavicon.AllowedExtensions = String.Join(";", FaviconMarkupBuilder.AllowedExtensions);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// Set the proper file selector visible
pnlSingleFileSelector.Visible = radSingleFavicon.Checked;
pnlMultipleFileSelector.Visible = radMultipleFavicons.Checked;
}
protected void component_Changed(object sender, EventArgs e)
{
RaiseOnChanged();
}
} | 26.477273 | 102 | 0.602146 | [
"MIT"
] | CMeeg/kentico-contrib | src/CMS/CMSAdminControls/UI/Selectors/FaviconSelector.ascx.cs | 2,332 | C# |
/*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold (oliver@weichhold.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Reactive;
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using Miningcore.Blockchain.Bitcoin.Configuration;
using Miningcore.Blockchain.Bitcoin.DaemonResponses;
using Miningcore.Configuration;
using Miningcore.Contracts;
using Miningcore.DaemonInterface;
using Miningcore.Extensions;
using Miningcore.JsonRpc;
using Miningcore.Messaging;
using Miningcore.Notifications.Messages;
using Miningcore.Stratum;
using Miningcore.Time;
using Newtonsoft.Json;
using NLog;
namespace Miningcore.Blockchain.Bitcoin
{
public class BitcoinJobManager : BitcoinJobManagerBase<BitcoinJob>
{
public BitcoinJobManager(
IComponentContext ctx,
IMasterClock clock,
IMessageBus messageBus,
IExtraNonceProvider extraNonceProvider) :
base(ctx, clock, messageBus, extraNonceProvider)
{
}
private BitcoinTemplate coin;
protected async Task<DaemonResponse<BlockTemplate>> GetBlockTemplateAsync()
{
logger.LogInvoke();
var result = await daemon.ExecuteCmdAnyAsync<BlockTemplate>(logger,
BitcoinCommands.GetBlockTemplate, extraPoolConfig?.GBTArgs ?? (object) getBlockTemplateParams);
return result;
}
protected DaemonResponse<BlockTemplate> GetBlockTemplateFromJson(string json)
{
logger.LogInvoke();
var result = JsonConvert.DeserializeObject<JsonRpcResponse>(json);
return new DaemonResponse<BlockTemplate>
{
Response = result.ResultAs<BlockTemplate>(),
};
}
private BitcoinJob CreateJob()
{
//switch (coin.Subfamily)
//{
//}
return new BitcoinJob();
}
protected override async Task<(bool IsNew, bool Force)> UpdateJob(bool forceUpdate, string via = null, string json = null)
{
logger.LogInvoke();
try
{
if(forceUpdate)
lastJobRebroadcast = clock.Now;
var response = string.IsNullOrEmpty(json) ?
await GetBlockTemplateAsync() :
GetBlockTemplateFromJson(json);
// may happen if daemon is currently not connected to peers
if(response.Error != null)
{
logger.Warn(() => $"Unable to update job. Daemon responded with: {response.Error.Message} Code {response.Error.Code}");
return (false, forceUpdate);
}
var blockTemplate = response.Response;
var job = currentJob;
var isNew = job == null ||
(blockTemplate != null &&
(job.BlockTemplate?.PreviousBlockhash != blockTemplate.PreviousBlockhash ||
blockTemplate.Height > job.BlockTemplate?.Height));
if(isNew)
messageBus.NotifyChainHeight(poolConfig.Id, blockTemplate.Height, poolConfig.Template);
if(isNew || forceUpdate)
{
job = CreateJob();
job.Init(blockTemplate, NextJobId(),
poolConfig, extraPoolConfig, clusterConfig, clock, poolAddressDestination, network, isPoS,
ShareMultiplier, coin.CoinbaseHasherValue, coin.HeaderHasherValue,
!isPoS ? coin.BlockHasherValue : coin.PoSBlockHasherValue ?? coin.BlockHasherValue);
lock(jobLock)
{
validJobs.Insert(0, job);
// trim active jobs
while(validJobs.Count > maxActiveJobs)
validJobs.RemoveAt(validJobs.Count - 1);
}
if(isNew)
{
if(via != null)
logger.Info(() => $"Detected new block {blockTemplate.Height} [{via}]");
else
logger.Info(() => $"Detected new block {blockTemplate.Height}");
// update stats
BlockchainStats.LastNetworkBlockTime = clock.Now;
BlockchainStats.BlockHeight = blockTemplate.Height;
BlockchainStats.NetworkDifficulty = job.Difficulty;
BlockchainStats.NextNetworkTarget = blockTemplate.Target;
BlockchainStats.NextNetworkBits = blockTemplate.Bits;
}
currentJob = job;
}
return (isNew, forceUpdate);
}
catch(Exception ex)
{
logger.Error(ex, () => $"Error during {nameof(UpdateJob)}");
}
return (false, forceUpdate);
}
protected override object GetJobParamsForStratum(bool isNew)
{
var job = currentJob;
return job?.GetJobParams(isNew);
}
#region API-Surface
public override void Configure(PoolConfig poolConfig, ClusterConfig clusterConfig)
{
coin = poolConfig.Template.As<BitcoinTemplate>();
extraPoolConfig = poolConfig.Extra.SafeExtensionDataAs<BitcoinPoolConfigExtra>();
extraPoolPaymentProcessingConfig = poolConfig.PaymentProcessing?.Extra?.SafeExtensionDataAs<BitcoinPoolPaymentProcessingConfigExtra>();
if(extraPoolConfig?.MaxActiveJobs.HasValue == true)
maxActiveJobs = extraPoolConfig.MaxActiveJobs.Value;
hasLegacyDaemon = extraPoolConfig?.HasLegacyDaemon == true;
base.Configure(poolConfig, clusterConfig);
}
public override object[] GetSubscriberData(StratumClient worker)
{
Contract.RequiresNonNull(worker, nameof(worker));
var context = worker.ContextAs<BitcoinWorkerContext>();
// assign unique ExtraNonce1 to worker (miner)
context.ExtraNonce1 = extraNonceProvider.Next();
// setup response data
var responseData = new object[]
{
context.ExtraNonce1,
BitcoinConstants.ExtranoncePlaceHolderLength - ExtranonceBytes,
};
return responseData;
}
public override async ValueTask<Share> SubmitShareAsync(StratumClient worker, object submission,
double stratumDifficultyBase, CancellationToken ct)
{
Contract.RequiresNonNull(worker, nameof(worker));
Contract.RequiresNonNull(submission, nameof(submission));
logger.LogInvoke(new[] { worker.ConnectionId });
if(!(submission is object[] submitParams))
throw new StratumException(StratumError.Other, "invalid params");
var context = worker.ContextAs<BitcoinWorkerContext>();
// extract params
var workerValue = (submitParams[0] as string)?.Trim();
var jobId = submitParams[1] as string;
var extraNonce2 = submitParams[2] as string;
var nTime = submitParams[3] as string;
var nonce = submitParams[4] as string;
var versionBits = context.VersionRollingMask.HasValue ? submitParams[5] as string : null;
if(string.IsNullOrEmpty(workerValue))
throw new StratumException(StratumError.Other, "missing or invalid workername");
BitcoinJob job;
lock(jobLock)
{
job = validJobs.FirstOrDefault(x => x.JobId == jobId);
}
if(job == null)
throw new StratumException(StratumError.JobNotFound, "job not found");
// extract worker/miner/payoutid
var split = workerValue.Split('.');
var minerName = split[0];
var workerName = split.Length > 1 ? split[1] : null;
// validate & process
var (share, blockHex) = job.ProcessShare(worker, extraNonce2, nTime, nonce, versionBits);
// enrich share with common data
share.PoolId = poolConfig.Id;
share.IpAddress = worker.RemoteEndpoint.Address.ToString();
share.Miner = minerName;
share.Worker = workerName;
share.UserAgent = context.UserAgent;
share.Source = clusterConfig.ClusterName;
share.Created = clock.Now;
// if block candidate, submit & check if accepted by network
if(share.IsBlockCandidate)
{
logger.Info(() => $"Submitting block {share.BlockHeight} [{share.BlockHash}]");
var acceptResponse = await SubmitBlockAsync(share, blockHex);
// is it still a block candidate?
share.IsBlockCandidate = acceptResponse.Accepted;
if(share.IsBlockCandidate)
{
logger.Info(() => $"Daemon accepted block {share.BlockHeight} [{share.BlockHash}] submitted by {minerName}");
OnBlockFound();
// persist the coinbase transaction-hash to allow the payment processor
// to verify later on that the pool has received the reward for the block
share.TransactionConfirmationData = acceptResponse.CoinbaseTx;
}
else
{
// clear fields that no longer apply
share.TransactionConfirmationData = null;
}
}
return share;
}
public double ShareMultiplier => coin.ShareMultiplier;
#endregion // API-Surface
}
}
| 37.532423 | 147 | 0.595344 | [
"MIT"
] | EsyWin/miningcore | src/Miningcore/Blockchain/Bitcoin/BitcoinJobManager.cs | 10,997 | C# |
using System;
namespace Shop.Module.Shipments.Abstractions.ViewModels
{
public class ShipmentQueryItemResult
{
public int Id { get; set; }
public int ShipmentId { get; set; }
public int OrderItemId { get; set; }
public int ProductId { get; set; }
/// <summary>
/// 产品名称(快照)
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// 产品图片(快照)
/// </summary>
public string ProductMediaUrl { get; set; }
/// <summary>
/// 下单数量
/// </summary>
public int OrderedQuantity { get; set; }
/// <summary>
/// 已发货数量
/// </summary>
public int ShippedQuantity { get; set; }
public int Quantity { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
}
}
| 21.428571 | 55 | 0.518889 | [
"MIT"
] | cn-cam/module-shop | src/server/src/Modules/Shop.Module.Shipments.Abstractions/ViewModels/ShipmentQueryItemResult.cs | 952 | C# |
/******************************************************
Writer:Du YanMing
Mail:dym880@163.com
Create Date:2020/8/18 16:58:35
Functional description: StringOrDelegate
******************************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace Anno.Rpc.Client.Ext
{
public class StringOrDelegate
{
public readonly Delegate DelegateParameter;
public readonly string StringParameter;
public StringOrDelegate(string value, Delegate @delegate = default)
{
DelegateParameter = @delegate;
StringParameter = value;
}
public StringOrDelegate(Delegate @delegate, string value = default)
{
DelegateParameter = @delegate;
StringParameter = value;
}
public static implicit operator StringOrDelegate(string value)
{
return new StringOrDelegate(value);
}
public static implicit operator StringOrDelegate(Delegate value)
{
return new StringOrDelegate(value);
}
}
}
| 28.384615 | 75 | 0.583559 | [
"Apache-2.0"
] | duyanming/Anno.Ext | Anno.Rpc.ExtClient/Ext/StringOrDelegate.cs | 1,111 | C# |
using System;
namespace Ela.Compilation
{
internal struct ExprData
{
internal static readonly ExprData Empty = new ExprData(DataKind.None, 0);
internal ExprData(DataKind type, int data)
{
Type = type;
Data = data;
}
internal readonly DataKind Type;
internal readonly int Data;
}
}
| 16.3 | 76 | 0.665644 | [
"MIT"
] | vorov2/ela | Ela/Ela/Compilation/ExprData.cs | 328 | C# |
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
using ClangSharp.Interop;
namespace ClangSharp
{
public sealed class CXXStaticCastExpr : CXXNamedCastExpr
{
internal CXXStaticCastExpr(CXCursor handle) : base(handle, CXCursorKind.CXCursor_CXXStaticCastExpr, CX_StmtClass.CX_StmtClass_CXXStaticCastExpr)
{
}
}
}
| 33.5 | 169 | 0.752665 | [
"MIT"
] | Color-Of-Code/ClangSharp | sources/ClangSharp/Cursors/Exprs/CXXStaticCastExpr.cs | 469 | C# |
using Fungus.Actor.Turn;
using Fungus.GameSystem;
using Fungus.GameSystem.Data;
using System;
using UnityEngine;
namespace Fungus.Actor.AI
{
public class NPCMemory : MonoBehaviour, ITurnCounter
{
private int forgetCounter;
private int increaseMemory;
private int maxMemory;
public int[] PCPosition { get; private set; }
public void Count()
{
forgetCounter--;
forgetCounter = Math.Max(0, forgetCounter);
if (forgetCounter == 0)
{
PCPosition = new int[2];
}
}
public bool RememberPC()
{
return forgetCounter > 0;
}
public void Trigger()
{
if (GetComponent<AIVision>().CanSeeTarget(SubObjectTag.PC))
{
PCPosition = FindObjects.GameLogic
.GetComponent<ConvertCoordinates>().Convert(
FindObjects.PC.transform.position);
forgetCounter += increaseMemory;
forgetCounter = Math.Min(maxMemory, forgetCounter);
}
}
private void Awake()
{
increaseMemory = 3;
maxMemory = 6;
PCPosition = new int[2];
forgetCounter = 0;
}
}
}
| 23.607143 | 71 | 0.526475 | [
"MIT"
] | Bozar/FungusCave | Assets/Scripts/NPCMemory.cs | 1,324 | C# |
// SPDX-FileCopyrightText: 2021 Open Energy Solutions Inc
//
// SPDX-License-Identifier: Apache-2.0
using OpenFMB.Adapters.Core;
using OpenFMB.Adapters.Core.Models;
using OpenFMB.Adapters.Core.Models.Logging;
using OpenFMB.Adapters.Core.Models.Plugins;
using OpenFMB.Adapters.Core.Parsers;
using OpenFMB.Adapters.Core.Utility;
using OpenFMB.Adapters.Core.Utility.Logs;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace OpenFMB.Adapters.Configuration
{
public partial class ConfigurationControl : UserControl, IWindowViewControl
{
private readonly string LoggingSectionKey = "LoggingSectionControl";
private readonly string PluginsSectionKey = "PluginsSectionControl";
private readonly string PluginKey = "PluginControl";
private readonly string SessionSettingsControlKey = "SessionSettingsControl";
private readonly string ProfileSettingsControlKey = "ProfileSettingsControl";
private readonly string AdapterConfigurationKey = "AdapterConfiguration";
private readonly string FileInfoControlKey = "FileInfoControl";
private readonly ConfigurationManager _configurationManager = ConfigurationManager.Instance;
private const int FolderIcon = 3;
private const int ActiveEditorIcon = 4;
private readonly ILogger _logger = MasterLogger.Instance;
private DataNode _copiedDataNode;
public string Caption
{
get { return _configurationManager.WorkingDirectory.TruncateFile(); }
}
public string WorkspaceDir
{
get { return _configurationManager.WorkingDirectory; }
}
public ConfigurationControl()
{
InitializeComponent();
toolTip.SetToolTip(expandButton, "Hide/Show Navigation Pane");
toolTip.SetToolTip(logShowHideButton, "Hide/Show Log Pane");
toolTip.SetToolTip(saveAdapterButton, "Save");
toolTip.SetToolTip(closeAdapterButton, "Close");
toolTip.SetToolTip(newConfigButton, "New Adapter Configuration");
toolTip.SetToolTip(newTemplateButton, "New Adapter Configuration");
_configurationManager.OnConfigurationSaved += OnConfigurationSaved;
LoadFile(_configurationManager.ActiveConfiguration);
LoadWorkspaceTree();
if (adapterTreeView.Nodes.Count > 0)
{
tabControl.SelectedIndex = 1;
}
else
{
tabControl.SelectedIndex = 0;
}
_configurationManager.OnFileSystemChanged += FileSystemWatcher_Changed;
_configurationManager.OnFileSystemDeleted += FileSystemWatcher_DeletedOrRenamed;
_configurationManager.OnFileSystemRenamed += FileSystemWatcher_DeletedOrRenamed;
_configurationManager.OnFileSystemCreated += FileSystemWatcher_Created;
// Hide logs
detailSplitContainer.Panel2Collapsed = true;
}
private void LoadFile(Editable editable)
{
if (editable is AdapterConfiguration)
{
LoadFile(editable as AdapterConfiguration);
}
else
{
LoadFile(editable as Session);
}
}
private void LoadFile(AdapterConfiguration adapterConfiguration)
{
adapterTreeView.Nodes.Clear();
activeEditorPanel.Visible = false;
if (adapterConfiguration == null)
{
return;
}
var adapterName = string.IsNullOrEmpty(adapterConfiguration.FullPath) ? "adapter" : Path.GetFileNameWithoutExtension(adapterConfiguration.FullPath);
TreeNode node = new TreeNode(adapterName);
node.ToolTipText = adapterConfiguration.FullPath;
node.Tag = adapterConfiguration;
adapterTreeView.Nodes.Add(node);
TreeNode logging = new TreeNode(adapterConfiguration.Logging.Name)
{
Tag = adapterConfiguration.Logging
};
node.Nodes.Add(logging);
TreeNode plugins = new TreeNode(adapterConfiguration.Plugins.Name)
{
Tag = adapterConfiguration.Plugins
};
node.Nodes.Add(plugins);
foreach (var p in adapterConfiguration.Plugins.Plugins)
{
var pNode = new TreeNode(p.Name)
{
Tag = p
};
plugins.Nodes.Add(pNode);
if (p is ISessionable)
{
foreach (var session in (p as ISessionable).Sessions)
{
var sNode = new TreeNode(session.Name)
{
Tag = session
};
pNode.Nodes.Add(sNode);
foreach (var profile in session.SessionConfiguration?.GetProfiles())
{
var profileNode = new ProfileTreeNode(profile)
{
Tag = profile
};
sNode.Nodes.Add(profileNode);
}
}
}
}
adapterTreeView.ExpandAll();
if (adapterTreeView.Nodes.Count > 0)
{
activeEditorLink.Text = Path.GetFileName(adapterConfiguration.FullPath);
toolTip.SetToolTip(activeEditorLink, $"{adapterConfiguration.FullPath}");
activeEditorLink.Tag = new FileNode
{
Path = adapterConfiguration.FullPath,
FileInformation = ConfigurationManager.GetFileInformation(adapterConfiguration.FullPath),
};
activeEditorPanel.Visible = true;
// enable save and close buttons
saveAdapterButton.Enabled = closeAdapterButton.Enabled = true;
}
}
private void LoadFile(Session session)
{
adapterTreeView.Nodes.Clear();
activeEditorPanel.Visible = false;
if (session == null)
{
return;
}
session.IsStandAlone = true;
var adapterName = session.LocalFilePath;
TreeNode node = new TreeNode(adapterName);
node.ToolTipText = session.LocalFilePath;
node.Tag = session;
adapterTreeView.Nodes.Add(node);
foreach (var profile in session.SessionConfiguration?.GetProfiles())
{
var profileNode = new ProfileTreeNode(profile)
{
Tag = profile
};
node.Nodes.Add(profileNode);
}
adapterTreeView.ExpandAll();
if (adapterTreeView.Nodes.Count > 0)
{
activeEditorLink.Text = Path.GetFileName(session.FullPath);
toolTip.SetToolTip(activeEditorLink, $"{session.FullPath}");
activeEditorLink.Tag = new FileNode
{
Path = session.FullPath,
FileInformation = ConfigurationManager.GetFileInformation(session.FullPath),
};
activeEditorPanel.Visible = true;
// enable save and close buttons
saveAdapterButton.Enabled = closeAdapterButton.Enabled = true;
}
}
private Control FindControl(string key)
{
var controls = placeHolder.Controls.Find(key, true);
return controls != null && controls.Length > 0 ? controls[0] : null;
}
private Control FindSessionControl(string key, object session)
{
var controls = placeHolder.Controls.Find(key, true);
if (controls != null)
{
foreach(Control c in controls)
{
SessionSettingsControl sc = c as SessionSettingsControl;
if (sc != null && sc.DataSource == session)
{
return sc;
}
}
}
return null;
}
private Control FindProfileControl(string key, object profile)
{
var controls = placeHolder.Controls.Find(key, true);
if (controls != null)
{
foreach (Control c in controls)
{
ProfileTreeControl sc = c as ProfileTreeControl;
if (sc != null && sc.DataSource == profile)
{
return sc;
}
}
}
return null;
}
private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node.Tag is LoggingSection)
{
LoggingSectionControl c = FindControl(LoggingSectionKey) as LoggingSectionControl;
if (c == null)
{
c = new LoggingSectionControl()
{
Name = LoggingSectionKey,
Dock = DockStyle.Fill
};
c.PropertyChanged += OnPropertyChanged;
placeHolder.Controls.Add(c);
}
c.DataSource = e.Node.Tag;
c.BringToFront();
}
else if (e.Node.Tag is PluginsSection)
{
PluginsSectionControl c = FindControl(PluginsSectionKey) as PluginsSectionControl;
if (c == null)
{
c = new PluginsSectionControl()
{
Name = PluginsSectionKey,
Dock = DockStyle.Fill
};
c.PropertyChanged += OnPropertyChanged;
c.OnPluginSelected += OnPluginSelected;
placeHolder.Controls.Add(c);
}
c.DataSource = e.Node.Tag;
c.BringToFront();
}
else if (e.Node.Tag is IPlugin)
{
var pluginType = e.Node.Tag.GetType().Name + "Control";
BaseDetailControl c = FindControl(pluginType) as BaseDetailControl;
if (c == null)
{
Type type = Type.GetType("OpenFMB.Adapters.Configuration." + pluginType);
if (type != null)
{
var temp = Activator.CreateInstance(type);
c = Activator.CreateInstance(type) as BaseDetailControl;
c.Name = pluginType;
c.Dock = DockStyle.Fill;
c.PropertyChanged += OnPropertyChanged;
placeHolder.Controls.Add(c);
}
}
if (c == null)
{
c = FindControl(PluginKey) as BaseDetailControl;
if (c == null)
{
c = new PluginControl()
{
Name = PluginKey,
Dock = DockStyle.Fill
};
c.PropertyChanged += OnPropertyChanged;
placeHolder.Controls.Add(c);
}
}
c.DataSource = e.Node.Tag;
c.BringToFront();
}
else if (e.Node.Tag is Session)
{
SessionSettingsControl c = FindSessionControl(SessionSettingsControlKey, e.Node.Tag) as SessionSettingsControl;
if (c == null)
{
c = new SessionSettingsControl()
{
Name = SessionSettingsControlKey,
Dock = DockStyle.Fill
};
c.DataSource = e.Node.Tag;
c.SelectedTreeNode = e.Node;
c.PropertyChanged += OnPropertyChanged;
c.OnLocalFilePathChanged += OnSessionLocalFilePathChanged;
placeHolder.Controls.Add(c);
}
c.BringToFront();
}
else if (e.Node.Tag is Profile)
{
ProfileTreeControl c = FindProfileControl(ProfileSettingsControlKey, e.Node.Tag) as ProfileTreeControl;
if (c == null)
{
c = new ProfileTreeControl()
{
Name = ProfileSettingsControlKey,
Dock = DockStyle.Fill
};
c.DataSource = e.Node.Tag;
c.PropertyChanged += OnPropertyChanged;
placeHolder.Controls.Add(c);
}
c.BringToFront();
}
else {
AdapterConfigurationDetailControl c = FindControl(AdapterConfigurationKey) as AdapterConfigurationDetailControl;
if (c == null)
{
c = new AdapterConfigurationDetailControl()
{
Name = AdapterConfigurationKey,
Dock = DockStyle.Fill
};
c.PropertyChanged += OnPropertyChanged;
placeHolder.Controls.Add(c);
}
c.DataSource = e.Node.Tag;
c.BringToFront();
}
}
private void OnSessionLocalFilePathChanged(object sender, FileChangedEventArgs e)
{
// Check if session is dirty
SessionSettingsControl control = sender as SessionSettingsControl;
var session = control.DataSource as Session;
if (session != null)
{
var result = MessageBox.Show(this, $"You are about apply new session file.{Environment.NewLine}Click YES to proceed.", Program.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.No)
{
return;
}
}
try
{
adapterTreeView.BeginUpdate();
// update
if (!string.IsNullOrWhiteSpace(e.SourceFilePath))
{
// need to copy to working dir
_configurationManager.CopyFile(e.SourceFilePath, e.DestFilePath);
}
var relative = FileHelper.MakeRelativePath(ConfigurationManager.Instance.WorkingDirectory, e.DestFilePath);
relative = FileHelper.ConvertToForwardSlash(relative);
session.Reload(_configurationManager.WorkingDirectory, relative);
TreeNode node = control.SelectedTreeNode;
node.Nodes.Clear();
foreach (var profile in session.SessionConfiguration?.GetProfiles())
{
var profileNode = new ProfileTreeNode(profile)
{
Tag = profile
};
node.Nodes.Add(profileNode);
}
node.Expand();
if (!string.IsNullOrWhiteSpace(e.SourceFilePath))
{
LoadWorkspaceTree();
}
}
catch (Exception ex)
{
MessageBox.Show(this, "An unexpected error occurred when trying to change session file path.", Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Log(Level.Error, ex.Message, ex);
}
finally
{
adapterTreeView.EndUpdate();
}
}
private void OnPluginSelected(object sender, EventArgs e)
{
// navigate to plugin
var section = sender as PluginsSectionControl;
if (section != null)
{
foreach(TreeNode node in adapterTreeView.Nodes[0].Nodes)
{
if (node.Tag == section.DataSource)
{
foreach(TreeNode n in node.Nodes)
{
if (n.Tag == section.Plugin)
{
adapterTreeView.SelectedNode = n;
return;
}
}
}
}
}
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
MarkDirty(true);
}
private void OnConfigurationSaved(object sender, EventArgs e)
{
MarkDirty(false);
}
private void MarkDirty(bool dirty)
{
if (adapterTreeView.Nodes.Count > 0)
{
MarkDirty(dirty, adapterTreeView.Nodes[0]);
}
MarkDirty(dirty, activeEditorLink);
}
private void MarkDirty(bool dirty, TreeNode node)
{
const string txt = " [UNSAVED]";
if (dirty)
{
if (!node.Text.EndsWith(txt))
{
node.Text = node.Text + txt;
}
}
else
{
node.Text = node.Text.Replace(txt, "");
}
}
private void MarkDirty(bool dirty, LinkLabel node)
{
const string txt = " [UNSAVED]";
if (dirty)
{
if (!node.Text.EndsWith(txt))
{
node.Text = node.Text + txt;
}
}
else
{
node.Text = node.Text.Replace(txt, "");
}
}
private void ContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
var selectedNode = adapterTreeView.SelectedNode;
if (selectedNode != null)
{
if (selectedNode.Tag is AdapterConfiguration)
{
openFolderInFileExplorerToolStripMenuItem.Visible = true;
openFolderInFileExplorerToolStripMenuItem.Enabled = true;
addSessionToolStripMenuItem.Visible = false;
deleteSessionToolStripMenuItem.Visible = false;
addProfileToolStripMenuItem.Visible = false;
addProfileFromCSVFileToolStripMenuItem.Visible = false;
deleteProfileToolStripMenuItem.Visible = false;
toolStripSeparator1.Visible = false;
return;
}
else
{
openFolderInFileExplorerToolStripMenuItem.Visible = false;
openFolderInFileExplorerToolStripMenuItem.Enabled = false;
addSessionToolStripMenuItem.Visible = true;
deleteSessionToolStripMenuItem.Visible = true;
addProfileToolStripMenuItem.Visible = true;
addProfileFromCSVFileToolStripMenuItem.Visible = true;
deleteProfileToolStripMenuItem.Visible = true;
toolStripSeparator1.Visible = true;
}
if (selectedNode.Tag is ISessionable)
{
addSessionToolStripMenuItem.Enabled = true;
deleteSessionToolStripMenuItem.Enabled = false;
addProfileToolStripMenuItem.Enabled = false;
addProfileFromCSVFileToolStripMenuItem.Enabled = false;
deleteProfileToolStripMenuItem.Enabled = false;
}
else if (selectedNode.Tag is Session)
{
if (selectedNode == adapterTreeView.Nodes[0])
{
addSessionToolStripMenuItem.Enabled = false;
deleteSessionToolStripMenuItem.Enabled = false;
}
else
{
addSessionToolStripMenuItem.Enabled = false;
deleteSessionToolStripMenuItem.Enabled = true;
}
addProfileToolStripMenuItem.Enabled = true;
addProfileFromCSVFileToolStripMenuItem.Enabled = true;
deleteProfileToolStripMenuItem.Enabled = false;
}
else if (selectedNode.Tag is Profile)
{
addSessionToolStripMenuItem.Enabled = false;
deleteSessionToolStripMenuItem.Enabled = false;
addProfileToolStripMenuItem.Enabled = false;
addProfileFromCSVFileToolStripMenuItem.Enabled = false;
deleteProfileToolStripMenuItem.Enabled = true;
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
}
private void AddProfileToolStripMenuItem_Click(object sender, EventArgs e)
{
Session session = adapterTreeView.SelectedNode?.Tag as Session;
if (session != null)
{
ProfileSelectionForm form = new ProfileSelectionForm();
if (form.ShowDialog() == DialogResult.OK)
{
try
{
var sessionNode = adapterTreeView.SelectedNode;
ISessionable plugin = adapterTreeView.SelectedNode.Parent?.Tag as ISessionable;
foreach (var p in form.SelectedProfiles)
{
MarkDirty(true);
if (plugin != null)
{
plugin.Enabled = true;
}
Profile profile = Profile.Create(p, session.PluginName);
session.SessionConfiguration.AddProfile(profile);
TreeNode pNode = new TreeNode(profile.ProfileName)
{
Tag = profile
};
sessionNode.Nodes.Add(pNode);
if (sessionNode.Nodes.Count > 0)
{
adapterTreeView.SelectedNode = sessionNode.Nodes[sessionNode.Nodes.Count - 1];
}
}
sessionNode.ExpandAll();
_configurationManager.UpdatePubSubTopics();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void AddProfileFromCSVFileToolStripMenuItem_Click(object sender, EventArgs e)
{
Session session = adapterTreeView.SelectedNode?.Tag as Session;
if (session != null)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
Cursor = Cursors.WaitCursor;
ISessionable plugin = adapterTreeView.SelectedNode.Parent?.Tag as ISessionable;
if (plugin != null)
{
plugin.Enabled = true;
}
var profile = CSVParser.Parse(session.PluginName, openFileDialog.FileName);
string mrid = session.LocalFilePath;
var row = profile.CsvData.FirstOrDefault(x => x.Path.EndsWith("mRID"));
if (row != null)
{
mrid = row.Value;
}
session.SessionConfiguration.AddProfile(profile);
TreeNode pNode = new TreeNode(profile.ProfileName)
{
Tag = profile
};
adapterTreeView.SelectedNode.Nodes.Add(pNode);
adapterTreeView.SelectedNode.Expand();
adapterTreeView.SelectedNode = pNode;
_configurationManager.UpdatePubSubTopics();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor = Cursors.Default;
}
}
}
}
private void DeleteProfileToolStripMenuItem_Click(object sender, EventArgs e)
{
var selectedNode = adapterTreeView.SelectedNode;
if (selectedNode != null)
{
var profile = selectedNode.Tag as Profile;
if (profile != null)
{
var parent = selectedNode.Parent;
var session = parent.Tag as Session;
session.SessionConfiguration.DeleteProfile(profile);
selectedNode.Parent.Nodes.Remove(selectedNode);
adapterTreeView.SelectedNode = parent;
parent.Expand();
MarkDirty(true);
var control = FindProfileControl(ProfileSettingsControlKey, profile);
if (control != null)
{
placeHolder.Controls.Remove(control);
}
}
}
}
private void AddSessionToolStripMenuItem_Click(object sender, EventArgs e)
{
ISessionable plugin = adapterTreeView.SelectedNode.Tag as ISessionable;
if (plugin != null)
{
CreateSessionForm form = new CreateSessionForm(plugin);
if (form.ShowDialog() == DialogResult.OK)
{
Session session = form.Output;
var sNode = new TreeNode(session.Name)
{
Tag = session
};
adapterTreeView.SelectedNode.Nodes.Add(sNode);
adapterTreeView.SelectedNode.Expand();
foreach (var profile in session.SessionConfiguration?.GetProfiles())
{
var profileNode = new ProfileTreeNode(profile)
{
Tag = profile
};
sNode.Nodes.Add(profileNode);
}
LoadWorkspaceTree();
MarkDirty(true);
}
}
}
private void DeleteSessionToolStripMenuItem_Click(object sender, EventArgs e)
{
Session session = adapterTreeView.SelectedNode?.Tag as Session;
if (session != null)
{
var result = MessageBox.Show(this, $"Session will be deleted.{Environment.NewLine}Click YES to also delete the referenced template file.{Environment.NewLine}Click NO to keep the referenced template file.{Environment.NewLine}Click CANCEL to abort.", Program.AppName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Cancel)
{
return;
}
var parent = adapterTreeView.SelectedNode.Parent;
var plugin = parent.Tag as ISessionable;
plugin.Sessions.Remove(session);
adapterTreeView.SelectedNode.Remove();
adapterTreeView.SelectedNode = parent;
MarkDirty(true);
var control = FindSessionControl(SessionSettingsControlKey, session);
if (control != null)
{
placeHolder.Controls.Remove(control);
}
if (result == DialogResult.Yes)
{
try
{
File.Delete(Path.Combine(WorkspaceDir, session.LocalFilePath));
}
catch (Exception ex)
{
_logger.Log(Level.Error, ex.Message, ex);
MessageBox.Show(this, $"Unable to delete {session.LocalFilePath}.", Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void OpenFolderInFileExplorerToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
var node = adapterTreeView.SelectedNode;
if (node != null)
{
var config = node.Tag as AdapterConfiguration;
if (config != null)
{
Process.Start(Path.GetDirectoryName(config.FullPath));
}
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ExpandButton_Click(object sender, EventArgs e)
{
mainSplitContainer.Panel1Collapsed = !mainSplitContainer.Panel1Collapsed;
}
private void LogShowHideButton_Click(object sender, EventArgs e)
{
detailSplitContainer.Panel2Collapsed = !detailSplitContainer.Panel2Collapsed;
}
private void LoadWorkspaceTree()
{
try
{
if (workspaceTree.InvokeRequired)
{
workspaceTree.Invoke(new Action(() =>
{
LoadWorkspaceTree();
}));
}
else
{
try
{
workspaceTree.BeginUpdate();
workspaceTree.Nodes.Clear();
var rootDirectoryInfo = new DirectoryInfo(WorkspaceDir);
workspaceTree.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
workspaceTree.ExpandAll();
}
finally
{
workspaceTree.EndUpdate();
}
}
}
catch (Exception ex)
{
_logger.Log(Level.Debug, ex.Message, ex);
}
}
private TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name)
{
Name = directoryInfo.FullName
};
directoryNode.Tag = new FolderNode()
{
Path = directoryInfo.FullName
};
directoryNode.ImageIndex = directoryNode.SelectedImageIndex = FolderIcon;
directoryNode.ToolTipText = directoryInfo.FullName;
foreach (var directory in directoryInfo.GetDirectories())
{
if (!directory.Attributes.HasFlag(FileAttributes.Hidden))
{
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
}
}
foreach (var file in directoryInfo.GetFiles())
{
var treeNode = new TreeNode(file.Name)
{
Name = file.FullName
};
var fileType = ConfigurationManager.GetFileInformation(file.FullName);
treeNode.Tag = new FileNode
{
Path = file.FullName,
FileInformation = fileType
};
var text = fileType.Id == ConfigFileType.MainAdapter ? "Adapter Configuration" : fileType.Id == ConfigFileType.Template ? "Template file" : "Not an OpenFMB config file";
treeNode.ToolTipText = $"{file.FullName} ({text})";
treeNode.ImageIndex = treeNode.SelectedImageIndex = (int)fileType.Id;
directoryNode.Nodes.Add(treeNode);
}
return directoryNode;
}
private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
{
HandleWorkspaceItemDeleting();
}
private void HandleWorkspaceItemDeleting()
{
if (workspaceTree.Nodes.Count > 0)
{
TreeNode node = workspaceTree.SelectedNode;
if (node == workspaceTree.Nodes[0])
{
// Can't delete root node
return;
}
if (node != null && node.Tag is DataNode)
{
var dataNode = node.Tag as DataNode;
string message;
if (dataNode is FolderNode)
{
message = $"Are you sure that you want to delete '{Path.GetFileName(dataNode.Path)}' and its contents?";
}
else
{
message = $"Are you sure that you want to delete '{Path.GetFileName(dataNode.Path)}'?";
}
if (MessageBox.Show(this, message, Program.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_configurationManager.SuspendFileWatcher();
if (node.Tag is FolderNode)
{
Directory.Delete((node.Tag as FolderNode).Path, true);
node.Remove();
}
else
{
File.Delete((node.Tag as DataNode).Path);
node.Remove();
}
}
finally
{
_configurationManager.ResumeFileWatcher();
}
// Check if active file path is still valid
if (_configurationManager.ActiveConfiguration != null)
{
if (!File.Exists(_configurationManager.ActiveConfiguration.FullPath))
{
// close it
CloseActiveConfiguration();
}
}
}
}
}
}
private void NewFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
var selectedNode = workspaceTree.SelectedNode;
if (selectedNode != null)
{
var folder = selectedNode.Tag as FolderNode;
if (folder != null)
{
NewFolderForm form = new NewFolderForm();
if (form.ShowDialog() == DialogResult.OK)
{
if (!string.IsNullOrEmpty(form.FolderName))
{
var path = Path.Combine(folder.Path, form.FolderName);
if (Directory.Exists(path))
{
MessageBox.Show(this, "Folder already exists", Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
try
{
_configurationManager.SuspendFileWatcher();
var directoryInfo = Directory.CreateDirectory(path);
var directoryNode = new TreeNode(directoryInfo.Name);
directoryNode.Tag = new FolderNode()
{
Path = directoryInfo.FullName
};
directoryNode.ImageIndex = directoryNode.SelectedImageIndex = FolderIcon;
selectedNode.Nodes.Add(directoryNode);
selectedNode.Expand();
}
finally
{
_configurationManager.ResumeFileWatcher();
}
}
}
}
}
}
}
private void ReloadToolStripMenuItem_Click(object sender, EventArgs e)
{
LoadWorkspaceTree();
}
internal bool IsFolderSelected()
{
return workspaceTree.SelectedNode?.Tag is FolderNode;
}
private void WorkspaceTreeContextMenu_Opening(object sender, CancelEventArgs e)
{
var selectedNode = workspaceTree.SelectedNode;
if (selectedNode == null)
{
e.Cancel = true;
}
else
{
deleteToolStripMenuItem.Enabled = renameToolStripMenuItem.Enabled = selectedNode != workspaceTree.Nodes[0]; // can't delete/rename root node
newFolderToolStripMenuItem.Enabled = selectedNode.Tag is FolderNode;
editToolStripMenuItem.Enabled = ((selectedNode.Tag as FileNode)?.FileInformation.Id == ConfigFileType.MainAdapter || (selectedNode.Tag as FileNode)?.FileInformation.Id == ConfigFileType.Template);
pasteToolStripMenuItem.Visible = _copiedDataNode != null;
}
}
private void NewConfigButton_Click(object sender, EventArgs e)
{
var selectedNode = workspaceTree.SelectedNode;
if (selectedNode == null)
{
selectedNode = workspaceTree.Nodes[0];
}
var folder = selectedNode.Tag as FolderNode;
if (folder == null)
{
selectedNode = selectedNode.Parent;
folder = selectedNode.Tag as FolderNode;
}
CreateNewConfiguration(folder.Path, selectedNode);
}
private void NewTemplateButton_Click(object sender, EventArgs e)
{
var selectedNode = workspaceTree.SelectedNode;
if (selectedNode == null)
{
selectedNode = workspaceTree.Nodes[0];
}
var folder = selectedNode.Tag as FolderNode;
if (folder == null)
{
selectedNode = selectedNode.Parent;
folder = selectedNode.Tag as FolderNode;
}
CreateNewTemplate(folder.Path, selectedNode);
}
private void CreateNewConfiguration(string folderPath, TreeNode selectedNode)
{
try
{
_configurationManager.SuspendFileWatcher();
CreateAdapterConfigurationForm form = new CreateAdapterConfigurationForm(folderPath, false);
if (form.ShowDialog() == DialogResult.OK)
{
Editable editable = form.Output;
HandleFileAddedToWorkspace(selectedNode, editable);
}
}
finally
{
Thread.Sleep(100);
_configurationManager.ResumeFileWatcher();
}
}
private void CreateNewTemplate(string folderPath, TreeNode selectedNode)
{
try
{
_configurationManager.SuspendFileWatcher();
CreateTemplateConfigurationForm form = new CreateTemplateConfigurationForm(folderPath, false);
if (form.ShowDialog() == DialogResult.OK)
{
Editable editable = form.Output;
HandleFileAddedToWorkspace(selectedNode, editable);
}
}
finally
{
Thread.Sleep(100);
_configurationManager.ResumeFileWatcher();
}
}
private void HandleFileAddedToWorkspace(TreeNode selectedNode, Editable editable)
{
var directory = Path.GetDirectoryName(editable.FullPath);
try
{
workspaceTree.BeginUpdate();
var parent = selectedNode.Parent;
var rootDirectoryInfo = new DirectoryInfo(directory);
var node = CreateDirectoryNode(rootDirectoryInfo);
if (parent != null)
{
selectedNode.Remove();
parent.Nodes.Add(node);
}
else
{
selectedNode.Remove();
workspaceTree.Nodes.Add(node);
}
workspaceTree.SelectedNode = node;
node.ExpandAll();
}
finally
{
workspaceTree.EndUpdate();
}
}
private void HandleOnEditFileRequested(FileNode fileNode)
{
try
{
if (_configurationManager.ActiveConfiguration != null)
{
if (FileHelper.FileEquals(_configurationManager.ActiveConfiguration.FullPath, fileNode.Path))
{
tabControl.SelectedIndex = 1;
return;
}
else
{
var result = MessageBox.Show(this, $"A file is already open in editor.{Environment.NewLine}Click YES to save and close it.{Environment.NewLine}Click NO to ignore all changes and close it.{Environment.NewLine}Click CANCEL to abort.", Program.AppName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Cancel)
{
return;
}
else if (result == DialogResult.Yes)
{
Save();
}
}
}
// open it
EditFile(fileNode);
}
catch (Exception ex)
{
_logger.Log(Level.Error, "Unable to open configuration file or its referencing template files.", ex);
detailSplitContainer.Panel2Collapsed = false;
}
}
private void OnEditFileRequested(object sender, EventArgs e)
{
var control = sender as FileInfoControl;
if (control != null)
{
if (control.DataNode is FileNode)
{
HandleOnEditFileRequested(control.DataNode as FileNode);
}
}
}
private void EditToolStripMenuItem_Click(object sender, EventArgs e)
{
var selectedNode = workspaceTree.SelectedNode;
if (selectedNode != null)
{
HandleOnEditFileRequested(selectedNode.Tag as FileNode);
}
}
private void EditFile(FileNode fileNode)
{
try
{
_configurationManager.LoadConfiguration(fileNode.Path, fileNode?.FileInformation.Id);
LoadFile(_configurationManager.ActiveConfiguration);
tabControl.SelectedIndex = 1;
}
catch (Exception ex)
{
_logger.Log(Level.Error, ex.Message, ex);
MessageBox.Show(this, "Failed to open file.", Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
var changedFile = FileHelper.ConvertToForwardSlash(e.Name);
if (_configurationManager.ActiveConfiguration != null)
{
var activeConfig = _configurationManager.ActiveConfiguration;
if (activeConfig is AdapterConfiguration)
{
var active = activeConfig as AdapterConfiguration;
if (FileHelper.FileEquals(active.FullPath, e.FullPath))
{
HandleActiveConfigFileChanged(e);
}
else
{
foreach (var p in active.Plugins.Plugins)
{
if (p is ISessionable)
{
foreach (var session in (p as ISessionable).Sessions)
{
if (FileHelper.FileEquals(session.LocalFilePath, changedFile))
{
HandleActiveConfigFileChanged(e);
}
}
}
}
}
}
else
{
var session = activeConfig as Session;
if (FileHelper.FileEquals(session.LocalFilePath, changedFile))
{
HandleActiveConfigFileChanged(e);
}
}
}
LoadWorkspaceTree();
}
private void HandleActiveConfigFileChanged(FileSystemEventArgs e)
{
Invoke(new Action(() =>
{
var activeFilePath = _configurationManager.ActiveConfiguration.FullPath;
var changedFile = Path.Combine(_configurationManager.WorkingDirectory, e.Name);
var result = MessageBox.Show(this, $"\"{changedFile}\"{Environment.NewLine}{Environment.NewLine}This file has been modified by another program.{Environment.NewLine}Do you want to reload it?", Program.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
try
{
_configurationManager.UnloadConfiguration();
adapterTreeView.Nodes.Clear();
activeEditorPanel.Visible = false;
placeHolder.Controls.Clear();
// disable save and close buttons
saveAdapterButton.Enabled = closeAdapterButton.Enabled = false;
_configurationManager.LoadConfiguration(activeFilePath);
LoadFile(_configurationManager.ActiveConfiguration);
}
catch (Exception ex)
{
_logger.Log(Level.Error, ex.Message, ex);
MessageBox.Show(this, "Failed to open file.", Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}));
}
private void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
LoadWorkspaceTree();
}
private void FileSystemWatcher_DeletedOrRenamed(object sender, FileSystemEventArgs e)
{
if (_configurationManager.ActiveConfiguration != null)
{
if (!File.Exists(_configurationManager.ActiveConfiguration.FullPath))
{
Invoke(new Action(() =>
{
var result = MessageBox.Show(this, $"File \"{_configurationManager.ActiveConfiguration.FullPath}\" no longer exists. Keep it in editor?", Program.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
MarkDirty(true);
}
else
{
CloseActiveConfiguration();
}
}));
}
}
LoadWorkspaceTree();
}
private void OpenContainingFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
var selectedNode = workspaceTree.SelectedNode?.Tag as DataNode;
if (selectedNode != null)
{
try
{
Process.Start(Path.GetDirectoryName(selectedNode.Path));
}
catch (Exception ex)
{
_logger.Log(Level.Error, ex.Message, ex);
}
}
}
private void ExpandAllToolStripMenuItem_Click(object sender, EventArgs e)
{
if (sender == workSpaceExpandAllToolStripMenuItem)
{
workspaceTree.ExpandAll();
}
else if (sender == adapterExpandAllToolStripMenuItem)
{
adapterTreeView.ExpandAll();
}
}
private void CollapseAllToolStripMenuItem_Click(object sender, EventArgs e)
{
if (sender == workspaceCollapseAllToolStripMenuItem)
{
workspaceTree.CollapseAll();
}
else if (sender == adapterCollapseAllToolStripMenuItem)
{
adapterTreeView.CollapseAll();
}
}
private void CloseAdapterButton_Click(object sender, EventArgs e)
{
if (_configurationManager.HasChanged())
{
var result = MessageBox.Show(this, "Do you want to save changes to your configuration files?\n\nYour changes will be lost if you don't save.", Program.AppName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Cancel)
{
return;
}
else if (result == DialogResult.Yes)
{
Save();
}
// NO, just close it
}
CloseActiveConfiguration();
// clear logs
outputControl.ClearAll();
// switch tab page
tabControl.SelectedIndex = 0;
}
private void CloseActiveConfiguration()
{
_configurationManager.UnloadConfiguration();
adapterTreeView.Nodes.Clear();
activeEditorPanel.Visible = false;
activeEditorLink.Text = string.Empty;
placeHolder.Controls.Clear();
// disable save and close buttons
saveAdapterButton.Enabled = closeAdapterButton.Enabled = false;
}
private void SaveAdapterButton_Click(object sender, EventArgs e)
{
Save();
}
private void Save()
{
try
{
Cursor = Cursors.WaitCursor;
saveAdapterButton.Enabled = false;
_configurationManager.Save();
Thread.Sleep(500);
}
catch (Exception ex)
{
MessageBox.Show(this, "An error occured when saving the files.", Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.Log(Level.Error, "An error occured when saving the files.", ex);
}
finally
{
Cursor = Cursors.Default;
saveAdapterButton.Enabled = true;
}
}
private void WorkspaceTree_AfterSelect(object sender, TreeViewEventArgs e)
{
SelectWorkspaceTreeNode(e.Node);
}
private void WorkspaceTree_NodeClick(object sender, EventArgs e)
{
TreeNode selectedNode = workspaceTree.SelectedNode;
if (selectedNode != null)
{
SelectWorkspaceTreeNode(selectedNode);
}
}
private void SelectWorkspaceTreeNode(TreeNode selectedNode)
{
FileInfoControl c = FindControl(FileInfoControlKey) as FileInfoControl;
if (c == null)
{
c = new FileInfoControl()
{
Name = FileInfoControlKey,
Dock = DockStyle.Fill
};
c.OnEditFileRequested += OnEditFileRequested;
placeHolder.Controls.Add(c);
}
var tag = selectedNode.Tag;
if (tag is FolderNode)
{
var folder = tag as FolderNode;
c.DataSource = folder;
c.BringToFront();
}
else if (tag is FileNode)
{
var file = tag as FileNode;
c.DataSource = file;
c.BringToFront();
}
}
private void WorkspaceTree_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
HandleWorkspaceItemDeleting();
}
else if (e.KeyData == (Keys.Control | Keys.C))
{
HandleWorkspaceNodeCopying();
e.Handled = e.SuppressKeyPress = true;
}
else if (e.KeyData == (Keys.Control | Keys.V))
{
HandleWorkspaceNodePasting();
e.Handled = e.SuppressKeyPress = true;
}
}
private void TabControl_SelectedIndexChanged(object sender, EventArgs e)
{
FileInfoControl c = FindControl(FileInfoControlKey) as FileInfoControl;
if (c != null)
{
if (tabControl.SelectedIndex == 0)
{
c.BringToFront();
}
else
{
c.SendToBack();
}
}
newConfigButton.Visible = newTemplateButton.Visible = tabControl.SelectedIndex == 0;
}
private void TreeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
if (e.Node == e.Node.TreeView.SelectedNode)
{
Font font = e.Node.NodeFont ?? e.Node.TreeView.Font;
Rectangle r = e.Bounds;
r.Offset(0, 1);
Brush brush = SystemBrushes.Highlight;
e.Graphics.FillRectangle(brush, e.Bounds);
TextRenderer.DrawText(e.Graphics, e.Node.Text, font, r, e.Node.ForeColor, TextFormatFlags.GlyphOverhangPadding);
}
else
e.DrawDefault = true;
}
private void ActiveEditorLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
tabControl.SelectedTab = tabPage2;
}
private void RenameToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode node = workspaceTree.SelectedNode;
if (node != null)
{
node.BeginEdit();
}
}
private void WorkspaceTree_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(e.Label))
{
e.CancelEdit = true;
return;
}
var dataNode = e.Node.Tag as DataNode;
if (dataNode is FolderNode)
{
var newPath = Path.Combine(Path.GetDirectoryName(dataNode.Path), e.Label);
if (Directory.Exists(newPath))
{
e.CancelEdit = true;
MessageBox.Show(this, $"Folder '{e.Label}' already exists.", Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
Directory.Move(dataNode.Path, newPath);
dataNode.Path = newPath;
}
}
else if (dataNode is FileNode)
{
var newPath = Path.Combine(Path.GetDirectoryName(dataNode.Path), e.Label);
if (Directory.Exists(newPath))
{
e.CancelEdit = true;
MessageBox.Show(this, $"File '{e.Label}' already exists.", Program.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
File.Move(dataNode.Path, newPath);
dataNode.Path = newPath;
}
}
}
catch (Exception ex)
{
_logger.Log(Level.Error, ex.Message, ex);
e.CancelEdit = true;
}
}
private void HandleWorkspaceNodeCopying()
{
TreeNode node = workspaceTree.SelectedNode;
if (node != null)
{
_copiedDataNode = node.Tag as DataNode;
}
}
private void HandleWorkspaceNodePasting()
{
TreeNode node = workspaceTree.SelectedNode;
if (node != null)
{
string parentFolder;
if (node.Tag is FileNode)
{
parentFolder = Path.GetDirectoryName((node.Tag as FileNode).Path);
}
else
{
parentFolder = (node.Tag as DataNode).Path;
}
var tag = _copiedDataNode;
if (tag != null)
{
if (tag is FolderNode)
{
string name = Path.GetFileName(tag.Path);
// Get next folder name
string newPath = parentFolder.GetNextFolderName(name);
FileHelper.DirectoryCopy(tag.Path, newPath);
}
else if (tag is FileNode)
{
string name = Path.GetFileNameWithoutExtension(tag.Path);
string extension = Path.GetExtension(tag.Path);
string newPath = parentFolder.GetNextFileName(name, extension);
File.Copy(tag.Path, newPath);
}
}
}
}
private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
{
HandleWorkspaceNodeCopying();
}
private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
{
HandleWorkspaceNodePasting();
}
}
[Serializable]
public abstract class DataNode
{
public string Path { get; set; }
public bool Selected { get; set; }
public bool Expanded { get; set; }
public string Name
{
get { return System.IO.Path.GetFileName(Path); }
}
}
[Serializable]
public class FileNode : DataNode
{
public FileInformation FileInformation { get; set; } = new FileInformation();
}
[Serializable]
public class FolderNode : DataNode
{
public bool CanDelete { get; set; } = true;
}
} | 36.836905 | 338 | 0.473306 | [
"Apache-2.0"
] | openenergysolutions/openfmb.adapters.config | OpenFMB.Adapters.Configuration/ConfigurationControl.cs | 61,886 | C# |
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using Dfe.Edis.Kafka.Consumer;
using Dfe.FE.Interventions.Application.FeProviders;
using Dfe.FE.Interventions.Consumer.Ukrlp.Ukrlp;
using Dfe.FE.Interventions.Domain.Configuration;
using Dfe.FE.Interventions.Domain.FeProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Dfe.FE.Interventions.Consumer.Ukrlp
{
public class Worker : BackgroundService
{
private readonly IKafkaConsumer<string, Provider> _ukrlpConsumer;
private readonly IFeProviderManager _providerManager;
private readonly IMapper _mapper;
private readonly DataServicesPlatformConfiguration _configuration;
private readonly ILogger<Worker> _logger;
public Worker(
IKafkaConsumer<string, Provider> ukrlpConsumer,
IFeProviderManager providerManager,
IOptions<DataServicesPlatformConfiguration> options,
IMapper mapper,
ILogger<Worker> logger)
{
_ukrlpConsumer = ukrlpConsumer;
_providerManager = providerManager;
_mapper = mapper;
_configuration = options.Value;
_logger = logger;
_ukrlpConsumer.SetMessageHandler(ProcessMessageFromTopic);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await _ukrlpConsumer.RunAsync(_configuration.UkrlpTopicName, stoppingToken);
}
private async Task ProcessMessageFromTopic(ConsumedMessage<string, Provider> message, CancellationToken cancellationToken)
{
_logger.LogInformation("Received update for provider {UKPRN} - {ProviderName} (topic: {Topic}, partition: {Partition}, offset: {Offset})",
message.Value.UnitedKingdomProviderReferenceNumber,
message.Value.ProviderName,
message.Topic,
message.Partition,
message.Offset);
var feProvider = _mapper.Map<FeProvider>(message.Value);
await _providerManager.UpsertProvider(feProvider, cancellationToken);
}
}
} | 38.827586 | 151 | 0.688277 | [
"MIT"
] | DFE-Digital/fe-interventions-api | src/Dfe.FE.Interventions.Consumer.Ukrlp/Worker.cs | 2,252 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Discord.WebSocket
{
public partial class BaseSocketClient
{
//Channels
/// <summary> Fired when a channel is created. </summary>
/// <remarks>
/// <para>
/// This event is fired when a generic channel has been created. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketChannel"/> as its parameter.
/// </para>
/// <para>
/// The newly created channel is passed into the event handler parameter. The given channel type may
/// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category);
/// see the derived classes of <see cref="SocketChannel"/> for more details.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs" region="ChannelCreated"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<SocketChannel, Task> ChannelCreated
{
add { _channelCreatedEvent.Add(value); }
remove { _channelCreatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketChannel, Task>> _channelCreatedEvent = new AsyncEvent<Func<SocketChannel, Task>>();
/// <summary> Fired when a channel is destroyed. </summary>
/// <remarks>
/// <para>
/// This event is fired when a generic channel has been destroyed. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketChannel"/> as its parameter.
/// </para>
/// <para>
/// The destroyed channel is passed into the event handler parameter. The given channel type may
/// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category);
/// see the derived classes of <see cref="SocketChannel"/> for more details.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs" region="ChannelDestroyed"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<SocketChannel, Task> ChannelDestroyed
{
add { _channelDestroyedEvent.Add(value); }
remove { _channelDestroyedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketChannel, Task>> _channelDestroyedEvent = new AsyncEvent<Func<SocketChannel, Task>>();
/// <summary> Fired when a channel is updated. </summary>
/// <remarks>
/// <para>
/// This event is fired when a generic channel has been destroyed. The event handler must return a
/// <see cref="Task"/> and accept 2 <see cref="SocketChannel"/> as its parameters.
/// </para>
/// <para>
/// The original (prior to update) channel is passed into the first <see cref="SocketChannel"/>, while
/// the updated channel is passed into the second. The given channel type may include, but not limited
/// to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); see the derived classes of
/// <see cref="SocketChannel"/> for more details.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs" region="ChannelUpdated"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<SocketChannel, SocketChannel, Task> ChannelUpdated
{
add { _channelUpdatedEvent.Add(value); }
remove { _channelUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketChannel, SocketChannel, Task>> _channelUpdatedEvent = new AsyncEvent<Func<SocketChannel, SocketChannel, Task>>();
//Messages
/// <summary> Fired when a message is received. </summary>
/// <remarks>
/// <para>
/// This event is fired when a message is received. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketMessage"/> as its parameter.
/// </para>
/// <para>
/// The message that is sent to the client is passed into the event handler parameter as
/// <see cref="SocketMessage"/>. This message may be a system message (i.e.
/// <see cref="SocketSystemMessage"/>) or a user message (i.e. <see cref="SocketUserMessage"/>. See the
/// derived classes of <see cref="SocketMessage"/> for more details.
/// </para>
/// </remarks>
/// <example>
/// <para>The example below checks if the newly received message contains the target user.</para>
/// <code language="cs" region="MessageReceived"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<SocketMessage, Task> MessageReceived
{
add { _messageReceivedEvent.Add(value); }
remove { _messageReceivedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketMessage, Task>> _messageReceivedEvent = new AsyncEvent<Func<SocketMessage, Task>>();
/// <summary> Fired when a message is deleted. </summary>
/// <remarks>
/// <para>
/// This event is fired when a message is deleted. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/> and
/// <see cref="ISocketMessageChannel"/> as its parameters.
/// </para>
/// <para>
/// <note type="important">
/// It is not possible to retrieve the message via
/// <see cref="Cacheable{TEntity,TId}.DownloadAsync"/>; the message cannot be retrieved by Discord
/// after the message has been deleted.
/// </note>
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the deleted message; otherwise, in event
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// <see cref="ulong"/>.
/// </para>
/// <para>
/// The source channel of the removed message will be passed into the
/// <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs" region="MessageDeleted"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs" />
/// </example>
public event Func<Cacheable<IMessage, ulong>, Cacheable<IMessageChannel, ulong>, Task> MessageDeleted {
add { _messageDeletedEvent.Add(value); }
remove { _messageDeletedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IMessage, ulong>, Cacheable<IMessageChannel, ulong>, Task>> _messageDeletedEvent = new AsyncEvent<Func<Cacheable<IMessage, ulong>, Cacheable<IMessageChannel, ulong>, Task>>();
/// <summary> Fired when multiple messages are bulk deleted. </summary>
/// <remarks>
/// <note>
/// The <see cref="MessageDeleted"/> event will not be fired for individual messages contained in this event.
/// </note>
/// <para>
/// This event is fired when multiple messages are bulk deleted. The event handler must return a
/// <see cref="Task"/> and accept an <see cref="IReadOnlyCollection{Cacheable}"/> and
/// <see cref="ISocketMessageChannel"/> as its parameters.
/// </para>
/// <para>
/// <note type="important">
/// It is not possible to retrieve the message via
/// <see cref="Cacheable{TEntity,TId}.DownloadAsync"/>; the message cannot be retrieved by Discord
/// after the message has been deleted.
/// </note>
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the deleted message; otherwise, in event
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// <see cref="ulong"/>.
/// </para>
/// <para>
/// The source channel of the removed message will be passed into the
/// <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// </remarks>
public event Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, Cacheable<IMessageChannel, ulong>, Task> MessagesBulkDeleted
{
add { _messagesBulkDeletedEvent.Add(value); }
remove { _messagesBulkDeletedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, Cacheable<IMessageChannel, ulong>, Task>> _messagesBulkDeletedEvent = new AsyncEvent<Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, Cacheable<IMessageChannel, ulong>, Task>>();
/// <summary> Fired when a message is updated. </summary>
/// <remarks>
/// <para>
/// This event is fired when a message is updated. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/>, <see cref="SocketMessage"/>,
/// and <see cref="ISocketMessageChannel"/> as its parameters.
/// </para>
/// <para>
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the original message; otherwise, in event
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// <see cref="ulong"/>.
/// </para>
/// <para>
/// The updated message will be passed into the <see cref="SocketMessage"/> parameter.
/// </para>
/// <para>
/// The source channel of the updated message will be passed into the
/// <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// </remarks>
public event Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task> MessageUpdated
{
add { _messageUpdatedEvent.Add(value); }
remove { _messageUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task>> _messageUpdatedEvent = new AsyncEvent<Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task>>();
/// <summary> Fired when a reaction is added to a message. </summary>
/// <remarks>
/// <para>
/// This event is fired when a reaction is added to a user message. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/>, an
/// <see cref="ISocketMessageChannel"/>, and a <see cref="SocketReaction"/> as its parameter.
/// </para>
/// <para>
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the original message; otherwise, in event
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// <see cref="ulong"/>.
/// </para>
/// <para>
/// The source channel of the reaction addition will be passed into the
/// <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// <para>
/// The reaction that was added will be passed into the <see cref="SocketReaction"/> parameter.
/// </para>
/// <note>
/// When fetching the reaction from this event, a user may not be provided under
/// <see cref="SocketReaction.User"/>. Please see the documentation of the property for more
/// information.
/// </note>
/// </remarks>
/// <example>
/// <code language="cs" region="ReactionAdded"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction, Task> ReactionAdded {
add { _reactionAddedEvent.Add(value); }
remove { _reactionAddedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction, Task>> _reactionAddedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction, Task>>();
/// <summary> Fired when a reaction is removed from a message. </summary>
public event Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction, Task> ReactionRemoved {
add { _reactionRemovedEvent.Add(value); }
remove { _reactionRemovedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction, Task>> _reactionRemovedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, SocketReaction, Task>>();
/// <summary> Fired when all reactions to a message are cleared. </summary>
public event Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, Task> ReactionsCleared {
add { _reactionsClearedEvent.Add(value); }
remove { _reactionsClearedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, Task>> _reactionsClearedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, Task>>();
/// <summary>
/// Fired when all reactions to a message with a specific emote are removed.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when all reactions to a message with a specific emote are removed.
/// The event handler must return a <see cref="Task"/> and accept a <see cref="ISocketMessageChannel"/> and
/// a <see cref="IEmote"/> as its parameters.
/// </para>
/// <para>
/// The channel where this message was sent will be passed into the <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// <para>
/// The emoji that all reactions had and were removed will be passed into the <see cref="IEmote"/> parameter.
/// </para>
/// </remarks>
public event Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, IEmote, Task> ReactionsRemovedForEmote
{
add { _reactionsRemovedForEmoteEvent.Add(value); }
remove { _reactionsRemovedForEmoteEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, IEmote, Task>> _reactionsRemovedForEmoteEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, Cacheable<IMessageChannel, ulong>, IEmote, Task>>();
//Roles
/// <summary> Fired when a role is created. </summary>
public event Func<SocketRole, Task> RoleCreated
{
add { _roleCreatedEvent.Add(value); }
remove { _roleCreatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketRole, Task>> _roleCreatedEvent = new AsyncEvent<Func<SocketRole, Task>>();
/// <summary> Fired when a role is deleted. </summary>
public event Func<SocketRole, Task> RoleDeleted
{
add { _roleDeletedEvent.Add(value); }
remove { _roleDeletedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketRole, Task>> _roleDeletedEvent = new AsyncEvent<Func<SocketRole, Task>>();
/// <summary> Fired when a role is updated. </summary>
public event Func<SocketRole, SocketRole, Task> RoleUpdated
{
add { _roleUpdatedEvent.Add(value); }
remove { _roleUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketRole, SocketRole, Task>> _roleUpdatedEvent = new AsyncEvent<Func<SocketRole, SocketRole, Task>>();
//Guilds
/// <summary> Fired when the connected account joins a guild. </summary>
public event Func<SocketGuild, Task> JoinedGuild
{
add { _joinedGuildEvent.Add(value); }
remove { _joinedGuildEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _joinedGuildEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when the connected account leaves a guild. </summary>
public event Func<SocketGuild, Task> LeftGuild
{
add { _leftGuildEvent.Add(value); }
remove { _leftGuildEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _leftGuildEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when a guild becomes available. </summary>
public event Func<SocketGuild, Task> GuildAvailable
{
add { _guildAvailableEvent.Add(value); }
remove { _guildAvailableEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildAvailableEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when a guild becomes unavailable. </summary>
public event Func<SocketGuild, Task> GuildUnavailable
{
add { _guildUnavailableEvent.Add(value); }
remove { _guildUnavailableEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildUnavailableEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when offline guild members are downloaded. </summary>
public event Func<SocketGuild, Task> GuildMembersDownloaded
{
add { _guildMembersDownloadedEvent.Add(value); }
remove { _guildMembersDownloadedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildMembersDownloadedEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when a guild is updated. </summary>
public event Func<SocketGuild, SocketGuild, Task> GuildUpdated
{
add { _guildUpdatedEvent.Add(value); }
remove { _guildUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, SocketGuild, Task>> _guildUpdatedEvent = new AsyncEvent<Func<SocketGuild, SocketGuild, Task>>();
//Users
/// <summary> Fired when a user joins a guild. </summary>
public event Func<SocketGuildUser, Task> UserJoined
{
add { _userJoinedEvent.Add(value); }
remove { _userJoinedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuildUser, Task>> _userJoinedEvent = new AsyncEvent<Func<SocketGuildUser, Task>>();
/// <summary> Fired when a user leaves a guild. </summary>
public event Func<SocketGuildUser, Task> UserLeft
{
add { _userLeftEvent.Add(value); }
remove { _userLeftEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuildUser, Task>> _userLeftEvent = new AsyncEvent<Func<SocketGuildUser, Task>>();
/// <summary> Fired when a user is banned from a guild. </summary>
public event Func<SocketUser, SocketGuild, Task> UserBanned
{
add { _userBannedEvent.Add(value); }
remove { _userBannedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketGuild, Task>> _userBannedEvent = new AsyncEvent<Func<SocketUser, SocketGuild, Task>>();
/// <summary> Fired when a user is unbanned from a guild. </summary>
public event Func<SocketUser, SocketGuild, Task> UserUnbanned
{
add { _userUnbannedEvent.Add(value); }
remove { _userUnbannedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketGuild, Task>> _userUnbannedEvent = new AsyncEvent<Func<SocketUser, SocketGuild, Task>>();
/// <summary> Fired when a user is updated. </summary>
public event Func<SocketUser, SocketUser, Task> UserUpdated
{
add { _userUpdatedEvent.Add(value); }
remove { _userUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketUser, Task>> _userUpdatedEvent = new AsyncEvent<Func<SocketUser, SocketUser, Task>>();
/// <summary> Fired when a guild member is updated, or a member presence is updated. </summary>
public event Func<Cacheable<SocketGuildUser, ulong>, SocketGuildUser, Task> GuildMemberUpdated {
add { _guildMemberUpdatedEvent.Add(value); }
remove { _guildMemberUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<SocketGuildUser, ulong>, SocketGuildUser, Task>> _guildMemberUpdatedEvent = new AsyncEvent<Func<Cacheable<SocketGuildUser, ulong>, SocketGuildUser, Task>>();
/// <summary> Fired when a user joins, leaves, or moves voice channels. </summary>
public event Func<SocketUser, SocketVoiceState, SocketVoiceState, Task> UserVoiceStateUpdated
{
add { _userVoiceStateUpdatedEvent.Add(value); }
remove { _userVoiceStateUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketVoiceState, SocketVoiceState, Task>> _userVoiceStateUpdatedEvent = new AsyncEvent<Func<SocketUser, SocketVoiceState, SocketVoiceState, Task>>();
/// <summary> Fired when the bot connects to a Discord voice server. </summary>
public event Func<SocketVoiceServer, Task> VoiceServerUpdated
{
add { _voiceServerUpdatedEvent.Add(value); }
remove { _voiceServerUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketVoiceServer, Task>> _voiceServerUpdatedEvent = new AsyncEvent<Func<SocketVoiceServer, Task>>();
/// <summary> Fired when the connected account is updated. </summary>
public event Func<SocketSelfUser, SocketSelfUser, Task> CurrentUserUpdated
{
add { _selfUpdatedEvent.Add(value); }
remove { _selfUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketSelfUser, SocketSelfUser, Task>> _selfUpdatedEvent = new AsyncEvent<Func<SocketSelfUser, SocketSelfUser, Task>>();
/// <summary> Fired when a user starts typing. </summary>
public event Func<Cacheable<IUser, ulong>, Cacheable<IMessageChannel, ulong>, Task> UserIsTyping {
add { _userIsTypingEvent.Add(value); }
remove { _userIsTypingEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUser, ulong>, Cacheable<IMessageChannel, ulong>, Task>> _userIsTypingEvent = new AsyncEvent<Func<Cacheable<IUser, ulong>, Cacheable<IMessageChannel, ulong>, Task>>();
/// <summary> Fired when a user joins a group channel. </summary>
public event Func<SocketGroupUser, Task> RecipientAdded
{
add { _recipientAddedEvent.Add(value); }
remove { _recipientAddedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientAddedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>();
/// <summary> Fired when a user is removed from a group channel. </summary>
public event Func<SocketGroupUser, Task> RecipientRemoved
{
add { _recipientRemovedEvent.Add(value); }
remove { _recipientRemovedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientRemovedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>();
//Invites
/// <summary>
/// Fired when an invite is created.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when an invite is created. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketInvite"/> as its parameter.
/// </para>
/// <para>
/// The invite created will be passed into the <see cref="SocketInvite"/> parameter.
/// </para>
/// </remarks>
public event Func<SocketInvite, Task> InviteCreated
{
add { _inviteCreatedEvent.Add(value); }
remove { _inviteCreatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketInvite, Task>> _inviteCreatedEvent = new AsyncEvent<Func<SocketInvite, Task>>();
/// <summary>
/// Fired when an invite is deleted.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when an invite is deleted. The event handler must return
/// a <see cref="Task"/> and accept a <see cref="SocketGuildChannel"/> and
/// <see cref="string"/> as its parameter.
/// </para>
/// <para>
/// The channel where this invite was created will be passed into the <see cref="SocketGuildChannel"/> parameter.
/// </para>
/// <para>
/// The code of the deleted invite will be passed into the <see cref="string"/> parameter.
/// </para>
/// </remarks>
public event Func<SocketGuildChannel, string, Task> InviteDeleted
{
add { _inviteDeletedEvent.Add(value); }
remove { _inviteDeletedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuildChannel, string, Task>> _inviteDeletedEvent = new AsyncEvent<Func<SocketGuildChannel, string, Task>>();
//Interactions
/// <summary>
/// Fired when an Interaction is created.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when an interaction is created. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketInteraction"/> as its parameter.
/// </para>
/// <para>
/// The interaction created will be passed into the <see cref="SocketInteraction"/> parameter.
/// </para>
/// </remarks>
public event Func<SocketInteraction, Task> InteractionCreated
{
add { _interactionCreatedEvent.Add(value); }
remove { _interactionCreatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketInteraction, Task>> _interactionCreatedEvent = new AsyncEvent<Func<SocketInteraction, Task>>();
/// <summary>
/// Fired when a guild application command is created.
///</summary>
///<remarks>
/// <para>
/// This event is fired when an application command is created. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketApplicationCommand"/> as its parameter.
/// </para>
/// <para>
/// The command that was deleted will be passed into the <see cref="SocketApplicationCommand"/> parameter.
/// </para>
/// <note>
/// <b>This event is an undocumented discord event and may break at any time, its not recommended to rely on this event</b>
/// </note>
/// </remarks>
public event Func<SocketApplicationCommand, Task> ApplicationCommandCreated
{
add { _applicationCommandCreated.Add(value); }
remove { _applicationCommandCreated.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketApplicationCommand, Task>> _applicationCommandCreated = new AsyncEvent<Func<SocketApplicationCommand, Task>>();
/// <summary>
/// Fired when a guild application command is updated.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when an application command is updated. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketApplicationCommand"/> as its parameter.
/// </para>
/// <para>
/// The command that was deleted will be passed into the <see cref="SocketApplicationCommand"/> parameter.
/// </para>
/// <note>
/// <b>This event is an undocumented discord event and may break at any time, its not recommended to rely on this event</b>
/// </note>
/// </remarks>
public event Func<SocketApplicationCommand, Task> ApplicationCommandUpdated
{
add { _applicationCommandUpdated.Add(value); }
remove { _applicationCommandUpdated.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketApplicationCommand, Task>> _applicationCommandUpdated = new AsyncEvent<Func<SocketApplicationCommand, Task>>();
/// <summary>
/// Fired when a guild application command is deleted.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when an application command is deleted. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketApplicationCommand"/> as its parameter.
/// </para>
/// <para>
/// The command that was deleted will be passed into the <see cref="SocketApplicationCommand"/> parameter.
/// </para>
/// <note>
/// <b>This event is an undocumented discord event and may break at any time, its not recommended to rely on this event</b>
/// </note>
/// </remarks>
public event Func<SocketApplicationCommand, Task> ApplicationCommandDeleted
{
add { _applicationCommandDeleted.Add(value); }
remove { _applicationCommandDeleted.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketApplicationCommand, Task>> _applicationCommandDeleted = new AsyncEvent<Func<SocketApplicationCommand, Task>>();
/// <summary>
/// Fired when a thread is created within a guild, or when the current user is added to a thread.
/// </summary>
public event Func<SocketThreadChannel, Task> ThreadCreated
{
add { _threadCreated.Add(value); }
remove { _threadCreated.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketThreadChannel, Task>> _threadCreated = new AsyncEvent<Func<SocketThreadChannel, Task>>();
/// <summary>
/// Fired when a thread is updated within a guild.
/// </summary>
public event Func<SocketThreadChannel, SocketThreadChannel, Task> ThreadUpdated
{
add { _threadUpdated.Add(value); }
remove { _threadUpdated.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketThreadChannel, SocketThreadChannel, Task>> _threadUpdated = new AsyncEvent<Func<SocketThreadChannel, SocketThreadChannel, Task>>();
/// <summary>
/// Fired when a thread is deleted.
/// </summary>
public event Func<Cacheable<SocketThreadChannel, ulong>, Task> ThreadDeleted
{
add { _threadDeleted.Add(value); }
remove { _threadDeleted.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<SocketThreadChannel, ulong>, Task>> _threadDeleted = new AsyncEvent<Func<Cacheable<SocketThreadChannel, ulong>, Task>>();
/// <summary>
/// Fired when a user joins a thread
/// </summary>
public event Func<SocketThreadUser, Task> ThreadMemberJoined
{
add { _threadMemberJoined.Add(value); }
remove { _threadMemberJoined.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketThreadUser, Task>> _threadMemberJoined = new AsyncEvent<Func<SocketThreadUser, Task>>();
/// <summary>
/// Fired when a user leaves a thread
/// </summary>
public event Func<SocketThreadUser, Task> ThreadMemberLeft
{
add { _threadMemberLeft.Add(value); }
remove { _threadMemberLeft.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketThreadUser, Task>> _threadMemberLeft = new AsyncEvent<Func<SocketThreadUser, Task>>();
/// <summary>
/// Fired when a stage is started.
/// </summary>
public event Func<SocketStageChannel, Task> StageStarted
{
add { _stageStarted.Add(value); }
remove { _stageStarted.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketStageChannel, Task>> _stageStarted = new AsyncEvent<Func<SocketStageChannel, Task>>();
/// <summary>
/// Fired when a stage ends.
/// </summary>
public event Func<SocketStageChannel, Task> StageEnded
{
add { _stageEnded.Add(value); }
remove { _stageEnded.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketStageChannel, Task>> _stageEnded = new AsyncEvent<Func<SocketStageChannel, Task>>();
/// <summary>
/// Fired when a stage is updated.
/// </summary>
public event Func<SocketStageChannel, SocketStageChannel, Task> StageUpdated
{
add { _stageUpdated.Add(value); }
remove { _stageUpdated.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketStageChannel, SocketStageChannel, Task>> _stageUpdated = new AsyncEvent<Func<SocketStageChannel, SocketStageChannel, Task>>();
/// <summary>
/// Fired when a user requests to speak within a stage channel.
/// </summary>
public event Func<SocketStageChannel, SocketGuildUser, Task> RequestToSpeak
{
add { _requestToSpeak.Add(value); }
remove { _requestToSpeak.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketStageChannel, SocketGuildUser, Task>> _requestToSpeak = new AsyncEvent<Func<SocketStageChannel, SocketGuildUser, Task>>();
/// <summary>
/// Fired when a speaker is added in a stage channel.
/// </summary>
public event Func<SocketStageChannel, SocketGuildUser, Task> SpeakerAdded
{
add { _speakerAdded.Add(value); }
remove { _speakerAdded.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketStageChannel, SocketGuildUser, Task>> _speakerAdded = new AsyncEvent<Func<SocketStageChannel, SocketGuildUser, Task>>();
/// <summary>
/// Fired when a speaker is removed from a stage channel.
/// </summary>
public event Func<SocketStageChannel, SocketGuildUser, Task> SpeakerRemoved
{
add { _speakerRemoved.Add(value); }
remove { _speakerRemoved.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketStageChannel, SocketGuildUser, Task>> _speakerRemoved = new AsyncEvent<Func<SocketStageChannel, SocketGuildUser, Task>>();
}
}
| 56.045732 | 274 | 0.609123 | [
"MIT"
] | INikonI/Discord.Net-Labs | src/Discord.Net.WebSocket/BaseSocketClient.Events.cs | 36,766 | C# |
namespace Norm
{
/// <summary>
/// Server details
/// </summary>
public class Server
{
/// <summary>
/// Gets or sets the host.
/// </summary>
/// <value>The host.</value>
public string Host { get; set; }
/// <summary>
/// Gets or sets the port.
/// </summary>
/// <value>The port.</value>
public int Port { get; set; }
}
}
| 19.590909 | 40 | 0.450116 | [
"BSD-3-Clause"
] | adzerk/NoRM | NoRM/Connections/Server.cs | 433 | C# |
// Copyright (c) 2017-2019 Jae-jun Kang
// See the file LICENSE for details.
using System;
using System.Collections.Generic;
namespace x2net
{
// Hash.Update
public partial struct Hash
{
public void Update(bool value)
{
Code = Update(Code, value);
}
public void Update(sbyte value)
{
Code = Update(Code, value);
}
public void Update(byte value)
{
Code = Update(Code, value);
}
public void Update(short value)
{
Code = Update(Code, value);
}
public void Update(ushort value)
{
Code = Update(Code, value);
}
public void Update(int value)
{
Code = Update(Code, value);
}
public void Update(uint value)
{
Code = Update(Code, value);
}
public void Update(long value)
{
Code = Update(Code, value);
}
public void Update(ulong value)
{
Code = Update(Code, value);
}
public void Update(float value)
{
Code = Update(Code, value);
}
public void Update(double value)
{
Code = Update(Code, value);
}
public void Update(string value)
{
Code = Update(Code, value);
}
public void Update(DateTime value)
{
Code = Update(Code, value);
}
public void Update(byte[] value)
{
Code = Update(Code, value);
}
public void Update<T>(List<T> value)
{
Code = Update(Code, value);
}
public void Update<T>(T value)
{
Code = Update(Code, value);
}
}
}
| 19.677419 | 44 | 0.469399 | [
"MIT"
] | jaykang920/x2net | src/x2net/Util/Hash.Update.cs | 1,832 | C# |
using System;
using Npgsql;
namespace Discount.Grpc.Data
{
public interface ICouponContext
{
public NpgsqlConnection NpgsqlConnection { get; }
}
}
| 15.363636 | 57 | 0.692308 | [
"Apache-2.0"
] | ChiaChiaPing/AspnetMicroservices | src/Services/Discount/Discount.Grpc/Data/ICouponContext.cs | 171 | C# |
using System;
using System.Globalization;
using Java.IO;
using Java.Lang;
namespace XamarinAppStartupTime.Droid.Services
{
internal static class StartupTimeHelper
{
private static DateTime? StartupTime;
private static bool _attemptedToGetStartupTime;
public static DateTime? GetAppStartupTimeUtc()
{
if(_attemptedToGetStartupTime)
{
return StartupTime;
}
if (!StartupTime.HasValue)
{
StartupTime = GetStartupTimeUtcFromLogcat();
_attemptedToGetStartupTime = true;
}
return StartupTime;
}
private static DateTime? GetStartupTimeUtcFromLogcat()
{
var pid = Android.OS.Process.MyPid();
var process = new ProcessBuilder().
RedirectErrorStream(true).
Command("/system/bin/logcat", $"--pid={pid}", "-m", "1", "-v", "year,UTC").Start();
using (var bufferedReader = new BufferedReader(new InputStreamReader(process.InputStream)))
{
string line = null;
while ((line = bufferedReader.ReadLine()) != null)
{
if (ParseLogDateTime(line, out DateTime date))
{
return date;
}
}
}
return null;
}
const string LogcatTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
private static bool ParseLogDateTime(string logLine, out DateTime dateTime)
{
if(logLine.Length < LogcatTimeFormat.Length)
{
dateTime = new DateTime();
return false;
}
var timeStr = logLine.Substring(0, LogcatTimeFormat.Length);
return DateTime.TryParseExact(timeStr, LogcatTimeFormat,
CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out dateTime);
}
}
} | 31.859375 | 103 | 0.53899 | [
"MIT"
] | toomasz/XamarinAppStartupTime | XamarinAppStartupTime/XamarinAppStartupTime.Android/Services/StartupTimeHelper.cs | 2,041 | C# |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using NUnit.Framework;
using OpenTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Timing;
using osu.Game.Screens.Menu;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public class TestCaseIntroSequence : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(OsuLogo),
};
public TestCaseIntroSequence()
{
OsuLogo logo;
var rateAdjustClock = new StopwatchClock(true);
var framedClock = new FramedClock(rateAdjustClock);
framedClock.ProcessFrame();
Add(new Container
{
RelativeSizeAxes = Axes.Both,
Clock = framedClock,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
},
logo = new OsuLogo
{
Anchor = Anchor.Centre,
}
}
});
AddStep(@"Restart", logo.PlayIntro);
AddSliderStep("Playback speed", 0.0, 2.0, 1, v => rateAdjustClock.Rate = v);
}
}
}
| 29.436364 | 93 | 0.520692 | [
"MIT"
] | AtomCrafty/osu | osu.Game.Tests/Visual/TestCaseIntroSequence.cs | 1,567 | C# |
using SC2Sharp.Agents;
namespace SC2Sharp.StrategyAnalysis
{
public class Reaper : Strategy
{
private static Reaper Singleton = new Reaper();
public static Strategy Get()
{
return Singleton;
}
public override bool Detect()
{
return Bot.Main.EnemyStrategyAnalyzer.Count(UnitTypes.REAPER) > 0;
}
public override string Name()
{
return "Reaper";
}
}
}
| 19.28 | 78 | 0.553942 | [
"MIT"
] | SimonPrins/TyrSc2 | Tyr/StrategyAnalysis/Reaper.cs | 484 | C# |
using System;
using Chromium;
using Chromium.Event;
using Neutronium.WPF;
namespace Neutronium.WebBrowserEngine.ChromiumFx
{
public abstract class ChromiumFxWebBrowserApp : HTMLApp
{
protected virtual bool DisableGpu => true;
protected override IWPFWebWindowFactory GetWindowFactory() =>
new ChromiumFXWPFWebWindowFactory(UpdateChromiumSettings, Updater());
protected virtual void UpdateChromiumSettings(CfxSettings settings)
{
}
private Action<CfxOnBeforeCommandLineProcessingEventArgs> Updater()
{
return DisableGpu ? PrivateUpdateLineCommandArg: default(Action<CfxOnBeforeCommandLineProcessingEventArgs>);
}
private void PrivateUpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand)
{
beforeLineCommand.CommandLine.AppendSwitch("disable-gpu");
UpdateLineCommandArg(beforeLineCommand);
}
protected virtual void UpdateLineCommandArg(CfxOnBeforeCommandLineProcessingEventArgs beforeLineCommand)
{
}
}
}
| 32.028571 | 120 | 0.715433 | [
"MIT"
] | simonbuehler/Neutronium | WebBrowserEngine/ChromiumFX/HTMEngine.ChromiumFX/ChromiumFxWebBrowserApp.cs | 1,123 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
[SerializeField]
private int maxLives = 3;
private static int _remainingLives = 3;
public static int RemainingLives
{
get { return _remainingLives; }
}
private void Awake()
{
if (Instance == null)
Instance = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
}
public bool isNormal = true;
public bool isBouncy = false;
public bool isHard = false;
public Transform playerPrefab;
public Transform spawnPoint;
public int spawnDelay = 2;
public Transform spawnPrefab;
[SerializeField]
private GameObject gameOverUI;
private float startTime;
[HideInInspector]
public float roundDuration;
[HideInInspector]
public string minutes;
[HideInInspector]
public string seconds;
public bool isGameOver = false;
public Text livesText;
//Sound
AudioManager audioManager;
// public string gameOverSound;
public string playerDeath;
public string enemyDeath;
public string playerRespawn;
private void Start()
{
_remainingLives = maxLives;
Time.timeScale = 1;
startTime = Time.time;
audioManager = AudioManager.Instance;
}
private void Update()
{
UpdateTime();
}
public void EndGame()
{
isGameOver = true;
//audioManager.PlaySound(gameOverSound);
Debug.Log("GAME OVER");
gameOverUI.SetActive(true);
float bestTime = PlayerPrefs.GetFloat("BestTime");
if (roundDuration < bestTime || bestTime == 0.0f)
{
PlayerPrefs.SetFloat("BestTime", roundDuration);
}
int score = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().stats.CurScore;
if (PlayerPrefs.GetInt("HighScore") < score)
{
PlayerPrefs.SetInt("HighScore", score);
}
Time.timeScale = 0;
}
public IEnumerator _RespawnPlayer()
{
livesText.text = "Souls x" + RemainingLives;
yield return new WaitForSeconds(spawnDelay);
audioManager.PlaySound(playerRespawn);
Instantiate(playerPrefab, spawnPoint.position, spawnPoint.rotation);
Transform clone = Instantiate(spawnPrefab, spawnPoint.position, spawnPoint.rotation) as Transform;
Destroy(clone.gameObject, 3f);
livesText.text = "";
}
public static void KillPlayer(Player player)
{
Instance._KillPlayer(player);
}
public void _KillPlayer(Player player)
{
audioManager.PlaySound(playerDeath);
Destroy(player.gameObject);
_remainingLives -= 1;
if (_remainingLives <= 0)
{
Instance.EndGame();
}
else
{
Instance.StartCoroutine(Instance._RespawnPlayer());
}
}
private void UpdateTime()
{
roundDuration = Time.time - startTime;
minutes = ((int)roundDuration / 60).ToString("00");
seconds = (roundDuration % 60).ToString("00.00");
}
public static void KillEnemy(Enemy enemy)
{
Instance._KillEnemy(enemy);
}
public void _KillEnemy(Enemy _enemy)
{
audioManager.PlaySound(enemyDeath);
Transform _clone = Instantiate(_enemy.enemyDeathParticles, _enemy.transform.position, Quaternion.identity) as Transform;
Destroy(_enemy.gameObject);
Destroy(_clone.gameObject, 3f);
}
}
| 25.503497 | 128 | 0.638333 | [
"MIT"
] | adityadutta/TOJam13 | Assets/Scripts/Managers/GameManager.cs | 3,649 | C# |
/*
* OpenBots Server API
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: v1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = OpenBots.Service.API.Client.SwaggerDateConverter;
namespace OpenBots.Service.API.Model
{
/// <summary>
/// Stores the values corresponding to a job's checkpoints
/// </summary>
[DataContract]
public partial class JobCheckpoint : IEquatable<JobCheckpoint>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="JobCheckpoint" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="isDeleted">isDeleted (default to false).</param>
/// <param name="createdBy">createdBy.</param>
/// <param name="createdOn">createdOn.</param>
/// <param name="deletedBy">deletedBy.</param>
/// <param name="deleteOn">deleteOn.</param>
/// <param name="timestamp">timestamp.</param>
/// <param name="updatedOn">updatedOn.</param>
/// <param name="updatedBy">updatedBy.</param>
/// <param name="name">name (required).</param>
/// <param name="message">message.</param>
/// <param name="iterator">iterator.</param>
/// <param name="iteratorValue">iteratorValue.</param>
/// <param name="iteratorPosition">iteratorPosition.</param>
/// <param name="iteratorCount">iteratorCount.</param>
/// <param name="jobId">jobId.</param>
public JobCheckpoint(Guid? id = default(Guid?), bool? isDeleted = false, string createdBy = default(string), DateTime? createdOn = default(DateTime?), string deletedBy = default(string), DateTime? deleteOn = default(DateTime?), byte[] timestamp = default(byte[]), DateTime? updatedOn = default(DateTime?), string updatedBy = default(string), string name = default(string), string message = default(string), string iterator = default(string), string iteratorValue = default(string), int? iteratorPosition = default(int?), int? iteratorCount = default(int?), Guid? jobId = default(Guid?))
{
// to ensure "name" is required (not null)
if (name == null)
{
throw new InvalidDataException("name is a required property for JobCheckpoint and cannot be null");
}
else
{
this.Name = name;
}
this.Id = id;
// use default value if no "isDeleted" provided
if (isDeleted == null)
{
this.IsDeleted = false;
}
else
{
this.IsDeleted = isDeleted;
}
this.CreatedBy = createdBy;
this.CreatedOn = createdOn;
this.DeletedBy = deletedBy;
this.DeleteOn = deleteOn;
this.Timestamp = timestamp;
this.UpdatedOn = updatedOn;
this.UpdatedBy = updatedBy;
this.Message = message;
this.Iterator = iterator;
this.IteratorValue = iteratorValue;
this.IteratorPosition = iteratorPosition;
this.IteratorCount = iteratorCount;
this.JobId = jobId;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public Guid? Id { get; set; }
/// <summary>
/// Gets or Sets IsDeleted
/// </summary>
[DataMember(Name="isDeleted", EmitDefaultValue=false)]
public bool? IsDeleted { get; set; }
/// <summary>
/// Gets or Sets CreatedBy
/// </summary>
[DataMember(Name="createdBy", EmitDefaultValue=false)]
public string CreatedBy { get; set; }
/// <summary>
/// Gets or Sets CreatedOn
/// </summary>
[DataMember(Name="createdOn", EmitDefaultValue=false)]
public DateTime? CreatedOn { get; set; }
/// <summary>
/// Gets or Sets DeletedBy
/// </summary>
[DataMember(Name="deletedBy", EmitDefaultValue=false)]
public string DeletedBy { get; set; }
/// <summary>
/// Gets or Sets DeleteOn
/// </summary>
[DataMember(Name="deleteOn", EmitDefaultValue=false)]
public DateTime? DeleteOn { get; set; }
/// <summary>
/// Gets or Sets Timestamp
/// </summary>
[DataMember(Name="timestamp", EmitDefaultValue=false)]
public byte[] Timestamp { get; set; }
/// <summary>
/// Gets or Sets UpdatedOn
/// </summary>
[DataMember(Name="updatedOn", EmitDefaultValue=false)]
public DateTime? UpdatedOn { get; set; }
/// <summary>
/// Gets or Sets UpdatedBy
/// </summary>
[DataMember(Name="updatedBy", EmitDefaultValue=false)]
public string UpdatedBy { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Message
/// </summary>
[DataMember(Name="message", EmitDefaultValue=false)]
public string Message { get; set; }
/// <summary>
/// Gets or Sets Iterator
/// </summary>
[DataMember(Name="iterator", EmitDefaultValue=false)]
public string Iterator { get; set; }
/// <summary>
/// Gets or Sets IteratorValue
/// </summary>
[DataMember(Name="iteratorValue", EmitDefaultValue=false)]
public string IteratorValue { get; set; }
/// <summary>
/// Gets or Sets IteratorPosition
/// </summary>
[DataMember(Name="iteratorPosition", EmitDefaultValue=false)]
public int? IteratorPosition { get; set; }
/// <summary>
/// Gets or Sets IteratorCount
/// </summary>
[DataMember(Name="iteratorCount", EmitDefaultValue=false)]
public int? IteratorCount { get; set; }
/// <summary>
/// Gets or Sets JobId
/// </summary>
[DataMember(Name="jobId", EmitDefaultValue=false)]
public Guid? JobId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class JobCheckpoint {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" IsDeleted: ").Append(IsDeleted).Append("\n");
sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n");
sb.Append(" CreatedOn: ").Append(CreatedOn).Append("\n");
sb.Append(" DeletedBy: ").Append(DeletedBy).Append("\n");
sb.Append(" DeleteOn: ").Append(DeleteOn).Append("\n");
sb.Append(" Timestamp: ").Append(Timestamp).Append("\n");
sb.Append(" UpdatedOn: ").Append(UpdatedOn).Append("\n");
sb.Append(" UpdatedBy: ").Append(UpdatedBy).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append(" Iterator: ").Append(Iterator).Append("\n");
sb.Append(" IteratorValue: ").Append(IteratorValue).Append("\n");
sb.Append(" IteratorPosition: ").Append(IteratorPosition).Append("\n");
sb.Append(" IteratorCount: ").Append(IteratorCount).Append("\n");
sb.Append(" JobId: ").Append(JobId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as JobCheckpoint);
}
/// <summary>
/// Returns true if JobCheckpoint instances are equal
/// </summary>
/// <param name="input">Instance of JobCheckpoint to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(JobCheckpoint input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.IsDeleted == input.IsDeleted ||
(this.IsDeleted != null &&
this.IsDeleted.Equals(input.IsDeleted))
) &&
(
this.CreatedBy == input.CreatedBy ||
(this.CreatedBy != null &&
this.CreatedBy.Equals(input.CreatedBy))
) &&
(
this.CreatedOn == input.CreatedOn ||
(this.CreatedOn != null &&
this.CreatedOn.Equals(input.CreatedOn))
) &&
(
this.DeletedBy == input.DeletedBy ||
(this.DeletedBy != null &&
this.DeletedBy.Equals(input.DeletedBy))
) &&
(
this.DeleteOn == input.DeleteOn ||
(this.DeleteOn != null &&
this.DeleteOn.Equals(input.DeleteOn))
) &&
(
this.Timestamp == input.Timestamp ||
(this.Timestamp != null &&
this.Timestamp.Equals(input.Timestamp))
) &&
(
this.UpdatedOn == input.UpdatedOn ||
(this.UpdatedOn != null &&
this.UpdatedOn.Equals(input.UpdatedOn))
) &&
(
this.UpdatedBy == input.UpdatedBy ||
(this.UpdatedBy != null &&
this.UpdatedBy.Equals(input.UpdatedBy))
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Message == input.Message ||
(this.Message != null &&
this.Message.Equals(input.Message))
) &&
(
this.Iterator == input.Iterator ||
(this.Iterator != null &&
this.Iterator.Equals(input.Iterator))
) &&
(
this.IteratorValue == input.IteratorValue ||
(this.IteratorValue != null &&
this.IteratorValue.Equals(input.IteratorValue))
) &&
(
this.IteratorPosition == input.IteratorPosition ||
(this.IteratorPosition != null &&
this.IteratorPosition.Equals(input.IteratorPosition))
) &&
(
this.IteratorCount == input.IteratorCount ||
(this.IteratorCount != null &&
this.IteratorCount.Equals(input.IteratorCount))
) &&
(
this.JobId == input.JobId ||
(this.JobId != null &&
this.JobId.Equals(input.JobId))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.IsDeleted != null)
hashCode = hashCode * 59 + this.IsDeleted.GetHashCode();
if (this.CreatedBy != null)
hashCode = hashCode * 59 + this.CreatedBy.GetHashCode();
if (this.CreatedOn != null)
hashCode = hashCode * 59 + this.CreatedOn.GetHashCode();
if (this.DeletedBy != null)
hashCode = hashCode * 59 + this.DeletedBy.GetHashCode();
if (this.DeleteOn != null)
hashCode = hashCode * 59 + this.DeleteOn.GetHashCode();
if (this.Timestamp != null)
hashCode = hashCode * 59 + this.Timestamp.GetHashCode();
if (this.UpdatedOn != null)
hashCode = hashCode * 59 + this.UpdatedOn.GetHashCode();
if (this.UpdatedBy != null)
hashCode = hashCode * 59 + this.UpdatedBy.GetHashCode();
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.Message != null)
hashCode = hashCode * 59 + this.Message.GetHashCode();
if (this.Iterator != null)
hashCode = hashCode * 59 + this.Iterator.GetHashCode();
if (this.IteratorValue != null)
hashCode = hashCode * 59 + this.IteratorValue.GetHashCode();
if (this.IteratorPosition != null)
hashCode = hashCode * 59 + this.IteratorPosition.GetHashCode();
if (this.IteratorCount != null)
hashCode = hashCode * 59 + this.IteratorCount.GetHashCode();
if (this.JobId != null)
hashCode = hashCode * 59 + this.JobId.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 39.984169 | 594 | 0.518147 | [
"Apache-2.0"
] | arenabilgisayar/OpenBots.Agent | OpenBots.Service.API/Model/JobCheckpoint.cs | 15,154 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DCL.Camera;
using DCL.Configuration;
using DCL.Controllers;
using DCL.Helpers;
using UnityEngine;
using Cysharp.Threading.Tasks;
using DCL.Builder.Manifest;
using DCL.Components;
using DCL.Interface;
using DCL.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DCL.Builder
{
public class SceneManager : ISceneManager
{
internal static bool BYPASS_LAND_OWNERSHIP_CHECK = false;
private const float MAX_DISTANCE_STOP_TRYING_TO_ENTER = 16;
private const string SOURCE_BUILDER_PANEl = "BuilderPanel";
private const string SOURCE_SHORTCUT = "Shortcut";
public enum State
{
IDLE = 0,
LOADING_CATALOG = 1,
CATALOG_LOADED = 2,
LOADING_SCENE = 3,
SCENE_LOADED = 4,
EDITING = 5
}
internal State currentState = State.IDLE;
private InputAction_Trigger editModeChangeInputAction;
internal IContext context;
internal string sceneToEditId;
private UserProfile userProfile;
internal Coroutine updateLandsWithAcessCoroutine;
private bool alreadyAskedForLandPermissions = false;
private Vector3 askPermissionLastPosition;
private IWebRequestAsyncOperation catalogAsyncOp;
internal bool isWaitingForPermission = false;
internal IBuilderScene sceneToEdit;
private BiwSceneMetricsAnalyticsHelper sceneMetricsAnalyticsHelper;
private InputController inputController;
internal BuilderInWorldBridge builderInWorldBridge;
internal IInitialStateManager initialStateManager;
internal IBuilderInWorldLoadingController initialLoadingController;
private float beginStartFlowTimeStamp = 0;
internal bool catalogLoaded = false;
internal List<string> portableExperiencesToResume = new List<string>();
public void Initialize(IContext context)
{
this.context = context;
editModeChangeInputAction = context.inputsReferencesAsset.editModeChangeInputAction;
editModeChangeInputAction.OnTriggered += ChangeEditModeStatusByShortcut;
inputController = context.sceneReferences.inputController;
builderInWorldBridge = context.sceneReferences.biwBridgeGameObject.GetComponent<BuilderInWorldBridge>();
userProfile = UserProfile.GetOwnUserProfile();
context.editorContext.editorHUD.OnStartExitAction += StartExitMode;
context.editorContext.editorHUD.OnLogoutAction += ExitEditMode;
BIWTeleportAndEdit.OnTeleportEnd += OnPlayerTeleportedToEditScene;
context.builderAPIController.OnWebRequestCreated += WebRequestCreated;
initialStateManager = new InitialStateManager();
ConfigureLoadingController();
}
public void Dispose()
{
if (context.editorContext.editorHUD != null)
{
context.editorContext.editorHUD.OnStartExitAction -= StartExitMode;
context.editorContext.editorHUD.OnLogoutAction -= ExitEditMode;
}
sceneMetricsAnalyticsHelper?.Dispose();
initialLoadingController?.Dispose();
Environment.i.world.sceneController.OnNewSceneAdded -= NewSceneAdded;
Environment.i.world.sceneController.OnReadyScene -= NewSceneReady;
BIWTeleportAndEdit.OnTeleportEnd -= OnPlayerTeleportedToEditScene;
DCLCharacterController.OnPositionSet -= ExitAfterCharacterTeleport;
if (sceneToEdit?.scene != null)
sceneToEdit.scene.OnLoadingStateUpdated -= UpdateSceneLoadingProgress;
editModeChangeInputAction.OnTriggered -= ChangeEditModeStatusByShortcut;
context.builderAPIController.OnWebRequestCreated -= WebRequestCreated;
CoroutineStarter.Stop(updateLandsWithAcessCoroutine);
}
private void ConfigureLoadingController()
{
initialLoadingController = new BuilderInWorldLoadingController();
initialLoadingController.Initialize();
}
public void NextState()
{
currentState++;
switch (currentState)
{
case State.LOADING_CATALOG:
if (!catalogLoaded)
GetCatalog();
else
NextState();
break;
case State.CATALOG_LOADED:
NextState();
break;
case State.LOADING_SCENE:
LoadScene();
break;
case State.SCENE_LOADED:
EnterEditMode();
break;
}
}
private void SendManifestToScene()
{
//We remove the old assets to they don't collide with the new ones
BIWUtils.RemoveAssetsFromCurrentScene();
//We add the assets from the scene to the catalog
var assets = sceneToEdit.manifest.scene.assets.Values.ToArray();
AssetCatalogBridge.i.AddScenesObjectToSceneCatalog(assets);
//We prepare the mappings to the scenes
Dictionary<string, string> contentDictionary = new Dictionary<string, string>();
foreach (var sceneObject in assets)
{
foreach (var content in sceneObject.contents)
{
if (!contentDictionary.ContainsKey(content.Key))
contentDictionary.Add(content.Key, content.Value);
}
}
//We add the mappings to the scene
BIWUtils.AddSceneMappings(contentDictionary, BIWUrlUtils.GetUrlSceneObjectContent(), sceneToEdit.scene.sceneData);
// We iterate all the entities to create the entity in the scene
foreach (BuilderEntity builderEntity in sceneToEdit.manifest.scene.entities.Values)
{
var entity = sceneToEdit.scene.CreateEntity(builderEntity.id.GetHashCode());
bool nameComponentFound = false;
// We iterate all the id of components in the entity, to add the component
foreach (string idComponent in builderEntity.components)
{
//This shouldn't happen, the component should be always in the scene, but just in case
if (!sceneToEdit.manifest.scene.components.ContainsKey(idComponent))
continue;
// We get the component from the scene and create it in the entity
BuilderComponent component = sceneToEdit.manifest.scene.components[idComponent];
switch (component.type)
{
case "Transform":
DCLTransform.Model model;
try
{
// This is a very ugly way to handle the things because some times the data can come serialize and other times it wont
// It will be deleted when we create the new builder server that only have 1 way to handle everything
model = JsonConvert.DeserializeObject<DCLTransform.Model>(component.data.ToString());
}
catch (Exception e)
{
// We may have create the component so de data is not serialized
model = JsonConvert.DeserializeObject<DCLTransform.Model>(JsonConvert.SerializeObject(component.data));
}
EntityComponentsUtils.AddTransformComponent(sceneToEdit.scene, entity, model);
break;
case "GLTFShape":
LoadableShape.Model gltfModel;
try
{
// This is a very ugly way to handle the things because some times the data can come serialize and other times it wont
// It will be deleted when we create the new builder server that only have 1 way to handle everything
gltfModel = JsonConvert.DeserializeObject<LoadableShape.Model>(component.data.ToString());
}
catch (Exception e)
{
// We may have create the component so de data is not serialized
gltfModel = (GLTFShape.Model)component.data;
}
EntityComponentsUtils.AddGLTFComponent(sceneToEdit.scene, entity, gltfModel, component.id);
break;
case "NFTShape":
//Builder use a different way to load the NFT so we convert it to our system
JObject jObject = JObject.Parse(component.data.ToString());
string url = jObject["url"].ToString();
string assedId = url.Replace(BIWSettings.NFT_ETHEREUM_PROTOCOL, "");
int index = assedId.IndexOf("/", StringComparison.Ordinal);
string partToremove = assedId.Substring(index);
assedId = assedId.Replace(partToremove, "");
NFTShape.Model nftModel = new NFTShape.Model();
nftModel.color = new Color(0.6404918f, 0.611472f, 0.8584906f);
nftModel.src = url;
nftModel.assetId = assedId;
EntityComponentsUtils.AddNFTShapeComponent(sceneToEdit.scene, entity, nftModel, component.id);
break;
case "Name":
nameComponentFound = true;
DCLName.Model nameModel = JsonConvert.DeserializeObject<DCLName.Model>(component.data.ToString());
nameModel.builderValue = builderEntity.name;
EntityComponentsUtils.AddNameComponent(sceneToEdit.scene , entity, nameModel, Guid.NewGuid().ToString());
break;
case "LockedOnEdit":
DCLLockedOnEdit.Model lockedModel = JsonConvert.DeserializeObject<DCLLockedOnEdit.Model>(component.data.ToString());
EntityComponentsUtils.AddLockedOnEditComponent(sceneToEdit.scene , entity, lockedModel, Guid.NewGuid().ToString());
break;
case "Script":
SmartItemComponent.Model smartModel = JsonConvert.DeserializeObject<SmartItemComponent.Model>(component.data.ToString());
sceneToEdit.scene.componentsManagerLegacy.EntityComponentCreateOrUpdate(entity.entityId, CLASS_ID_COMPONENT.SMART_ITEM, smartModel);
break;
}
}
// We need to mantain the builder name of the entity, so we create the equivalent part in biw. We do this so we can maintain the smart-item references
if (!nameComponentFound)
{
DCLName.Model nameModel = new DCLName.Model();
nameModel.value = builderEntity.name;
nameModel.builderValue = builderEntity.name;
EntityComponentsUtils.AddNameComponent(sceneToEdit.scene , entity, nameModel, Guid.NewGuid().ToString());
}
}
}
public void WebRequestCreated(IWebRequestAsyncOperation webRequest)
{
if (currentState == State.LOADING_CATALOG)
catalogAsyncOp = webRequest;
}
public void Update()
{
if (currentState != State.LOADING_CATALOG)
return;
if (catalogAsyncOp?.webRequest != null)
UpdateCatalogLoadingProgress(catalogAsyncOp.webRequest.downloadProgress * 100);
}
private void OnPlayerTeleportedToEditScene(Vector2Int coords)
{
var targetScene = Environment.i.world.state.scenesSortedByDistance
.FirstOrDefault(scene => scene.sceneData.parcels.Contains(coords));
StartFlowFromLandWithPermission(targetScene, SOURCE_BUILDER_PANEl);
}
public void StartFlowFromProject(Manifest.Manifest manifest)
{
bool hasBeenCreatedThisSession = !string.IsNullOrEmpty(DataStore.i.builderInWorld.lastProjectIdCreated.Get()) && DataStore.i.builderInWorld.lastProjectIdCreated.Get() == manifest.project.id;
DataStore.i.builderInWorld.lastProjectIdCreated.Set("");
BuilderScene builderScene = new BuilderScene(manifest, IBuilderScene.SceneType.PROJECT,hasBeenCreatedThisSession);
StartFlow(builderScene, SOURCE_BUILDER_PANEl);
}
public void StartFlowFromLandCoords(Vector2Int coords)
{
Scene deployedScene = GetDeployedSceneFromParcel(coords);
Vector2Int parcelSize = BIWUtils.GetSceneSize(deployedScene.parcels);
StartFromLand(deployedScene.@base, deployedScene, parcelSize, SOURCE_BUILDER_PANEl);
}
public void ShowBuilderLoading()
{
initialLoadingController.Show();
initialLoadingController.SetPercentage(0f);
}
public void HideBuilderLoading()
{
initialLoadingController.Hide();
}
public void StartExitMode()
{
context.cameraController.TakeSceneScreenshotFromResetPosition((sceneSnapshot) =>
{
if (sceneSnapshot != null)
{
sceneToEdit.sceneScreenshotTexture = sceneSnapshot;
if (sceneToEdit.manifest != null)
context.builderAPIController.SetThumbnail(sceneToEdit.manifest.project.id, sceneSnapshot);
}
});
if (context.editorContext.editorHUD == null )
return;
if (context.editorContext.publishController.HasUnpublishChanges() && sceneToEdit.sceneType == IBuilderScene.SceneType.LAND)
{
if (sceneToEdit.sceneType == IBuilderScene.SceneType.LAND)
context.editorContext.editorHUD.ConfigureConfirmationModal(
BIWSettings.EXIT_MODAL_TITLE,
BIWSettings.EXIT_WITHOUT_PUBLISH_MODAL_SUBTITLE,
BIWSettings.EXIT_WITHOUT_PUBLISH_MODAL_CANCEL_BUTTON,
BIWSettings.EXIT_WITHOUT_PUBLISH_MODAL_CONFIRM_BUTTON);
}
else
{
context.editorContext.editorHUD.ConfigureConfirmationModal(
BIWSettings.EXIT_MODAL_TITLE,
BIWSettings.EXIT_MODAL_SUBTITLE,
BIWSettings.EXIT_MODAL_CANCEL_BUTTON,
BIWSettings.EXIT_MODAL_CONFIRM_BUTTON);
}
}
public IParcelScene FindSceneToEdit()
{
foreach (IParcelScene scene in Environment.i.world.state.scenesSortedByDistance)
{
if (WorldStateUtils.IsCharacterInsideScene(scene))
return scene;
}
return null;
}
private void UpdateLandsWithAccess()
{
ICatalyst catalyst = Environment.i.platform.serviceProviders.catalyst;
ITheGraph theGraph = Environment.i.platform.serviceProviders.theGraph;
DeployedScenesFetcher.FetchLandsFromOwner(
catalyst,
theGraph,
userProfile.ethAddress,
KernelConfig.i.Get().network,
BIWSettings.CACHE_TIME_LAND,
BIWSettings.CACHE_TIME_SCENES)
.Then(lands =>
{
DataStore.i.builderInWorld.landsWithAccess.Set(lands.ToArray(), true);
if (isWaitingForPermission && Vector3.Distance(askPermissionLastPosition, DCLCharacterController.i.characterPosition.unityPosition) <= MAX_DISTANCE_STOP_TRYING_TO_ENTER)
{
CheckSceneToEditByShorcut();
}
isWaitingForPermission = false;
alreadyAskedForLandPermissions = true;
});
}
internal void CatalogLoaded()
{
catalogLoaded = true;
if ( context.editorContext.editorHUD != null)
context.editorContext.editorHUD.RefreshCatalogContent();
NextState();
}
internal void StartFlow(IBuilderScene targetScene, string source)
{
if (currentState != State.IDLE || targetScene == null)
return;
DataStore.i.exploreV2.isOpen.Set(false);
sceneToEditId = targetScene.manifest.project.scene_id;
sceneToEdit = targetScene;
NotificationsController.i.allowNotifications = false;
CommonScriptableObjects.allUIHidden.Set(true);
NotificationsController.i.allowNotifications = true;
inputController.inputTypeMode = InputTypeMode.BUILD_MODE_LOADING;
//We configure the loading part
ShowBuilderLoading();
DataStore.i.common.appMode.Set(AppMode.BUILDER_IN_WORLD_EDITION);
DataStore.i.virtualAudioMixer.sceneSFXVolume.Set(0f);
BIWAnalytics.StartEditorFlow(source);
beginStartFlowTimeStamp = Time.realtimeSinceStartup;
NextState();
}
internal void GetCatalog()
{
BIWNFTController.i.StartFetchingNft();
var catalogPromise = context.builderAPIController.GetCompleteCatalog(userProfile.ethAddress);
catalogPromise.Then(x =>
{
CatalogLoaded();
});
catalogPromise.Catch(error =>
{
BIWUtils.ShowGenericNotification(error);
});
}
public void ChangeEditModeStatusByShortcut(DCLAction_Trigger action)
{
if (currentState != State.EDITING && currentState != State.IDLE)
return;
if (currentState == State.EDITING )
{
context.editorContext.editorHUD.ExitStart();
return;
}
if (DataStore.i.builderInWorld.landsWithAccess.Get().Length == 0 && !alreadyAskedForLandPermissions)
{
ActivateLandAccessBackgroundChecker();
BIWUtils.ShowGenericNotification(BIWSettings.LAND_EDITION_WAITING_FOR_PERMISSIONS_MESSAGE, DCL.NotificationModel.Type.GENERIC_WITHOUT_BUTTON, BIWSettings.LAND_CHECK_MESSAGE_TIMER);
isWaitingForPermission = true;
askPermissionLastPosition = DCLCharacterController.i.characterPosition.unityPosition;
}
else
{
CheckSceneToEditByShorcut();
}
}
internal void CheckSceneToEditByShorcut()
{
var scene = FindSceneToEdit();
StartFlowFromLandWithPermission(scene, SOURCE_SHORTCUT);
}
internal void NewSceneAdded(IParcelScene newScene)
{
if (newScene.sceneData.id != sceneToEditId)
return;
Environment.i.world.sceneController.OnNewSceneAdded -= NewSceneAdded;
var scene = Environment.i.world.state.GetScene(sceneToEditId);
sceneToEdit.SetScene(scene);
sceneMetricsAnalyticsHelper = new BiwSceneMetricsAnalyticsHelper(sceneToEdit.scene);
sceneToEdit.scene.OnLoadingStateUpdated += UpdateSceneLoadingProgress;
SendManifestToScene();
context.cameraController.ActivateCamera(sceneToEdit.scene);
}
private void NewSceneReady(string id)
{
if (sceneToEditId != id)
return;
sceneToEdit.scene.OnLoadingStateUpdated -= UpdateSceneLoadingProgress;
Environment.i.world.sceneController.OnReadyScene -= NewSceneReady;
sceneToEditId = null;
NextState();
}
internal bool UserHasPermissionOnParcelScene(IParcelScene sceneToCheck)
{
if (BYPASS_LAND_OWNERSHIP_CHECK)
return true;
List<Vector2Int> allParcelsWithAccess = DataStore.i.builderInWorld.landsWithAccess.Get().SelectMany(land => land.parcels).ToList();
foreach (Vector2Int parcel in allParcelsWithAccess)
{
if (sceneToCheck.sceneData.parcels.Any(currentParcel => currentParcel.x == parcel.x && currentParcel.y == parcel.y))
return true;
}
return false;
}
internal Scene GetDeployedSceneFromParcel(Vector2Int coords)
{
List<Scene> allDeployedScenesWithAccess = DataStore.i.builderInWorld.landsWithAccess.Get().SelectMany(land => land.scenes).ToList();
foreach (Scene scene in allDeployedScenesWithAccess)
{
List<Vector2Int> scenes = scene.parcels.ToList();
foreach (Vector2Int parcel in scenes)
{
if (coords.x == parcel.x && coords.y == parcel.y)
return scene;
}
}
return null;
}
internal Scene GetDeployedSceneFromParcel(IParcelScene sceneToCheck)
{
List<Scene> allDeployedScenesWithAccess = DataStore.i.builderInWorld.landsWithAccess.Get().SelectMany(land => land.scenes).ToList();
foreach (Scene scene in allDeployedScenesWithAccess)
{
List<Vector2Int> scenes = scene.parcels.ToList();
foreach (Vector2Int parcel in scenes)
{
if (sceneToCheck.sceneData.parcels.Any(currentParcel => currentParcel.x == parcel.x && currentParcel.y == parcel.y))
return scene;
}
}
return null;
}
internal bool IsParcelSceneDeployedFromSDK(IParcelScene sceneToCheck)
{
List<Scene> allDeployedScenesWithAccess = DataStore.i.builderInWorld.landsWithAccess.Get().SelectMany(land => land.scenes).ToList();
foreach (Scene scene in allDeployedScenesWithAccess)
{
if (scene.source != Scene.Source.SDK)
continue;
List<Vector2Int> parcelsDeployedFromSDK = scene.parcels.ToList();
foreach (Vector2Int parcel in parcelsDeployedFromSDK)
{
if (sceneToCheck.sceneData.parcels.Any(currentParcel => currentParcel.x == parcel.x && currentParcel.y == parcel.y))
return true;
}
}
return false;
}
internal void EnterEditMode()
{
initialLoadingController.SetPercentage(100f);
initialLoadingController.Hide(true, onHideAction: () =>
{
inputController.inputTypeMode = InputTypeMode.BUILD_MODE;
context.editorContext.editorHUD?.SetVisibility(true);
CommonScriptableObjects.allUIHidden.Set(true);
});
DCLCharacterController.OnPositionSet += ExitAfterCharacterTeleport;
portableExperiencesToResume = DataStore.i.experiencesViewer.activeExperience.Get();
WebInterface.SetDisabledPortableExperiences(DataStore.i.experiencesViewer.activeExperience.Get().ToArray());
context.editor.EnterEditMode(sceneToEdit);
DataStore.i.player.canPlayerMove.Set(false);
BIWAnalytics.EnterEditor( Time.realtimeSinceStartup - beginStartFlowTimeStamp);
}
internal void ExitEditMode()
{
currentState = State.IDLE;
DataStore.i.HUDs.loadingHUD.visible.Set(true);
initialLoadingController.Hide(true);
inputController.inputTypeMode = InputTypeMode.GENERAL;
CommonScriptableObjects.allUIHidden.Set(false);
context.cameraController.DeactivateCamera();
context.editor.ExitEditMode();
builderInWorldBridge.StopIsolatedMode();
Utils.UnlockCursor();
DataStore.i.player.canPlayerMove.Set(true);
DCLCharacterController.OnPositionSet -= ExitAfterCharacterTeleport;
}
public void StartFlowFromLandWithPermission(IParcelScene targetScene, string source)
{
if (currentState != State.IDLE || targetScene == null)
return;
if (!UserHasPermissionOnParcelScene(targetScene))
{
BIWUtils.ShowGenericNotification(BIWSettings.LAND_EDITION_NOT_ALLOWED_BY_PERMISSIONS_MESSAGE);
return;
}
else if (IsParcelSceneDeployedFromSDK(targetScene))
{
BIWUtils.ShowGenericNotification(BIWSettings.LAND_EDITION_NOT_ALLOWED_BY_SDK_LIMITATION_MESSAGE);
return;
}
Scene deployedScene = GetDeployedSceneFromParcel(targetScene);
Vector2Int parcelSize = BIWUtils.GetSceneSize(targetScene);
StartFromLand(targetScene.sceneData.basePosition, deployedScene, parcelSize, source);
}
private void StartFromLand(Vector2Int landCoordsVector, Scene deployedScene, Vector2Int parcelSize, string source)
{
string landCoords = landCoordsVector.x + "," + landCoordsVector.y;
Promise<InitialStateResponse> manifestPromise = initialStateManager.GetInitialManifest(context.builderAPIController, landCoords, deployedScene, parcelSize);
manifestPromise.Then(response =>
{
BuilderScene builderScene = new BuilderScene(response.manifest, IBuilderScene.SceneType.LAND, response.hasBeenCreated);
builderScene.landCoordsAsociated = landCoordsVector;
StartFlow(builderScene, source);
});
manifestPromise.Catch( error =>
{
BIWUtils.ShowGenericNotification(error);
ExitEditMode();
});
}
private void LoadScene()
{
Environment.i.platform.cullingController.Stop();
// In this point we're sure that the catalog loading (the first half of our progress bar) has already finished
initialLoadingController.SetPercentage(50f);
Environment.i.world.sceneController.OnNewSceneAdded += NewSceneAdded;
Environment.i.world.sceneController.OnReadyScene += NewSceneReady;
Environment.i.world.blockersController.SetEnabled(false);
ILand land = BIWUtils.CreateILandFromManifest(sceneToEdit.manifest, DataStore.i.player.playerPosition.Get());
builderInWorldBridge.StartIsolatedMode(land);
}
internal void ActivateLandAccessBackgroundChecker()
{
userProfile = UserProfile.GetOwnUserProfile();
if (!string.IsNullOrEmpty(userProfile.userId))
{
if (updateLandsWithAcessCoroutine != null)
CoroutineStarter.Stop(updateLandsWithAcessCoroutine);
updateLandsWithAcessCoroutine = CoroutineStarter.Start(CheckLandsAccess());
}
}
private void UpdateSceneLoadingProgress(float sceneLoadingProgress) { initialLoadingController.SetPercentage(50f + (sceneLoadingProgress / 2)); }
private void UpdateCatalogLoadingProgress(float catalogLoadingProgress) { initialLoadingController.SetPercentage(catalogLoadingProgress / 2); }
internal void ExitAfterCharacterTeleport(DCLCharacterPosition position) { ExitEditMode(); }
private IEnumerator CheckLandsAccess()
{
while (true)
{
UpdateLandsWithAccess();
yield return WaitForSecondsCache.Get(BIWSettings.REFRESH_LANDS_WITH_ACCESS_INTERVAL);
}
}
}
} | 43.283383 | 206 | 0.59058 | [
"Apache-2.0"
] | Timothyoung97/unity-renderer | unity-renderer/Assets/DCLPlugins/BuilderInWorld/Scripts/SceneManager/SceneManager.cs | 29,173 | C# |
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Voltaire.Views.Info
{
public static class MultipleGuildSendResponse
{
public static Tuple<string, Embed> Response(ShardedCommandContext context, IEnumerable<SocketGuild> guilds, string message)
{
var embed = new EmbedBuilder
{
Author = new EmbedAuthorBuilder
{
Name = "send_server"
},
ThumbnailUrl = "https://nminchow.github.io/VoltaireWeb/images/quill.png",
Description = "It looks like you belong to multiple servers where Voltaire is installed. Please specify your server using the following command: `send_server (server_name) (channel_name) (message)`\n\n" +
"**Servers:**",
Color = new Color(111, 111, 111)
};
guilds.Select(x => {
embed.AddField(x.Name, $"ex: `!volt send_server \"{x.Name}\" {x.Channels.FirstOrDefault().Name} {message}`");
return true;
}).ToList();
return new Tuple<string, Embed>("", embed.Build());
}
}
}
| 33.394737 | 220 | 0.589441 | [
"MIT"
] | AntiGuide/Voltaire | Voltaire/Views/Info/MultipleGuildSendResponse.cs | 1,271 | C# |
using System;
namespace TRx.Helpers
{
/// <summary>
/// Identifier for underlying data
/// </summary>
public interface IIdentifiedString
{
/// <summary>
/// Identifier for underlying data
/// </summary>
string Id
{
get;
set;
}
}
}
| 17.263158 | 42 | 0.481707 | [
"Apache-2.0"
] | wouldyougo/TRx | TRx.Helpers/IIdentifiedString.cs | 330 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("UserTest")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("UserTest")]
[assembly: System.Reflection.AssemblyTitleAttribute("UserTest")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// 由 MSBuild WriteCodeFragment 类生成。
| 36.166667 | 80 | 0.626728 | [
"MIT"
] | Wscar/MyMicroServiceProject | User.API/UserTest/obj/Debug/netcoreapp2.0/UserTest.AssemblyInfo.cs | 984 | C# |
using System.Collections.Generic;
using Mina.Core.Buffer;
namespace FSO.Common.Serialization.Primitives
{
public class cTSOProperty : IoBufferSerializable, IoBufferDeserializable
{
public uint StructType;
public List<cTSOPropertyField> StructFields;
public void Serialize(IoBuffer output, ISerializationContext context)
{
output.PutUInt32(0x89739A79);
output.PutUInt32(StructType);
output.PutUInt32((uint)StructFields.Count);
foreach (var item in StructFields)
{
output.PutUInt32(item.StructFieldID);
context.ModelSerializer.Serialize(output, item.Value, context, true);
}
}
public void Deserialize(IoBuffer input, ISerializationContext context)
{
//Unknown
input.GetUInt32();
StructType = input.GetUInt32();
StructFields = new List<cTSOPropertyField>();
var numFields = input.GetUInt32();
for(int i=0; i < numFields; i++){
var fieldId = input.GetUInt32();
var typeId = input.GetUInt32();
var value = context.ModelSerializer.Deserialize(typeId, input, context);
StructFields.Add(new cTSOPropertyField
{
StructFieldID = fieldId,
Value = value
});
}
}
}
public class cTSOPropertyField
{
public uint StructFieldID;
public object Value;
}
}
| 29.166667 | 88 | 0.573968 | [
"MPL-2.0"
] | HarryFreeMyLand/newso | Src/tso.common/Serialization/Primitives/cTSOProperty.cs | 1,577 | 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 chime-2018-05-01.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.Chime.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Chime.Model.Internal.MarshallTransformations
{
/// <summary>
/// DescribeAppInstanceUser Request Marshaller
/// </summary>
public class DescribeAppInstanceUserRequestMarshaller : IMarshaller<IRequest, DescribeAppInstanceUserRequest> , 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((DescribeAppInstanceUserRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DescribeAppInstanceUserRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Chime");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-05-01";
request.HttpMethod = "GET";
if (!publicRequest.IsSetAppInstanceUserArn())
throw new AmazonChimeException("Request object does not have required field AppInstanceUserArn set");
request.AddPathResource("{appInstanceUserArn}", StringUtils.FromString(publicRequest.AppInstanceUserArn));
request.ResourcePath = "/app-instance-users/{appInstanceUserArn}";
request.MarshallerVersion = 2;
request.HostPrefix = $"identity-";
return request;
}
private static DescribeAppInstanceUserRequestMarshaller _instance = new DescribeAppInstanceUserRequestMarshaller();
internal static DescribeAppInstanceUserRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeAppInstanceUserRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.833333 | 161 | 0.663256 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/Chime/Generated/Model/Internal/MarshallTransformations/DescribeAppInstanceUserRequestMarshaller.cs | 3,225 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime:4.0.30319.42000
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("Practica5.formLoginError.xaml", "formLoginError.xaml", typeof(global::Practica5.formLoginError))]
namespace Practica5 {
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("formLoginError.xaml")]
public partial class formLoginError : global::Xamarin.Forms.ContentPage {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(formLoginError));
}
}
}
| 42.52 | 160 | 0.603951 | [
"Apache-2.0"
] | PabloCM03/PabloTAP | 2P/Practica5/C#/Practica5/obj/Debug/netstandard2.0/formLoginError.xaml.g.cs | 1,068 | C# |
using System.Collections.Generic;
using OpenMod.API.Permissions;
using Rocket.API.Serialisation;
namespace OpenMod.Unturned.RocketMod.Permissions
{
public class OpenModPermissionRoleWrapper : IPermissionRole
{
public OpenModPermissionRoleWrapper(RocketPermissionsGroup @group)
{
Id = group.Id;
Type = "role";
DisplayName = @group.DisplayName;
Priority = 0;
Parents = new HashSet<string>();
IsAutoAssigned = false;
if (!string.IsNullOrEmpty(@group.ParentGroup))
{
Parents.Add(@group.ParentGroup);
}
FullActorName = $"rocketmodRole/{Id} ({DisplayName})";
}
public string Id { get; }
public string Type { get; }
public string DisplayName { get; }
public string FullActorName { get; }
public int Priority { get; set; }
public HashSet<string> Parents { get; }
public bool IsAutoAssigned { get; set; }
}
} | 30.352941 | 74 | 0.591085 | [
"MIT"
] | 01-Feli/openmod | unturned/OpenMod.Unturned/RocketMod/Permissions/OpenModPermissionRoleWrapper.cs | 1,034 | C# |
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.VisioApi.Enums
{
/// <summary>
/// SupportByVersion Visio 14, 15, 16
/// </summary>
///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/ff765529(v=office.14).aspx </remarks>
[SupportByVersion("Visio", 14,15,16)]
[EntityType(EntityType.IsEnum)]
public enum VisDeleteFlags
{
/// <summary>
/// SupportByVersion Visio 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("Visio", 14,15,16)]
visDeleteNormal = 0,
/// <summary>
/// SupportByVersion Visio 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("Visio", 14,15,16)]
visDeleteHealConnectors = 1,
/// <summary>
/// SupportByVersion Visio 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersion("Visio", 14,15,16)]
visDeleteNoHealConnectors = 2,
/// <summary>
/// SupportByVersion Visio 14, 15, 16
/// </summary>
/// <remarks>4</remarks>
[SupportByVersion("Visio", 14,15,16)]
visDeleteNoContainerMembers = 4,
/// <summary>
/// SupportByVersion Visio 14, 15, 16
/// </summary>
/// <remarks>8</remarks>
[SupportByVersion("Visio", 14,15,16)]
visDeleteNoAssociatedCallouts = 8
}
} | 26.428571 | 125 | 0.640927 | [
"MIT"
] | DominikPalo/NetOffice | Source/Visio/Enums/VisDeleteFlags.cs | 1,297 | C# |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Ess;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Tsp;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Cms;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Tsp
{
public class TimeStampTokenGenerator
{
private int accuracySeconds = -1;
private int accuracyMillis = -1;
private int accuracyMicros = -1;
private bool ordering = false;
private GeneralName tsa = null;
private string tsaPolicyOID;
private AsymmetricKeyParameter key;
private X509Certificate cert;
private string digestOID;
private Asn1.Cms.AttributeTable signedAttr;
private Asn1.Cms.AttributeTable unsignedAttr;
private IX509Store x509Certs;
private IX509Store x509Crls;
/**
* basic creation - only the default attributes will be included here.
*/
public TimeStampTokenGenerator(
AsymmetricKeyParameter key,
X509Certificate cert,
string digestOID,
string tsaPolicyOID)
: this(key, cert, digestOID, tsaPolicyOID, null, null)
{
}
/**
* create with a signer with extra signed/unsigned attributes.
*/
public TimeStampTokenGenerator(
AsymmetricKeyParameter key,
X509Certificate cert,
string digestOID,
string tsaPolicyOID,
Asn1.Cms.AttributeTable signedAttr,
Asn1.Cms.AttributeTable unsignedAttr)
{
this.key = key;
this.cert = cert;
this.digestOID = digestOID;
this.tsaPolicyOID = tsaPolicyOID;
this.unsignedAttr = unsignedAttr;
TspUtil.ValidateCertificate(cert);
//
// Add the ESSCertID attribute
//
IDictionary signedAttrs;
if (signedAttr != null)
{
signedAttrs = signedAttr.ToDictionary();
}
else
{
signedAttrs = Platform.CreateHashtable();
}
try
{
byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());
EssCertID essCertid = new EssCertID(hash);
Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
PkcsObjectIdentifiers.IdAASigningCertificate,
new DerSet(new SigningCertificate(essCertid)));
signedAttrs[attr.AttrType] = attr;
}
catch (CertificateEncodingException e)
{
throw new TspException("Exception processing certificate.", e);
}
catch (SecurityUtilityException e)
{
throw new TspException("Can't find a SHA-1 implementation.", e);
}
this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
}
public void SetCertificates(
IX509Store certificates)
{
this.x509Certs = certificates;
}
public void SetCrls(
IX509Store crls)
{
this.x509Crls = crls;
}
public void SetAccuracySeconds(
int accuracySeconds)
{
this.accuracySeconds = accuracySeconds;
}
public void SetAccuracyMillis(
int accuracyMillis)
{
this.accuracyMillis = accuracyMillis;
}
public void SetAccuracyMicros(
int accuracyMicros)
{
this.accuracyMicros = accuracyMicros;
}
public void SetOrdering(
bool ordering)
{
this.ordering = ordering;
}
public void SetTsa(
GeneralName tsa)
{
this.tsa = tsa;
}
//------------------------------------------------------------------------------
public TimeStampToken Generate(
TimeStampRequest request,
BigInteger serialNumber,
DateTime genTime)
{
DerObjectIdentifier digestAlgOID = new DerObjectIdentifier(request.MessageImprintAlgOid);
AlgorithmIdentifier algID = new AlgorithmIdentifier(digestAlgOID, DerNull.Instance);
MessageImprint messageImprint = new MessageImprint(algID, request.GetMessageImprintDigest());
Accuracy accuracy = null;
if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0)
{
DerInteger seconds = null;
if (accuracySeconds > 0)
{
seconds = new DerInteger(accuracySeconds);
}
DerInteger millis = null;
if (accuracyMillis > 0)
{
millis = new DerInteger(accuracyMillis);
}
DerInteger micros = null;
if (accuracyMicros > 0)
{
micros = new DerInteger(accuracyMicros);
}
accuracy = new Accuracy(seconds, millis, micros);
}
DerBoolean derOrdering = null;
if (ordering)
{
derOrdering = DerBoolean.GetInstance(ordering);
}
DerInteger nonce = null;
if (request.Nonce != null)
{
nonce = new DerInteger(request.Nonce);
}
DerObjectIdentifier tsaPolicy = new DerObjectIdentifier(tsaPolicyOID);
if (request.ReqPolicy != null)
{
tsaPolicy = new DerObjectIdentifier(request.ReqPolicy);
}
TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint,
new DerInteger(serialNumber), new DerGeneralizedTime(genTime), accuracy,
derOrdering, nonce, tsa, request.Extensions);
try
{
CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator();
byte[] derEncodedTstInfo = tstInfo.GetDerEncoded();
if (request.CertReq)
{
signedDataGenerator.AddCertificates(x509Certs);
}
signedDataGenerator.AddCrls(x509Crls);
signedDataGenerator.AddSigner(key, cert, digestOID, signedAttr, unsignedAttr);
CmsSignedData signedData = signedDataGenerator.Generate(
PkcsObjectIdentifiers.IdCTTstInfo.Id,
new CmsProcessableByteArray(derEncodedTstInfo),
true);
return new TimeStampToken(signedData);
}
catch (CmsException cmsEx)
{
throw new TspException("Error generating time-stamp token", cmsEx);
}
catch (IOException e)
{
throw new TspException("Exception encoding info", e);
}
catch (X509StoreException e)
{
throw new TspException("Exception handling CertStore", e);
}
// catch (InvalidAlgorithmParameterException e)
// {
// throw new TspException("Exception handling CertStore CRLs", e);
// }
}
}
}
| 25.313008 | 97 | 0.673197 | [
"BSD-3-Clause"
] | GaloisInc/hacrypto | src/C#/BouncyCastle/BouncyCastle-1.7/crypto/src/tsp/TimeStampTokenGenerator.cs | 6,227 | C# |
using System;
using System.Runtime.InteropServices;
/// <remarks>
/// CREDITS: https://github.com/MScholtes/VirtualDesktop
///
/// MIT License
///
/// Copyright(c) 2017 Markus Scholtes
///
/// 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.
/// </remarks>
namespace MScholtes.VirtualDesktop
{
public class Desktop
{
private IVirtualDesktop ivd;
private Desktop(IVirtualDesktop desktop) { ivd = desktop; }
/// <summary>
/// Get hash
/// </summary>
public override int GetHashCode()
{
return ivd.GetHashCode();
}
/// <summary>
/// Compares with object
/// </summary>
public override bool Equals(object obj)
{
return obj is Desktop desk && ReferenceEquals(ivd, desk.ivd);
}
/// <summary>
/// Returns the number of desktops
/// </summary>
public static int Count => DesktopManager.VirtualDesktopManagerInternal.GetCount();
/// <summary>
/// Returns current desktop
/// </summary>
public static Desktop Current => new Desktop(DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop());
/// <summary>
/// Create desktop object from index
/// </summary>
/// <param name="index">0..Count-1</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
public static Desktop FromIndex(int index)
{
return new Desktop(DesktopManager.GetDesktop(index));
}
/// <summary>
/// Creates desktop object on which window <paramref name="hWnd"/> is displayed
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="hWnd"/> is <c>default</c>.</exception>
public static Desktop FromWindow(IntPtr hWnd)
{
try
{
return FromWindowInternal(hWnd);
}
catch (COMException exception) when ((uint)exception.HResult == 0x800706BA)
{
DesktopManager.Initialize();
return FromWindowInternal(hWnd);
}
}
private static Desktop FromWindowInternal(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
try
{
var id = DesktopManager.VirtualDesktopManager.GetWindowDesktopId(hWnd);
if (id == default)
return default;
return new Desktop(DesktopManager.VirtualDesktopManagerInternal.FindDesktop(ref id));
}
catch (COMException exception) when ((uint)exception.HResult == 0x8002802B)
{
return null;
}
}
/// <summary>
/// Returns index of desktop object or -1 if not found
/// </summary>
/// <param name="desktop"></param>
/// <returns></returns>
public static int FromDesktop(Desktop desktop)
{
return DesktopManager.GetDesktopIndex(desktop.ivd);
}
/// <summary>
/// Create a new desktop
/// </summary>
public static Desktop Create()
{
return new Desktop(DesktopManager.VirtualDesktopManagerInternal.CreateDesktop());
}
/// <summary>
/// Destroy desktop and switch to <paramref name="fallback"/>
/// </summary>
/// <param name="fallback">if no fallback is given use desktop to the left except for desktop 0.</param>
public void Remove(Desktop fallback = null)
{
IVirtualDesktop fallbackdesktop;
if (fallback == null)
{ // if no fallback is given use desktop to the left except for desktop 0.
var dtToCheck = new Desktop(DesktopManager.GetDesktop(0));
if (Equals(dtToCheck))
{ // desktop 0: set fallback to second desktop (= "right" desktop)
DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 4, out fallbackdesktop); // 4 = RightDirection
}
else
{ // set fallback to "left" desktop
DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 3, out fallbackdesktop); // 3 = LeftDirection
}
}
else
// set fallback desktop
fallbackdesktop = fallback.ivd;
DesktopManager.VirtualDesktopManagerInternal.RemoveDesktop(ivd, fallbackdesktop);
}
/// <summary>
/// Returns <true> if this desktop is the current displayed one
/// </summary>
public bool IsVisible
{
get { return ReferenceEquals(ivd, DesktopManager.VirtualDesktopManagerInternal.GetCurrentDesktop()); }
}
/// <summary>
/// Make this desktop visible
/// </summary>
public void MakeVisible()
{
DesktopManager.VirtualDesktopManagerInternal.SwitchDesktop(ivd);
}
/// <summary>
/// Returns desktop at the left of this one, null if none
/// </summary>
public Desktop Left
{
get
{
int hr = DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 3, out var desktop); // 3 = LeftDirection
if (hr == 0)
return new Desktop(desktop);
else
return null;
}
}
/// <summary>
/// Returns desktop at the right of this one, null if none
/// </summary>
public Desktop Right
{
get
{
int hr = DesktopManager.VirtualDesktopManagerInternal.GetAdjacentDesktop(ivd, 4, out var desktop); // 4 = RightDirection
if (hr == 0)
return new Desktop(desktop);
else
return null;
}
}
/// <summary>
/// Move window <paramref name="hWnd"/> to this desktop
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="hWnd"/> is <c>null</c>.</exception>
public void MoveWindow(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
GetWindowThreadProcessId(hWnd, out int processId);
if (System.Diagnostics.Process.GetCurrentProcess().Id == processId)
{ // window of process
try // the easy way (if we are owner)
{
DesktopManager.VirtualDesktopManager.MoveWindowToDesktop(hWnd, ivd.GetId());
}
catch // window of process, but we are not the owner
{
DesktopManager.ApplicationViewCollection.GetViewForHwnd(hWnd, out var view);
DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd);
}
}
else
{ // window of other process
DesktopManager.ApplicationViewCollection.GetViewForHwnd(hWnd, out var view);
DesktopManager.VirtualDesktopManagerInternal.MoveViewToDesktop(view, ivd);
}
}
/// <summary>
/// Returns true if window <paramref name="hWnd"/> is on this desktop
/// </summary>
/// <param name="hWnd"></param>
public bool HasWindow(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
return ivd.GetId() == DesktopManager.VirtualDesktopManager.GetWindowDesktopId(hWnd);
}
/// <summary>
/// Returns true if window <paramref name="hWnd"/> is pinned to all desktops
/// </summary>
public static bool IsWindowPinned(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
return DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(hWnd.GetApplicationView());
}
/// <summary>
/// pin window <paramref name="hWnd"/> to all desktops
/// </summary>
public static void PinWindow(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
if (!DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(view))
{ // pin only if not already pinned
DesktopManager.VirtualDesktopPinnedApps.PinView(view);
}
}
/// <summary>
/// unpin window <paramref name="hWnd"/> from all desktops
/// </summary>
public static void UnpinWindow(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
if (DesktopManager.VirtualDesktopPinnedApps.IsViewPinned(view))
{ // unpin only if not already unpinned
DesktopManager.VirtualDesktopPinnedApps.UnpinView(view);
}
}
/// <summary>
/// Returns true if application for window <paramref name="hWnd"/> is pinned to all desktops
/// </summary>
public static bool IsApplicationPinned(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
return DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(DesktopManager.GetAppId(hWnd));
}
/// <summary>
/// pin application for window <paramref name="hWnd"/> to all desktops
/// </summary>
public static void PinApplication(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
string appId = DesktopManager.GetAppId(hWnd);
if (!DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(appId))
{ // pin only if not already pinned
DesktopManager.VirtualDesktopPinnedApps.PinAppID(appId);
}
}
/// <summary>
/// unpin application for window <paramref name="hWnd"/> from all desktops
/// </summary>
public static void UnpinApplication(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
throw new ArgumentNullException();
var view = hWnd.GetApplicationView();
string appId = DesktopManager.GetAppId(hWnd);
if (DesktopManager.VirtualDesktopPinnedApps.IsAppIdPinned(appId))
{ // unpin only if already pinned
DesktopManager.VirtualDesktopPinnedApps.UnpinAppID(appId);
}
}
/// <summary>Get process id to window handle</summary>
[DllImport("user32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
}
} | 31.529968 | 124 | 0.698949 | [
"MIT"
] | LinqLover/Videfix | MScholtes.VirtualDesktop/Desktop.cs | 9,997 | C# |
using Microsoft.Extensions.Logging;
using Oliver.Client.Services;
using Oliver.Common.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Oliver.Client.Executing
{
internal class LogSender : ILogSender
{
private readonly IApiClient apiClient;
private readonly ILogger<LogSender> logger;
private readonly ConcurrentQueue<Action> queue;
private readonly CancellationTokenSource cancellation;
public LogSender(IApiClient apiClient, ILogger<LogSender> logger)
{
this.apiClient = apiClient;
this.logger = logger;
this.queue = new ConcurrentQueue<Action>();
this.cancellation = new CancellationTokenSource();
Task.Run(QueueListenerAsync, this.cancellation.Token);
}
public Task LogStep(long executionId, int stepId, bool isLastStep = false, List<string> logs = null, CancellationToken cancellationToken = default)
{
cancellationToken.Register(() => this.cancellation.Cancel());
this.queue.Enqueue(async () =>
{
await this.apiClient.SendExecutionLog(executionId, isLastStep, new Execution.StepState
{
Executor = Environment.MachineName,
StepId = stepId,
IsSuccess = true,
Log = logs
}, cancellationToken);
});
this.logger.LogInformation($"ExecutionId: {executionId};\nStepId: {stepId}");
this.logger.LogInformation(string.Join('\n', logs));
return Task.CompletedTask;
}
public Task LogError(long executionId, string message, int stepId = 0, bool isLastStep = false, Exception error = null, List<string> logs = null, CancellationToken cancellationToken = default)
{
cancellationToken.Register(() => this.cancellation.Cancel());
this.queue.Enqueue(async () =>
{
logs ??= new List<string>();
logs.Add(message);
if (error != null)
{
logs.Add(error.Message);
logs.Add(error.StackTrace);
}
await this.apiClient.SendExecutionLog(executionId, isLastStep, new Execution.StepState
{
Executor = Environment.MachineName,
StepId = stepId,
IsSuccess = false,
Log = logs
}, cancellationToken);
});
this.logger.LogWarning(error, $"{message}\nExecutionId: {executionId};\nStepId: {stepId}");
return Task.CompletedTask;
}
private async Task QueueListenerAsync()
{
while (!this.cancellation.IsCancellationRequested)
{
if (this.queue.TryDequeue(out var action))
{
try
{
action();
}
catch (System.Net.WebException e)
{
this.logger.LogWarning(e, "Error while trying to send step log...");
this.queue.Enqueue(action);
}
catch (Exception e)
{
this.logger.LogWarning(e, "Error while trying to send step log...");
}
}
await Task.Delay(100);
}
}
}
internal interface ILogSender
{
Task LogStep(long executionId, int stepId, bool isLastStep = false, List<string> logs = null, CancellationToken cancellationToken = default);
Task LogError(long executionId, string message, int stepId = 0, bool isLastStep = false, Exception error = null, List<string> logs = null, CancellationToken cancellationToken = default);
}
}
| 37.691589 | 200 | 0.554178 | [
"MIT"
] | MISTikus/Oliver | src/Oliver.Client/Executing/LogSender.cs | 4,035 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Media_Player.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.419355 | 151 | 0.582006 | [
"MIT"
] | seymenguney/Media-Player | Properties/Settings.Designer.cs | 1,069 | 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.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
/// <summary>
/// The type WorkbookFunctionsCombinaRequestBody.
/// </summary>
[DataContract]
public partial class WorkbookFunctionsCombinaRequestBody
{
/// <summary>
/// Gets or sets Number.
/// </summary>
[DataMember(Name = "number", EmitDefaultValue = false, IsRequired = false)]
public Newtonsoft.Json.Linq.JToken Number { get; set; }
/// <summary>
/// Gets or sets NumberChosen.
/// </summary>
[DataMember(Name = "numberChosen", EmitDefaultValue = false, IsRequired = false)]
public Newtonsoft.Json.Linq.JToken NumberChosen { get; set; }
}
}
| 33.888889 | 153 | 0.559836 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Models/Generated/WorkbookFunctionsCombinaRequestBody.cs | 1,220 | C# |
namespace Foundation.Features.Events.CalendarBlock
{
public class CalendarBlockData
{
public int BlockId { get; set; }
}
}
| 18 | 51 | 0.666667 | [
"Apache-2.0"
] | palle-mertz-merkle/Foundation | src/Foundation/Features/Events/CalendarBlock/CalendarBlockData.cs | 146 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Markup;
using System.Windows;
using System.Reflection;
using System.Globalization;
using System.Windows.Data;
using System.ComponentModel;
using System.Threading;
using System.Windows.Threading;
namespace More.Net.Windows.Localization
{
/// <summary>
/// Enables localization of properties.
/// </summary>
[ContentProperty("Key")]
[MarkupExtensionReturnType(typeof(Object))]
public class LocalizedResourceExtension : MarkupExtension
{
/// <summary>
/// The resource key to use to format the values.
/// </summary>
public String Key
{
get { return key; }
set { this.key = value; }
}
/// <summary>
/// The converter to use to convert the value before it is assigned to the property.
/// </summary>
public IValueConverter Converter
{
get;
set;
}
/// <summary>
/// The parameter to pass to the converter.
/// </summary>
public Object ConverterParameter
{
get;
set;
}
/// <summary>
/// The parameter to pass to the converter.
/// </summary>
public CultureInfo ConverterCulture
{
get;
set;
}
public LocalizedResourceExtension()
{
}
public LocalizedResourceExtension(String key)
{
this.key = key;
}
private String key;
public override Object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget service = serviceProvider
.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
if (service == null)
{
return null;
}
if (service.TargetObject is DependencyObject)
{
LocalizedDependencyProperty property = null;
if (service.TargetProperty is DependencyProperty)
{
property = new LocalizedDependencyProperty(
(DependencyObject)service.TargetObject,
(DependencyProperty)service.TargetProperty);
}
else if (service.TargetProperty is PropertyInfo)
{
//property = new LocalizedNonDependencyProperty(
// (DependencyObject)service.TargetObject,
// (PropertyInfo)service.TargetProperty
// );
}
else
{
return null;
}
property.Converter = Converter;
property.ConverterParameter = ConverterParameter;
var localizedValue = new LocalizedResourceValue(property, key);
if (localizedValue == null)
{
return null;
}
LocalizationScope.AddLocalizedValue(localizedValue);
if (property.IsInDesignMode)
{
// At design time VS designer does not set the parent of any control
// before its properties are set. For this reason the correct values
// of inherited attached properties cannot be obtained.
// Therefore, to display the correct localized value it must be updated
// later ater the parrent of the control has been set.
((DependencyObject)service.TargetObject).Dispatcher.BeginInvoke(
new SendOrPostCallback(x => ((LocalizedResourceValue)x).UpdateValue()),
DispatcherPriority.ApplicationIdle,
localizedValue);
}
return localizedValue.GetValue();
}
else if (
service.TargetProperty is DependencyProperty ||
service.TargetProperty is PropertyInfo)
{
// The extension is used in a template
return this;
}
else
{
return null;
}
}
}
}
| 29.951724 | 95 | 0.523371 | [
"MIT"
] | fallfromgrace/More.Net.Windows.Presentation | More.Net.Windows.Presentation/Localization/LocalizedResourceExtension.cs | 4,345 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
namespace Azure.Analytics.Synapse.Artifacts.Models
{
/// <summary> The LinkConnectionTargetDatabase. </summary>
public partial class LinkConnectionTargetDatabase
{
/// <summary> Initializes a new instance of LinkConnectionTargetDatabase. </summary>
public LinkConnectionTargetDatabase()
{
}
/// <summary> Initializes a new instance of LinkConnectionTargetDatabase. </summary>
/// <param name="linkedService"> Linked service reference. </param>
internal LinkConnectionTargetDatabase(LinkedServiceReference linkedService)
{
LinkedService = linkedService;
}
/// <summary> Linked service reference. </summary>
public LinkedServiceReference LinkedService { get; set; }
}
}
| 31.862069 | 92 | 0.686147 | [
"MIT"
] | ChenTanyi/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/LinkConnectionTargetDatabase.cs | 924 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Collections.Generic;
using System.Threading.Tasks;
using Squidex.ClientLibrary;
using TestSuite.Fixtures;
using TestSuite.Model;
using Xunit;
#pragma warning disable SA1300 // Element should begin with upper-case letter
#pragma warning disable SA1507 // Code should not contain multiple blank lines in a row
namespace TestSuite.ApiTests
{
public class ContentReferencesTests : IClassFixture<ContentReferencesFixture>
{
public ContentReferencesFixture _ { get; }
public ContentReferencesTests(ContentReferencesFixture fixture)
{
_ = fixture;
}
[Fact]
public async Task Should_not_deliver_unpublished_references()
{
// STEP 1: Create a referenced content.
var dataA = new TestEntityWithReferencesData();
var contentA_1 = await _.Contents.CreateAsync(dataA);
// STEP 2: Create a content with a reference.
var dataB = new TestEntityWithReferencesData { References = new[] { contentA_1.Id } };
var contentB_1 = await _.Contents.CreateAsync(dataB, true);
// STEP 3: Query new item
var contentB_2 = await _.Contents.GetAsync(contentB_1.Id);
Assert.Empty(contentB_2.Data.References);
// STEP 4: Publish reference
await _.Contents.ChangeStatusAsync(contentA_1.Id, "Published");
// STEP 5: Query new item again
var contentB_3 = await _.Contents.GetAsync(contentB_1.Id);
Assert.Equal(new string[] { contentA_1.Id }, contentB_3.Data.References);
}
[Fact]
public async Task Should_not_delete_when_referenced()
{
// STEP 1: Create a referenced content.
var dataA = new TestEntityWithReferencesData();
var contentA_1 = await _.Contents.CreateAsync(dataA, true);
// STEP 2: Create a content with a reference.
var dataB = new TestEntityWithReferencesData { References = new[] { contentA_1.Id } };
await _.Contents.CreateAsync(dataB, true);
// STEP 3: Try to delete with referrer check.
await Assert.ThrowsAsync<SquidexException>(() => _.Contents.DeleteAsync(contentA_1.Id, checkReferrers: true));
// STEP 4: Delete without referrer check
await _.Contents.DeleteAsync(contentA_1.Id, checkReferrers: false);
}
[Fact]
public async Task Should_not_unpublish_when_referenced()
{
// STEP 1: Create a published referenced content.
var dataA = new TestEntityWithReferencesData();
var contentA_1 = await _.Contents.CreateAsync(dataA, true);
// STEP 2: Create a content with a reference.
var dataB = new TestEntityWithReferencesData { References = new[] { contentA_1.Id } };
await _.Contents.CreateAsync(dataB, true);
// STEP 3: Try to delete with referrer check.
await Assert.ThrowsAsync<SquidexException>(() => _.Contents.ChangeStatusAsync(contentA_1.Id, new ChangeStatus
{
Status = "Draft",
CheckReferrers = true
}));
// STEP 4: Delete without referrer check
await _.Contents.ChangeStatusAsync(contentA_1.Id, new ChangeStatus
{
Status = "Draft",
CheckReferrers = false
});
}
[Fact]
public async Task Should_not_delete_with_bulk_when_referenced()
{
// STEP 1: Create a referenced content.
var dataA = new TestEntityWithReferencesData();
var contentA_1 = await _.Contents.CreateAsync(dataA, true);
// STEP 2: Create a content with a reference.
var dataB = new TestEntityWithReferencesData { References = new[] { contentA_1.Id } };
await _.Contents.CreateAsync(dataB, true);
// STEP 3: Try to delete with referrer check.
var result1 = await _.Contents.BulkUpdateAsync(new BulkUpdate
{
Jobs = new List<BulkUpdateJob>
{
new BulkUpdateJob
{
Id = contentA_1.Id,
Type = BulkUpdateType.Delete,
Status = "Draft"
}
},
CheckReferrers = true
});
Assert.NotNull(result1[0].Error);
// STEP 4: Delete without referrer check
var result2 = await _.Contents.BulkUpdateAsync(new BulkUpdate
{
Jobs = new List<BulkUpdateJob>
{
new BulkUpdateJob
{
Id = contentA_1.Id,
Type = BulkUpdateType.Delete,
Status = "Draft"
}
},
CheckReferrers = false
});
Assert.Null(result2[0].Error);
}
[Fact]
public async Task Should_not_unpublish_with_bulk_when_referenced()
{
// STEP 1: Create a published referenced content.
var dataA = new TestEntityWithReferencesData();
var contentA_1 = await _.Contents.CreateAsync(dataA, true);
// STEP 2: Create a published content with a reference.
var dataB = new TestEntityWithReferencesData { References = new[] { contentA_1.Id } };
await _.Contents.CreateAsync(dataB, true);
// STEP 3: Try to delete with referrer check.
var result1 = await _.Contents.BulkUpdateAsync(new BulkUpdate
{
Jobs = new List<BulkUpdateJob>
{
new BulkUpdateJob
{
Id = contentA_1.Id,
Type = BulkUpdateType.ChangeStatus,
Status = "Draft"
}
},
CheckReferrers = true
});
Assert.NotNull(result1[0].Error);
// STEP 4: Delete without referrer check
var result2 = await _.Contents.BulkUpdateAsync(new BulkUpdate
{
Jobs = new List<BulkUpdateJob>
{
new BulkUpdateJob
{
Id = contentA_1.Id,
Type = BulkUpdateType.ChangeStatus,
Status = "Draft"
}
},
CheckReferrers = false
});
Assert.Null(result2[0].Error);
}
}
}
| 32.700461 | 122 | 0.531567 | [
"MIT"
] | BrightsDigi/squidex | backend/tools/TestSuite/TestSuite.ApiTests/ContentReferencesTests.cs | 7,098 | C# |
using System;
using System.Collections.Generic;
using SFA.DAS.AssessorService.Api.Types.Models;
namespace SFA.DAS.AssessorService.Web.ViewModels.Search
{
public class SearchRequestViewModel
{
public string Uln { get; set; }
public string Surname { get; set; }
public bool IsPrivatelyFunded { get; set; }
public IEnumerable<ResultViewModel> SearchResults { get; set; }
}
public class ChooseStandardViewModel
{
public string StdCode { get; set; }
public IEnumerable<ResultViewModel> SearchResults { get; set; }
}
public class SelectedStandardViewModel
{
public string GivenNames { get; set; }
public string FamilyName { get; set; }
public string Uln { get; set; }
public string Standard { get; set; }
public string StdCode { get; set; }
public string OverallGrade { get; set; }
public string CertificateReference { get; set; }
public string Level { get; set; }
public string SubmittedAt { get; set; }
public string SubmittedBy { get; set; }
public string LearnerStartDate { get; set; }
public string AchievementDate { get; set; }
public bool UlnAlreadyExists { get; set; }
public bool ShowExtraInfo { get; set; }
public bool IsNoMatchingFamilyName { get; set; }
}
} | 35.153846 | 71 | 0.642597 | [
"MIT"
] | codescene-org/das-assessor-service | src/SFA.DAS.AssessorService.Web/ViewModels/Search/SearchRequestViewModel.cs | 1,373 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
* 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 TencentCloud.Gaap.V20180529.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class CreateHTTPSListenerRequest : AbstractModel
{
/// <summary>
/// 监听器名称
/// </summary>
[JsonProperty("ListenerName")]
public string ListenerName{ get; set; }
/// <summary>
/// 监听器端口,基于同种传输层协议(TCP 或 UDP)的监听器,端口不可重复
/// </summary>
[JsonProperty("Port")]
public ulong? Port{ get; set; }
/// <summary>
/// 服务器证书ID
/// </summary>
[JsonProperty("CertificateId")]
public string CertificateId{ get; set; }
/// <summary>
/// 加速通道转发到源站的协议类型:HTTP | HTTPS
/// </summary>
[JsonProperty("ForwardProtocol")]
public string ForwardProtocol{ get; set; }
/// <summary>
/// 通道ID,与GroupId之间只能设置一个。表示创建通道的监听器。
/// </summary>
[JsonProperty("ProxyId")]
public string ProxyId{ get; set; }
/// <summary>
/// 认证类型,其中:
/// 0,单向认证;
/// 1,双向认证。
/// 默认使用单向认证。
/// </summary>
[JsonProperty("AuthType")]
public ulong? AuthType{ get; set; }
/// <summary>
/// 客户端CA单证书ID,仅当双向认证时设置该参数或PolyClientCertificateIds参数
/// </summary>
[JsonProperty("ClientCertificateId")]
public string ClientCertificateId{ get; set; }
/// <summary>
/// 新的客户端多CA证书ID,仅当双向认证时设置该参数或设置ClientCertificateId参数
/// </summary>
[JsonProperty("PolyClientCertificateIds")]
public string[] PolyClientCertificateIds{ get; set; }
/// <summary>
/// 通道组ID,与ProxyId之间只能设置一个。表示创建通道组的监听器。
/// </summary>
[JsonProperty("GroupId")]
public string GroupId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "ListenerName", this.ListenerName);
this.SetParamSimple(map, prefix + "Port", this.Port);
this.SetParamSimple(map, prefix + "CertificateId", this.CertificateId);
this.SetParamSimple(map, prefix + "ForwardProtocol", this.ForwardProtocol);
this.SetParamSimple(map, prefix + "ProxyId", this.ProxyId);
this.SetParamSimple(map, prefix + "AuthType", this.AuthType);
this.SetParamSimple(map, prefix + "ClientCertificateId", this.ClientCertificateId);
this.SetParamArraySimple(map, prefix + "PolyClientCertificateIds.", this.PolyClientCertificateIds);
this.SetParamSimple(map, prefix + "GroupId", this.GroupId);
}
}
}
| 33.553398 | 111 | 0.609086 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Gaap/V20180529/Models/CreateHTTPSListenerRequest.cs | 3,818 | C# |
namespace MyBlog.Configuration
{
public static class AppSettingNames
{
public const string UiTheme = "App.UiTheme";
}
}
| 17.625 | 52 | 0.666667 | [
"MIT"
] | 15079229761/MyBlog | aspnet-core/src/MyBlog.Core/Configuration/AppSettingNames.cs | 143 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccessLayer
{
[Table("Roles")]
public class Role
{
public Role(string role, bool disabled)
{
//RoleID = Guid.NewGuid();
RoleName = role;
this.isEnabled = disabled;
}
/// <summary>
/// The overloaded constructor for creating a role
/// </summary>
/// <param name="role">The role that we are creating</param>
public Role()
{
}
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RoleID { get; set; }
[Required]
public string RoleName { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DateCreated { get; set; }
[Required]
public bool isEnabled { get; set; }
public virtual ICollection<RolePermission> RolePermissions { get; set; }
}
}
| 24.12766 | 80 | 0.595238 | [
"MIT"
] | zanderlx/F5-broadwayBuilder | DataAccessLayer/Models/Role.cs | 1,136 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.sae.Model.V20190506;
namespace Aliyun.Acs.sae.Transform.V20190506
{
public class UpdateNamespaceVpcResponseUnmarshaller
{
public static UpdateNamespaceVpcResponse Unmarshall(UnmarshallerContext _ctx)
{
UpdateNamespaceVpcResponse updateNamespaceVpcResponse = new UpdateNamespaceVpcResponse();
updateNamespaceVpcResponse.HttpResponse = _ctx.HttpResponse;
updateNamespaceVpcResponse.RequestId = _ctx.StringValue("UpdateNamespaceVpc.RequestId");
updateNamespaceVpcResponse.Code = _ctx.StringValue("UpdateNamespaceVpc.Code");
updateNamespaceVpcResponse.Message = _ctx.StringValue("UpdateNamespaceVpc.Message");
updateNamespaceVpcResponse.ErrorCode = _ctx.StringValue("UpdateNamespaceVpc.ErrorCode");
updateNamespaceVpcResponse.TraceId = _ctx.StringValue("UpdateNamespaceVpc.TraceId");
updateNamespaceVpcResponse.Success = _ctx.BooleanValue("UpdateNamespaceVpc.Success");
return updateNamespaceVpcResponse;
}
}
}
| 42.2 | 93 | 0.775145 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-sae/Sae/Transform/V20190506/UpdateNamespaceVpcResponseUnmarshaller.cs | 1,899 | C# |
namespace IServiceCollectionExtension.LazyLoadService.Test.TestClasses
{
class SomeClass : ISomeClass
{
public static readonly string ConstructorStepName = $"{nameof(SomeClass)}:constructor";
public const string PingResponse = "Pong";
public SomeClass(StepChecker stepChecker)
{
stepChecker.AddStep(ConstructorStepName);
}
public string Ping()
{
return PingResponse;
}
}
}
| 26.333333 | 95 | 0.637131 | [
"Apache-2.0"
] | InsonusK/IServiceCollectionExtension.LazyLoadService | src/IServiceCollectionExtension.LazyLoadService.Test/TestClasses/SomeClass.cs | 474 | C# |
using Newtonsoft.Json;
namespace Tatum.Net.RestObjects
{
public class VeChainTransactionClause
{
[JsonProperty("to")]
public string To { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("data")]
public string Data { get; set; }
}
} | 20.625 | 41 | 0.587879 | [
"MIT"
] | burakoner/Tatum.Net | Tatum.Net/RestObjects/VeChain/VeChainTransactionClause.cs | 332 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 05:01:12 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using static go.builtin;
using @unsafe = go.@unsafe_package;
#nullable enable
namespace go
{
public static partial class syscall_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
public partial struct SysProcAttr
{
// Constructors
public SysProcAttr(NilType _)
{
this.Chroot = default;
this.Credential = default;
this.Ptrace = default;
this.Setsid = default;
this.Setpgid = default;
this.Setctty = default;
this.Noctty = default;
this.Ctty = default;
this.Foreground = default;
this.Pgid = default;
}
public SysProcAttr(@string Chroot = default, ref ptr<Credential> Credential = default, bool Ptrace = default, bool Setsid = default, bool Setpgid = default, bool Setctty = default, bool Noctty = default, long Ctty = default, bool Foreground = default, long Pgid = default)
{
this.Chroot = Chroot;
this.Credential = Credential;
this.Ptrace = Ptrace;
this.Setsid = Setsid;
this.Setpgid = Setpgid;
this.Setctty = Setctty;
this.Noctty = Noctty;
this.Ctty = Ctty;
this.Foreground = Foreground;
this.Pgid = Pgid;
}
// Enable comparisons between nil and SysProcAttr struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(SysProcAttr value, NilType nil) => value.Equals(default(SysProcAttr));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(SysProcAttr value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, SysProcAttr value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, SysProcAttr value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator SysProcAttr(NilType nil) => default(SysProcAttr);
}
[GeneratedCode("go2cs", "0.1.0.0")]
public static SysProcAttr SysProcAttr_cast(dynamic value)
{
return new SysProcAttr(value.Chroot, ref value.Credential, value.Ptrace, value.Setsid, value.Setpgid, value.Setctty, value.Noctty, value.Ctty, value.Foreground, value.Pgid);
}
}
} | 39.924051 | 284 | 0.582118 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/syscall/exec_bsd_SysProcAttrStruct.cs | 3,154 | C# |
#region BSD License
/*
*
* Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
* © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved.
*
* New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE)
* Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2021. All rights reserved.
*
*/
#endregion
using System;
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("5.500.3.0")]
[assembly: AssemblyFileVersion("5.500.3.0")]
[assembly: AssemblyCopyright("© Component Factory Pty Ltd, 2006 - 2016. All rights reserved.")]
[assembly: AssemblyInformationalVersion("5.500.3.0")]
[assembly: AssemblyProduct("ButtonSpec Playground")]
[assembly: AssemblyDefaultAlias("ButtonSpecPlayground.dll")]
[assembly: AssemblyTitle("ButtonSpec Playground")]
[assembly: AssemblyCompany("Component Factory")]
[assembly: AssemblyDescription("ButtonSpec Playground")]
[assembly: AssemblyConfiguration("Production")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: StringFreezing]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: Dependency("System", LoadHint.Always)]
[assembly: Dependency("System.Drawing", LoadHint.Always)]
[assembly: Dependency("System.Windows.Forms", LoadHint.Always)]
[assembly: Dependency("Krypton.Toolkit", LoadHint.Always)]
| 41.054054 | 119 | 0.76761 | [
"BSD-3-Clause"
] | Krypton-Suite/Standard-Toolkit-Demos | Source/Krypton Toolkit Examples/ButtonSpec Playground/Properties/AssemblyInfo.cs | 1,523 | C# |
bool isInfiniteProcess(int a, int b) {
if(a>b){
return true;
}
if(a==b){
return false;
}
if(a < b){
if((b-a)%2==0){
return false;
} else {
return true;
}
}
return false;
}
| 13.52381 | 38 | 0.366197 | [
"Unlicense"
] | DKLynch/CodeSignal-Tasks | The Core/At The Crossroads/12. Is Infinite Process/isInfiniteProcess.cs | 284 | C# |
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
namespace Havit.Blazor.Components.Web.Bootstrap.Documentation.Server.Controllers
{
public class FileUploadControllerDemo : ControllerBase
{
private const int BoundaryLengthLimit = 512 * 1024;
// https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0#upload-large-files-with-streaming
// https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/mvc/models/file-uploads/samples/
[HttpPost("/file-upload-streamed/")]
public async Task<IActionResult> UploadStreamedFile()
{
if (!IsMultipartContentType(Request.ContentType))
{
ModelState.AddModelError("File", $"The request couldn't be processed (Error 1).");
return BadRequest(ModelState);
}
var boundary = GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), lengthLimit: BoundaryLengthLimit);
var reader = new MultipartReader(boundary, HttpContext.Request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
if (hasContentDispositionHeader)
{
// THIS IS WHERE YOU PASS THE FILE STREAM TO THE FACADE, the code below is not to be directly used here!
// Don't trust the file name sent by the client. To display the file name, HTML-encode the value.
var trustedFileNameForDisplay = WebUtility.HtmlEncode(contentDisposition.FileName.Value);
var trustedFileNameForFileStorage = Path.GetRandomFileName();
// using (var targetStream = System.IO.File.Create(Path.Combine(Path.GetTempPath(), trustedFileNameForFileStorage)))
// {
// await section.Body.CopyToAsync(targetStream);
// }
await section.Body.CopyToAsync(Stream.Null);
return Ok(trustedFileNameForFileStorage);
}
// Drain any remaining section body that hasn't been consumed and read the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
return BadRequest();
}
// Content-Type: multipart/form-data; boundary="----WebKitFormBoundarymx2fSWqWSd0OxQqq"
// The spec at https://tools.ietf.org/html/rfc2046#section-5.1 states that 70 characters is a reasonable limit.
public static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit)
{
var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary).Value;
if (string.IsNullOrWhiteSpace(boundary))
{
throw new InvalidDataException("Missing content-type boundary.");
}
if (boundary.Length > lengthLimit)
{
throw new InvalidDataException($"Multipart boundary length limit {lengthLimit} exceeded.");
}
return boundary;
}
public static bool IsMultipartContentType(string contentType)
{
return !string.IsNullOrEmpty(contentType)
&& contentType.IndexOf("multipart/", StringComparison.OrdinalIgnoreCase) >= 0;
}
public static bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition)
{
// Content-Disposition: form-data; name="key";
return contentDisposition != null
&& contentDisposition.DispositionType.Equals("form-data")
&& string.IsNullOrEmpty(contentDisposition.FileName.Value)
&& string.IsNullOrEmpty(contentDisposition.FileNameStar.Value);
}
public static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition)
{
// Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg"
return contentDisposition != null
&& contentDisposition.DispositionType.Equals("form-data")
&& (!string.IsNullOrEmpty(contentDisposition.FileName.Value)
|| !string.IsNullOrEmpty(contentDisposition.FileNameStar.Value));
}
}
}
| 38.333333 | 133 | 0.755243 | [
"MIT"
] | HybridSolutions/Havit.Blazor | Havit.Blazor.Components.Web.Bootstrap.Documentation.Server/Controllers/FileUploadControllerDemo.cs | 3,912 | C# |
using Physics.Interfaces;
using Physics.Models;
namespace Physics.Items
{
public class Weapon : IItem, IOffenseMods
{
private int BonusAim = 5;
private int BonusDamage = 5;
public OffenseMods GetOffenseModifiers()
{
return new OffenseMods()
{
totalAim = BonusAim,
totalDamage = BonusDamage
};
}
}
} | 21 | 48 | 0.547619 | [
"MIT"
] | jr101dallas/roguelike-tutorial | physics/Items/Weapon.cs | 420 | 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("RequireJsSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RequireJsSample")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("84e0e8d0-6641-4a8b-8971-f2c71fa37fef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.805556 | 84 | 0.749449 | [
"MIT"
] | WS-QA/cassette | src/RequireJsSample/Properties/AssemblyInfo.cs | 1,364 | C# |
namespace Person
{
using System;
public class Child : Person
{
private int age;
public Child(string name,int age)
:base(name,age)
{
this.age = age;
}
public override int Age
{
get
{
return this.age;
}
set
{
if (value<=15)
{
this.age = value;
}
else
{
throw new ArgumentException("child age cannot be more than 15!");
}
}
}
public override string ToString()
{
return base.ToString();
}
}
}
| 17.953488 | 85 | 0.349741 | [
"MIT"
] | amartinn/SoftUni | C# Advanced September 2019/C# OOP/exercises/Inheritance - Exercise/Person/Child.cs | 774 | C# |
// This file was automatically generated and may be regenerated at any
// time. To ensure any changes are retained, modify the tool with any segment/component/group/field name
// or type changes.
namespace Machete.HL7Schema.V26
{
using System;
using HL7;
/// <summary>
/// AIS (Segment) - Appointment Information
/// </summary>
public interface AIS :
HL7V26Segment
{
/// <summary>
/// AIS-1: Set ID - AIS
/// </summary>
Value<int> SetId { get; }
/// <summary>
/// AIS-2: Segment Action Code
/// </summary>
Value<string> SegmentActionCode { get; }
/// <summary>
/// AIS-3: Universal Service Identifier
/// </summary>
Value<CWE> UniversalServiceIdentifier { get; }
/// <summary>
/// AIS-4: Start Date/Time
/// </summary>
Value<DateTimeOffset> StartDateTime { get; }
/// <summary>
/// AIS-5: Start Date/Time Offset
/// </summary>
Value<decimal> StartDateTimeOffset { get; }
/// <summary>
/// AIS-6: Start Date/Time Offset Units
/// </summary>
Value<CNE> StartDateTimeOffsetUnits { get; }
/// <summary>
/// AIS-7: Duration
/// </summary>
Value<decimal> Duration { get; }
/// <summary>
/// AIS-8: Duration Units
/// </summary>
Value<CNE> DurationUnits { get; }
/// <summary>
/// AIS-9: Allow Substitution Code
/// </summary>
Value<string> AllowSubstitutionCode { get; }
/// <summary>
/// AIS-10: Filler Status Code
/// </summary>
Value<CWE> FillerStatusCode { get; }
/// <summary>
/// AIS-11: Placer Supplemental Service Information
/// </summary>
ValueList<CWE> PlacerSupplementalServiceInformation { get; }
/// <summary>
/// AIS-12: Filler Supplemental Service Information
/// </summary>
ValueList<CWE> FillerSupplementalServiceInformation { get; }
}
} | 27.826667 | 105 | 0.542405 | [
"Apache-2.0"
] | amccool/Machete | src/Machete.HL7Schema/Generated/V26/Segments/AIS.cs | 2,087 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using WinDirStat.Net.Controls;
using WinDirStat.Net.Settings.Geometry;
namespace WinDirStat.Net.Model.Data.Extensions {
[Serializable]
public class ExtensionRecord : INotifyPropertyChanged, IComparable<ExtensionRecord>, IComparable {
public static readonly ExtensionRecord Empty = new ExtensionRecord();
private readonly ExtensionRecords records;
private readonly string extension;
private Rgb24Color color;
private long size;
private int fileCount;
public event ExtensionRecordEventHandler Changed;
private void RaiseChanged(ExtensionRecordEventArgs e) {
Changed?.Invoke(this, e);
}
private void RaiseChanged(ExtensionRecordAction action) {
Changed?.Invoke(this, new ExtensionRecordEventArgs(action));
}
public object GetView() {
ExtensionRecordEventArgs e = new ExtensionRecordEventArgs(ExtensionRecordAction.GetView);
RaiseChanged(e);
return e.View;
}
public TView GetView<TView>() {
ExtensionRecordEventArgs e = new ExtensionRecordEventArgs(ExtensionRecordAction.GetView);
RaiseChanged(e);
return (TView) e.View;
}
private ExtensionRecord() {
extension = "";
//name = "Not a File";
}
public ExtensionRecord(ExtensionRecords records, string extension) {
this.records = records;
this.extension = extension.ToLower();
color = new Rgb24Color(150, 150, 150);
/*if (IsEmptyExtension)
name = "File";
else
name = extension.TrimStart('.').ToUpper() + " File";*/
}
public string Extension {
get => extension;
}
/*public string Name {
get => name;
internal set {
if (name != value) {
name = value;
AutoRaisePropertyChanged();
}
}
}
public ImageSource Icon {
get => icon;
internal set {
if (icon != value) {
icon = value;
AutoRaisePropertyChanged();
}
}
}
public ImageSource Preview {
get => preview;
internal set {
if (preview != value) {
preview = value;
AutoRaisePropertyChanged();
}
}
}*/
public Rgb24Color Color {
get => color;
set {
//if (color != value) {
color = value;
AutoRaisePropertyChanged();
//}
}
}
public long Size {
get => size;
set {
if (size != value) {
size = value;
AutoRaisePropertyChanged();
RaisePropertyChanged(nameof(Percent));
}
}
}
public double Percent {
get => (double) size / records.TotalSize;
}
public int FileCount {
get => fileCount;
set {
if (fileCount != value) {
fileCount = value;
AutoRaisePropertyChanged();
}
}
}
public bool IsEmptyExtension {
get => extension == ".";
}
public event PropertyChangedEventHandler PropertyChanged;
internal void RaisePropertyChanged(string name) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private void AutoRaisePropertyChanged([CallerMemberName] string name = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
public int CompareTo(ExtensionRecord other) {
int diff = other.size.CompareTo(size);
if (diff == 0)
return string.Compare(extension, other.extension, true);
return diff;
}
int IComparable.CompareTo(object obj) {
return CompareTo((ExtensionRecord) obj);
}
public override string ToString() {
return extension;
}
}
}
| 22.720497 | 99 | 0.689721 | [
"MIT"
] | ImportTaste/WinDirStat.Net | WinDirStat.Net/Model/Data/Extensions/ExtensionRecord.cs | 3,660 | C# |
using UnityEngine;
namespace TowerColor
{
/// <summary>
/// Sound player
/// </summary>
public class SoundPlayer : MonoBehaviour, ISoundPlayer
{
public bool SoundEnabled { get; set; }
public void PlaySound(AudioSource sound)
{
if (!SoundEnabled) return;
sound.Play();
}
}
} | 20.166667 | 58 | 0.548209 | [
"MIT"
] | RLefrancoise/TowerColor | Assets/Scripts/SoundPlayer.cs | 363 | 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.Compute.V20190701
{
public static class GetProximityPlacementGroup
{
/// <summary>
/// Specifies information about the proximity placement group.
/// </summary>
public static Task<GetProximityPlacementGroupResult> InvokeAsync(GetProximityPlacementGroupArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetProximityPlacementGroupResult>("azure-nextgen:compute/v20190701:getProximityPlacementGroup", args ?? new GetProximityPlacementGroupArgs(), options.WithVersion());
}
public sealed class GetProximityPlacementGroupArgs : Pulumi.InvokeArgs
{
/// <summary>
/// includeColocationStatus=true enables fetching the colocation status of all the resources in the proximity placement group.
/// </summary>
[Input("includeColocationStatus")]
public string? IncludeColocationStatus { get; set; }
/// <summary>
/// The name of the proximity placement group.
/// </summary>
[Input("proximityPlacementGroupName", required: true)]
public string ProximityPlacementGroupName { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetProximityPlacementGroupArgs()
{
}
}
[OutputType]
public sealed class GetProximityPlacementGroupResult
{
/// <summary>
/// A list of references to all availability sets in the proximity placement group.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceWithColocationStatusResponse> AvailabilitySets;
/// <summary>
/// Describes colocation status of the Proximity Placement Group.
/// </summary>
public readonly Outputs.InstanceViewStatusResponse? ColocationStatus;
/// <summary>
/// Resource Id
/// </summary>
public readonly string Id;
/// <summary>
/// Resource location
/// </summary>
public readonly string Location;
/// <summary>
/// Resource name
/// </summary>
public readonly string Name;
/// <summary>
/// Specifies the type of the proximity placement group. <br><br> Possible values are: <br><br> **Standard** : Co-locate resources within an Azure region or Availability Zone. <br><br> **Ultra** : For future use.
/// </summary>
public readonly string? ProximityPlacementGroupType;
/// <summary>
/// Resource tags
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type
/// </summary>
public readonly string Type;
/// <summary>
/// A list of references to all virtual machine scale sets in the proximity placement group.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceWithColocationStatusResponse> VirtualMachineScaleSets;
/// <summary>
/// A list of references to all virtual machines in the proximity placement group.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceWithColocationStatusResponse> VirtualMachines;
[OutputConstructor]
private GetProximityPlacementGroupResult(
ImmutableArray<Outputs.SubResourceWithColocationStatusResponse> availabilitySets,
Outputs.InstanceViewStatusResponse? colocationStatus,
string id,
string location,
string name,
string? proximityPlacementGroupType,
ImmutableDictionary<string, string>? tags,
string type,
ImmutableArray<Outputs.SubResourceWithColocationStatusResponse> virtualMachineScaleSets,
ImmutableArray<Outputs.SubResourceWithColocationStatusResponse> virtualMachines)
{
AvailabilitySets = availabilitySets;
ColocationStatus = colocationStatus;
Id = id;
Location = location;
Name = name;
ProximityPlacementGroupType = proximityPlacementGroupType;
Tags = tags;
Type = type;
VirtualMachineScaleSets = virtualMachineScaleSets;
VirtualMachines = virtualMachines;
}
}
}
| 37.929134 | 256 | 0.648744 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/V20190701/GetProximityPlacementGroup.cs | 4,817 | C# |
namespace Magnesium.Metal
{
public interface IAmtQueueFence
{
void Signal();
}
} | 12.285714 | 32 | 0.72093 | [
"MIT"
] | tgsstdio/Mg | Magnesium.Metal/Queue/IAmtQueueFence.cs | 88 | C# |
using ConvertToSARIF.Engine.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ConvertToSARIF.Engine
{
public class FilePathResolver
{
public virtual string Resolver(string filePath, string currentPath)
{
if (string.IsNullOrEmpty(Path.GetFileName(filePath)))
{
throw new FileNotFoundException(Resources.FileNotProvided);
}
if (!Path.IsPathRooted(filePath))
{
filePath = Path.Combine(currentPath ?? string.Empty, filePath);
}
return filePath;
}
}
}
| 24.407407 | 79 | 0.611533 | [
"MIT"
] | microsoft/ConvertTo-SARIF | src/ConvertToSARIF.Engine/FilePathResolver.cs | 661 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.Set, "AzureLoadBalancerFrontendIpConfig"), OutputType(typeof(PSLoadBalancer))]
public class SetAzureLoadBalancerFrontendIpConfigCommand : AzureLoadBalancerFrontendIpConfigBase
{
[Parameter(
Mandatory = true,
HelpMessage = "The name of the FrontendIpConfiguration")]
[ValidateNotNullOrEmpty]
public override string Name { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
HelpMessage = "The load balancer")]
public PSLoadBalancer LoadBalancer { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
var frontendIpConfig = this.LoadBalancer.FrontendIpConfigurations.SingleOrDefault(resource => string.Equals(resource.Name, this.Name, System.StringComparison.CurrentCultureIgnoreCase));
if (frontendIpConfig == null)
{
throw new ArgumentException("FrontendIpConfiguration with the specified name does not exist");
}
// Get the subnetId and publicIpAddressId from the object if specified
if (string.Equals(ParameterSetName, "id"))
{
this.SubnetId = this.Subnet.Id;
if (PublicIpAddress != null)
{
this.PublicIpAddressId = this.PublicIpAddress.Id;
}
}
frontendIpConfig.Name = this.Name;
if (!string.IsNullOrEmpty(this.SubnetId))
{
frontendIpConfig.Subnet = new PSResourceId();
frontendIpConfig.Subnet.Id = this.SubnetId;
if (!string.IsNullOrEmpty(this.PrivateIpAddress))
{
frontendIpConfig.PrivateIpAddress = this.PrivateIpAddress;
frontendIpConfig.PrivateIpAllocationMethod = Management.Network.Models.IpAllocationMethod.Static;
}
else
{
frontendIpConfig.PrivateIpAllocationMethod = Management.Network.Models.IpAllocationMethod.Dynamic;
}
}
if (!string.IsNullOrEmpty(this.PrivateIpAddress))
{
frontendIpConfig.PrivateIpAddress = this.PrivateIpAddress;
}
frontendIpConfig.Subnet = null;
if (!string.IsNullOrEmpty(this.SubnetId))
{
frontendIpConfig.Subnet = new PSResourceId();
frontendIpConfig.Subnet.Id = this.SubnetId;
}
frontendIpConfig.PublicIpAddress = null;
if (!string.IsNullOrEmpty(this.PublicIpAddressId))
{
frontendIpConfig.PublicIpAddress = new PSResourceId();
frontendIpConfig.PublicIpAddress.Id = this.PublicIpAddressId;
}
WriteObject(this.LoadBalancer);
}
}
}
| 39.267327 | 198 | 0.58119 | [
"MIT"
] | matt-gibbs/azure-powershell | src/ResourceManager/Network/Commands.Network/LoadBalancer/FrontendIpConfiguration/SetAzureLoadBalancerFrontendIpConfigCommand.cs | 3,868 | C# |
namespace Example.FormsApp.Modules.Wizard
{
using System.Threading.Tasks;
using Smart.ComponentModel;
using Smart.Forms.Input;
using Smart.Navigation;
using Smart.Navigation.Plugins.Scope;
public class WizardResultViewModel : AppViewModelBase
{
[Scope]
public NotificationValue<WizardContext> Context { get; } = new();
public AsyncCommand<ViewId> ForwardCommand { get; }
public WizardResultViewModel(ApplicationState applicationState)
: base(applicationState)
{
ForwardCommand = MakeAsyncCommand<ViewId>(x => Navigator.ForwardAsync(x));
}
protected override Task OnNotifyFunction1Async()
{
return Navigator.ForwardAsync(ViewId.WizardInput2);
}
protected override Task OnNotifyFunction4Async()
{
return Navigator.ForwardAsync(ViewId.Menu);
}
}
}
| 27.264706 | 86 | 0.6548 | [
"MIT"
] | usausa/Smart-Net-Navigation | Example.FormsApp/Example.FormsApp/Modules/Wizard/WizardResultViewModel.cs | 927 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TypeInferences.Types;
namespace TypeInferences.Expressions
{
public sealed class Increment : AvalonExpression
{
private readonly AvalonExpression parameter;
internal Increment(AvalonExpression parameter) =>
this.parameter = parameter;
public override AvalonType InferenceType =>
this.parameter.InferenceType.ToWide(AvalonType.FromClrType<int>());
}
}
| 25.35 | 79 | 0.723866 | [
"Apache-2.0"
] | kekyo/Favalon.PoC | TypeInference/TypeInference/Expressions/Increment.cs | 509 | C# |
using System;
using System.Diagnostics;
using Eto.Forms;
namespace Eto.GtkSharp.Forms
{
public class OpenWithDialogHandler : WidgetHandler<Gtk.Dialog, OpenWithDialog, OpenWithDialog.ICallback>, OpenWithDialog.IHandler
{
public string FilePath { get; set; }
public DialogResult ShowDialog(Window parent)
{
var handle = parent == null ? IntPtr.Zero : (parent.ControlObject as Gtk.Window).Handle;
var adialoghandle = NativeMethods.gtk_app_chooser_dialog_new(handle, 5, NativeMethods.g_file_new_for_path(FilePath));
var adialog = new Gtk.AppChooserDialog(adialoghandle);
if (adialog.Run() == (int)Gtk.ResponseType.Ok)
Process.Start(adialog.AppInfo.Executable, "\"" + FilePath + "\"");
adialog.Destroy();
return DialogResult.Ok;
}
}
}
| 30.72 | 130 | 0.744792 | [
"BSD-3-Clause"
] | k5jae/Eto | Source/Eto.Gtk/Forms/OpenWithDialogHandler.cs | 770 | C# |
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace SimpleIdServer.OAuth.DTOs
{
public static class OAuthClientParameters
{
public const string ClientId = "client_id";
public const string ClientSecret = "client_secret";
public const string ClientIdIssuedAt = "client_id_issued_at";
public const string ClientSecretExpiresAt = "client_secret_expires_at";
public const string RegistrationAccessToken = "registration_access_token";
public const string GrantTypes = "grant_types";
public const string RedirectUris = "redirect_uris";
public const string TokenEndpointAuthMethod = "token_endpoint_auth_method";
public const string ResponseTypes = "response_types";
public const string ClientName = "client_name";
public const string ClientUri = "client_uri";
public const string LogoUri = "logo_uri";
public const string Scope = "scope";
public const string Contacts = "contacts";
public const string TosUri = "tos_uri";
public const string PolicyUri = "policy_uri";
public const string JwksUri = "jwks_uri";
public const string Jwks = "jwks";
public const string SoftwareId = "software_id";
public const string SoftwareVersion = "software_version";
public const string SoftwareStatement = "software_statement";
public const string TokenSignedResponseAlg = "token_signed_response_alg";
public const string TokenEncryptedResponseAlg = "token_encrypted_response_alg";
public const string TokenEncryptedResponseEnc = "token_encrypted_response_enc";
public const string TokenExpirationTimeInSeconds = "token_expiration_time_seconds";
public const string RefreshTokenExpirationTimeInSeconds = "refresh_token_expiration_time_seconds";
public const string RegistrationClientUri = "registration_client_uri";
public const string TlsClientAuthSubjectDN = "tls_client_auth_subject_dn";
public const string TlsClientAuthSanDNS = "tls_client_auth_san_dns";
public const string TlsClientAuthSanUri = "tls_client_auth_san_uri";
public const string TlsClientAuthSanIp = "tls_client_auth_san_ip";
public const string TlsClientAuthSanEmail = "tls_client_auth_san_email";
public const string UpdateDateTime = "update_datetime";
public const string CreateDateTime = "create_datetime";
}
}
| 58.386364 | 107 | 0.736084 | [
"Apache-2.0"
] | LaTranche31/SimpleIdServer | src/OAuth/SimpleIdServer.OAuth/DTOs/OAuthClientParameters.cs | 2,571 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SayWhatStarterWebhook")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SayWhatStarterWebhook")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("abb3c066-41e3-4353-aace-d7f00e538641")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.028571 | 84 | 0.751315 | [
"MIT"
] | MFazio23/TC2018-SayWhatStarter | csharp/SayWhatStarterWebhook/Properties/AssemblyInfo.cs | 1,334 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleSync
{
public class Validator
{
private Validator() { }
public class Param
{
public static readonly Func<string, bool> Folder = name =>
{
if (name == null || name.Length == 0) return false;
if (System.IO.Directory.Exists(name) == false) throw new ArgumentException(Message.IO.FolderNotFound(name));
return true;
};
public static readonly Func<string, bool> Level = number =>
{
int.TryParse(number, out int level);
if (level <= 0) throw new ArgumentException(Message.Number.GreaterThan(number, 0));
return true;
};
public static readonly Func<string, bool> SavePath = name =>
{
if (name == null || name.Length == 0) return false;
if (System.IO.Directory.Exists(name) == false) throw new ArgumentException(Message.IO.FolderNotFound(name));
return true;
};
}
public class Unique
{
public static readonly Func<string, string, bool> FolderSavePath = (folder, savePath) =>
{
var folderFullPath = System.IO.Path.GetFullPath(folder);
var saveFullPath = System.IO.Path.GetFullPath(savePath);
var isSameFolder = folderFullPath.CompareTo(saveFullPath) == 0;
var isContain = folderFullPath.StartsWith(saveFullPath) || saveFullPath.StartsWith(folderFullPath);
if (isSameFolder) throw new ArgumentException(Message.IO.FolderAreSame(folderFullPath, saveFullPath));
if (isContain) throw new ArgumentException(Message.IO.FolderAreContain(folderFullPath, saveFullPath));
return true;
};
}
}
}
| 28.684211 | 112 | 0.706422 | [
"MIT"
] | tuyennv216/SimpleSync | SimpleSync/Constant/Validator.cs | 1,637 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics.ContractsLight;
using BuildXL.Processes;
using BuildXL.Scheduler.IncrementalScheduling;
using BuildXL.Scheduler.Tracing;
using BuildXL.Storage.ChangeTracking;
using BuildXL.Utilities;
namespace BuildXL.Scheduler
{
/// <summary>
/// Test hooks for BuildXL scheduler.
/// </summary>
/// <remarks>
/// These hooks are used to query private information about the state of the scheduler.
/// </remarks>
public class SchedulerTestHooks
{
/// <summary>
/// Incremental scheduling state owned by the scheduler.
/// </summary>
public IIncrementalSchedulingState IncrementalSchedulingState { get; set; }
/// <summary>
/// Action to validate incremental scheduling state after journal scan.
/// </summary>
public Action<IIncrementalSchedulingState> IncrementalSchedulingStateAfterJournalScanAction { get; set; }
/// <summary>
/// Validates incremental scheduling state after journal scan.
/// </summary>
internal void ValidateIncrementalSchedulingStateAfterJournalScan(IIncrementalSchedulingState incrementalSchedulingState)
{
Contract.Requires(incrementalSchedulingState != null);
IncrementalSchedulingStateAfterJournalScanAction?.Invoke(incrementalSchedulingState);
}
/// <summary>
/// Test hooks for the <see cref="FingerprintStore"/>.
/// </summary>
public FingerprintStoreTestHooks FingerprintStoreTestHooks { get; set; }
/// <summary>
/// Listener to collect detours reported accesses
/// </summary>
public IDetoursEventListener DetoursListener { get; set; }
/// <summary>
/// A synthetic machine perf info to pass it to Scheduler to test various functions related to cancellation.
/// </summary>
public PerformanceCollector.MachinePerfInfo SyntheticMachinePerfInfo { get; set; }
}
}
| 38.596491 | 129 | 0.668636 | [
"MIT"
] | mmiller-msft/BuildXL | Public/Src/Engine/Scheduler/SchedulerTestHooks.cs | 2,200 | C# |
//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2020年10月16日 18:03:51
//------------------------------------------------------------
using ETModel;
using IngameDebugConsole;
namespace Plugins.IngameDebugConsole.ETCmds
{
public class ETCmds
{
[ConsoleMethod("测试常规Log","这是一个测试常规的Log")]
public static void TestCommonLog()
{
Log.Info("这是一个测试常规的Log");
}
[ConsoleMethod("测试await/async的Log","这是一条测试await/async的Log")]
public static async void TestAsyncLog()
{
Log.Info("这是一个测试常规的Log--一秒后会Log加密通话");
await Game.Scene.GetComponent<TimerComponent>().WaitAsync(1000);
Log.Info("这是一个测试常规的Log--别比别比,别比巴伯");
}
}
} | 28.642857 | 76 | 0.51995 | [
"MIT"
] | mosheepdev/NKGMobaBasedOnET | Unity/Assets/Plugins/IngameDebugConsole/ETCmds/ETCmds.cs | 956 | C# |
using PW.MacroDeck.SoundPad.Services;
using SuchByte.MacroDeck.ActionButton;
using SuchByte.MacroDeck.GUI;
using SuchByte.MacroDeck.GUI.CustomControls;
using SuchByte.MacroDeck.Plugins;
using System;
using System.Collections.Generic;
using System.Text;
namespace PW.MacroDeck.SoundPad.Actions
{
public class StartRecordingAction : PluginAction
{
public override string Name => LocalizationManager.Instance.StartRecordingActionName;
public override string Description => LocalizationManager.Instance.StartRecordingActionDescription;
public override bool CanConfigure => true;
public override ActionConfigControl GetActionConfigControl(ActionConfigurator actionConfigurator)
{
return new Views.RecordActionConfigView(this);
}
public override void Trigger(string clientId, ActionButton actionButton)
{
SoundPadManager.Record(Configuration);
}
}
}
| 30.903226 | 107 | 0.749478 | [
"MIT"
] | PhoenixWyllow/MacroDeck.SoundPad | Actions/StartRecordingAction.cs | 960 | C# |
using Validation.Base;
namespace Validation.Implementations
{
public class NotEmptyValidationAttribute : ValidationAttribute
{
public NotEmptyValidationAttribute(string parameterName = null, string errorMessage = null,
bool defaultValue = true, string errorMessageKey = null) : base(parameterName, errorMessage, defaultValue,
errorMessageKey)
{
}
public override bool Validate(object input, object parameter = null)
{
var value = input?.ToString();
return !string.IsNullOrWhiteSpace(value) || !string.IsNullOrEmpty(value);
}
}
}
| 32 | 118 | 0.664063 | [
"MIT"
] | DenLavrov/PropertiesValidation | Validation/Implementations/NotEmptyValidation.cs | 642 | C# |
line1=Možnosti konfigurace,11
lease=Akceptovatelná prodleva (ve vteřinách) mezi systémovým a harwarovým časem,0
timeserver=Výchozí čas serveru,3,Nic
ntp_only=Použít pouze NTP pro časovou synchronizaci?,1,1-Ano,0-Ne
line2=Konfigurace systému,11
seconds=Formát nastavení systémového času,1,1-MMDDHHMMYYYY.SS,0-MMDDHHMMYY,2-YYYYMMDDHHMM.SS
zone_style=Metoda konfigurace časové zóny,4,linux-Linux,freebsd-FreeBSD,solaris-Solaris,-<Není v tomto OS podporován>
hwclock_flags=Signály příkazového řádku pro hw hodiny,10,-Nic,sysconfig-Z /etc/sysconfig/clock
| 61.777778 | 123 | 0.834532 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | A-damW/webmin | time/config.info.cs | 587 | 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.DataFactory.Outputs
{
/// <summary>
/// A copy activity Shopify Service source.
/// </summary>
[OutputType]
public sealed class ShopifySourceResponse
{
/// <summary>
/// Specifies the additional columns to be added to source data. Type: array of objects(AdditionalColumns) (or Expression with resultType array of objects).
/// </summary>
public readonly object? AdditionalColumns;
/// <summary>
/// If true, disable data store metrics collection. Default is false. Type: boolean (or Expression with resultType boolean).
/// </summary>
public readonly object? DisableMetricsCollection;
/// <summary>
/// The maximum concurrent connection count for the source data store. Type: integer (or Expression with resultType integer).
/// </summary>
public readonly object? MaxConcurrentConnections;
/// <summary>
/// A query to retrieve data from source. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? Query;
/// <summary>
/// Query timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
/// </summary>
public readonly object? QueryTimeout;
/// <summary>
/// Source retry count. Type: integer (or Expression with resultType integer).
/// </summary>
public readonly object? SourceRetryCount;
/// <summary>
/// Source retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
/// </summary>
public readonly object? SourceRetryWait;
/// <summary>
/// Copy source type.
/// Expected value is 'ShopifySource'.
/// </summary>
public readonly string Type;
[OutputConstructor]
private ShopifySourceResponse(
object? additionalColumns,
object? disableMetricsCollection,
object? maxConcurrentConnections,
object? query,
object? queryTimeout,
object? sourceRetryCount,
object? sourceRetryWait,
string type)
{
AdditionalColumns = additionalColumns;
DisableMetricsCollection = disableMetricsCollection;
MaxConcurrentConnections = maxConcurrentConnections;
Query = query;
QueryTimeout = queryTimeout;
SourceRetryCount = sourceRetryCount;
SourceRetryWait = sourceRetryWait;
Type = type;
}
}
}
| 36.670732 | 164 | 0.614566 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataFactory/Outputs/ShopifySourceResponse.cs | 3,007 | C# |
using AppInterfaces.Interfaces;
using Core.Domain;
using CoreEntities.CustomModels;
using ServiceLayer.Interfaces;
using System;
using System.Collections.Generic;
namespace ServiceLayer.Services
{
public class ScreenService : IScreenService
{
#region Global Variables
IScreenRepository _screenRepository = null;
#endregion
#region constructor
public ScreenService(IScreenRepository screenRepository)
{
_screenRepository = screenRepository;// new RepositoryLayer.Repositories.ScreenRepository();//_RolesRepository;
}
#endregion
#region Public Methods
public ResponseModel Createscreen(Screen screen)
{
return _screenRepository.Createscreen(screen);
}
// add screenAction
public ResponseModel AddScreenAction(ScreenAction screenAction)
{
return _screenRepository.AddScreenAction(screenAction);
}
public List<Screen> GetAllscreen(int limit, int offset, string order, string sort, string screenName, out int total)
{
return _screenRepository.GetAllscreen(limit, offset, order, sort, screenName, out total);
}
public String Editscreen(Screen screen)
{
screen.CreatedDate = DateTime.Now;
return _screenRepository.Editscreen(screen);
}
public bool Deletescreen(int id)
{
return _screenRepository.Deletescreen(id);
}
public List<ScreenAction> GetAllScreenAction(int limit, int offset, string order, string sort, int fk_screenId, out int total)
{
return _screenRepository.GetAllScreenAction(limit, offset, order, sort, fk_screenId, out total);
}
public Screen GetDropDown()
{
return _screenRepository.GetDropDown();
}
public List<ScreenAction> GetAllScreenActionByScreeiID(int fk_screenId)
{
return _screenRepository.GetAllScreenActionByScreeiID(fk_screenId);
}
public void EditScreenAction(ScreenAction screenAction)
{
screenAction.CreatedDate = DateTime.Now;
_screenRepository.EditScreenAction(screenAction);
}
public bool DeleteScreenAction(int id)
{
return _screenRepository.DeleteScreenAction(id);
}
#endregion
}
}
| 30.64557 | 134 | 0.654275 | [
"Apache-2.0"
] | joshisachin675/SocialMediaBroadcast | ServiceLayer/Services/ScreenService.cs | 2,423 | C# |
using UnityEngine;
using UnityEngine.UI;
public static class Score
{
public static int score = 0;
public static int Combo = 0;
private static int _maxCombo = 0;
public static int MaxCombo
{
get => _maxCombo;
set
{
if (value < _maxCombo) return;
_maxCombo = value;
}
}
public static int PerfectCount = 0;
public static int NiceCount = 0;
public static int OkCount = 0;
public static int BadCount = 0;
public static bool OnCombo = true;
public static Track music;
public static int AddCombo()
{
Jauge.Add();
Combo++;
MaxCombo = Combo;
OnCombo = true;
if (Combo < 5) return 0;
if (Combo < 15) return 1;
if (Combo < 30) return 5;
return 10;
}
public static void GotPerfect()
{
float scoreToAdd = 10 + AddCombo();
if (Jauge.isOutRun) scoreToAdd *= 2;
float speedMultiplier = PlayerPrefs.GetFloat("MusicSpeed");
scoreToAdd *= 1 + ((speedMultiplier - 1) / 2);
score += (int)scoreToAdd;
PerfectCount++;
ScoreUI.UpdateUI();
}
public static void GotNice()
{
float scoreToAdd = 5 + AddCombo();
if (Jauge.isOutRun) scoreToAdd *= 2;
float speedMultiplier = PlayerPrefs.GetFloat("MusicSpeed");
scoreToAdd *= 1 + ((speedMultiplier - 1) / 2);
score += (int)scoreToAdd;
NiceCount++;
ScoreUI.UpdateUI();
}
public static void GotOk()
{
float scoreToAdd = 1 + AddCombo();
if (Jauge.isOutRun) scoreToAdd *= 2;
float speedMultiplier = PlayerPrefs.GetFloat("MusicSpeed");
scoreToAdd *= 1 + ((speedMultiplier - 1) / 2);
score += (int)scoreToAdd;
OkCount++;
ScoreUI.UpdateUI();
}
public static void GotBad()
{
Combo = 0;
Jauge.Remove();
OnCombo = false;
BadCount++;
ScoreUI.UpdateUI();
}
public static void ResetScore()
{
score = 0;
OnCombo = true;
Combo = 0;
BadCount = 0;
OkCount = 0;
NiceCount = 0;
PerfectCount = 0;
_maxCombo = 0;
}
} | 23.726316 | 67 | 0.538598 | [
"Apache-2.0"
] | enzobenedetti/RythmSynthwave | Assets/Prod/Scripts/Score.cs | 2,256 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Logika
{
public class Weather
{
private double temperature;
private double humidity;
private double windSpeed;
public double GetTemperature() { return this.temperature; }
public double GetHumidity() { return this.humidity; }
public double GetWindSpeed() { return this.windSpeed; }
public void SetTemperature(double temperature) { this.temperature = temperature; }
public void SetHumidity(double humidity) { this.humidity = humidity; }
public void SetWindSpeed(double windSpeed) { this.windSpeed = windSpeed; }
public Weather()
{
this.temperature = 0;
this.humidity = 0;
this.windSpeed = 0;
}
public Weather(double temperature, double humidity, double windSpeed)
{
this.temperature = temperature;
this.humidity = humidity;
this.windSpeed = windSpeed;
}
public double CalculateFeelsLikeTemperature()
{
const double c1 = -8.78469475556;
const double c2 = 1.61139411;
const double c3 = 2.33854883889;
const double c4 = -0.14611605;
const double c5 = -0.012308094;
const double c6 = -0.0164248277778;
const double c7 = 0.002211732;
const double c8 = 0.00072546;
const double c9 = -0.000003582;
double humidityPercentage = GetHumidity();
double heatIndex = c1 + (c2 * GetTemperature()) + (c3 * humidityPercentage) + (c4 * GetTemperature() * humidityPercentage) + (c5 * Math.Pow(GetTemperature(), 2)) + (c6 * Math.Pow(humidityPercentage, 2)) + (c7 * Math.Pow(GetTemperature(), 2) * humidityPercentage) + (c8 * GetTemperature() * Math.Pow(humidityPercentage, 2) + (c9 * Math.Pow(GetTemperature(), 2)) * Math.Pow(humidityPercentage, 2));
return heatIndex;
}
public double CalculateWindChill()
{
double WCI = 0;
if (GetTemperature() <= 10 && GetWindSpeed() > 4.8)
WCI = 13.12 + (0.6215 * GetTemperature()) - (11.37 * Math.Pow(GetWindSpeed(), 0.16)) + (0.3965 * GetTemperature() * Math.Pow(GetWindSpeed(), 0.16));
else WCI = 0;
return WCI;
}
public string GetAsString()
{
return $"T={temperature}°C w={windSpeed} km/h h={humidity}%";
}
}
}
| 35.479452 | 409 | 0.56834 | [
"MIT"
] | esalaj4/DZ-oop | DZ2/Weather.cs | 2,593 | C# |
// Accord Imaging Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Imaging.Filters
{
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Filter to mark (highlight) feature points in a image.
/// </summary>
///
/// <remarks>
/// <para>The filter highlights feature points on the image using a given set of points.</para>
///
/// <para>The filter accepts 8 bpp grayscale and 24 color images for processing.</para>
/// </remarks>
///
public class FeaturesMarker : BaseFilter
{
private IEnumerable<SpeededUpRobustFeaturePoint> points;
private Dictionary<PixelFormat, PixelFormat> formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
private GrayscaleToRGB toRGB = new GrayscaleToRGB();
private double scale = 5;
/// <summary>
/// Format translations dictionary.
/// </summary>
///
public override Dictionary<PixelFormat, PixelFormat> FormatTranslations
{
get { return formatTranslations; }
}
/// <summary>
/// Gets or sets the initial size for a feature point in the map. Default is 5.
/// </summary>
///
public double Scale
{
get { return scale; }
set { scale = value; }
}
/// <summary>
/// Gets or sets the set of points to mark.
/// </summary>
///
public IEnumerable<SpeededUpRobustFeaturePoint> Points
{
get { return points; }
set { points = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="FeaturesMarker"/> class.
/// </summary>
///
public FeaturesMarker()
: this(new SpeededUpRobustFeaturePoint[0])
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FeaturesMarker"/> class.
/// </summary>
///
public FeaturesMarker(IEnumerable<SpeededUpRobustFeaturePoint> points)
{
init(points);
}
/// <summary>
/// Initializes a new instance of the <see cref="FeaturesMarker"/> class.
/// </summary>
///
public FeaturesMarker(IEnumerable<FastRetinaKeypoint> points)
{
init(points.Select(p =>
new SpeededUpRobustFeaturePoint(p.X, p.Y, p.Scale, 1, p.Orientation, 10)));
}
/// <summary>
/// Initializes a new instance of the <see cref="FeaturesMarker"/> class.
/// </summary>
///
public FeaturesMarker(IEnumerable<SpeededUpRobustFeaturePoint> points, double scale)
{
init(points);
this.scale = scale;
}
/// <summary>
/// Initializes a new instance of the <see cref="FeaturesMarker"/> class.
/// </summary>
///
public FeaturesMarker(IEnumerable<FastRetinaKeypoint> points, double scale)
{
init(points.Select(p =>
new SpeededUpRobustFeaturePoint(p.X, p.Y, p.Scale, 1, p.Orientation, 10)));
this.scale = scale;
}
private void init(IEnumerable<SpeededUpRobustFeaturePoint> points)
{
this.points = points;
formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format24bppRgb;
formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb;
formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format32bppArgb;
}
/// <summary>
/// Process the filter on the specified image.
/// </summary>
///
/// <param name="sourceData">Source image data.</param>
/// <param name="destinationData">Destination image data.</param>
///
protected override void ProcessFilter(UnmanagedImage sourceData, UnmanagedImage destinationData)
{
if (sourceData.PixelFormat == PixelFormat.Format8bppIndexed)
sourceData = toRGB.Apply(sourceData);
// Copy image contents
sourceData.Copy(destinationData);
Bitmap managedImage = destinationData.ToManagedImage(makeCopy: false);
using (Graphics g = Graphics.FromImage(managedImage))
using (Pen positive = new Pen(Color.Red))
using (Pen negative = new Pen(Color.Blue))
using (Pen line = new Pen(Color.FromArgb(0, 255, 0)))
{
// mark all points
foreach (SpeededUpRobustFeaturePoint p in points)
{
int S = (int)(scale * p.Scale);
int R = (int)(S / 2f);
Point pt = new Point((int)p.X, (int)p.Y);
Point ptR = new Point((int)(R * System.Math.Cos(p.Orientation)),
(int)(R * System.Math.Sin(p.Orientation)));
Pen myPen = (p.Laplacian > 0 ? negative : positive);
g.DrawEllipse(myPen, pt.X - R, pt.Y - R, S, S);
g.DrawLine(line, new Point(pt.X, pt.Y), new Point(pt.X + ptR.X, pt.Y + ptR.Y));
}
}
}
}
} | 34.843575 | 117 | 0.573994 | [
"MIT"
] | mastercs999/fn-trading | src/Accord/Accord.Imaging/Filters/FeaturesMarker.cs | 6,241 | C# |
#region Copyright & License
// Copyright © 2012 - 2013 François Chabot, Yves Dierick
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using Be.Stateless.BizTalk.ContextProperties;
using Be.Stateless.BizTalk.Unit.RuleEngine;
using NUnit.Framework;
namespace Be.Stateless.BizTalk.Dsl.RuleEngine
{
[TestFixture]
public class BoxingRuleFixture : PolicyFixture<BoxingRuleFixture.BoxingRuleSet>
{
[Test]
public void ImplicitBoxingIsHandledDuringTranslation()
{
ExecutePolicy();
Facts.Verify(Context.Property(BizTalkFactoryProperties.CorrelationToken).WithAnyValue().HasBeenWritten());
}
public class BoxingRuleSet : RuleSet
{
public BoxingRuleSet()
{
Rules.Add(
Rule("ImplicitBoxing")
.If(() => true)
.Then(() => Context.Write(BizTalkFactoryProperties.CorrelationToken, string.Format("The time is {0}.", DateTime.UtcNow)))
);
}
}
}
}
| 30.081633 | 128 | 0.713026 | [
"Apache-2.0"
] | icraftsoftware/BizTalk.Factory | src/BizTalk.Dsl.Tests/Dsl/RuleEngine/BoxingRuleFixture.cs | 1,478 | C# |
using LSCode.Validations.NotifiableValidations;
using System;
namespace LSCode.Validations.ValueObjects.Technologies
{
/// <summary>Assists in the use, validation and formatting of file length in KB.</summary>
public class FileLengthKB : Notifier
{
/// <value>File length in KB.</value>
public string Value { get; private set; }
/// <summary>Constructor of the FileLengthKB class.</summary>
/// <remarks>
/// Input formats: 1597,44. <br></br>
/// Output format: 1,56 GB.
/// </remarks>
/// <param name="valueInBytes">File length in bytes (numbers only).</param>
/// <returns>Create an instance of the FileLengthKB class.</returns>
public FileLengthKB(string valueInBytes)
{
try
{
Value = valueInBytes;
if (string.IsNullOrWhiteSpace(Value))
AddNotification("FileLengthKB", "Content cannot be null or empty");
else
{
var length = decimal.Parse(valueInBytes);
// Bytes to KBytes
length /= 1024;
Value = $"{length:N2} KB";
}
}
catch (Exception ex)
{
AddNotification("FileLengthKB", $"Error: {ex.Message}");
}
}
/// <summary>Returns the file length in KiloBytes.</summary>
public override string ToString() => Value;
}
} | 33.173913 | 94 | 0.532765 | [
"MIT"
] | lsantoss/LSCode.Validations | LSCode.Validations/ValueObjects/Technologies/FileLengthKB.cs | 1,528 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml.Controls.Primitives;
namespace Windows.UI.Xaml.Controls
{
public partial class ComboBoxItem : SelectorItem
{
public ComboBoxItem()
{
}
}
} | 15.933333 | 49 | 0.757322 | [
"Apache-2.0"
] | billchungiii/Uno | src/Uno.UI/UI/Xaml/Controls/ComboBox/ComboBoxItem.cs | 241 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ParameterKey.cs" company="Exit Games GmbH">
// Copyright (c) Exit Games GmbH. All rights reserved.
// </copyright>
// <summary>
// Parameter keys are used as event-keys, operation-parameter keys and operation-return keys alike.
// The values are partly taken from Exit Games Photon, which contains many more keys.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Lite.Operations
{
/// <summary>
/// Parameter keys are used as event-keys, operation-parameter keys and operation-return keys alike.
/// The values are partly taken from Exit Games Photon, which contains many more keys.
/// </summary>
public enum ParameterKey : byte
{
/// <summary>
/// The game id.
/// </summary>
GameId = 255,
/// <summary>
/// The actor nr
/// used as op-key and ev-key
/// </summary>
ActorNr = 254,
/// <summary>
/// The target actor nr.
/// </summary>
TargetActorNr = 253,
/// <summary>
/// The actors.
/// </summary>
Actors = 252,
/// <summary>
/// The properties.
/// </summary>
Properties = 251,
/// <summary>
/// The broadcast.
/// </summary>
Broadcast = 250,
/// <summary>
/// The actor properties.
/// </summary>
ActorProperties = 249,
/// <summary>
/// The game properties.
/// </summary>
GameProperties = 248,
/// <summary>
/// Event parameter to indicate whether events are cached for new actors.
/// </summary>
Cache = 247,
/// <summary>
/// Event parameter containing a <see cref="Lite.Operations.ReceiverGroup"/> value.
/// </summary>
ReceiverGroup = 246,
/// <summary>
/// The data.
/// </summary>
Data = 245,
/// <summary>
/// The paramter code for the <see cref="RaiseEventRequest">raise event</see> operations event code.
/// </summary>
Code = 244,
/// <summary>
/// the flush event code for raise event.
/// </summary>
Flush = 243,
/// <summary>
/// Event parameter to indicate whether cached events are deleted automaticly for actors leaving a room.
/// </summary>
DeleteCacheOnLeave = 241,
/// <summary>
/// The group this event should be sent to. No error is happening if the group is empty or not existing.
/// </summary>
Group = 240,
/// <summary>
/// Groups to leave. Null won't remove any groups. byte[0] will remove ALL groups. Otherwise only the groups listed will be removed.
/// </summary>
GroupsForRemove = 239,
/// <summary>
/// Groups to enter. Null won't add groups. byte[0] will add ALL groups. Otherwise only the groups listed will be added.
/// </summary>
GroupsForAdd = 238,
/// <summary>
/// A parameter indicating if common room events (Join, Leave) will be suppressed.
/// </summary>
SuppressRoomEvents = 237,
}
} | 31.381818 | 140 | 0.500869 | [
"MIT"
] | LevchenkovHeyworks/Networking | Playground/.runtime/photon/src-server/Lite/Lite/Operations/ParameterKey.cs | 3,454 | C# |
/*******************************************************************
* Copyright(c) 2020 tianci
* All rights reserved.
*
* 文件名称: EmojiText.cs 1.0
* Unity版本: 2018.4.6f1
* 简要描述:
*
* 创建日期: 2020/06/30 11:36:30
* 作者: tianci
* 说明:
******************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace UF
{
public class EmojiText : Text, IPointerClickHandler
{
#region 需要用到的数据类
private class MatchResult
{
public int Width;
public int Height;
private Color mColor;
private string mUpColorStr;
private Color mDownColor;
private string mDownColorStr;
public string Prefix;
public string CustomInfo;
public EmojiType Type;
public string Url;
private void Reset()
{
Type = EmojiType.None;
Prefix = string.Empty;
Width = 0;
Height = 0;
mUpColorStr = string.Empty;
Url = string.Empty;
CustomInfo = string.Empty;
}
public void Parse(Match match, int fontSize)
{
Reset();
if (!match.Success || match.Groups.Count != 8)
return;
Prefix = match.Groups[1].Value;
if (match.Groups[2].Success)
{
var widthHeigthStr = match.Groups[2].Value;
var sp = widthHeigthStr.Split('|');
Width = sp.Length > 1 ? int.Parse(sp[1]) : fontSize;
Height = sp.Length == 3 ? int.Parse(sp[2]) : Width;
}
else
{
Width = fontSize;
Height = Width;
}
if (match.Groups[4].Success && !string.IsNullOrEmpty(match.Groups[4].Value))
mUpColorStr = match.Groups[4].Value.Substring(0, 7);
if (match.Groups[5].Success) mDownColorStr = match.Groups[5].Value;
if (match.Groups[6].Success) Url = match.Groups[6].Value.Substring(1);
if (match.Groups[7].Success) CustomInfo = match.Groups[7].Value.Substring(1);
if (Prefix.Equals("0x01"))
{
if (!string.IsNullOrEmpty(Url) && !string.IsNullOrEmpty(CustomInfo))
Type = EmojiType.HyperLink;
}
else if (Prefix.Equals("0x02"))
{
if (!string.IsNullOrEmpty(CustomInfo))
Type = EmojiType.Texture;
}
else Type = EmojiType.Emoji;
}
public Color GetColor(Color fontColor)
{
if (string.IsNullOrEmpty(mUpColorStr))
return fontColor;
ColorUtility.TryParseHtmlString(mUpColorStr, out mColor);
return mColor;
}
public Color GetGradientColor(Color fontColor)
{
if (string.IsNullOrEmpty(mDownColorStr))
return GetColor(fontColor);
ColorUtility.TryParseHtmlString(mDownColorStr, out mDownColor);
return mDownColor;
}
public string GetHtmlString(Color fontColor)
{
return !string.IsNullOrEmpty(mUpColorStr) ? mUpColorStr : ColorUtility.ToHtmlStringRGBA(fontColor);
}
}
private class TableInfo
{
public int Frame;
public int Index;
}
private class TextureInfo
{
public Image Img;
public int Index;
public Vector3 Pos;
public RectTransform RectTrans;
public string CustomInfo;
}
private class EmojiInfo
{
public int Height;
public TableInfo Table;
public TextureInfo TexInfo;
public EmojiType Type;
public int Width;
}
public enum EmojiType
{
None,
/// <summary>
/// 将表情打包成图集
/// </summary>
Emoji,
/// <summary>
/// 超链接类型 0x01
/// </summary>
HyperLink,
/// <summary>
/// 自定义图片 0x02
/// </summary>
Texture
}
private class HrefInfo
{
public string Url;
public bool IsShowUnderline;
public Color UpColor;
public int StartIndex;
public int EndIndex;
public Color DownColor;
public readonly List<Rect> Boxes = new List<Rect>();
public readonly List<Vector3> VertPosList = new List<Vector3>();
public readonly List<Rect> UnderLineRectList = new List<Rect>();
}
#endregion
#region 可以外部获取的字段
/// <summary>
/// 表情填充回调 0x02
/// </summary>
public Action<Image, string> EmojiFillHandler;
/// <summary>
/// 超链接点击回调 0x01
/// </summary>
public Action<string> HyperLinkClick;
/// <summary>
/// 点击 Text 但是没有点击到超链接的回调
/// </summary>
public Action OutHyperLinkClick;
/// <summary>
/// 是否需要下划线
/// </summary>
public bool NeedUnderLine = true;
#endregion
private static Dictionary<string, TableInfo> mSpriteDict;
private static readonly string mRegexTag = "\\[([0-9A-Za-z]+)((\\|[0-9]+){0,2})((#[0-9a-fA-F]{6}){0,2})(#[^=\\]]+)?(=[^\\]]+)?\\]";
private readonly Dictionary<int, EmojiInfo> mEmojiDict = new Dictionary<int, EmojiInfo>();
private readonly List<HrefInfo> mHrefList = new List<HrefInfo>();
private readonly List<Image> mImageList = new List<Image>();
private readonly MatchResult mMatchResult = new MatchResult();
private readonly List<RectTransform> mRectTransList = new List<RectTransform>();
private readonly StringBuilder mStrBuilder = new StringBuilder();
private readonly UIVertex[] mTempVerts = new UIVertex[4];
private string mOutputText = "";
public override float preferredWidth
{
get
{
var settings = GetGenerationSettings(Vector2.zero);
return cachedTextGeneratorForLayout.GetPreferredWidth(mOutputText, settings) / pixelsPerUnit;
}
}
public override float preferredHeight
{
get
{
var settings = GetGenerationSettings(new Vector2(rectTransform.rect.size.x, 0.0f));
return cachedTextGeneratorForLayout.GetPreferredHeight(mOutputText, settings) / pixelsPerUnit;
}
}
/// <summary>
/// 文本
/// </summary>
public override string text
{
get => m_Text;
set
{
ParseText(value);
base.text = value;
}
}
public void OnPointerClick(PointerEventData eventData)
{
var isClickHyperLink = false;//是否点击在超链接范围内
RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out var localPoint);
for (var h = 0; h < mHrefList.Count; h++)
{
if (isClickHyperLink) break;
var hrefInfo = mHrefList[h];
for (var i = 0; i < hrefInfo.Boxes.Count; ++i)
{
if (hrefInfo.Boxes[i].Contains(localPoint))
{
isClickHyperLink = true;
HyperLinkClick?.Invoke(hrefInfo.Url);
break;
}
}
}
if (!isClickHyperLink)
OutHyperLinkClick?.Invoke();
}
protected override void Awake()
{
base.Awake();
if (mSpriteDict == null)
{
mSpriteDict = new Dictionary<string, TableInfo>();
#if UNITY_EDITOR
var dir = new System.IO.DirectoryInfo(Application.dataPath);
var files = dir.GetFiles("EmojiText.txt", System.IO.SearchOption.AllDirectories);
var index = files[0].FullName.IndexOf("Assets");
var tablePath = files[0].FullName.Substring(index).Replace('\\', '/');
var emojiTable = UnityEditor.AssetDatabase.LoadAssetAtPath<TextAsset>(tablePath).text;
material = UnityEditor.AssetDatabase.LoadAssetAtPath<Material>(tablePath.Replace("txt", "mat"));
#else
var emojiTable = Resoreces.Load<TextAsset>("");//TODO
material = Resoreces.Load<TextAsset>("");//TODO
#endif
var lines = emojiTable.Split('\n');
for (var i = 1; i < lines.Length; i++)
{
if (string.IsNullOrEmpty(lines[i]))
continue;
var strs = lines[i].Split('\t');
var info = new TableInfo { Frame = int.Parse(strs[1]), Index = int.Parse(strs[2]) };
mSpriteDict.Add(strs[0], info);
}
}
#if UNITY_EDITOR
HyperLinkClick = (url) => Debug.Log("点击超链接区域:" + url);
OutHyperLinkClick = () => Debug.Log("点击到非超链接区域");
EmojiFillHandler = (img, customInfo) =>
{
Debug.Log("Emoji表情填充完毕");
var dir = new System.IO.DirectoryInfo(Application.dataPath);
var files = dir.GetFiles(customInfo + ".png", System.IO.SearchOption.AllDirectories);
var index = files[0].FullName.IndexOf("Assets");
var texPath = files[0].FullName.Substring(index).Replace('\\', '/');
var tex2D = UnityEditor.AssetDatabase.LoadAssetAtPath<Texture2D>(texPath);
if(tex2D != null)
img.sprite = Sprite.Create(tex2D, new Rect(Vector2.zero, new Vector2(tex2D.width, tex2D.height)), Vector2.zero);
};
#endif
}
protected override void OnPopulateMesh(VertexHelper toFill)
{
if (font == null)
return;
ParseText(m_Text);
m_DisableFontTextureRebuiltCallback = true;
var extents = rectTransform.rect.size;
var settings = GetGenerationSettings(extents);
cachedTextGenerator.Populate(mOutputText, settings);
var verts = cachedTextGenerator.verts;
var unitsPerPixel = 1 / pixelsPerUnit;
var vertCount = verts.Count - 4;
if (vertCount <= 0)
{
toFill.Clear();
return;
}
var repairVec = new Vector3(0, fontSize * 0.3f, 0);
var roundingOffset = new Vector2(verts[0].position.x, verts[0].position.y) * unitsPerPixel;
roundingOffset = PixelAdjustPoint(roundingOffset) - roundingOffset;
toFill.Clear();
if (roundingOffset != Vector2.zero)
{
for (var i = 0; i < vertCount; ++i)
{
var tempVertsIndex = i & 3;
mTempVerts[tempVertsIndex] = verts[i];
mTempVerts[tempVertsIndex].position *= unitsPerPixel;
mTempVerts[tempVertsIndex].position.x += roundingOffset.x;
mTempVerts[tempVertsIndex].position.y += roundingOffset.y;
if (tempVertsIndex == 3)
toFill.AddUIVertexQuad(mTempVerts);
}
}
else
{
var uv = Vector2.zero;
for (var i = 0; i < vertCount; ++i)
{
var index = i / 4;
var tempVertIndex = i & 3;
if (mEmojiDict.TryGetValue(index, out var info))
{
mTempVerts[tempVertIndex] = verts[i];
mTempVerts[tempVertIndex].position -= repairVec;
if (info.Type == EmojiType.Emoji)
{
uv.x = info.Table.Index;
uv.y = info.Table.Frame;
mTempVerts[tempVertIndex].uv0 += uv * 10;
}
else
{
if (tempVertIndex == 3)
info.TexInfo.Pos = mTempVerts[tempVertIndex].position;
mTempVerts[tempVertIndex].position = mTempVerts[0].position;
}
mTempVerts[tempVertIndex].position *= unitsPerPixel;
if (tempVertIndex == 3)
toFill.AddUIVertexQuad(mTempVerts);
}
else
{
mTempVerts[tempVertIndex] = verts[i];
mTempVerts[tempVertIndex].position *= unitsPerPixel;
if (tempVertIndex == 3)
toFill.AddUIVertexQuad(mTempVerts);
}
}
ComputeBoundsInfo(toFill);
if (NeedUnderLine) DrawUnderLine(toFill);
TwoColorGradient(toFill);
}
m_DisableFontTextureRebuiltCallback = false;
StartCoroutine(ShowImages());
}
private void ParseText(string inputText)
{
if (mSpriteDict == null || !Application.isPlaying)// || !Application.isPlaying
{
mOutputText = inputText;
return;
}
mStrBuilder.Clear();
mEmojiDict.Clear();
mHrefList.Clear();
ClearChildrenImage();
var matches = Regex.Matches(inputText, mRegexTag);
if (matches.Count > 0)
{
var textIndex = 0;
var imgIdx = 0;
var rectIdx = 0;
for (var i = 0; i < matches.Count; i++)
{
var match = matches[i];
mMatchResult.Parse(match, fontSize);
switch (mMatchResult.Type)
{
case EmojiType.Emoji:
{
if (mSpriteDict.TryGetValue(mMatchResult.Prefix, out var info))
{
mStrBuilder.Append(inputText.Substring(textIndex, match.Index - textIndex));
var temIndex = mStrBuilder.Length;
mStrBuilder.Append("<quad size=");
mStrBuilder.Append(mMatchResult.Height);
mStrBuilder.Append(" width=");
mStrBuilder.Append((mMatchResult.Width * 1.0f / mMatchResult.Height).ToString("f2"));
mStrBuilder.Append(" />");
mEmojiDict.Add(temIndex, new EmojiInfo
{
Type = EmojiType.Emoji,
Table = info,
Width = mMatchResult.Width,
Height = mMatchResult.Height
});
if (!string.IsNullOrEmpty(mMatchResult.Url))
{
var hrefInfo = new HrefInfo
{
IsShowUnderline = false,
StartIndex = temIndex * 4,
EndIndex = temIndex * 4 + 3,
Url = mMatchResult.Url,
UpColor = mMatchResult.GetColor(color),
DownColor = mMatchResult.GetGradientColor(color)
};
mHrefList.Add(hrefInfo);
}
textIndex = match.Index + match.Length;
}
break;
}
case EmojiType.HyperLink:
{
mStrBuilder.Append(inputText.Substring(textIndex, match.Index - textIndex));
mStrBuilder.Append("<color=");
mStrBuilder.Append(mMatchResult.GetHtmlString(color));
mStrBuilder.Append(">");
var href = new HrefInfo { IsShowUnderline = true, StartIndex = mStrBuilder.Length * 4 };
mStrBuilder.Append(mMatchResult.CustomInfo);
href.EndIndex = mStrBuilder.Length * 4 - 1;
href.Url = mMatchResult.Url;
href.UpColor = mMatchResult.GetColor(color);
href.DownColor = mMatchResult.GetGradientColor(color);
mHrefList.Add(href);
mStrBuilder.Append("</color>");
textIndex = match.Index + match.Length;
break;
}
case EmojiType.Texture:
{
mStrBuilder.Append(inputText.Substring(textIndex, match.Index - textIndex));
var temIndex = mStrBuilder.Length;
mStrBuilder.Append("<quad size=");
mStrBuilder.Append(mMatchResult.Height);
mStrBuilder.Append(" width=");
mStrBuilder.Append((mMatchResult.Width * 1.0f / mMatchResult.Height).ToString("f2"));
mStrBuilder.Append(" />");
mEmojiDict.Add(temIndex, new EmojiInfo
{
Type = mMatchResult.Type,
Width = mMatchResult.Width,
Height = mMatchResult.Height,
TexInfo = new TextureInfo
{
CustomInfo = mMatchResult.CustomInfo,
Index = mMatchResult.Type == EmojiType.Texture ? imgIdx++ : rectIdx++
}
});
if (!string.IsNullOrEmpty(mMatchResult.Url))
{
var hrefInfo = new HrefInfo
{
IsShowUnderline = false,
StartIndex = temIndex * 4,
EndIndex = temIndex * 4 + 3,
Url = mMatchResult.Url,
UpColor = mMatchResult.GetColor(color),
DownColor = mMatchResult.GetGradientColor(color)
};
mHrefList.Add(hrefInfo);
}
textIndex = match.Index + match.Length;
break;
}
}
}
mStrBuilder.Append(inputText.Substring(textIndex, inputText.Length - textIndex));
mOutputText = mStrBuilder.ToString();
}
else mOutputText = inputText;
}
/// <summary>
/// 计算边界信息
/// </summary>
/// <param name="toFill"></param>
private void ComputeBoundsInfo(VertexHelper toFill)
{
var vert = new UIVertex();
for (var u = 0; u < mHrefList.Count; u++)
{
var underline = mHrefList[u];
underline.Boxes.Clear();
underline.VertPosList.Clear();
underline.UnderLineRectList.Clear();
if (underline.StartIndex >= toFill.currentVertCount)
continue;
toFill.PopulateUIVertex(ref vert, underline.StartIndex);
var pos = vert.position;
var bounds = new Bounds(pos, Vector3.zero);
for (int i = underline.StartIndex; i < underline.EndIndex; i++)
{
if (i >= toFill.currentVertCount)
break;
toFill.PopulateUIVertex(ref vert, i);
pos = vert.position;
underline.VertPosList.Add(pos);
if (pos.x < bounds.min.x)
{
underline.Boxes.Add(new Rect(bounds.min, bounds.size));
bounds = new Bounds(pos, Vector3.zero);
}
else bounds.Encapsulate(pos);
}
underline.Boxes.Add(new Rect(bounds.min, bounds.size));
toFill.PopulateUIVertex(ref vert, underline.EndIndex);
pos = vert.position;
underline.VertPosList.Add(pos);
float height = (underline.VertPosList[1].y - underline.VertPosList[3].y) / 5;//1/5作为下划线的高度
float yPos = underline.VertPosList[3].y - height / 2;//首字符的 Y 值决定剩余下划线的 Y 值
for (int i = 0; i < underline.VertPosList.Count; i += 4)
{
if (i > 0)
{
if (Math.Abs(underline.VertPosList[i + 3].y - yPos) > height * 3)//高度偏差太大说明换行了
{
yPos = underline.VertPosList[i + 3].y - height / 2;
}
else
{
var lastXRight = underline.VertPosList[i - 2].x;
var xLeft = underline.VertPosList[i].x;
if (xLeft > lastXRight)//需要在衔接断层处填充下划线
{
float spaceWidth = xLeft - lastXRight;
float spaceXPos = lastXRight;
underline.UnderLineRectList.Add(new Rect(new Vector2(spaceXPos, yPos), new Vector2(spaceWidth, height)));
}
}
}
float width = underline.VertPosList[i + 1].x - underline.VertPosList[i + 3].x;
float xPos = underline.VertPosList[i].x;
underline.UnderLineRectList.Add(new Rect(new Vector2(xPos, yPos), new Vector2(width, height)));
}
}
}
/// <summary>
/// 绘制下划线
/// </summary>
/// <param name="toFill"></param>
private void DrawUnderLine(VertexHelper toFill)
{
if (mHrefList.Count <= 0)
return;
var extents = rectTransform.rect.size;
var settings = GetGenerationSettings(extents);
cachedTextGenerator.Populate("_", settings);
var uList = cachedTextGenerator.verts;
var h = uList[2].position.y - uList[1].position.y;
var temVecs = new Vector3[4];
for (var i = 0; i < mHrefList.Count; i++)
{
var info = mHrefList[i];
if (!info.IsShowUnderline) continue;
for (int j = 0; j < info.UnderLineRectList.Count; j++)
{
var center = info.UnderLineRectList[j].center;
var halfWidth = info.UnderLineRectList[j].size.x / 2 * 1.35f;//由于 "_" 的渲染结果,两边有一些渐变
var min = info.UnderLineRectList[j].min;
var max = info.UnderLineRectList[j].max;
temVecs[0] = new Vector3(center.x - halfWidth, max.y);
temVecs[1] = new Vector3(center.x + halfWidth, max.y);
temVecs[2] = new Vector3(center.x + halfWidth, min.y);
temVecs[3] = new Vector3(center.x - halfWidth, min.y);
for (int k = 0; k < 4; k++)
{
mTempVerts[k] = uList[k];
mTempVerts[k].color = info.DownColor;
mTempVerts[k].position = temVecs[k];
}
toFill.AddUIVertexQuad(mTempVerts);
}
}
}
private static UIVertex mTmpVert;
/// <summary>
/// 双色渐变
/// </summary>
/// <param name="toFill"></param>
private void TwoColorGradient(VertexHelper toFill)
{
foreach (var hrefInfo in mHrefList)
{
if (hrefInfo.StartIndex >= toFill.currentVertCount)
continue;
for (int i = hrefInfo.StartIndex, m = hrefInfo.EndIndex; i < m; i += 4)
{
if (i >= toFill.currentVertCount)
break;
toFill.PopulateUIVertex(ref mTmpVert, i);
mTmpVert.color = hrefInfo.UpColor;
toFill.SetUIVertex(mTmpVert, i);
toFill.PopulateUIVertex(ref mTmpVert, i + 1);
mTmpVert.color = hrefInfo.UpColor;
toFill.SetUIVertex(mTmpVert, i + 1);
toFill.PopulateUIVertex(ref mTmpVert, i + 2);
mTmpVert.color = hrefInfo.DownColor;
toFill.SetUIVertex(mTmpVert, i + 2);
toFill.PopulateUIVertex(ref mTmpVert, i + 3);
mTmpVert.color = hrefInfo.DownColor;
toFill.SetUIVertex(mTmpVert, i + 3);
}
}
}
private void ClearChildrenImage()
{
for (var i = 0; i < mImageList.Count; i++) mImageList[i].rectTransform.localScale = Vector3.zero;
for (var i = 0; i < mRectTransList.Count; i++) mRectTransList[i].localScale = Vector3.zero;
}
private IEnumerator ShowImages()
{
yield return null;
foreach (var emojiInfo in mEmojiDict.Values)
{
if (emojiInfo.Type == EmojiType.Texture)
{
emojiInfo.TexInfo.Img = GetImage(emojiInfo.TexInfo, emojiInfo.Width, emojiInfo.Height);
EmojiFillHandler?.Invoke(emojiInfo.TexInfo.Img, emojiInfo.TexInfo.CustomInfo);
}
}
}
private Image GetImage(TextureInfo info, int width, int height)
{
Image img = null;
if (mImageList.Count > info.Index)
img = mImageList[info.Index];
if (img == null)
{
var obj = new GameObject("Emoji_" + info.Index);
img = obj.AddComponent<Image>();
obj.transform.SetParent(transform);
obj.transform.localPosition = Vector3.zero;
img.rectTransform.pivot = Vector2.zero;
img.raycastTarget = false;
if (mImageList.Count > info.Index)
mImageList[info.Index] = img;
else
mImageList.Add(img);
}
img.rectTransform.localScale = Vector3.one;
img.rectTransform.sizeDelta = new Vector2(width, height);
img.rectTransform.anchoredPosition = info.Pos;
return img;
}
}
}
| 41.218391 | 151 | 0.455138 | [
"MIT"
] | HedgehogSir/EmojiText | EmojiText.cs | 29,086 | C# |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Xml;
namespace fyiReporting.RDL
{
///<summary>
/// Contains list of DataSource about how to connect to sources of data used by the DataSets.
///</summary>
[Serializable]
public class DataSources : IEnumerable
{
Report _rpt; // Runtime report
ListDictionary _Items; // list of report items
internal DataSources(Report rpt, DataSourcesDefn dsds)
{
_rpt = rpt;
_Items = new ListDictionary();
// Loop thru all the child nodes
foreach(DataSourceDefn dsd in dsds.Items.Values)
{
DataSource ds = new DataSource(rpt, dsd);
_Items.Add(dsd.Name.Nm, ds);
}
}
public DataSource this[string name]
{
get
{
return _Items[name] as DataSource;
}
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return _Items.Values.GetEnumerator();
}
#endregion
}
}
| 26 | 94 | 0.673077 | [
"Apache-2.0"
] | gregberns/ZipRdlProjectDev410 | src/RdlEngine/Runtime/DataSources.cs | 1,820 | C# |
// Generated class v2.19.0.0, don't modify
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace NHtmlUnit.Javascript.Host.Media.Midi
{
public partial class MIDIPort : NHtmlUnit.Javascript.Host.Events.EventTarget
{
static MIDIPort()
{
ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.media.midi.MIDIPort o) =>
new MIDIPort(o));
}
public MIDIPort(com.gargoylesoftware.htmlunit.javascript.host.media.midi.MIDIPort wrappedObject) : base(wrappedObject) {}
public new com.gargoylesoftware.htmlunit.javascript.host.media.midi.MIDIPort WObj
{
get { return (com.gargoylesoftware.htmlunit.javascript.host.media.midi.MIDIPort)WrappedObject; }
}
public MIDIPort()
: this(new com.gargoylesoftware.htmlunit.javascript.host.media.midi.MIDIPort()) {}
}
}
| 29.060606 | 127 | 0.721585 | [
"Apache-2.0"
] | JonAnders/NHtmlUnit | app/NHtmlUnit/Generated/Javascript/Host/Media/Midi/MIDIPort.cs | 959 | C# |
using System.Collections.Generic;
using System.Net;
using System.Linq;
using System.Threading.Tasks;
using DNS.Client.RequestResolver;
using DNS.Protocol;
using DNS.Protocol.ResourceRecords;
using DNS.Server;
using System;
using SharpPcap;
using PacketDotNet;
using MeshProxy.Network;
namespace MeshProxy.Services
{
public class PeerManager : Service, IRequestResolver
{
public List<Peer> Peers = new List<Peer>();
private PeerDiscovery Discovery => Owner.GetService<PeerDiscovery>();
private MeshProxyLog Log => Owner.GetService<MeshProxyLog>();
private IPTableRouter IP => Owner.GetService<IPTableRouter>();
private DnsServer server;
public string[] KnownPeers
{
get { return Peers.Select(p => p.Name).ToArray(); }
}
public MeshProxyConfig Config => Owner.GetService<MeshProxyConfig>();
protected override async Task OnInit()
{
Log.Info("Starting DNS server");
server = new DnsServer(this);
server.Errored += Server_Errored;
await server.Listen();
}
void Server_Errored(System.Exception e)
{
Log.Error(e);
}
public async Task<IResponse> Resolve(IRequest request)
{
IResponse response = Response.FromRequest(request);
foreach (Question question in response.Questions)
{
if (!question.Name.ToString().EndsWith(".local", StringComparison.Ordinal)) continue;
string domain = question.Name.ToString();
string peerName = domain.Substring(0, domain.Length - ".local".Length);
Log.Info("Resolving for " + domain + " => " + peerName);
List<Peer> resolvedPeers = await PeerLookup(peerName);
Log.Info("Found " + resolvedPeers.Count + " peers");
switch (question.Type)
{
case RecordType.A:
{
foreach (var peer in resolvedPeers)
{
IResourceRecord record = new IPAddressResourceRecord(
question.Name, IPAddress.Parse(peer.InternalIP));
response.AnswerRecords.Add(record);
}
break;
}
}
}
return response;
}
public void SendPacket(Peer toPeer, byte[] packet)
{
Discovery.UdpClient.Send(packet, packet.Length, toPeer.ExternalEndPoint);
}
private async Task<List<Peer>> PeerLookup(string peerName)
{
List<Peer> results = new List<Peer>();
//First search our lookup table
results.AddRange(results.Where(p => p.Name == peerName));
//If we don't have it in our lookup table, ask the network if any of them know it
if (results.Count != 0) return results;
foreach (var peer in Peers)
{
if (await peer.HasConnection(peerName))
{
results.Add(peer);
}
}
return results;
}
public async Task<byte[]> HandshakeNode(IPEndPoint recvBufferRemoteEndPoint, PacketPayload.Handshake payload)
{
if (KnownPeers.Contains(payload.Name))
{
var rejectPayload = new PacketPayload.Reject("Peer with same name already connected!").Compile();
Log.Warn("Responding with REJECT!\n\tA peer with that name is already connected.");
return rejectPayload;
}
//Setup UDP client
Peer peer = new Peer(recvBufferRemoteEndPoint, payload, this);
bool result = await IP.CreateVirtualFor(peer);
if (!result)
{
Log.Warn("Responding with REJECT\n\tCould not create virtual IP for this peer. Please check you're configuration.");
var rejectPayload = new PacketPayload.Reject("Could not create local virtaul IP!").Compile();
return rejectPayload;
}
Peers.Add(peer);
Log.Info("Peer connected and stored " + payload.Name);
var handshake = new PacketPayload.Handshake(Config.Name, MeshProxy.Version, KnownPeers).Compile();
handshake[1] = 0x02;
return handshake;
}
}
} | 32.237762 | 132 | 0.549675 | [
"MIT"
] | ecp4224/mesh-proxy | MeshProxy/Service/PeerManager.cs | 4,612 | C# |
#region PDFSharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2017 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// 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
#define ITALIC_SIMULATION
using System;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Text;
#if GDI
using System.DrawingCore;
using System.DrawingCore.Drawing2D;
#endif
#if WPF
using System.Windows;
using System.Windows.Media;
using SysPoint = System.Windows.Point;
using SysSize = System.Windows.Size;
#endif
#if NETFX_CORE
using Windows.UI.Xaml.Media;
using SysPoint = Windows.Foundation.Point;
using SysSize = Windows.Foundation.Size;
#endif
using PDFSharp.Fonts.OpenType;
using PDFSharp.Internal;
using PDFSharp.Interop;
using PDFSharp.Interop.Internal;
using PDFSharp.Interop.Advanced;
// ReSharper disable RedundantNameQualifier
// ReSharper disable CompareOfFloatsByEqualityOperator
namespace PDFSharp.Drawing.PDF
{
/// <summary>
/// Represents a drawing surface for PDFPages.
/// </summary>
internal class XGraphicsPDFRenderer : IXGraphicsRenderer
{
public XGraphicsPDFRenderer(PDFPage page, XGraphics gfx, XGraphicsPDFPageOptions options)
{
_page = page;
_colorMode = page._document.Options.ColorMode;
PageOptions = options;
Gfx = gfx;
_content = new StringBuilder();
page.RenderContent._pdfRenderer = this;
_gfxState = new PDFGraphicsState(this);
}
public XGraphicsPDFRenderer(XForm form, XGraphics gfx)
{
_form = form;
_colorMode = form.Owner.Options.ColorMode;
Gfx = gfx;
_content = new StringBuilder();
form.PDFRenderer = this;
_gfxState = new PDFGraphicsState(this);
}
/// <summary>
/// Gets the content created by this renderer.
/// </summary>
string GetContent()
{
EndPage();
return _content.ToString();
}
public XGraphicsPDFPageOptions PageOptions { get; }
public void Close()
{
if (_page != null)
{
PDFContent content2 = _page.RenderContent;
content2.CreateStream(PDFEncoders.RawEncoding.GetBytes(GetContent()));
Gfx = null;
_page.RenderContent._pdfRenderer = null;
_page.RenderContent = null;
_page = null;
}
else if (_form != null)
{
_form._pdfForm.CreateStream(PDFEncoders.RawEncoding.GetBytes(GetContent()));
Gfx = null;
_form.PDFRenderer = null;
_form = null;
}
}
// --------------------------------------------------------------------------------------------
#region Drawing
//void SetPageLayout(down, point(0, 0), unit
// ----- DrawLine -----------------------------------------------------------------------------
/// <summary>
/// Strokes a single connection of two points.
/// </summary>
public void DrawLine(XPen pen, double x1, double y1, double x2, double y2) => DrawLines(pen, new XPoint[] { new XPoint(x1, y1), new XPoint(x2, y2) });
// ----- DrawLines ----------------------------------------------------------------------------
/// <summary>
/// Strokes a series of connected points.
/// </summary>
public void DrawLines(XPen pen, XPoint[] points)
{
if (pen == null)
throw new ArgumentNullException("pen");
if (points == null)
throw new ArgumentNullException("points");
int count = points.Length;
if (count == 0)
return;
Realize(pen);
const string format = Config.SignificantFigures4;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", points[0].X, points[0].Y);
for (int idx = 1; idx < count; idx++)
AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", points[idx].X, points[idx].Y);
_content.Append("S\n");
}
// ----- DrawBezier ---------------------------------------------------------------------------
public void DrawBezier(XPen pen, double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) => DrawBeziers(pen, new XPoint[] { new XPoint(x1, y1), new XPoint(x2, y2), new XPoint(x3, y3), new XPoint(x4, y4) });
// ----- DrawBeziers --------------------------------------------------------------------------
public void DrawBeziers(XPen pen, XPoint[] points)
{
if (pen == null)
throw new ArgumentNullException("pen");
if (points == null)
throw new ArgumentNullException("points");
int count = points.Length;
if (count == 0)
return;
if ((count - 1) % 3 != 0)
throw new ArgumentException("Invalid number of points for bezier curves. Number must fulfil 4+3n.", "points");
Realize(pen);
const string format = Config.SignificantFigures4;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", points[0].X, points[0].Y);
for (int idx = 1; idx < count; idx += 3)
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
points[idx].X, points[idx].Y,
points[idx + 1].X, points[idx + 1].Y,
points[idx + 2].X, points[idx + 2].Y);
AppendStrokeFill(pen, null, XFillMode.Alternate, false);
}
// ----- DrawCurve ----------------------------------------------------------------------------
public void DrawCurve(XPen pen, XPoint[] points, double tension)
{
if (pen == null)
throw new ArgumentNullException("pen");
if (points == null)
throw new ArgumentNullException("points");
int count = points.Length;
if (count == 0)
return;
if (count < 2)
throw new ArgumentException("Not enough points", "points");
// See http://pubpages.unh.edu/~cs770/a5/cardinal.html // Link is down...
tension /= 3;
Realize(pen);
const string format = Config.SignificantFigures4;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", points[0].X, points[0].Y);
if (count == 2)
{
// Just draws a line.
AppendCurveSegment(points[0], points[0], points[1], points[1], tension);
}
else
{
AppendCurveSegment(points[0], points[0], points[1], points[2], tension);
for (int idx = 1; idx < count - 2; idx++)
AppendCurveSegment(points[idx - 1], points[idx], points[idx + 1], points[idx + 2], tension);
AppendCurveSegment(points[count - 3], points[count - 2], points[count - 1], points[count - 1], tension);
}
AppendStrokeFill(pen, null, XFillMode.Alternate, false);
}
// ----- DrawArc ------------------------------------------------------------------------------
public void DrawArc(XPen pen, double x, double y, double width, double height, double startAngle, double sweepAngle)
{
if (pen == null)
throw new ArgumentNullException("pen");
Realize(pen);
AppendPartialArc(x, y, width, height, startAngle, sweepAngle, PathStart.MoveTo1st, new XMatrix());
AppendStrokeFill(pen, null, XFillMode.Alternate, false);
}
// ----- DrawRectangle ------------------------------------------------------------------------
public void DrawRectangle(XPen pen, XBrush brush, double x, double y, double width, double height)
{
if (pen == null && brush == null)
throw new ArgumentNullException("pen and brush");
const string format = Config.SignificantFigures3;
Realize(pen, brush);
//AppendFormat123("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} re\n", x, y, width, -height);
AppendFormatRect("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} re\n", x, y + height, width, height);
if (pen != null && brush != null)
_content.Append("B\n");
else if (pen != null)
_content.Append("S\n");
else
_content.Append("f\n");
}
// ----- DrawRectangles -----------------------------------------------------------------------
public void DrawRectangles(XPen pen, XBrush brush, XRect[] rects)
{
int count = rects.Length;
for (int idx = 0; idx < count; idx++)
{
XRect rect = rects[idx];
DrawRectangle(pen, brush, rect.X, rect.Y, rect.Width, rect.Height);
}
}
// ----- DrawRoundedRectangle -----------------------------------------------------------------
public void DrawRoundedRectangle(XPen pen, XBrush brush, double x, double y, double width, double height, double ellipseWidth, double ellipseHeight)
{
XGraphicsPath path = new XGraphicsPath();
path.AddRoundedRectangle(x, y, width, height, ellipseWidth, ellipseHeight);
DrawPath(pen, brush, path);
}
// ----- DrawEllipse --------------------------------------------------------------------------
public void DrawEllipse(XPen pen, XBrush brush, double x, double y, double width, double height)
{
Realize(pen, brush);
// Useful information is here http://home.t-online.de/home/Robert.Rossmair/ellipse.htm (note: link was dead on November 2, 2015)
// or here http://www.whizkidtech.redprince.net/bezier/circle/
// Deeper but more difficult: http://www.tinaja.com/cubic01.asp
XRect rect = new XRect(x, y, width, height);
double δx = rect.Width / 2;
double δy = rect.Height / 2;
double fx = δx * Const.κ;
double fy = δy * Const.κ;
double x0 = rect.X + δx;
double y0 = rect.Y + δy;
// Approximate an ellipse by drawing four cubic splines.
const string format = Config.SignificantFigures4;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", x0 + δx, y0);
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
x0 + δx, y0 + fy, x0 + fx, y0 + δy, x0, y0 + δy);
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
x0 - fx, y0 + δy, x0 - δx, y0 + fy, x0 - δx, y0);
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
x0 - δx, y0 - fy, x0 - fx, y0 - δy, x0, y0 - δy);
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
x0 + fx, y0 - δy, x0 + δx, y0 - fy, x0 + δx, y0);
AppendStrokeFill(pen, brush, XFillMode.Winding, true);
}
// ----- DrawPolygon --------------------------------------------------------------------------
public void DrawPolygon(XPen pen, XBrush brush, XPoint[] points, XFillMode fillmode)
{
Realize(pen, brush);
int count = points.Length;
if (points.Length < 2)
throw new ArgumentException(PSSR.PointArrayAtLeast(2), "points");
const string format = Config.SignificantFigures4;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", points[0].X, points[0].Y);
for (int idx = 1; idx < count; idx++)
AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", points[idx].X, points[idx].Y);
AppendStrokeFill(pen, brush, fillmode, true);
}
// ----- DrawPie ------------------------------------------------------------------------------
public void DrawPie(XPen pen, XBrush brush, double x, double y, double width, double height,
double startAngle, double sweepAngle)
{
Realize(pen, brush);
const string format = Config.SignificantFigures4;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", x + width / 2, y + height / 2);
AppendPartialArc(x, y, width, height, startAngle, sweepAngle, PathStart.LineTo1st, new XMatrix());
AppendStrokeFill(pen, brush, XFillMode.Alternate, true);
}
// ----- DrawClosedCurve ----------------------------------------------------------------------
public void DrawClosedCurve(XPen pen, XBrush brush, XPoint[] points, double tension, XFillMode fillmode)
{
int count = points.Length;
if (count == 0)
return;
if (count < 2)
throw new ArgumentException("Not enough points.", "points");
// Simply tried out. Not proofed why it is correct.
tension /= 3;
Realize(pen, brush);
const string format = Config.SignificantFigures4;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", points[0].X, points[0].Y);
if (count == 2)
{
// Just draw a line.
AppendCurveSegment(points[0], points[0], points[1], points[1], tension);
}
else
{
AppendCurveSegment(points[count - 1], points[0], points[1], points[2], tension);
for (int idx = 1; idx < count - 2; idx++)
AppendCurveSegment(points[idx - 1], points[idx], points[idx + 1], points[idx + 2], tension);
AppendCurveSegment(points[count - 3], points[count - 2], points[count - 1], points[0], tension);
AppendCurveSegment(points[count - 2], points[count - 1], points[0], points[1], tension);
}
AppendStrokeFill(pen, brush, fillmode, true);
}
// ----- DrawPath -----------------------------------------------------------------------------
public void DrawPath(XPen pen, XBrush brush, XGraphicsPath path)
{
if (pen == null && brush == null)
throw new ArgumentNullException("pen");
#if CORE
Realize(pen, brush);
AppendPath(path._corePath);
AppendStrokeFill(pen, brush, path.FillMode, false);
#endif
#if GDI && !WPF
Realize(pen, brush);
AppendPath(path._gdipPath);
AppendStrokeFill(pen, brush, path.FillMode, false);
#endif
#if WPF && !GDI
Realize(pen, brush);
AppendPath(path._pathGeometry);
AppendStrokeFill(pen, brush, path.FillMode, false);
#endif
#if WPF && GDI
Realize(pen, brush);
if (_gfx.TargetContext == XGraphicTargetContext.GDI)
AppendPath(path._gdipPath);
else
AppendPath(path._pathGeometry);
AppendStrokeFill(pen, brush, path.FillMode, false);
#endif
#if NETFX_CORE
Realize(pen, brush);
AppendPath(path._pathGeometry);
AppendStrokeFill(pen, brush, path.FillMode, false);
#endif
}
// ----- DrawString ---------------------------------------------------------------------------
public void DrawString(string s, XFont font, XBrush brush, XRect rect, XStringFormat format)
{
double x = rect.X;
double y = rect.Y;
double lineSpace = font.GetHeight();
double cyAscent = lineSpace * font.CellAscent / font.CellSpace;
double cyDescent = lineSpace * font.CellDescent / font.CellSpace;
double width = Gfx.MeasureString(s, font).Width;
bool italicSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.ItalicSimulation) != 0;
bool boldSimulation = (font.GlyphTypeface.StyleSimulations & XStyleSimulations.BoldSimulation) != 0;
bool strikeout = (font.Style & XFontStyle.Strikeout) != 0;
bool underline = (font.Style & XFontStyle.Underline) != 0;
Realize(font, brush, boldSimulation ? 2 : 0);
switch (format.Alignment)
{
case XStringAlignment.Near:
// nothing to do
break;
case XStringAlignment.Center:
x += (rect.Width - width) / 2;
break;
case XStringAlignment.Far:
x += rect.Width - width;
break;
}
if (Gfx.PageDirection == XPageDirection.Downwards)
{
switch (format.LineAlignment)
{
case XLineAlignment.Near:
y += cyAscent;
break;
case XLineAlignment.Center:
// TODO: Use CapHeight. PDFlib also uses 3/4 of ascent
y += cyAscent * 3 / 4 / 2 + rect.Height / 2;
break;
case XLineAlignment.Far:
y += -cyDescent + rect.Height;
break;
case XLineAlignment.BaseLine:
// Nothing to do.
break;
}
}
else
{
switch (format.LineAlignment)
{
case XLineAlignment.Near:
y += cyDescent;
break;
case XLineAlignment.Center:
// TODO: Use CapHeight. PDFlib also uses 3/4 of ascent
y += -(cyAscent * 3 / 4) / 2 + rect.Height / 2;
break;
case XLineAlignment.Far:
y += -cyAscent + rect.Height;
break;
case XLineAlignment.BaseLine:
// Nothing to do.
break;
}
}
PDFFont realizedFont = _gfxState._realizedFont;
Debug.Assert(realizedFont != null);
realizedFont.AddChars(s);
const string format2 = Config.SignificantFigures4;
OpenTypeDescriptor descriptor = realizedFont.FontDescriptor._descriptor;
string text = null;
if (font.Unicode)
{
StringBuilder sb = new StringBuilder();
bool isSymbolFont = descriptor.FontFace.cmap.symbol;
for (int idx = 0; idx < s.Length; idx++)
{
char ch = s[idx];
if (isSymbolFont)
{
// Remap ch for symbol fonts.
ch = (char)(ch | (descriptor.FontFace.os2.usFirstCharIndex & 0xFF00)); // @@@ refactor
}
int glyphID = descriptor.CharCodeToGlyphIndex(ch);
sb.Append((char)glyphID);
}
s = sb.ToString();
byte[] bytes = PDFEncoders.RawUnicodeEncoding.GetBytes(s);
bytes = PDFEncoders.FormatStringLiteral(bytes, true, false, true, null);
text = PDFEncoders.RawEncoding.GetString(bytes, 0, bytes.Length);
}
else
{
byte[] bytes = PDFEncoders.WinAnsiEncoding.GetBytes(s);
text = PDFEncoders.ToStringLiteral(bytes, false, null);
}
// Map absolute position to PDF world space.
XPoint pos = new XPoint(x, y);
pos = WorldToView(pos);
double verticalOffset = 0;
if (boldSimulation)
{
// Adjust baseline in case of bold simulation???
// No, because this would change the center of the glyphs.
//verticalOffset = font.Size * Const.BoldEmphasis / 2;
}
#if ITALIC_SIMULATION
if (italicSimulation)
{
if (_gfxState.ItalicSimulationOn)
{
AdjustTdOffset(ref pos, verticalOffset, true);
AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} Td\n{2} Tj\n", pos.X, pos.Y, text);
}
else
{
// Italic simulation is done by skewing characters 20° to the right.
XMatrix m = new XMatrix(1, 0, Const.ItalicSkewAngleSinus, 1, pos.X, pos.Y);
AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} {2:" + format2 + "} {3:" + format2 + "} {4:" + format2 + "} {5:" + format2 + "} Tm\n{6} Tj\n",
m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY, text);
_gfxState.ItalicSimulationOn = true;
AdjustTdOffset(ref pos, verticalOffset, false);
}
}
else
{
if (_gfxState.ItalicSimulationOn)
{
XMatrix m = new XMatrix(1, 0, 0, 1, pos.X, pos.Y);
AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} {2:" + format2 + "} {3:" + format2 + "} {4:" + format2 + "} {5:" + format2 + "} Tm\n{6} Tj\n",
m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY, text);
_gfxState.ItalicSimulationOn = false;
AdjustTdOffset(ref pos, verticalOffset, false);
}
else
{
AdjustTdOffset(ref pos, verticalOffset, false);
AppendFormatArgs("{0:" + format2 + "} {1:" + format2 + "} Td {2} Tj\n", pos.X, pos.Y, text);
}
}
#else
AdjustTextMatrix(ref pos);
AppendFormat2("{0:" + format2 + "} {1:" + format2 + "} Td {2} Tj\n", pos.X, pos.Y, text);
#endif
if (underline)
{
double underlinePosition = lineSpace * realizedFont.FontDescriptor._descriptor.UnderlinePosition / font.CellSpace;
double underlineThickness = lineSpace * realizedFont.FontDescriptor._descriptor.UnderlineThickness / font.CellSpace;
//DrawRectangle(null, brush, x, y - underlinePosition, width, underlineThickness);
double underlineRectY = Gfx.PageDirection == XPageDirection.Downwards
? y - underlinePosition
: y + underlinePosition - underlineThickness;
DrawRectangle(null, brush, x, underlineRectY, width, underlineThickness);
}
if (strikeout)
{
double strikeoutPosition = lineSpace * realizedFont.FontDescriptor._descriptor.StrikeoutPosition / font.CellSpace;
double strikeoutSize = lineSpace * realizedFont.FontDescriptor._descriptor.StrikeoutSize / font.CellSpace;
//DrawRectangle(null, brush, x, y - strikeoutPosition - strikeoutSize, width, strikeoutSize);
double strikeoutRectY = Gfx.PageDirection == XPageDirection.Downwards
? y - strikeoutPosition
: y + strikeoutPosition - strikeoutSize;
DrawRectangle(null, brush, x, strikeoutRectY, width, strikeoutSize);
}
}
// ----- DrawImage ----------------------------------------------------------------------------
//public void DrawImage(Image image, Point point);
//public void DrawImage(Image image, PointF point);
//public void DrawImage(Image image, Point[] destPoints);
//public void DrawImage(Image image, PointF[] destPoints);
//public void DrawImage(Image image, Rectangle rect);
//public void DrawImage(Image image, RectangleF rect);
//public void DrawImage(Image image, int x, int y);
//public void DrawImage(Image image, float x, float y);
//public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit);
//public void DrawImage(Image image, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit);
//public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit);
//public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit);
//public void DrawImage(Image image, int x, int y, Rectangle srcRect, GraphicsUnit srcUnit);
//public void DrawImage(Image image, float x, float y, RectangleF srcRect, GraphicsUnit srcUnit);
//public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes imageAttr);
//public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes imageAttr);
//public void DrawImage(Image image, int x, int y, int width, int height);
//public void DrawImage(Image image, float x, float y, float width, float height);
//public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback);
//public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback);
//public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, GraphicsUnit srcUnit);
//public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, GraphicsUnit srcUnit);
//public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback, int callbackData);
//public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback, int callbackData);
//public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttr);
//public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs);
//public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback);
//public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs, DrawImageAbort callback);
//public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY, int srcWidth, int srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs, DrawImageAbort callback, IntPtr callbackData);
//public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY, float srcWidth, float srcHeight, GraphicsUnit srcUnit, ImageAttributes
public void DrawImage(XImage image, double x, double y, double width, double height)
{
const string format = Config.SignificantFigures4;
string name = Realize(image);
if (!(image is XForm))
{
if (Gfx.PageDirection == XPageDirection.Downwards)
{
AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
x, y + height, width, height, name);
}
else
{
AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
x, y, width, height, name);
}
}
else
{
BeginPage();
XForm form = (XForm)image;
form.Finish();
PDFFormXObject pdfForm = Owner.ExternalDocumentTable.GetForm(form);
double cx = width / image.PointWidth;
double cy = height / image.PointHeight;
if (cx != 0 && cy != 0)
{
XPDFForm xForm = image as XPDFForm;
if (Gfx.PageDirection == XPageDirection.Downwards)
{
// If we have an XPDFForm, then we take the MediaBox into account.
double xDraw = x;
double yDraw = y;
if (xForm != null)
{
// Yes, it is an XPDFForm - adjust the position where the page will be drawn.
xDraw -= xForm.Page.MediaBox.X1;
yDraw += xForm.Page.MediaBox.Y1;
}
AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm 100 Tz {4} Do Q\n",
xDraw, yDraw + height, cx, cy, name);
}
else
{
// TODO Translation for MediaBox.
AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
x, y, cx, cy, name);
}
}
}
}
// TODO: incomplete - srcRect not used
public void DrawImage(XImage image, XRect destRect, XRect srcRect, XGraphicsUnit srcUnit)
{
const string format = Config.SignificantFigures4;
double x = destRect.X;
double y = destRect.Y;
double width = destRect.Width;
double height = destRect.Height;
string name = Realize(image);
if (!(image is XForm))
{
if (Gfx.PageDirection == XPageDirection.Downwards)
{
AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do\nQ\n",
x, y + height, width, height, name);
}
else
{
AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
x, y, width, height, name);
}
}
else
{
BeginPage();
XForm form = (XForm)image;
form.Finish();
PDFFormXObject pdfForm = Owner.ExternalDocumentTable.GetForm(form);
double cx = width / image.PointWidth;
double cy = height / image.PointHeight;
if (cx != 0 && cy != 0)
{
XPDFForm xForm = image as XPDFForm;
if (Gfx.PageDirection == XPageDirection.Downwards)
{
double xDraw = x;
double yDraw = y;
if (xForm != null)
{
// Yes, it is an XPDFForm - adjust the position where the page will be drawn.
xDraw -= xForm.Page.MediaBox.X1;
yDraw += xForm.Page.MediaBox.Y1;
}
AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
xDraw, yDraw + height, cx, cy, name);
}
else
{
// TODO Translation for MediaBox.
AppendFormatImage("q {2:" + format + "} 0 0 {3:" + format + "} {0:" + format + "} {1:" + format + "} cm {4} Do Q\n",
x, y, cx, cy, name);
}
}
}
}
#endregion
// --------------------------------------------------------------------------------------------
#region Save and Restore
/// <summary>
/// Clones the current graphics state and push it on a stack.
/// </summary>
public void Save(XGraphicsState state)
{
// Before saving, the current transformation matrix must be completely realized.
BeginGraphicMode();
RealizeTransform();
// Associate the XGraphicsState with the current PdgGraphicsState.
_gfxState.InternalState = state.InternalState;
SaveState();
}
public void Restore(XGraphicsState state)
{
BeginGraphicMode();
RestoreState(state.InternalState);
}
public void BeginContainer(XGraphicsContainer container, XRect dstrect, XRect srcrect, XGraphicsUnit unit)
{
// Before saving, the current transformation matrix must be completely realized.
BeginGraphicMode();
RealizeTransform();
_gfxState.InternalState = container.InternalState;
SaveState();
}
public void EndContainer(XGraphicsContainer container)
{
BeginGraphicMode();
RestoreState(container.InternalState);
}
#endregion
// --------------------------------------------------------------------------------------------
#region Transformation
//public void SetPageTransform(XPageDirection direction, XPoint origion, XGraphicsUnit unit)
//{
// if (_gfxStateStack.Count > 0)
// throw new InvalidOperationException("PageTransformation can be modified only when the graphics stack is empty.");
// throw new NotImplementedException("SetPageTransform");
//}
public XMatrix Transform => _gfxState.UnrealizedCtm.IsIdentity ? _gfxState.EffectiveCtm : _gfxState.UnrealizedCtm * _gfxState.RealizedCtm;
public void AddTransform(XMatrix value, XMatrixOrder matrixOrder) => _gfxState.AddTransform(value, matrixOrder);
#endregion
// --------------------------------------------------------------------------------------------
#region Clipping
public void SetClip(XGraphicsPath path, XCombineMode combineMode)
{
if (path == null)
throw new NotImplementedException("SetClip with no path.");
// Ensure that the graphics state stack level is at least 2, because otherwise an error
// occurs when someone set the clip region before something was drawn.
if (_gfxState.Level < GraphicsStackLevelWorldSpace)
RealizeTransform(); // TODO: refactor this function
if (combineMode == XCombineMode.Replace)
{
if (_clipLevel != 0)
{
if (_clipLevel != _gfxState.Level)
throw new NotImplementedException("Cannot set new clip region in an inner graphic state level.");
else
ResetClip();
}
_clipLevel = _gfxState.Level;
}
else if (combineMode == XCombineMode.Intersect)
{
if (_clipLevel == 0)
_clipLevel = _gfxState.Level;
}
else
{
Debug.Assert(false, "Invalid XCombineMode in internal function.");
}
_gfxState.SetAndRealizeClipPath(path);
}
/// <summary>
/// Sets the clip path empty. Only possible if graphic state level has the same value as it has when
/// the first time SetClip was invoked.
/// </summary>
public void ResetClip()
{
// No clip level means no clipping occurs and nothing is to do.
if (_clipLevel == 0)
return;
// Only at the clipLevel the clipping can be reset.
if (_clipLevel != _gfxState.Level)
throw new NotImplementedException("Cannot reset clip region in an inner graphic state level.");
// Must be in graphical mode before popping the graphics state.
BeginGraphicMode();
// Save InternalGraphicsState and transformation of the current graphical state.
InternalGraphicsState state = _gfxState.InternalState;
XMatrix ctm = _gfxState.EffectiveCtm;
// Empty clip path by switching back to the previous state.
RestoreState();
SaveState();
// Save internal state
_gfxState.InternalState = state;
// Restore CTM
// TODO: check rest of clip
//GfxState.Transform = ctm;
}
/// <summary>
/// The nesting level of the PDF graphics state stack when the clip region was set to non empty.
/// Because of the way PDF is made the clip region can only be reset at this level.
/// </summary>
int _clipLevel;
#endregion
// --------------------------------------------------------------------------------------------
#region Miscellaneous
/// <summary>
/// Writes a comment to the PDF content stream. May be useful for debugging purposes.
/// </summary>
public void WriteComment(string comment)
{
comment = comment.Replace("\n", "\n% ");
// TODO: Some more checks necessary?
Append("% " + comment + "\n");
}
#endregion
// --------------------------------------------------------------------------------------------
#region Append to PDF stream
/// <summary>
/// Appends one or up to five Bézier curves that interpolate the arc.
/// </summary>
void AppendPartialArc(double x, double y, double width, double height, double startAngle, double sweepAngle, PathStart pathStart, XMatrix matrix)
{
// Normalize the angles
double α = startAngle;
if (α < 0)
α = α + (1 + Math.Floor(Math.Abs(α) / 360)) * 360;
else if (α > 360)
α = α - Math.Floor(α / 360) * 360;
Debug.Assert(α >= 0 && α <= 360);
double β = sweepAngle;
if (β < -360)
β = -360;
else if (β > 360)
β = 360;
if (α == 0 && β < 0)
α = 360;
else if (α == 360 && β > 0)
α = 0;
// Is it possible that the arc is small starts and ends in same quadrant?
bool smallAngle = Math.Abs(β) <= 90;
β = α + β;
if (β < 0)
β = β + (1 + Math.Floor(Math.Abs(β) / 360)) * 360;
bool clockwise = sweepAngle > 0;
int startQuadrant = Quadrant(α, true, clockwise);
int endQuadrant = Quadrant(β, false, clockwise);
if (startQuadrant == endQuadrant && smallAngle)
AppendPartialArcQuadrant(x, y, width, height, α, β, pathStart, matrix);
else
{
int currentQuadrant = startQuadrant;
bool firstLoop = true;
do
{
if (currentQuadrant == startQuadrant && firstLoop)
{
double ξ = currentQuadrant * 90 + (clockwise ? 90 : 0);
AppendPartialArcQuadrant(x, y, width, height, α, ξ, pathStart, matrix);
}
else if (currentQuadrant == endQuadrant)
{
double ξ = currentQuadrant * 90 + (clockwise ? 0 : 90);
AppendPartialArcQuadrant(x, y, width, height, ξ, β, PathStart.Ignore1st, matrix);
}
else
{
double ξ1 = currentQuadrant * 90 + (clockwise ? 0 : 90);
double ξ2 = currentQuadrant * 90 + (clockwise ? 90 : 0);
AppendPartialArcQuadrant(x, y, width, height, ξ1, ξ2, PathStart.Ignore1st, matrix);
}
// Don't stop immediately if arc is greater than 270 degrees
if (currentQuadrant == endQuadrant && smallAngle)
break;
smallAngle = true;
currentQuadrant = clockwise ? currentQuadrant == 3 ? 0 : currentQuadrant + 1 : currentQuadrant == 0 ? 3 : currentQuadrant - 1;
firstLoop = false;
} while (true);
}
}
/// <summary>
/// Gets the quadrant (0 through 3) of the specified angle. If the angle lies on an edge
/// (0, 90, 180, etc.) the result depends on the details how the angle is used.
/// </summary>
int Quadrant(double φ, bool start, bool clockwise)
{
Debug.Assert(φ >= 0);
if (φ > 360)
φ = φ - Math.Floor(φ / 360) * 360;
int quadrant = (int)(φ / 90);
if (quadrant * 90 == φ)
{
if (start && !clockwise || !start && clockwise)
quadrant = quadrant == 0 ? 3 : quadrant - 1;
}
else
quadrant = clockwise ? (int)Math.Floor(φ / 90) % 4 : (int)Math.Floor(φ / 90);
return quadrant;
}
/// <summary>
/// Appends a Bézier curve for an arc within a quadrant.
/// </summary>
void AppendPartialArcQuadrant(double x, double y, double width, double height, double α, double β, PathStart pathStart, XMatrix matrix)
{
Debug.Assert(α >= 0 && α <= 360);
Debug.Assert(β >= 0);
if (β > 360)
β = β - Math.Floor(β / 360) * 360;
Debug.Assert(Math.Abs(α - β) <= 90);
// Scanling factor
double δx = width / 2;
double δy = height / 2;
// Center of ellipse
double x0 = x + δx;
double y0 = y + δy;
// We have the following quarters:
// |
// 2 | 3
// ----+-----
// 1 | 0
// |
// If the angles lie in quarter 2 or 3, their values are subtracted by 180 and the
// resulting curve is reflected at the center. This algorithm works as expected (simply tried out).
// There may be a mathematically more elegant solution...
bool reflect = false;
if (α >= 180 && β >= 180)
{
α -= 180;
β -= 180;
reflect = true;
}
double sinα, sinβ;
if (width == height)
{
// Circular arc needs no correction.
α = α * Calc.Deg2Rad;
β = β * Calc.Deg2Rad;
}
else
{
// Elliptic arc needs the angles to be adjusted such that the scaling transformation is compensated.
α = α * Calc.Deg2Rad;
sinα = Math.Sin(α);
if (Math.Abs(sinα) > 1E-10)
α = Math.PI / 2 - Math.Atan(δy * Math.Cos(α) / (δx * sinα));
β = β * Calc.Deg2Rad;
sinβ = Math.Sin(β);
if (Math.Abs(sinβ) > 1E-10)
β = Math.PI / 2 - Math.Atan(δy * Math.Cos(β) / (δx * sinβ));
}
double κ = 4 * (1 - Math.Cos((α - β) / 2)) / (3 * Math.Sin((β - α) / 2));
sinα = Math.Sin(α);
double cosα = Math.Cos(α);
sinβ = Math.Sin(β);
double cosβ = Math.Cos(β);
const string format = Config.SignificantFigures3;
XPoint pt1, pt2, pt3;
if (!reflect)
{
// Calculation for quarter 0 and 1
switch (pathStart)
{
case PathStart.MoveTo1st:
pt1 = matrix.Transform(new XPoint(x0 + δx * cosα, y0 + δy * sinα));
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", pt1.X, pt1.Y);
break;
case PathStart.LineTo1st:
pt1 = matrix.Transform(new XPoint(x0 + δx * cosα, y0 + δy * sinα));
AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", pt1.X, pt1.Y);
break;
case PathStart.Ignore1st:
break;
}
pt1 = matrix.Transform(new XPoint(x0 + δx * (cosα - κ * sinα), y0 + δy * (sinα + κ * cosα)));
pt2 = matrix.Transform(new XPoint(x0 + δx * (cosβ + κ * sinβ), y0 + δy * (sinβ - κ * cosβ)));
pt3 = matrix.Transform(new XPoint(x0 + δx * cosβ, y0 + δy * sinβ));
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y);
}
else
{
// Calculation for quarter 2 and 3.
switch (pathStart)
{
case PathStart.MoveTo1st:
pt1 = matrix.Transform(new XPoint(x0 - δx * cosα, y0 - δy * sinα));
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", pt1.X, pt1.Y);
break;
case PathStart.LineTo1st:
pt1 = matrix.Transform(new XPoint(x0 - δx * cosα, y0 - δy * sinα));
AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", pt1.X, pt1.Y);
break;
case PathStart.Ignore1st:
break;
}
pt1 = matrix.Transform(new XPoint(x0 - δx * (cosα - κ * sinα), y0 - δy * (sinα + κ * cosα)));
pt2 = matrix.Transform(new XPoint(x0 - δx * (cosβ + κ * sinβ), y0 - δy * (sinβ - κ * cosβ)));
pt3 = matrix.Transform(new XPoint(x0 - δx * cosβ, y0 - δy * sinβ));
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y);
}
}
#if WPF || NETFX_CORE
void AppendPartialArc(SysPoint point1, SysPoint point2, double rotationAngle,
SysSize size, bool isLargeArc, SweepDirection sweepDirection, PathStart pathStart)
{
const string format = Config.SignificantFigures4;
Debug.Assert(pathStart == PathStart.Ignore1st);
int pieces;
PointCollection points = GeometryHelper.ArcToBezier(point1.X, point1.Y, size.Width, size.Height, rotationAngle, isLargeArc,
sweepDirection == SweepDirection.Clockwise, point2.X, point2.Y, out pieces);
int count = points.Count;
int start = count % 3 == 1 ? 1 : 0;
if (start == 1)
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", points[0].X, points[0].Y);
for (int idx = start; idx < count; idx += 3)
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
points[idx].X, points[idx].Y,
points[idx + 1].X, points[idx + 1].Y,
points[idx + 2].X, points[idx + 2].Y);
}
#endif
/// <summary>
/// Appends a Bézier curve for a cardinal spline through pt1 and pt2.
/// </summary>
void AppendCurveSegment(XPoint pt0, XPoint pt1, XPoint pt2, XPoint pt3, double tension3)
{
const string format = Config.SignificantFigures4;
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
pt1.X + tension3 * (pt2.X - pt0.X), pt1.Y + tension3 * (pt2.Y - pt0.Y),
pt2.X - tension3 * (pt3.X - pt1.X), pt2.Y - tension3 * (pt3.Y - pt1.Y),
pt2.X, pt2.Y);
}
#if CORE_
/// <summary>
/// Appends the content of a GraphicsPath object.
/// </summary>
internal void AppendPath(GraphicsPath path)
{
int count = path.PointCount;
if (count == 0)
return;
PointF[] points = path.PathPoints;
Byte[] types = path.PathTypes;
for (int idx = 0; idx < count; idx++)
{
// From GDI+ documentation:
const byte PathPointTypeStart = 0; // move
const byte PathPointTypeLine = 1; // line
const byte PathPointTypeBezier = 3; // default Bezier (= cubic Bezier)
const byte PathPointTypePathTypeMask = 0x07; // type mask (lowest 3 bits).
//const byte PathPointTypeDashMode = 0x10; // currently in dash mode.
//const byte PathPointTypePathMarker = 0x20; // a marker for the path.
const byte PathPointTypeCloseSubpath = 0x80; // closed flag
byte type = types[idx];
switch (type & PathPointTypePathTypeMask)
{
case PathPointTypeStart:
//PDF_moveto(pdf, points[idx].X, points[idx].Y);
AppendFormat("{0:" + format + "} {1:" + format + "} m\n", points[idx].X, points[idx].Y);
break;
case PathPointTypeLine:
//PDF_lineto(pdf, points[idx].X, points[idx].Y);
AppendFormat("{0:" + format + "} {1:" + format + "} l\n", points[idx].X, points[idx].Y);
if ((type & PathPointTypeCloseSubpath) != 0)
Append("h\n");
break;
case PathPointTypeBezier:
Debug.Assert(idx + 2 < count);
//PDF_curveto(pdf, points[idx].X, points[idx].Y,
// points[idx + 1].X, points[idx + 1].Y,
// points[idx + 2].X, points[idx + 2].Y);
AppendFormat("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n", points[idx].X, points[idx].Y,
points[++idx].X, points[idx].Y, points[++idx].X, points[idx].Y);
if ((types[idx] & PathPointTypeCloseSubpath) != 0)
Append("h\n");
break;
}
}
}
#endif
#if CORE
/// <summary>
/// Appends the content of a GraphicsPath object.
/// </summary>
internal void AppendPath(CoreGraphicsPath path) => AppendPath(path.PathPoints, path.PathTypes);//XPoint[] points = path.PathPoints;//Byte[] types = path.PathTypes;//int count = points.Length;//if (count == 0)// return;//for (int idx = 0; idx < count; idx++)//{// // From GDI+ documentation:// const byte PathPointTypeStart = 0; // move// const byte PathPointTypeLine = 1; // line// const byte PathPointTypeBezier = 3; // default Bezier (= cubic Bezier)// const byte PathPointTypePathTypeMask = 0x07; // type mask (lowest 3 bits).// //const byte PathPointTypeDashMode = 0x10; // currently in dash mode.// //const byte PathPointTypePathMarker = 0x20; // a marker for the path.// const byte PathPointTypeCloseSubpath = 0x80; // closed flag// byte type = types[idx];// switch (type & PathPointTypePathTypeMask)// {// case PathPointTypeStart:// //PDF_moveto(pdf, points[idx].X, points[idx].Y);// AppendFormat("{0:" + format + "} {1:" + format + "} m\n", points[idx].X, points[idx].Y);// break;// case PathPointTypeLine:// //PDF_lineto(pdf, points[idx].X, points[idx].Y);// AppendFormat("{0:" + format + "} {1:" + format + "} l\n", points[idx].X, points[idx].Y);// if ((type & PathPointTypeCloseSubpath) != 0)// Append("h\n");// break;// case PathPointTypeBezier:// Debug.Assert(idx + 2 < count);// //PDF_curveto(pdf, points[idx].X, points[idx].Y, // // points[idx + 1].X, points[idx + 1].Y, // // points[idx + 2].X, points[idx + 2].Y);// AppendFormat("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n", points[idx].X, points[idx].Y,// points[++idx].X, points[idx].Y, points[++idx].X, points[idx].Y);// if ((types[idx] & PathPointTypeCloseSubpath) != 0)// Append("h\n");// break;// }//}
#endif
#if GDI
/// <summary>
/// Appends the content of a GraphicsPath object.
/// </summary>
internal void AppendPath(GraphicsPath path)
{
#if true
AppendPath(XGraphics.MakeXPointArray(path.PathPoints, 0, path.PathPoints.Length), path.PathTypes);
#else
int count = path.PointCount;
if (count == 0)
return;
PointF[] points = path.PathPoints;
Byte[] types = path.PathTypes;
for (int idx = 0; idx < count; idx++)
{
// From GDI+ documentation:
const byte PathPointTypeStart = 0; // move
const byte PathPointTypeLine = 1; // line
const byte PathPointTypeBezier = 3; // default Bezier (= cubic Bezier)
const byte PathPointTypePathTypeMask = 0x07; // type mask (lowest 3 bits).
//const byte PathPointTypeDashMode = 0x10; // currently in dash mode.
//const byte PathPointTypePathMarker = 0x20; // a marker for the path.
const byte PathPointTypeCloseSubpath = 0x80; // closed flag
byte type = types[idx];
switch (type & PathPointTypePathTypeMask)
{
case PathPointTypeStart:
//PDF_moveto(pdf, points[idx].X, points[idx].Y);
AppendFormat("{0:" + format + "} {1:" + format + "} m\n", points[idx].X, points[idx].Y);
break;
case PathPointTypeLine:
//PDF_lineto(pdf, points[idx].X, points[idx].Y);
AppendFormat("{0:" + format + "} {1:" + format + "} l\n", points[idx].X, points[idx].Y);
if ((type & PathPointTypeCloseSubpath) != 0)
Append("h\n");
break;
case PathPointTypeBezier:
Debug.Assert(idx + 2 < count);
//PDF_curveto(pdf, points[idx].X, points[idx].Y,
// points[idx + 1].X, points[idx + 1].Y,
// points[idx + 2].X, points[idx + 2].Y);
AppendFormat("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n", points[idx].X, points[idx].Y,
points[++idx].X, points[idx].Y, points[++idx].X, points[idx].Y);
if ((types[idx] & PathPointTypeCloseSubpath) != 0)
Append("h\n");
break;
}
}
#endif
}
#endif
#if CORE || GDI
void AppendPath(XPoint[] points, byte[] types)
{
const string format = Config.SignificantFigures4;
int count = points.Length;
if (count == 0)
return;
for (int idx = 0; idx < count; idx++)
{
// ReSharper disable InconsistentNaming
// From GDI+ documentation:
const byte PathPointTypeStart = 0; // move
const byte PathPointTypeLine = 1; // line
const byte PathPointTypeBezier = 3; // default Bezier (= cubic Bezier)
const byte PathPointTypePathTypeMask = 0x07; // type mask (lowest 3 bits).
//const byte PathPointTypeDashMode = 0x10; // currently in dash mode.
//const byte PathPointTypePathMarker = 0x20; // a marker for the path.
const byte PathPointTypeCloseSubpath = 0x80; // closed flag
// ReSharper restore InconsistentNaming
byte type = types[idx];
switch (type & PathPointTypePathTypeMask)
{
case PathPointTypeStart:
//PDF_moveto(pdf, points[idx].X, points[idx].Y);
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", points[idx].X, points[idx].Y);
break;
case PathPointTypeLine:
//PDF_lineto(pdf, points[idx].X, points[idx].Y);
AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", points[idx].X, points[idx].Y);
if ((type & PathPointTypeCloseSubpath) != 0)
Append("h\n");
break;
case PathPointTypeBezier:
Debug.Assert(idx + 2 < count);
//PDF_curveto(pdf, points[idx].X, points[idx].Y,
// points[idx + 1].X, points[idx + 1].Y,
// points[idx + 2].X, points[idx + 2].Y);
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n", points[idx].X, points[idx].Y,
points[++idx].X, points[idx].Y, points[++idx].X, points[idx].Y);
if ((types[idx] & PathPointTypeCloseSubpath) != 0)
Append("h\n");
break;
}
}
}
#endif
#if WPF || NETFX_CORE
/// <summary>
/// Appends the content of a PathGeometry object.
/// </summary>
internal void AppendPath(PathGeometry geometry)
{
const string format = Config.SignificantFigures4;
foreach (PathFigure figure in geometry.Figures)
{
#if DEBUG
//#warning For DdlGBE_Chart_Layout (WPF) execution stucks at this Assertion.
// The empty Figure is added via XGraphicsPath.CurrentPathFigure Getter.
// Some methods like XGraphicsPath.AddRectangle() or AddLine() use this emtpy Figure to add Segments, others like AddEllipse() don't.
// Here, _pathGeometry.AddGeometry() of course ignores this first Figure and adds a second.
// Encapsulate relevant Add methods to delete a first emty Figure or move the Addition of an first empty Figure to a GetOrCreateCurrentPathFigure() or simply remove Assertion?
// Look for:
// MAOS4STLA: CurrentPathFigure.
if (figure.Segments.Count == 0)
42.GetType();
Debug.Assert(figure.Segments.Count > 0);
#endif
// Skip the Move if the segment is empty. Workaround for empty segments. Empty segments should not occur (see Debug.Assert above).
if (figure.Segments.Count > 0)
{
// Move to start point.
SysPoint currentPoint = figure.StartPoint;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} m\n", currentPoint.X, currentPoint.Y);
foreach (PathSegment segment in figure.Segments)
{
Type type = segment.GetType();
if (type == typeof(LineSegment))
{
// Draw a single line.
SysPoint point = ((LineSegment)segment).Point;
currentPoint = point;
AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", point.X, point.Y);
}
else if (type == typeof(PolyLineSegment))
{
// Draw connected lines.
PointCollection points = ((PolyLineSegment)segment).Points;
foreach (SysPoint point in points)
{
currentPoint = point; // I forced myself not to optimize this assignment.
AppendFormatPoint("{0:" + format + "} {1:" + format + "} l\n", point.X, point.Y);
}
}
else if (type == typeof(BezierSegment))
{
// Draw Bézier curve.
BezierSegment seg = (BezierSegment)segment;
SysPoint point1 = seg.Point1;
SysPoint point2 = seg.Point2;
SysPoint point3 = seg.Point3;
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
point1.X, point1.Y, point2.X, point2.Y, point3.X, point3.Y);
currentPoint = point3;
}
else if (type == typeof(PolyBezierSegment))
{
// Draw connected Bézier curves.
PointCollection points = ((PolyBezierSegment)segment).Points;
int count = points.Count;
if (count > 0)
{
Debug.Assert(count % 3 == 0, "Number of Points in PolyBezierSegment are not a multiple of 3.");
for (int idx = 0; idx < count - 2; idx += 3)
{
SysPoint point1 = points[idx];
SysPoint point2 = points[idx + 1];
SysPoint point3 = points[idx + 2];
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} c\n",
point1.X, point1.Y, point2.X, point2.Y, point3.X, point3.Y);
}
currentPoint = points[count - 1];
}
}
else if (type == typeof(ArcSegment))
{
// Draw arc.
ArcSegment seg = (ArcSegment)segment;
AppendPartialArc(currentPoint, seg.Point, seg.RotationAngle, seg.Size, seg.IsLargeArc, seg.SweepDirection, PathStart.Ignore1st);
currentPoint = seg.Point;
}
else if (type == typeof(QuadraticBezierSegment))
{
QuadraticBezierSegment seg = (QuadraticBezierSegment)segment;
currentPoint = seg.Point2;
// TODOWPF: Undone because XGraphics has no such curve type
throw new NotImplementedException("AppendPath with QuadraticBezierSegment.");
}
else if (type == typeof(PolyQuadraticBezierSegment))
{
PolyQuadraticBezierSegment seg = (PolyQuadraticBezierSegment)segment;
currentPoint = seg.Points[seg.Points.Count - 1];
// TODOWPF: Undone because XGraphics has no such curve type
throw new NotImplementedException("AppendPath with PolyQuadraticBezierSegment.");
}
}
if (figure.IsClosed)
Append("h\n");
}
}
}
#endif
internal void Append(string value) => _content.Append(value);
internal void AppendFormatArgs(string format, params object[] args)
{
_content.AppendFormat(CultureInfo.InvariantCulture, format, args);
#if DEBUG
string dummy = _content.ToString();
dummy = dummy.Substring(Math.Max(0, dummy.Length - 100));
dummy.GetType();
#endif
}
internal void AppendFormatString(string format, string s) => _content.AppendFormat(CultureInfo.InvariantCulture, format, s);
internal void AppendFormatFont(string format, string s, double d) => _content.AppendFormat(CultureInfo.InvariantCulture, format, s, d);
internal void AppendFormatInt(string format, int n) => _content.AppendFormat(CultureInfo.InvariantCulture, format, n);
internal void AppendFormatDouble(string format, double d) => _content.AppendFormat(CultureInfo.InvariantCulture, format, d);
internal void AppendFormatPoint(string format, double x, double y)
{
XPoint result = WorldToView(new XPoint(x, y));
_content.AppendFormat(CultureInfo.InvariantCulture, format, result.X, result.Y);
}
internal void AppendFormatRect(string format, double x, double y, double width, double height)
{
XPoint point1 = WorldToView(new XPoint(x, y));
_content.AppendFormat(CultureInfo.InvariantCulture, format, point1.X, point1.Y, width, height);
}
internal void AppendFormat3Points(string format, double x1, double y1, double x2, double y2, double x3, double y3)
{
XPoint point1 = WorldToView(new XPoint(x1, y1));
XPoint point2 = WorldToView(new XPoint(x2, y2));
XPoint point3 = WorldToView(new XPoint(x3, y3));
_content.AppendFormat(CultureInfo.InvariantCulture, format, point1.X, point1.Y, point2.X, point2.Y, point3.X, point3.Y);
}
internal void AppendFormat(string format, XPoint point)
{
XPoint result = WorldToView(point);
_content.AppendFormat(CultureInfo.InvariantCulture, format, result.X, result.Y);
}
internal void AppendFormat(string format, double x, double y, string s)
{
XPoint result = WorldToView(new XPoint(x, y));
_content.AppendFormat(CultureInfo.InvariantCulture, format, result.X, result.Y, s);
}
internal void AppendFormatImage(string format, double x, double y, double width, double height, string name)
{
XPoint result = WorldToView(new XPoint(x, y));
_content.AppendFormat(CultureInfo.InvariantCulture, format, result.X, result.Y, width, height, name);
}
void AppendStrokeFill(XPen pen, XBrush brush, XFillMode fillMode, bool closePath)
{
if (closePath)
_content.Append("h ");
if (fillMode == XFillMode.Winding)
{
if (pen != null && brush != null)
_content.Append("B\n");
else if (pen != null)
_content.Append("S\n");
else
_content.Append("f\n");
}
else
{
if (pen != null && brush != null)
_content.Append("B*\n");
else if (pen != null)
_content.Append("S\n");
else
_content.Append("f*\n");
}
}
#endregion
// --------------------------------------------------------------------------------------------
#region Realizing graphical state
/// <summary>
/// Initializes the default view transformation, i.e. the transformation from the user page
/// space to the PDF page space.
/// </summary>
void BeginPage()
{
if (_gfxState.Level == GraphicsStackLevelInitial)
{
// TODO: Is PageOriging and PageScale (== Viewport) useful? Or just public DefaultViewMatrix (like Presentation Manager has had)
// May be a BeginContainer(windows, viewport) is useful for userer that are not familar with maxtrix transformations.
// Flip page horizontally and mirror text.
// PDF uses a standard right-handed Cartesian coordinate system with the y axis directed up
// and the rotation counterclockwise. Windows uses the opposite convertion with y axis
// directed down and rotation clockwise. When I started with PDFSharp I flipped pages horizontally
// and then mirrored text to compensate the effect that the fipping turns text upside down.
// I found this technique during analysis of PDF documents generated with PDFlib. Unfortunately
// this technique leads to several problems with programms that compose or view PDF documents
// generated with PDFSharp.
// In PDFSharp 1.4 I implement a revised technique that does not need text mirroring any more.
DefaultViewMatrix = new XMatrix();
if (Gfx.PageDirection == XPageDirection.Downwards)
{
// Take TrimBox into account.
PageHeightPt = Size.Height;
XPoint trimOffset = new XPoint();
if (_page != null && _page.TrimMargins.AreSet)
{
PageHeightPt += _page.TrimMargins.Top.Point + _page.TrimMargins.Bottom.Point;
trimOffset = new XPoint(_page.TrimMargins.Left.Point, _page.TrimMargins.Top.Point);
}
// Scale with page units.
switch (Gfx.PageUnit)
{
case XGraphicsUnit.Point:
// Factor is 1.
// DefaultViewMatrix.ScalePrepend(XUnit.PointFactor);
break;
case XGraphicsUnit.Presentation:
DefaultViewMatrix.ScalePrepend(XUnit.PresentationFactor);
break;
case XGraphicsUnit.Inch:
DefaultViewMatrix.ScalePrepend(XUnit.InchFactor);
break;
case XGraphicsUnit.Millimeter:
DefaultViewMatrix.ScalePrepend(XUnit.MillimeterFactor);
break;
case XGraphicsUnit.Centimeter:
DefaultViewMatrix.ScalePrepend(XUnit.CentimeterFactor);
break;
}
if (trimOffset != new XPoint())
{
Debug.Assert(Gfx.PageUnit == XGraphicsUnit.Point, "With TrimMargins set the page units must be Point. Ohter cases nyi.");
DefaultViewMatrix.TranslatePrepend(trimOffset.X, -trimOffset.Y);
}
// Save initial graphic state.
SaveState();
// Set default page transformation, if any.
if (!DefaultViewMatrix.IsIdentity)
{
Debug.Assert(_gfxState.RealizedCtm.IsIdentity);
//_gfxState.RealizedCtm = DefaultViewMatrix;
const string format = Config.SignificantFigures7;
double[] cm = DefaultViewMatrix.GetElements();
AppendFormatArgs("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} cm ",
cm[0], cm[1], cm[2], cm[3], cm[4], cm[5]);
}
// Set page transformation
//double[] cm = DefaultViewMatrix.GetElements();
//AppendFormat("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} cm ",
// cm[0], cm[1], cm[2], cm[3], cm[4], cm[5]);
}
else
{
// Scale with page units.
switch (Gfx.PageUnit)
{
case XGraphicsUnit.Point:
// Factor is 1.
// DefaultViewMatrix.ScalePrepend(XUnit.PointFactor);
break;
case XGraphicsUnit.Presentation:
DefaultViewMatrix.ScalePrepend(XUnit.PresentationFactor);
break;
case XGraphicsUnit.Inch:
DefaultViewMatrix.ScalePrepend(XUnit.InchFactor);
break;
case XGraphicsUnit.Millimeter:
DefaultViewMatrix.ScalePrepend(XUnit.MillimeterFactor);
break;
case XGraphicsUnit.Centimeter:
DefaultViewMatrix.ScalePrepend(XUnit.CentimeterFactor);
break;
}
// Save initial graphic state.
SaveState();
// Set page transformation.
const string format = Config.SignificantFigures7;
double[] cm = DefaultViewMatrix.GetElements();
AppendFormat3Points("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} cm ",
cm[0], cm[1], cm[2], cm[3], cm[4], cm[5]);
}
}
}
/// <summary>
/// Ends the content stream, i.e. ends the text mode and balances the graphic state stack.
/// </summary>
void EndPage()
{
if (_streamMode == StreamMode.Text)
{
_content.Append("ET\n");
_streamMode = StreamMode.Graphic;
}
while (_gfxStateStack.Count != 0)
RestoreState();
}
/// <summary>
/// Begins the graphic mode (i.e. ends the text mode).
/// </summary>
internal void BeginGraphicMode()
{
if (_streamMode != StreamMode.Graphic)
{
if (_streamMode == StreamMode.Text)
_content.Append("ET\n");
_streamMode = StreamMode.Graphic;
}
}
/// <summary>
/// Begins the graphic mode (i.e. ends the text mode).
/// </summary>
internal void BeginTextMode()
{
if (_streamMode != StreamMode.Text)
{
_streamMode = StreamMode.Text;
_content.Append("BT\n");
// Text matrix is empty after BT
_gfxState.RealizedTextPosition = new XPoint();
_gfxState.ItalicSimulationOn = false;
}
}
StreamMode _streamMode;
/// <summary>
/// Makes the specified pen and brush to the current graphics objects.
/// </summary>
private void Realize(XPen pen, XBrush brush)
{
BeginPage();
BeginGraphicMode();
RealizeTransform();
if (pen != null)
_gfxState.RealizePen(pen, _colorMode); // page.document.Options.ColorMode);
if (brush != null)
{
// Render mode is 0 except for bold simulation.
_gfxState.RealizeBrush(brush, _colorMode, 0, 0); // page.document.Options.ColorMode);
}
}
/// <summary>
/// Makes the specified pen to the current graphics object.
/// </summary>
void Realize(XPen pen) => Realize(pen, null);
/// <summary>
/// Makes the specified brush to the current graphics object.
/// </summary>
void Realize(XBrush brush) => Realize(null, brush);
/// <summary>
/// Makes the specified font and brush to the current graphics objects.
/// </summary>
void Realize(XFont font, XBrush brush, int renderingMode)
{
BeginPage();
RealizeTransform();
BeginTextMode();
_gfxState.RealizeFont(font, brush, renderingMode);
}
/// <summary>
/// PDFSharp uses the Td operator to set the text position. Td just sets the offset of the text matrix
/// and produces lesser code as Tm.
/// </summary>
/// <param name="pos">The absolute text position.</param>
/// <param name="dy">The dy.</param>
/// <param name="adjustSkew">true if skewing for italic simulation is currently on.</param>
void AdjustTdOffset(ref XPoint pos, double dy, bool adjustSkew)
{
pos.Y += dy;
// Reference: TABLE 5.5 Text-positioning operators / Page 406
XPoint posSave = pos;
// Map from absolute to relative position.
pos = pos - new XVector(_gfxState.RealizedTextPosition.X, _gfxState.RealizedTextPosition.Y);
if (adjustSkew)
{
// In case that italic simulation is on X must be adjusted according to Y offset. Weird but works :-)
pos.X -= Const.ItalicSkewAngleSinus * pos.Y;
}
_gfxState.RealizedTextPosition = posSave;
}
/// <summary>
/// Makes the specified image to the current graphics object.
/// </summary>
string Realize(XImage image)
{
BeginPage();
BeginGraphicMode();
RealizeTransform();
// The transparency set for a brush also applies to images. Set opacity to 100% so image will be drawn without transparency.
_gfxState.RealizeNonStrokeTransparency(1, _colorMode);
return image is XForm form ? GetFormName(form) : GetImageName(image);
}
/// <summary>
/// Realizes the current transformation matrix, if necessary.
/// </summary>
void RealizeTransform()
{
BeginPage();
if (_gfxState.Level == GraphicsStackLevelPageSpace)
{
BeginGraphicMode();
SaveState();
}
//if (gfxState.MustRealizeCtm)
if (!_gfxState.UnrealizedCtm.IsIdentity)
{
BeginGraphicMode();
_gfxState.RealizeCtm();
}
}
/// <summary>
/// Convert a point from Windows world space to PDF world space.
/// </summary>
internal XPoint WorldToView(XPoint point)
{
// If EffectiveCtm is not yet realized InverseEffectiveCtm is invalid.
Debug.Assert(_gfxState.UnrealizedCtm.IsIdentity, "Somewhere a RealizeTransform is missing.");
#if true
// See in #else case why this is correct.
XPoint pt = _gfxState.WorldTransform.Transform(point);
return _gfxState.InverseEffectiveCtm.Transform(new XPoint(pt.X, PageHeightPt / DefaultViewMatrix.M22 - pt.Y));
#else
// Get inverted PDF world transform matrix.
XMatrix invers = _gfxState.EffectiveCtm;
invers.Invert();
// Apply transform in Windows world space.
XPoint pt1 = _gfxState.WorldTransform.Transform(point);
#if true
// Do the transformation (see #else case) in one step.
XPoint pt2 = new XPoint(pt1.X, PageHeightPt / DefaultViewMatrix.M22 - pt1.Y);
#else
// Replicable version
// Apply default transformation.
pt1.X = pt1.X * DefaultViewMatrix.M11;
pt1.Y = pt1.Y * DefaultViewMatrix.M22;
// Convert from Windows space to PDF space.
XPoint pt2 = new XPoint(pt1.X, PageHeightPt - pt1.Y);
pt2.X = pt2.X / DefaultViewMatrix.M11;
pt2.Y = pt2.Y / DefaultViewMatrix.M22;
#endif
XPoint pt3 = invers.Transform(pt2);
return pt3;
#endif
}
#endregion
#if GDI
[Conditional("DEBUG")]
void DumpPathData(PathData pathData)
{
XPoint[] points = new XPoint[pathData.Points.Length];
for (int i = 0; i < points.Length; i++)
points[i] = new XPoint(pathData.Points[i].X, pathData.Points[i].Y);
DumpPathData(points, pathData.Types);
}
#endif
#if CORE || GDI
[Conditional("DEBUG")]
void DumpPathData(XPoint[] points, byte[] types)
{
int count = points.Length;
for (int idx = 0; idx < count; idx++)
{
string info = PDFEncoders.Format("{0:X} {1:####0.000} {2:####0.000}", types[idx], points[idx].X, points[idx].Y);
Debug.WriteLine(info, "PathData");
}
}
#endif
/// <summary>
/// Gets the owning PDFDocument of this page or form.
/// </summary>
internal PDFDocument Owner => _page != null ? _page.Owner : _form.Owner;
internal XGraphics Gfx { get; private set; }
/// <summary>
/// Gets the PDFResources of this page or form.
/// </summary>
internal PDFResources Resources => _page != null ? _page.Resources : _form.Resources;
/// <summary>
/// Gets the size of this page or form.
/// </summary>
internal XSize Size => _page != null ? new XSize(_page.Width, _page.Height) : _form.Size;
/// <summary>
/// Gets the resource name of the specified font within this page or form.
/// </summary>
internal string GetFontName(XFont font, out PDFFont pdfFont) => _page != null ? _page.GetFontName(font, out pdfFont) : _form.GetFontName(font, out pdfFont);
/// <summary>
/// Gets the resource name of the specified image within this page or form.
/// </summary>
internal string GetImageName(XImage image) => _page != null ? _page.GetImageName(image) : _form.GetImageName(image);
/// <summary>
/// Gets the resource name of the specified form within this page or form.
/// </summary>
internal string GetFormName(XForm form) => _page != null ? _page.GetFormName(form) : _form.GetFormName(form);
internal PDFPage _page;
internal XForm _form;
internal PDFColorMode _colorMode;
readonly StringBuilder _content;
/// <summary>
/// The q/Q nesting level is 0.
/// </summary>
const int GraphicsStackLevelInitial = 0;
/// <summary>
/// The q/Q nesting level is 1.
/// </summary>
const int GraphicsStackLevelPageSpace = 1;
/// <summary>
/// The q/Q nesting level is 2.
/// </summary>
const int GraphicsStackLevelWorldSpace = 2;
#region PDF Graphics State
/// <summary>
/// Saves the current graphical state.
/// </summary>
void SaveState()
{
Debug.Assert(_streamMode == StreamMode.Graphic, "Cannot save state in text mode.");
_gfxStateStack.Push(_gfxState);
_gfxState = _gfxState.Clone();
_gfxState.Level = _gfxStateStack.Count;
Append("q\n");
}
/// <summary>
/// Restores the previous graphical state.
/// </summary>
void RestoreState()
{
Debug.Assert(_streamMode == StreamMode.Graphic, "Cannot restore state in text mode.");
_gfxState = _gfxStateStack.Pop();
Append("Q\n");
}
PDFGraphicsState RestoreState(InternalGraphicsState state)
{
int count = 1;
PDFGraphicsState top = _gfxStateStack.Pop();
while (top.InternalState != state)
{
Append("Q\n");
count++;
top = _gfxStateStack.Pop();
}
Append("Q\n");
_gfxState = top;
return top;
}
/// <summary>
/// The current graphical state.
/// </summary>
PDFGraphicsState _gfxState;
/// <summary>
/// The graphical state stack.
/// </summary>
readonly Stack<PDFGraphicsState> _gfxStateStack = new Stack<PDFGraphicsState>();
#endregion
/// <summary>
/// The height of the PDF page in point including the trim box.
/// </summary>
public double PageHeightPt;
/// <summary>
/// The final transformation from the world space to the default page space.
/// </summary>
public XMatrix DefaultViewMatrix;
}
} | 44.74389 | 2,048 | 0.501155 | [
"MIT"
] | RefactorForce/PDFSharp | PDFSharp/Drawing/PDF/XGraphicsPDFRenderer.cs | 88,074 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
namespace System.Net.Mime
{
/// <summary>
/// This stream performs in-place decoding of quoted-printable
/// encoded streams. Encoding requires copying into a separate
/// buffer as the data being encoded will most likely grow.
/// Encoding and decoding is done transparently to the caller.
///
/// This stream should only be used for the e-mail content.
/// Use QEncodedStream for encoding headers.
/// </summary>
internal class QuotedPrintableStream : DelegatedStream, IEncodableStream
{
//should we encode CRLF or not?
private bool _encodeCRLF;
//number of bytes needed for a soft CRLF in folding
private const int SizeOfSoftCRLF = 3;
//each encoded byte occupies three bytes when encoded
private const int SizeOfEncodedChar = 3;
//it takes six bytes to encode a CRLF character (a CRLF that does not indicate folding)
private const int SizeOfEncodedCRLF = 6;
//if we aren't encoding CRLF then it occupies two chars
private const int SizeOfNonEncodedCRLF = 2;
private static readonly byte[] s_hexDecodeMap = new byte[]
{
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 2
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,255,255,255,255,255,255, // 3
255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 4
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 5
255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 6
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 7
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // F
};
private static readonly byte[] s_hexEncodeMap = new byte[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70 };
private int _lineLength;
private ReadStateInfo _readState;
private WriteStateInfoBase _writeState;
/// <summary>
/// ctor.
/// </summary>
/// <param name="stream">Underlying stream</param>
/// <param name="lineLength">Preferred maximum line-length for writes</param>
internal QuotedPrintableStream(Stream stream, int lineLength) : base(stream)
{
if (lineLength < 0)
{
throw new ArgumentOutOfRangeException(nameof(lineLength));
}
_lineLength = lineLength;
}
internal QuotedPrintableStream(Stream stream, bool encodeCRLF) : this(stream, EncodedStreamFactory.DefaultMaxLineLength)
{
_encodeCRLF = encodeCRLF;
}
private ReadStateInfo ReadState => _readState ?? (_readState = new ReadStateInfo());
internal WriteStateInfoBase WriteState => _writeState ?? (_writeState = new WriteStateInfoBase(1024, null, null, _lineLength));
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
WriteAsyncResult result = new WriteAsyncResult(this, buffer, offset, count, callback, state);
result.Write();
return result;
}
public override void Close()
{
FlushInternal();
base.Close();
}
public unsafe int DecodeBytes(byte[] buffer, int offset, int count)
{
fixed (byte* pBuffer = buffer)
{
byte* start = pBuffer + offset;
byte* source = start;
byte* dest = start;
byte* end = start + count;
// if the last read ended in a partially decoded
// sequence, pick up where we left off.
if (ReadState.IsEscaped)
{
// this will be -1 if the previous read ended
// with an escape character.
if (ReadState.Byte == -1)
{
// if we only read one byte from the underlying
// stream, we'll need to save the byte and
// ask for more.
if (count == 1)
{
ReadState.Byte = *source;
return 0;
}
// '=\r\n' means a soft (aka. invisible) CRLF sequence...
if (source[0] != '\r' || source[1] != '\n')
{
byte b1 = s_hexDecodeMap[source[0]];
byte b2 = s_hexDecodeMap[source[1]];
if (b1 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b1));
if (b2 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b2));
*dest++ = (byte)((b1 << 4) + b2);
}
source += 2;
}
else
{
// '=\r\n' means a soft (aka. invisible) CRLF sequence...
if (ReadState.Byte != '\r' || *source != '\n')
{
byte b1 = s_hexDecodeMap[ReadState.Byte];
byte b2 = s_hexDecodeMap[*source];
if (b1 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b1));
if (b2 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b2));
*dest++ = (byte)((b1 << 4) + b2);
}
source++;
}
// reset state for next read.
ReadState.IsEscaped = false;
ReadState.Byte = -1;
}
// Here's where most of the decoding takes place.
// We'll loop around until we've inspected all the
// bytes read.
while (source < end)
{
// if the source is not an escape character, then
// just copy as-is.
if (*source != '=')
{
*dest++ = *source++;
}
else
{
// determine where we are relative to the end
// of the data. If we don't have enough data to
// decode the escape sequence, save off what we
// have and continue the decoding in the next
// read. Otherwise, decode the data and copy
// into dest.
switch (end - source)
{
case 2:
ReadState.Byte = source[1];
goto case 1;
case 1:
ReadState.IsEscaped = true;
goto EndWhile;
default:
if (source[1] != '\r' || source[2] != '\n')
{
byte b1 = s_hexDecodeMap[source[1]];
byte b2 = s_hexDecodeMap[source[2]];
if (b1 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b1));
if (b2 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b2));
*dest++ = (byte)((b1 << 4) + b2);
}
source += 3;
break;
}
}
}
EndWhile:
return (int)(dest - start);
}
}
public int EncodeBytes(byte[] buffer, int offset, int count)
{
int cur = offset;
for (; cur < count + offset; cur++)
{
//only fold if we're before a whitespace or if we're at the line limit
//add two to the encoded Byte Length to be conservative so that we guarantee that the line length is acceptable
if ((_lineLength != -1 && WriteState.CurrentLineLength + SizeOfEncodedChar + 2 >= _lineLength && (buffer[cur] == ' ' ||
buffer[cur] == '\t' || buffer[cur] == '\r' || buffer[cur] == '\n')) ||
_writeState.CurrentLineLength + SizeOfEncodedChar + 2 >= EncodedStreamFactory.DefaultMaxLineLength)
{
if (WriteState.Buffer.Length - WriteState.Length < SizeOfSoftCRLF)
{
return cur - offset; //ok because folding happens externally
}
WriteState.Append((byte)'=');
WriteState.AppendCRLF(false);
}
// We don't need to worry about RFC 2821 4.5.2 (encoding first dot on a line),
// it is done by the underlying 7BitStream
//detect a CRLF in the input and encode it.
if (buffer[cur] == '\r' && cur + 1 < count + offset && buffer[cur + 1] == '\n')
{
if (WriteState.Buffer.Length - WriteState.Length < (_encodeCRLF ? SizeOfEncodedCRLF : SizeOfNonEncodedCRLF))
{
return cur - offset;
}
cur++;
if (_encodeCRLF)
{
// The encoding for CRLF is =0D=0A
WriteState.Append((byte)'=', (byte)'0', (byte)'D', (byte)'=', (byte)'0', (byte)'A');
}
else
{
WriteState.AppendCRLF(false);
}
}
//ascii chars less than 32 (control chars) and greater than 126 (non-ascii) are not allowed so we have to encode
else if ((buffer[cur] < 32 && buffer[cur] != '\t') ||
buffer[cur] == '=' ||
buffer[cur] > 126)
{
if (WriteState.Buffer.Length - WriteState.Length < SizeOfSoftCRLF)
{
return cur - offset;
}
//append an = to indicate an encoded character
WriteState.Append((byte)'=');
//shift 4 to get the first four bytes only and look up the hex digit
WriteState.Append(s_hexEncodeMap[buffer[cur] >> 4]);
//clear the first four bytes to get the last four and look up the hex digit
WriteState.Append(s_hexEncodeMap[buffer[cur] & 0xF]);
}
else
{
if (WriteState.Buffer.Length - WriteState.Length < 1)
{
return cur - offset;
}
//detect special case: is whitespace at end of line? we must encode it if it is
if ((buffer[cur] == (byte)'\t' || buffer[cur] == (byte)' ') &&
(cur + 1 >= count + offset))
{
if (WriteState.Buffer.Length - WriteState.Length < SizeOfEncodedChar)
{
return cur - offset;
}
//append an = to indicate an encoded character
WriteState.Append((byte)'=');
//shift 4 to get the first four bytes only and look up the hex digit
WriteState.Append(s_hexEncodeMap[buffer[cur] >> 4]);
//clear the first four bytes to get the last four and look up the hex digit
WriteState.Append(s_hexEncodeMap[buffer[cur] & 0xF]);
}
else
{
WriteState.Append(buffer[cur]);
}
}
}
return cur - offset;
}
public Stream GetStream() => this;
public string GetEncodedString() => Encoding.ASCII.GetString(WriteState.Buffer, 0, WriteState.Length);
public override void EndWrite(IAsyncResult asyncResult) => WriteAsyncResult.End(asyncResult);
public override void Flush()
{
FlushInternal();
base.Flush();
}
private void FlushInternal()
{
if (_writeState != null && _writeState.Length > 0)
{
base.Write(WriteState.Buffer, 0, WriteState.Length);
WriteState.BufferFlushed();
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
int written = 0;
for (;;)
{
written += EncodeBytes(buffer, offset + written, count - written);
if (written < count)
{
FlushInternal();
}
else
{
break;
}
}
}
private sealed class ReadStateInfo
{
internal bool IsEscaped { get; set; }
internal short Byte { get; set; } = -1;
}
private sealed class WriteAsyncResult : LazyAsyncResult
{
private readonly QuotedPrintableStream _parent;
private readonly byte[] _buffer;
private readonly int _offset;
private readonly int _count;
private readonly static AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
private int _written;
internal WriteAsyncResult(QuotedPrintableStream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
_offset = offset;
_count = count;
}
private void CompleteWrite(IAsyncResult result)
{
_parent.BaseStream.EndWrite(result);
_parent.WriteState.BufferFlushed();
}
internal static void End(IAsyncResult result)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result;
thisPtr.InternalWaitForCompletion();
Debug.Assert(thisPtr._written == thisPtr._count);
}
private static void OnWrite(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
try
{
thisPtr.CompleteWrite(result);
thisPtr.Write();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
internal void Write()
{
for (;;)
{
_written += _parent.EncodeBytes(_buffer, _offset + _written, _count - _written);
if (_written < _count)
{
IAsyncResult result = _parent.BaseStream.BeginWrite(_parent.WriteState.Buffer, 0, _parent.WriteState.Length, s_onWrite, this);
if (!result.CompletedSynchronously)
break;
CompleteWrite(result);
}
else
{
InvokeCallback();
break;
}
}
}
}
}
}
| 41.49095 | 173 | 0.46093 | [
"MIT"
] | Roibal/corefx | src/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs | 18,339 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace NetEaseMusic_DiscordRPC.Win32Api
{
public class User32
{
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
private static extern IntPtr GetShellWindow();
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowRect(IntPtr hwnd, out RECT rc);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
private delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
private static extern void GetClassName(IntPtr hwnd, StringBuilder sb, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int pid);
private static string GetClassName(IntPtr hwnd)
{
var sb = new StringBuilder(256);
GetClassName(hwnd, sb, 256);
return sb.ToString();
}
private static string GetWindowTitle(IntPtr hwnd)
{
var length = GetWindowTextLength(hwnd);
var sb = new StringBuilder(256);
GetWindowText(hwnd, sb, length + 1);
return sb.ToString();
}
public static bool IsFullscreenAppRunning()
{
var desktopHandle = GetDesktopWindow();
var shellHandle = GetShellWindow();
var window = GetForegroundWindow();
if (window != IntPtr.Zero)
{
if (!(window.Equals(desktopHandle) || window.Equals(shellHandle)))
{
GetWindowRect(window, out var appBounds);
System.Drawing.Rectangle screenBounds = Screen.FromHandle(window).Bounds;
if ((appBounds.Bottom - appBounds.Top) == screenBounds.Height && (appBounds.Right - appBounds.Left) == screenBounds.Width && GetClassName(window)!= "OrpheusBrowserHost")
{
// In full screen.
return true;
}
}
}
return false;
}
private static string window_name = null;
public static bool IsWhitelistAppRunning()
{
// VisualStudioAppManagement
// VSCodeCrashServiceWindow
// Valve001
// UnrealWindow
// Rainbow Six
if (!File.Exists(Application.StartupPath + "\\whiteList.txt"))
{
// Config file doesn't exits...
return false;
}
using var sr = new StreamReader(Application.StartupPath + "\\whiteList.txt", Encoding.UTF8);
while ((window_name = sr.ReadLine()) != null)
{
// TrimString
window_name = window_name.Trim();
if (window_name.StartsWith("//") || window_name.Length < 3)
{
// ignore comments or spacer
continue;
}
if (window_name.EndsWith(".exe"))
{
return Process.GetProcessesByName(window_name.Replace(".exe", "")).Length > 0;
}
else
{
var window = FindWindow(window_name, null);
if (window != IntPtr.Zero)
{
Debug.WriteLine($"FindWindow {window_name}");
return true;
}
}
}
return false;
}
public static bool GetWindowTitle(string match, out string text, out int pid)
{
var title = string.Empty;
var processId = 0;
EnumWindows
(
delegate (IntPtr handle, int param)
{
var classname = GetClassName(handle);
if (match.Equals(classname) && GetWindowThreadProcessId(handle, out var xpid) != 0 && xpid != 0)
{
title = GetWindowTitle(handle);
processId = xpid;
}
return true;
},
IntPtr.Zero
);
text = title;
pid = processId;
return !string.IsNullOrEmpty(title) && pid > 0;
}
}
} | 32.792683 | 190 | 0.528077 | [
"MIT"
] | GaXyRay/NetEase-Cloud-Music-DiscordRPC | NetEaseMusic-DiscordRPC/win32Api.cs | 5,380 | C# |
/*
* Problem 7. Sum of 5 Numbers
* Write a program that enters 5 numbers (given in a single line, separated by a space), calculates and prints their sum.
*/
using System;
class SumOfFiveNumbers
{
static void Main()
{
Console.WriteLine("Please enter 5 numbers, separated by a space:");
string numbers = Console.ReadLine();
float[] splitNumbers = new float[5];
float sum = 0.0F;
for (int index = 0; index < 5; index++)
{
splitNumbers[index] = float.Parse(numbers.Split(' ')[index]);
sum = sum + splitNumbers[index];
}
Console.WriteLine("The sum of the 5 numbers is: {0:F2}", sum);
}
} | 28.708333 | 121 | 0.595065 | [
"MIT"
] | dimanov/Console-In-and-Out | SumOfFiveNumbers/FiveNumbers.cs | 691 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using GTTG.Core.Time;
using GTTG.Model.Model.Events;
using SZDC.Editor;
using SZDC.Editor.Interfaces;
using SZDC.Editor.TrainTimetables;
namespace SZDC.Wpf.TrainGraph {
/// <summary>
/// Interaction logic for DynamicTrainGraphWindow.xaml
/// </summary>
public partial class DynamicTrainGraphWindow : Window, IDynamicDataReceiver {
private CancellationTokenSource _cancellationTokenSource;
private DynamicTrainTimetable _dynamicTrainTimetable;
public ApplicationEditor ApplicationEditor { get; set; }
public DynamicTrainGraphWindow() {
InitializeComponent();
Loaded += OnLoaded;
Closed += OnClosed;
}
private void OnLoaded(object sender, RoutedEventArgs e) {
if (DataContext is DynamicTrainTimetable dynamicTrainTimetable && ApplicationEditor != null) {
_dynamicTrainTimetable = dynamicTrainTimetable;
var interval = ApplicationEditor.DynamicDataProvider.CurrentTimeInterval;
_dynamicTrainTimetable.UpdateDateTimeContext(new DateTimeContext(interval, interval));
_dynamicTrainTimetable.EventManagementService.ScheduleChanged += EventManagementServiceOnScheduleChanged;
ReceiverDescription = dynamicTrainTimetable.TimetableInfo.RailwaySegmentDetailedDescription;
ApplicationEditor.DynamicDataProvider.Register(this);
_cancellationTokenSource = new CancellationTokenSource();
var synchronizationContext = SynchronizationContext.Current;
Task.Factory.StartNew(() => {
while (!_cancellationTokenSource.IsCancellationRequested) {
Thread.Sleep(60 * 1000); // 1 minute
synchronizationContext.Send((state) => {
_dynamicTrainTimetable.UpdateDynamicContext();
}, null);
}
}, _cancellationTokenSource.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
}
private void EventManagementServiceOnScheduleChanged(int arg1, ImmutableList<TrainEvent> arg2) {
ApplicationEditor.DynamicDataProvider.Modify(arg1, arg2.ToImmutableArray());
}
private void OnClosed(object sender, EventArgs e) {
ApplicationEditor.DynamicDataProvider.RemoveReceiver(this);
_cancellationTokenSource?.Cancel();
}
public RailwaySegmentDetailedDescription ReceiverDescription { get; set; }
public void Update(DateTimeInterval contentInterval, Dictionary<int, (StaticTrainDescription, ImmutableArray<TrainEvent>)> schedules) {
_dynamicTrainTimetable.ChangeContentTimeInterval(contentInterval);
_dynamicTrainTimetable.ChangeTrafficView(schedules); // add / removes train views to match current schedules
}
public void Modify(int trainNumber, ImmutableArray<TrainEvent> schedule) {
_dynamicTrainTimetable.Modify(trainNumber, schedule);
}
}
}
| 39.904762 | 143 | 0.667959 | [
"MIT"
] | Sykoj/GTTG | solution/SZDC.WPF/TrainGraph/DynamicTrainGraphWindow.xaml.cs | 3,354 | C# |
namespace FrameworkTester.ViewModels.Interfaces
{
public interface IWinBioAsyncFrameworkViewModel
{
IHandleRepositoryViewModel<IFrameworkHandleViewModel> HandleRepository
{
get;
}
}
} | 17.785714 | 79 | 0.638554 | [
"MIT"
] | poseidonjm/WinBiometricDotNet | examples/FrameworkTester/ViewModels/Interfaces/IWinBioAsyncFrameworkViewModel.cs | 251 | C# |
namespace SharpVectors.Dom.Svg
{
/// <summary>
/// The SvgDefsElement interface corresponds to the 'defs' element.
/// </summary>
/// <developer>niklas@protocol7.com</developer>
/// <completed>99</completed>
public interface ISvgDefsElement : ISvgElement,
ISvgTests,
ISvgLangSpace,
ISvgExternalResourcesRequired,
ISvgStylable,
ISvgTransformable/*,
org.w3c.dom.events.IEventTarget*/
{
}
} | 24.058824 | 70 | 0.728606 | [
"BSD-3-Clause"
] | codebutler/savagesvg | src/SharpVectorBindings/SharpVectors/Dom/Svg/Document Structure/ISvgDefsElement.cs | 409 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.Outputs
{
[OutputType]
public sealed class AzureFirewallSkuResponse
{
/// <summary>
/// Name of an Azure Firewall SKU.
/// </summary>
public readonly string? Name;
/// <summary>
/// Tier of an Azure Firewall.
/// </summary>
public readonly string? Tier;
[OutputConstructor]
private AzureFirewallSkuResponse(
string? name,
string? tier)
{
Name = name;
Tier = tier;
}
}
}
| 24.138889 | 81 | 0.59954 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Network/Outputs/AzureFirewallSkuResponse.cs | 869 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text;
using System.Text.Tests;
using Xunit;
namespace System.Text.Encodings.Tests
{
public class EncodingVirtualTests
{
[Theory]
[MemberData(nameof(UTF8EncodingEncode.Encode_TestData), MemberType = typeof(UTF8EncodingEncode))]
public void Encode(string chars, int index, int count, byte[] expected) =>
EncodingHelpers.Encode(new CustomEncoding(), chars, index, count, expected);
[Theory]
[MemberData(nameof(UTF8EncodingDecode.Decode_TestData), MemberType = typeof(UTF8EncodingDecode))]
public void Decode(byte[] bytes, int index, int count, string expected) =>
EncodingHelpers.Decode(new CustomEncoding(), bytes, index, count, expected);
// Explicitly not overriding virtual methods to test their base implementations
private sealed class CustomEncoding : Encoding
{
private readonly Encoding _encoding = Encoding.UTF8;
public override int GetByteCount(char[] chars, int index, int count) =>
_encoding.GetByteCount(chars, index, count);
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) =>
_encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
public override int GetCharCount(byte[] bytes, int index, int count) =>
_encoding.GetCharCount(bytes, index, count);
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) =>
_encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
public override int GetMaxByteCount(int charCount) => throw new System.NotImplementedException();
public override int GetMaxCharCount(int byteCount) => throw new System.NotImplementedException();
}
}
}
| 45.191489 | 116 | 0.688795 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Text.Encoding/tests/Encoding/EncodingVirtualTests.cs | 2,124 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Voximplant.API.Response {
public class AddRuleResponse : BaseResponse
{
/// <summary>
/// 1
/// </summary>
[JsonProperty("result")]
public long Result { get; private set; }
/// <summary>
/// The new rule ID.
/// </summary>
[JsonProperty("rule_id")]
public long RuleId { get; private set; }
}
} | 21.363636 | 48 | 0.559574 | [
"MIT"
] | voximplant/apiclient-dotnet | apiclient/Response/AddRuleResponse.cs | 470 | C# |
using System;
class KnightGame
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
var board = new char[n][];
for (int i = 0; i < n; i++)
{
board[i] = Console.ReadLine().ToCharArray();
}
int maxAttacked = 0;
int maxRow = 0;
int maxColumn = 0;
int countOfRemovedKnights = 0;
do
{
if (maxAttacked > 0)
{
board[maxRow][maxColumn] = '0';
maxAttacked = 0;
countOfRemovedKnights++;
}
int currentAttacks = 0;
for (int row = 0; row < n; row++)
{
for (int column = 0; column < n; column++)
{
if (board[row][column] == 'K')
{
currentAttacks = CalculateAttacks(row, column, board);
if (currentAttacks > maxAttacked)
{
maxAttacked = currentAttacks;
maxRow = row;
maxColumn = column;
}
}
}
}
}
while (maxAttacked > 0);
Console.WriteLine(countOfRemovedKnights);
}
private static int CalculateAttacks(int row, int column, char[][] board)
{
int result = 0;
if (IsPositionAttacked(row - 2, column - 1, board)) result++;
if (IsPositionAttacked(row - 2, column + 1, board)) result++;
if (IsPositionAttacked(row - 1, column - 2, board)) result++;
if (IsPositionAttacked(row - 1, column + 2, board)) result++;
if (IsPositionAttacked(row + 1, column - 2, board)) result++;
if (IsPositionAttacked(row + 1, column + 2, board)) result++;
if (IsPositionAttacked(row + 2, column - 1, board)) result++;
if (IsPositionAttacked(row + 2, column + 1, board)) result++;
return result;
}
private static bool IsPositionAttacked(int row, int column, char[][] board)
{
return IsOnChessBoard(row, column, board[0].Length)
&& board[row][column] == 'K';
}
private static bool IsOnChessBoard(int row, int column, int n)
{
return (row >= 0 && row < n && column >= 0 && column < n);
}
} | 29.5875 | 79 | 0.472328 | [
"MIT"
] | markodjunev/Softuni | C#/C# Advanced/Multidimensional Arrays - Exercise/Knight Game/Knight Game.cs | 2,369 | C# |
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.CSharp.RowsColumns.Grouping
{
public class SummaryRowBelow
{
public static void Run()
{
// ExStart:1
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
Worksheet worksheet = workbook.Worksheets[0];
// Grouping first six rows and first three columns
worksheet.Cells.GroupRows(0, 5, true);
worksheet.Cells.GroupColumns(0, 2, true);
// Setting SummaryRowBelow property to false
worksheet.Outline.SummaryRowBelow = false;
// Saving the modified Excel file
workbook.Save(dataDir + "output.xls");
// ExEnd:1
}
}
}
| 30.866667 | 115 | 0.614471 | [
"MIT"
] | Aspose/Aspose.Cells-for-.NET | Examples/CSharp/RowsColumns/Grouping/SummaryRowBelow.cs | 926 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.