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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using System;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace Dox2Word.Generator
{
public class StyleManager
{
public const string TableStyleId = "DoxTable";
public const string ParameterTableStyleId = "DoxParameterTable";
public const string MiniHeadingStyleId = "DoxMiniHeading";
public const string ParHeadingStyleId = "DoxParHeading";
public const string CodeListingStyleId = "DoxCodeListing";
public const string CodeStyleId = "DoxCode";
public const string CodeCharStyleId = "DoxCodeChar";
public const string WarningStyleId = "DoxWarning";
public const string NoteStyleId = "DoxNote";
public const string BlockQuoteStyleId = "DoxBlockQuote";
public const string DefinitionTermStyleId = "DoxDefinitionTerm";
public const string HyperlinkStyleId = "Hyperlink";
public const string CaptionStyleId = "Caption";
public const string ListParagraphStyleId = "ListParagraph";
private readonly StyleDefinitionsPart stylesPart;
public int DefaultFontSize { get; }
public StyleManager(StyleDefinitionsPart stylesPart)
{
this.stylesPart = stylesPart;
this.DefaultFontSize = this.stylesPart.Styles!.DocDefaults?.RunPropertiesDefault?.RunPropertiesBaseStyle?.FontSize is { } size
? int.Parse(size.Val)
: 22;
}
public void EnsureStyles()
{
this.AddIfNotExists(TableStyleId, StyleValues.Table, "DoxTableStyle.xml");
this.AddIfNotExists(ParameterTableStyleId, StyleValues.Table, "Dox Parameter Table", style =>
{
style.BasedOn = new BasedOn() { Val = "TableNormal" };
style.StyleTableProperties = new StyleTableProperties()
{
TableBorders = new TableBorders()
{
TopBorder = new TopBorder() { Val = BorderValues.Single, Color = "999999", },
LeftBorder = new LeftBorder() { Val = BorderValues.Single, Color = "999999", },
BottomBorder = new BottomBorder() { Val = BorderValues.Single, Color = "999999", },
RightBorder = new RightBorder() { Val = BorderValues.Single, Color = "999999", },
InsideHorizontalBorder = new InsideHorizontalBorder() { Val = BorderValues.Dotted, Color = "999999", },
InsideVerticalBorder = new InsideVerticalBorder() { Val = BorderValues.Dotted, Color = "999999", },
}
};
});
this.AddIfNotExists(MiniHeadingStyleId, StyleValues.Paragraph, "Dox Mini Heading", style =>
{
style.BasedOn = new BasedOn() { Val = "Normal" };
style.PrimaryStyle = new PrimaryStyle();
style.StyleRunProperties = new StyleRunProperties()
{
Bold = new Bold(),
FontSize = new FontSize() { Val = (this.DefaultFontSize + 2).ToString() },
};
style.StyleParagraphProperties = new StyleParagraphProperties()
{
SpacingBetweenLines = new SpacingBetweenLines()
{
LineRule = LineSpacingRuleValues.Auto,
Before = "160",
Line = "240",
},
KeepNext = new KeepNext(),
};
});
this.AddIfNotExists(ParHeadingStyleId, StyleValues.Paragraph, "Dox Par Heading", style =>
{
style.BasedOn = new BasedOn() { Val = "Normal" };
style.PrimaryStyle = new PrimaryStyle();
style.StyleRunProperties = new StyleRunProperties()
{
Bold = new Bold(),
FontSize = new FontSize() { Val = (this.DefaultFontSize + 1).ToString() },
};
style.StyleParagraphProperties = new StyleParagraphProperties()
{
SpacingBetweenLines = new SpacingBetweenLines()
{
LineRule = LineSpacingRuleValues.Auto,
Before = "160",
Line = "240",
},
KeepNext = new KeepNext(),
};
});
this.AddIfNotExists(CodeCharStyleId, StyleValues.Character, "Dox Code Char", style =>
{
style.BasedOn = new BasedOn() { Val = "DefaultParagraphFont" };
style.LinkedStyle = new LinkedStyle() { Val = CodeStyleId };
style.StyleRunProperties = new StyleRunProperties()
{
FontSize = new FontSize() { Val = (this.DefaultFontSize - 2).ToString() },
RunFonts = new RunFonts() { Ascii = "Consolas" },
};
});
this.AddIfNotExists(CodeStyleId, StyleValues.Paragraph, "Dox Code", style =>
{
style.BasedOn = new BasedOn() { Val = "Normal" };
style.LinkedStyle = new LinkedStyle() { Val = CodeCharStyleId };
style.PrimaryStyle = new PrimaryStyle();
style.StyleParagraphProperties = new StyleParagraphProperties()
{
KeepNext = new KeepNext(),
KeepLines = new KeepLines(),
SpacingBetweenLines = new SpacingBetweenLines()
{
Line = "240",
LineRule = LineSpacingRuleValues.Auto,
},
ContextualSpacing = new ContextualSpacing(),
};
style.StyleRunProperties = new StyleRunProperties()
{
FontSize = new FontSize() { Val = (this.DefaultFontSize - 2).ToString() },
RunFonts = new RunFonts() { Ascii = "Consolas" },
};
});
this.AddIfNotExists(CodeListingStyleId, StyleValues.Paragraph, "Dox Code Listing", style =>
{
style.BasedOn = new BasedOn() { Val = CodeStyleId };
style.LinkedStyle = new LinkedStyle() { Val = CodeCharStyleId };
style.PrimaryStyle = new PrimaryStyle();
style.StyleParagraphProperties = new StyleParagraphProperties()
{
ParagraphBorders = new ParagraphBorders()
{
TopBorder = new TopBorder() { Val = BorderValues.Single },
LeftBorder = new LeftBorder() { Val = BorderValues.Single },
BottomBorder = new BottomBorder() { Val = BorderValues.Single },
RightBorder = new RightBorder() { Val = BorderValues.Single },
},
};
});
this.AddIfNotExists(WarningStyleId, StyleValues.Paragraph, "Dox Warning", style =>
{
style.BasedOn = new BasedOn() { Val = "Normal" };
style.PrimaryStyle = new PrimaryStyle();
style.StyleParagraphProperties = new StyleParagraphProperties()
{
ParagraphBorders = new ParagraphBorders(new LeftBorder()
{
Val = BorderValues.Single,
Space = 4,
Size = 18,
Color = "FF0000",
}),
};
});
this.AddIfNotExists(NoteStyleId, StyleValues.Paragraph, "Dox Note", style =>
{
style.BasedOn = new BasedOn() { Val = "Normal" };
style.PrimaryStyle = new PrimaryStyle();
style.StyleParagraphProperties = new StyleParagraphProperties()
{
ParagraphBorders = new ParagraphBorders(new LeftBorder()
{
Val = BorderValues.Single,
Space = 4,
Size = 18,
Color = "D0C000",
}),
};
});
this.AddIfNotExists(BlockQuoteStyleId, StyleValues.Paragraph, "Dox Block Quote", style =>
{
style.BasedOn = new BasedOn() { Val = "Normal" };
style.PrimaryStyle = new PrimaryStyle();
style.StyleParagraphProperties = new StyleParagraphProperties()
{
Indentation = new Indentation() { Left = "567" },
};
});
this.AddIfNotExists(DefinitionTermStyleId, StyleValues.Paragraph, "Dox Definition Term", style =>
{
style.BasedOn = new BasedOn() { Val = "Normal" };
style.PrimaryStyle = new PrimaryStyle();
style.StyleRunProperties = new StyleRunProperties()
{
Bold = new Bold(),
};
});
this.AddIfNotExists(HyperlinkStyleId, StyleValues.Character, "Hyperlink", style =>
{
style.BasedOn = new BasedOn() { Val = "DefaultParagraphFont" };
style.UnhideWhenUsed = new UnhideWhenUsed();
style.StyleRunProperties = new StyleRunProperties()
{
Color = new Color() { ThemeColor = ThemeColorValues.Hyperlink, Val = "0563C1" },
Underline = new Underline() { Val = UnderlineValues.Single },
};
});
this.AddIfNotExists(CaptionStyleId, StyleValues.Paragraph, "Caption", style =>
{
style.BasedOn = new BasedOn() { Val = "Normal" };
style.NextParagraphStyle = new NextParagraphStyle() { Val = "Normal" };
style.UnhideWhenUsed = new UnhideWhenUsed();
style.PrimaryStyle = new PrimaryStyle();
style.StyleParagraphProperties = new StyleParagraphProperties()
{
SpacingBetweenLines = new SpacingBetweenLines()
{
LineRule = LineSpacingRuleValues.Auto,
Line = "240",
After = "200",
},
};
style.StyleRunProperties = new StyleRunProperties()
{
Italic = new Italic(),
ItalicComplexScript = new ItalicComplexScript(),
Color = new Color() { Val = "44546A", ThemeColor = ThemeColorValues.Text2 },
FontSize = new FontSize() { Val = "18" },
FontSizeComplexScript = new FontSizeComplexScript() { Val = "18" },
};
});
this.AddIfNotExists(ListParagraphStyleId, StyleValues.Paragraph, "List Paragraph", style =>
{
// In order to get list items next to each other, but still have space under the list, we
// apply the same style to each, and set "Don't add space between paragraphs of the same style"
// (ContextualSpacing). Since we apply the same style to each, this works. This is what Word does: if
// the document already has a list, Word will have inserted this style; if not, we need to do it
// ourselves.
style.BasedOn = new BasedOn() { Val = "Normal" };
style.StyleParagraphProperties = new StyleParagraphProperties()
{
ContextualSpacing = new ContextualSpacing(),
};
});
}
public bool HasStyleWithId(string styleId)
{
return this.stylesPart.Styles!.Elements<Style>().Any(x => x.StyleId == styleId);
}
public void AddListStyle(string styleId, string styleName, int numId)
{
if (!this.HasStyleWithId(styleId))
{
this.stylesPart.Styles!.AppendChild(new Style()
{
StyleId = styleId,
StyleName = new StyleName() { Val = styleName },
Type = StyleValues.Numbering,
CustomStyle = true,
StyleParagraphProperties = new StyleParagraphProperties()
{
NumberingProperties = new NumberingProperties()
{
NumberingId = new NumberingId() { Val = numId },
},
},
});
}
}
private void AddIfNotExists(string styleId, StyleValues styleType, string filename)
{
if (!this.HasStyleWithId(styleId))
{
var style = this.stylesPart.Styles!.AppendChild(new Style()
{
StyleId = styleId,
Type = styleType,
CustomStyle = true,
});
using var sr = new StreamReader(typeof(StyleManager).Assembly.GetManifestResourceStream($"Dox2Word.Generator.{filename}"));
style.InnerXml = sr.ReadToEnd();
}
}
private void AddIfNotExists(string styleId, StyleValues styleType, string styleName, Action<Style> configurer)
{
if (!this.HasStyleWithId(styleId))
{
var style = this.stylesPart.Styles!.AppendChild(new Style()
{
StyleId = styleId,
StyleName = new StyleName() { Val = styleName },
Type = styleType,
CustomStyle = true,
});
configurer(style);
}
}
}
}
| 44.894569 | 139 | 0.507259 | [
"MIT"
] | canton7/Dox2Word | src/Generator/StyleManager.cs | 14,054 | C# |
using Ankh_Morpork_game.Abstract;
using System.ComponentModel.DataAnnotations;
namespace Ankh_Morpork_webapp_MVC.Models
{
public class Assassin : INPC
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public decimal MinReward { get; set; }
public decimal MaxReward { get; set; }
public bool IsOccupied { get; set; }
public string ImageUrl { get; set; }
public static void Kill(Player player)
{
player.IsAlive = false;
}
}
} | 26.454545 | 46 | 0.603093 | [
"Apache-2.0"
] | Mykhailo-Kholm/Ankh-Morpork | Ankh-Morpork-webapp-MVC/Ankh-Morpork-webapp-MVC/Models/Assassin.cs | 584 | C# |
namespace ProviderPayments.TestStack.Core.Workflow.Common
{
internal abstract class DataLockEventsTaskBase : RunExternalTask
{
private const string AssemblyName = "SFA.DAS.Provider.Events.DataLock";
private const string TypeName = "SFA.DAS.Provider.Events.DataLock.DataLockEventsTask";
protected DataLockEventsTaskBase(ILogger logger)
: base(ComponentType.DataLockEvents, AssemblyName, TypeName, logger)
{
}
protected override string[] GetOrderedSqlFiles(string sqlDirectory)
{
var orderedSqlFiles = base.GetOrderedSqlFiles(sqlDirectory);
return FilterOrderedSqlFiles(orderedSqlFiles);
}
protected abstract string[] FilterOrderedSqlFiles(string[] orderedSqlFiles);
}
}
| 36.045455 | 94 | 0.704918 | [
"MIT"
] | SkillsFundingAgency/das-providerpayments | src/AcceptanceTesting/Common/ProviderPayments.TestStack.Core/Workflow/Common/DataLockEventsTaskBase.cs | 795 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Blog.Models
{
public class Article
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Title { get; set; }
[Required]
public string Content { get; set; }
[ForeignKey("Author")]
public string AuthorId { get; set; }
public virtual ApplicationUser Author { get; set; }
public bool IsAuthor (string name)
{
return this.Author.UserName.Equals(name);
}
}
} | 22.03125 | 59 | 0.615603 | [
"MIT"
] | msotiroff/Softuni-learning | Tech Module/Software Technologies/C#/Blog Basic Functionality/Blog/Models/Article.cs | 707 | C# |
public sealed class TupleFormatter<T1> : IMessagePackFormatter<Tuple<T1>>, IMessagePackFormatter // TypeDefIndex: 5501
{
// Methods
// RVA: -1 Offset: -1 Slot: 4
public void Serialize(ref MessagePackWriter writer, Tuple<T1> value, MessagePackSerializerOptions options) { }
/* GenericInstMethod :
|
|-RVA: 0x28648D0 Offset: 0x28649D1 VA: 0x28648D0
|-TupleFormatter<object>.Serialize
*/
// RVA: -1 Offset: -1 Slot: 5
public Tuple<T1> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { }
/* GenericInstMethod :
|
|-RVA: 0x2864A50 Offset: 0x2864B51 VA: 0x2864A50
|-TupleFormatter<object>.Deserialize
*/
// RVA: -1 Offset: -1
public void .ctor() { }
/* GenericInstMethod :
|
|-RVA: 0x2864D10 Offset: 0x2864E11 VA: 0x2864D10
|-TupleFormatter<object>..ctor
*/
}
| 27.066667 | 118 | 0.724138 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | MessagePack/Formatters/TupleFormatter--T1--.cs | 812 | C# |
using System.ComponentModel.DataAnnotations;
namespace Furiza.AspNetCore.WebApp.Configuration
{
public class ReCaptchaConfiguration
{
[Required]
public string SiteKey { get; set; }
[Required]
public string SecretKey { get; set; }
}
} | 21.538462 | 48 | 0.660714 | [
"MIT"
] | ivanborges/furiza-aspnetcore-webapp | src/Furiza.AspNetCore.WebApp.Configuration/reCaptchaConfiguration.cs | 282 | C# |
using System;
public interface ILogger
{
void Log(string message);
public void Log(Exception ex) => Log(ex.Message);
}
| 16.125 | 53 | 0.689922 | [
"MIT"
] | CyMadigan/ProfessionalCSharp2021 | 1_CS/ObjectOrientation/DefaultInterfaceMethods/ILogger.cs | 131 | C# |
// Modified by SignalFx
using System;
using SignalFx.Tracing.Configuration;
using SignalFx.Tracing.Propagation;
using SignalFx.Tracing.Sampling;
namespace SignalFx.Tracing
{
internal interface ISignalFxTracer
{
string DefaultServiceName { get; }
IScopeManager ScopeManager { get; }
ISampler Sampler { get; }
IPropagator Propagator { get; }
TracerSettings Settings { get; }
Span StartSpan(string operationName);
Span StartSpan(string operationName, ISpanContext parent);
Span StartSpan(string operationName, ISpanContext parent, string serviceName, DateTimeOffset? startTime, bool ignoreActiveScope, ulong? spanId);
void Write(Span[] span);
/// <summary>
/// Make a span the active span and return its new scope.
/// </summary>
/// <param name="span">The span to activate.</param>
/// <returns>A Scope object wrapping this span.</returns>
Scope ActivateSpan(Span span);
/// <summary>
/// Make a span the active span and return its new scope.
/// </summary>
/// <param name="span">The span to activate.</param>
/// <param name="finishOnClose">Determines whether closing the returned scope will also finish the span.</param>
/// <returns>A Scope object wrapping this span.</returns>
Scope ActivateSpan(Span span, bool finishOnClose);
}
}
| 31.866667 | 152 | 0.656206 | [
"Apache-2.0"
] | AJJLVizio/signalfx-dotnet-tracing | src/Datadog.Trace/ISignalFxTracer.cs | 1,434 | C# |
namespace Newtonsoft.Json
{
public enum JsonToken
{
None,
StartObject,
StartArray,
StartConstructor,
PropertyName,
Comment,
Raw,
Integer,
Float,
String,
Boolean,
Null,
Undefined,
EndObject,
EndArray,
EndConstructor,
Date,
Bytes
}
}
| 10.84 | 25 | 0.675277 | [
"MIT"
] | HuyTruong19x/DDTank4.1 | Source Server/SourceQuest4.5/Newtonsoft.Json/Newtonsoft.Json/JsonToken.cs | 271 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataSift
{
internal class Messages
{
internal const string INVALID_APIKEY = "API key should be a 32 character string of lower-case letters and numbers";
internal const string INVALID_STREAM_HASH = "Hash should be a 32 character string of lower-case letters and numbers";
internal const string INVALID_RECORDING_ID = "ID should be a 40 character string of lower-case letters and numbers";
internal const string INVALID_TASK_ID = "ID should be a 40 character string of lower-case letters and numbers";
internal const string INVALID_IDENTITY_ID = "ID should be a 32 character string of lower-case letters and numbers";
internal const string INVALID_SUBSCRIPTION_ID = "Subscription ID should be a 32 character string of lower-case letters and numbers";
internal const string INVALID_CURSOR = "Cursor should be a 32 character string of lower-case letters and numbers";
internal const string INVALID_HISTORICS_ID = "Historics ID should be a 20 character string of lower-case letters and numbers";
internal const string INVALID_HISTORICS_PREVIEW_ID = "Preview ID should be a 32 character string of lower-case letters and numbers";
internal const string INVALID_SOURCE_ID = "Source ID should be a 32 character string of lower-case letters and numbers";
internal const string INVALID_LIST_ID = "List ID is not in the correct format";
internal const string INVALID_COUNT = "Count value must be between 10 and 100";
internal const string HISTORICS_END_TOO_LATE = "End must be at least one hour ago";
internal const string HISTORICS_START_TOO_LATE = "Start must be at least two hours ago";
internal const string HISTORICS_START_TOO_EARLY = "Start cannot be before 2010";
internal const string HISTORICS_START_MUST_BE_BEFORE_END = "Start date must be before end date";
internal const string HISTORICS_END_CANNOT_BE_IN_FUTURE = "End cannot be in the future";
internal const string PUSH_MUST_PROVIDE_HASH_OR_HISTORIC = "You must provide either a hash or historicsId";
internal const string PUSH_ONLY_HASH_OR_HISTORIC = "You cannot specify both a hash AND historicsId";
internal const string UNRECOGNISED_DATA_FORMAT = "Unrecognised serialization format for data";
internal const string ANALYSIS_START_TOO_LATE = "Start cannot be in the future";
internal const string ANALYSIS_END_TOO_LATE = "End cannot be in the future";
internal const string ANALYSIS_START_MUST_BE_BEFORE_END = "Start date must be before end date";
}
}
| 68.375 | 140 | 0.755759 | [
"MIT"
] | datasift/datasift-dotnet | DataSift/Messages.cs | 2,737 | C# |
using System;
using System.Collections.Generic;
using Terraria.ModLoader;
namespace Terraria.ModLoader.Default
{
public class MysteryTile : ModTile
{
public override void SetDefaults()
{
Main.tileSolid[Type] = true;
Main.tileFrameImportant[Type] = true;
}
}
}
| 17.25 | 40 | 0.73913 | [
"MIT"
] | BloodARG/tModLoaderTShock | patches/tModLoader/Terraria.ModLoader.Default/MysteryTile.cs | 276 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace garagebot.alert
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.586207 | 70 | 0.656334 | [
"MIT"
] | devsgarage/garagebot.next | garagebot.alert/Program.cs | 742 | C# |
//BY FHIZ
//MODIFIED BY DX4D
//using OpenMMO;
//using OpenMMO.Zones;
//using System.Diagnostics;
//using OpenMMO.Debugging;
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using Mirror;
using OpenMMO.Network;
using OpenMMO.Database;
using OpenMMO.UI;
namespace OpenMMO.Zones
{
// ===================================================================================
// ZoneManager
// ===================================================================================
//[RequireComponent(typeof(OpenMMO.Network.NetworkManager))]
//[RequireComponent(typeof(Mirror.TelepathyTransport))]
[DisallowMultipleComponent]
public partial class ZoneManager : MonoBehaviour
{
const int DEFAULT_PORT = 9999;
[Header("ZONE OPTIONS")]
public bool active;
[Header("ZONE LAUNCHER")]
public ZoneServerProcessLauncher zoneLauncher;
[Header("ZONE CONFIG")]
public ZoneConfigTemplate zoneConfig;
[Header("MIRROR COMPONENTS")]
[SerializeField] protected Network.NetworkManager networkManager;
[SerializeField] protected Transport networkTransport;
//[Header("Debug Helper")]
//public DebugHelper debug = new DebugHelper(); //REMOVED DX4D
// -------------------------------------------------------------------------------
public static ZoneManager singleton;
protected ushort originalPort;
protected int zoneIndex = -1;
protected int securityToken = 0;
protected NetworkZoneTemplate currentZone = null;
protected string mainZoneName = "_mainZone";
protected const string argZoneIndex = "-zone";
protected string autoPlayerName = "";
protected bool autoConnectClient = false;
protected bool subZonesHaveBeenLaunched = false;
// -------------------------------------------------------------------------------
// Awake
// -------------------------------------------------------------------------------
void Awake()
{
singleton = this;
networkManager = null; //RESET COMPONENT
networkTransport = null; //RESET COMPONENT
//if (!networkManager) networkManager = FindObjectOfType<Network.NetworkManager>();
OnValidate(); //LOADS MISSING COMPONENTS (The ones we just reset)
originalPort = GetTransportPort();
//originalPort = networkTransport.port; //REPLACED - DX4D
SceneManager.sceneLoaded += OnSceneLoaded;
//if (!active || GetIsMainZone || !GetCanSwitchZone) //REMOVED - GetCanSwitchZone already checks active - DX4D
if (GetIsMainZone || !GetCanSwitchZone)
{
currentZone = zoneConfig.mainZone;
//debug.LogFormat(this.name, nameof(Awake), "mainZone"); //DEBUG //REMOVED DX4D
return;
}
currentZone = zoneConfig.subZones[zoneIndex];
foreach (NetworkZoneTemplate template in zoneConfig.subZones)
{
if (template == currentZone)
{
InitAsSubZone(template);
}
}
}
private void OnValidate()
{
//ZONE CONFIG
if (!zoneConfig) zoneConfig = Resources.Load<ZoneConfigTemplate>("ZoneConfig/DefaultZoneConfig");
//ZONE LAUNCHER
if (!zoneLauncher) zoneLauncher = Resources.Load<ZoneServerProcessLauncher>("System/DefaultZoneServerProcessLauncher");
//NETWORK MANAGER
if (!networkManager) networkManager = GetComponent<Network.NetworkManager>();
if (!networkManager) networkManager = FindObjectOfType<Network.NetworkManager>();
//KCP
if (!networkTransport) networkTransport = GetComponent<kcp2k.KcpTransport>();
if (!networkTransport) networkTransport = FindObjectOfType<kcp2k.KcpTransport>();
//TELEPATHY
if (!networkTransport) networkTransport = GetComponent<TelepathyTransport>();
if (!networkTransport) networkTransport = FindObjectOfType<TelepathyTransport>();
}
// ============================== GETTERS ========================================
//GET TRANSPORT PORT
//@SERVER
ushort GetTransportPort()
{
//KCP TRANSPORT - GET PORT
if (networkTransport is kcp2k.KcpTransport)
{
return (networkTransport as kcp2k.KcpTransport).Port;
}
//TELEPATHY TRANSPORT - GET PORT
if (networkTransport is TelepathyTransport)
{
return (networkTransport as TelepathyTransport).port;
}
return DEFAULT_PORT; //NO TRANSPORTS - USE DEFAULT PORT
}
//UPDATE TRANSPORT PORT
//@SERVER @CLIENT
void UpdateTransportPort(ushort newPort)
{
const string SPACER = " - ";
string TRANSPORT = "[UNDEFINED TRANSPORT] - [ZONES]";
#if _CLIENT
const string HEADER = "<b>[<color=green>CLIENT STARTUP</color>] - [ZONES]</b>";
#elif _SERVER
const string HEADER = "[SERVER STARTUP] - [ZONES]";
#else
const string HEADER = "[STANDALONE STARTUP] - [ZONES]";
#endif
UnityEngine.Debug.Log(HEADER + SPACER
+ "Assigning port " + newPort + " to " + networkTransport.name + "...");
//KCP TRANSPORT
if (networkTransport is kcp2k.KcpTransport)
{
TRANSPORT = "[KCP Transport]";
(networkTransport as kcp2k.KcpTransport).Port = newPort;
}
//TELEPATHY TRANSPORT
else if (networkTransport is TelepathyTransport)
{
TRANSPORT = "[Telepathy Transport]";
(networkTransport as TelepathyTransport).port = newPort;
}
UnityEngine.Debug.Log(HEADER + SPACER + TRANSPORT + SPACER
+ "Port set to " + newPort + "!");
//TODO: ADD MORE TRANSPORTS
//TODO: There should be a better way to do this...
}
// -------------------------------------------------------------------------------
// GetIsMainZone
// -------------------------------------------------------------------------------
public bool GetIsMainZone
{
get
{
if (zoneIndex == -1)
zoneIndex = Tools.GetArgumentInt(argZoneIndex);
return (zoneIndex == -1);
}
}
// -------------------------------------------------------------------------------
// GetZonePort
// -------------------------------------------------------------------------------
public ushort GetZonePort
{
get
{
return (ushort)(originalPort + zoneIndex + 1);
}
}
// -------------------------------------------------------------------------------
// GetAutoConnect
// -------------------------------------------------------------------------------
public bool GetAutoConnect
{
get
{
return autoConnectClient || !String.IsNullOrWhiteSpace(autoPlayerName);
}
}
// -------------------------------------------------------------------------------
// GetCanSwitchZone
// -------------------------------------------------------------------------------
public bool GetCanSwitchZone
{
get
{
if (ServerConfigTemplate.singleton.GetNetworkType == NetworkType.HostAndPlay)
{
return false;
}
return active;
}
}
// -------------------------------------------------------------------------------
// GetToken
// Fetches the current token or generates a new one if its 0.
// -------------------------------------------------------------------------------
public int GetToken
{
get
{
return securityToken;
}
}
// -------------------------------------------------------------------------------
// GetSubZoneTimeoutInterval
// -------------------------------------------------------------------------------
protected float GetSubZoneTimeoutInterval
{
get {
return zoneConfig.zoneSaveInterval * currentZone.zoneTimeoutMultiplier;
}
}
// ================================ OTHER PUBLIC =================================
// -------------------------------------------------------------------------------
// RefreshToken
// Generates a new security token for server switch.
//@CLIENT
public void RefreshToken()
{
securityToken = UnityEngine.Random.Range(1000,9999);
#if _SERVER && _CLIENT
Debug.Log("[ZONE HOST] - " + "Generated Security Token #" + securityToken);
#elif _SERVER
Debug.Log("[ZONE SERVER] - " + "Generated Security Token #" + securityToken);
#elif _CLIENT
Debug.Log("[ZONE CLIENT] - " + "Generated Security Token #" + securityToken);
#endif
}
// =========================== MAIN METHODS ======================================
// -------------------------------------------------------------------------------
// InitAsSubZone
//@SERVER
// -------------------------------------------------------------------------------
/// <summary>Initializes the sub-zone in a new server instance.</summary>
/// <param name="_template">The NetworkZoneTemplate that holds the Server info for this zone</param>
protected void InitAsSubZone(NetworkZoneTemplate _template)
{
//UPDATE TRANSPORTS
UpdateTransportPort(GetZonePort);
//networkTransport.port = GetZonePort; //REPLACED - DX4D
networkManager.networkAddress = _template.server.ip;
networkManager.onlineScene = _template.scene.SceneName;
UnityEngine.Debug.Log("[ZONE SERVER STARTUP] - "
+ "Loading Zone " + _template.title + " @" + _template.server.ip + "...");
networkManager.StartServer();
UnityEngine.Debug.Log("[ZONE SERVER STARTUP] - "
+ "Successfully Loaded Zone " + _template.title + " @" + _template.server.ip + "!!!");
//debug.LogFormat(this.name, nameof(InitAsSubZone), _template.name); //DEBUG //REMOVED DX4D
}
//LAUNCH ZONE SERVERS
// @SERVER
/// <summary>Utilizes <see cref="zoneLauncher"/> -
/// References <see cref="zoneConfig"/> -
/// Launches multiple instances of the server executable to handle each sub-zone
/// </summary>
public void LaunchZoneServers()
{
//DebugManager.Log(">>>>spawn subzones"); //REMOVED DX4D
if (!GetIsMainZone || !GetCanSwitchZone || subZonesHaveBeenLaunched) return;
//LAUNCH MAIN ZONE SAVE ROUTINE
LaunchZoneSaveRoutine(); //LAUNCH SAVE ROUTINE
//SEARCH ZONE CONFIG FOR ZONES TO LAUNCH
for (int i = 0; i < zoneConfig.subZones.Count; i++)
{
if (zoneConfig.subZones[i] != currentZone)
{
// LaunchSubZoneServer(i); //DEPRECIATED - HANDLED BY ZONE LAUNCHER NOW - DX4D
//LAUNCH ZONE PROCESS SERVER
UnityEngine.Debug.Log("[ZONE SERVER STARTUP] - "
+ "Attempting to launch Zone Server - " + zoneConfig.subZones[i].title + "...");
if (zoneLauncher.LaunchProcess(i))
{
UnityEngine.Debug.Log("[ZONE SERVER STARTUP] - "
+ "Successfully launched Zone Server " + zoneConfig.subZones[i].title + "!!!");
}
else
{
UnityEngine.Debug.Log(">>>ISSUE<<< [ZONE SERVER STARTUP] - "
+ "Failed to launch Zone Server " + zoneConfig.subZones[i].title);
}
}
}
subZonesHaveBeenLaunched = true;
//debug.LogFormat(this.name, nameof(LaunchSubZoneServers), zoneConfig.subZones.Count.ToString()); //DEBUG //REMOVED DX4D
}
//LAUNCH ZONE SAVE ROUTINE
/// <summary>Invokes the <see cref="SaveZone"/> method repeatedly
/// based on the interval set in <see cref="zoneConfig"/></summary>
void LaunchZoneSaveRoutine()
{
UnityEngine.Debug.Log("[ZONE SERVER STARTUP] - "
+ "Attempting to launch Main Zone Save Routine - " + zoneConfig.mainZone.title + "...");
InvokeRepeating(nameof(SaveZone), 0, zoneConfig.zoneSaveInterval);
UnityEngine.Debug.Log("[ZONE SERVER STARTUP] - "
+ "Successfully launched Main Zone Save Routine " + zoneConfig.mainZone.title + "!!!");
}
/* //DEPRECIATED - HANDLED BY ZONE LAUNCHER NOW - DX4D
// -------------------------------------------------------------------------------
// @SERVER
// -------------------------------------------------------------------------------
public enum AppExtension { exe, x86_64, app }
protected void LaunchSubZoneServer(int index)
{
AppExtension extension = AppExtension.exe;
switch (Application.platform)
{
//STANDALONE
case RuntimePlatform.WindowsPlayer: extension = AppExtension.exe; break;
case RuntimePlatform.OSXPlayer: extension = AppExtension.app; break;
case RuntimePlatform.LinuxPlayer: extension = AppExtension.x86_64; break;
//EDITOR
case RuntimePlatform.WindowsEditor: extension = AppExtension.exe; break;
case RuntimePlatform.OSXEditor: extension = AppExtension.app; break;
case RuntimePlatform.LinuxEditor: extension = AppExtension.x86_64; break;
//MOBILE + CONSOLE
//NOTE: Probably no reason to use these for a server...maybe in some cases though (couch co-op games etc)
//case RuntimePlatform.WebGLPlayer: break; case RuntimePlatform.IPhonePlayer: break; case RuntimePlatform.Android: break;
//case RuntimePlatform.PS4: break; case RuntimePlatform.XboxOne: break; case RuntimePlatform.Switch: break;
}
Process process = new Process();
string _fileName;
//NOTE: This is a workaround, we leave the switch logic above just in case we ever check this extension variable in the future to extend this method.
if (Application.platform == RuntimePlatform.OSXPlayer)
{
string[] args = Environment.GetCommandLineArgs();
if (args != null)
{
if (!String.IsNullOrWhiteSpace(args[0]))
{
_fileName = args[0];
}
}
_fileName = String.Empty;
//_fileName = Tools.GetProcessPath; //OSX
//TODO: This is a potential fix for the server executable being locked into requiring a specific name.
//process.StartInfo.FileName = Path.GetFullPath(Tools.GetProcessPath) + "/" + Path.GetFileNameWithoutExtension(Tools.GetProcessPath) + "." + Path.GetExtension(Tools.GetProcessPath);
}
else
{
_fileName = "server" + "." + extension.ToString(); //LINUX and WINDOWS
//TODO: This is a potential fix for the server executable being locked into requiring a specific name.
//process.StartInfo.FileName = Path.GetFileNameWithoutExtension(Tools.GetProcessPath) + "." + Path.GetExtension(Tools.GetProcessPath);
}
//SETUP PROCESS LAUNCH PARAMS
process.StartInfo.FileName = _fileName;
process.StartInfo.Arguments = argZoneIndex + " " + index.ToString();
string filePath = process.StartInfo.WorkingDirectory + process.StartInfo.FileName;
//UnityEngine.Debug.Log("[SERVER] - Zone Server - Launching Server @" + filePath + "...");
if (System.IO.File.Exists(process.StartInfo.FileName)) //FILE EXISTS - LAUNCH PROCESS
{
process.Start(); //LAUNCH THE SERVER PROCESS
UnityEngine.Debug.Log("[SERVER STARTUP] - [ZONES] - Successfully launched Zone Server " + zoneConfig.subZones[index].title + " @" + filePath);
}
else //NO SERVER EXE FOUND TO LAUNCH PROCESS
{
UnityEngine.Debug.Log("[SERVER STARTUP ISSUE] - [ZONES] - Could not find server file @" + filePath);
//NOTE: We started anyway, even if the file does not exist
//TODO: Make this conditional (once the above condition is tested)
process.Start(); //TODO: Validate that File Exists - DONE
}
//debug.LogFormat(this.name, nameof(LaunchSubZoneServer), index.ToString()); //DEBUG //REMOVED DX4D
}*/
// ====================== MESSAGE EVENT HANDLERS =================================
// -------------------------------------------------------------------------------
// OnServerMessageResponsePlayerSwitchServer
// @Client
// -------------------------------------------------------------------------------
//public void OnServerMessageResponsePlayerSwitchServer(NetworkConnection conn, ServerResponsePlayerSwitchServer msg) //REMOVED - DX4D
public void OnServerMessageResponsePlayerSwitchServer(ServerResponsePlayerSwitchServer msg) //ADDED - DX4D
{
Network.NetworkManager newNetworkManager = networkManager;
if (!newNetworkManager)
{
UnityEngine.Debug.Log("<b>[<color=blue>CLIENT</color>] - [ZONES]</b> - "
+ "<b>Creating New Network Manager...</b>");
newNetworkManager = new Network.NetworkManager();
}
UnityEngine.Debug.Log("<b>[<color=blue>CLIENT</color>] - [ZONES]</b> - "
+ "<b>Stopping Client connected to Network Manager...</b>");
if (networkManager) networkManager.StopClient();
UnityEngine.Debug.Log("<b>[<color=blue>CLIENT</color>] - [ZONES]</b> - "
+ "<b>Shutting Down Network Client on the current Server...</b>");
NetworkClient.Shutdown();
UnityEngine.Debug.Log("<b>[<color=blue>CLIENT</color>] - [ZONES]</b> - "
+ "<b>Shutting Down Active Network Manager...</b>");
Network.NetworkManager.Shutdown();
UnityEngine.Debug.Log("<b>[<color=blue>CLIENT</color>] - [ZONES]</b> - "
+ "<b>Setting New Network Manager...</b>");
Network.NetworkManager.singleton = newNetworkManager;//networkManager;
autoPlayerName = msg.playername;
for (int i = 0; i < zoneConfig.subZones.Count; i++)
{
if (msg.zonename == zoneConfig.subZones[i].name)
{
zoneIndex = i; //MOVED - Before UpdateTransportPort - DX4D
autoConnectClient = true;
//UPDATE TRANSPORTS
UpdateTransportPort(GetZonePort);
//networkTransport.port = GetZonePort; //REPLACED - DX4D
UnityEngine.Debug.Log("<b>[<color=blue>CLIENT</color>] - [ZONES]</b> - "
+ "<b>Loading zone number " + zoneIndex + " - " + msg.zonename + "...</b>");
LoadSubZone(zoneIndex);
//debug.LogFormat(this.name, nameof(OnServerMessageResponsePlayerSwitchServer), i.ToString()); //DEBUG //REMOVED DX4D
return;
}
}
UnityEngine.Debug.Log("<b>[<color=red>CLIENT</color>] - [ZONES]</b> - "
+ "<b>Could not find zone number " + zoneIndex + " - " + msg.zonename + "...</b>");
//debug.LogFormat(this.name, nameof(OnServerMessageResponsePlayerSwitchServer), "NOT FOUND"); //DEBUG //REMOVED DX4D
}
// -------------------------------------------------------------------------------
// OnServerMessageResponsePlayerAutoLogin
// @Client
// -------------------------------------------------------------------------------
//public void OnServerMessageResponsePlayerAutoLogin(NetworkConnection conn, ServerResponsePlayerAutoLogin msg) //REMOVED - DX4D
public void OnServerMessageResponsePlayerAutoLogin(ServerResponsePlayerAutoLogin msg) //ADDED - DX4D
{
autoPlayerName = "";
if (UIPopupNotify.singleton)
UIPopupNotify.singleton.Hide();
}
// =================================== OTHER ====================================
// -------------------------------------------------------------------------------
// ReloadSubZone
// @Client
// -------------------------------------------------------------------------------
int subZoneIndex = 0;
void LoadSubZone(int zoneIndex)
{
subZoneIndex = zoneIndex;
Invoke(nameof(ReloadSubZone), 0.25f);
}
void ReloadSubZone()
{
string zoneName = zoneConfig.subZones[subZoneIndex].scene.SceneName;
SceneManager.LoadScene(zoneName); //LOAD ZONE TO CURRENT SCENE
UnityEngine.Debug.Log("<b>[<color=green>CLIENT</color>] - [ZONES]</b> - "
+ "<b>Loaded zone number " + zoneIndex + " - " + zoneName + "!</b>");
}
// -------------------------------------------------------------------------------
// OnSceneLoaded
// @Client / @Server
// -------------------------------------------------------------------------------
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (NetworkServer.active && !GetIsMainZone)
{
if (GetSubZoneTimeoutInterval > 0)
{
InvokeRepeating(nameof(CheckSubZone), GetSubZoneTimeoutInterval, GetSubZoneTimeoutInterval);
}
}
if (autoConnectClient)
{
networkManager.StartClient();
autoConnectClient = false;
}
}
// -------------------------------------------------------------------------------
// AutoLogin
// @Client
// -------------------------------------------------------------------------------
public void AutoLogin(NetworkConnection conn)
{
if (!String.IsNullOrWhiteSpace(autoPlayerName))
networkManager.TryAutoLoginPlayer(conn, autoPlayerName, GetToken);
}
// ================================= OTHER =======================================
// -------------------------------------------------------------------------------
// SaveZone
// @Server
// -------------------------------------------------------------------------------
void SaveZone()
{
UnityEngine.Debug.Log("[ZONE SERVER] - [SAVE] - "
+ "Saving Zone " + mainZoneName + "...");
DatabaseManager.singleton.SaveZoneTime(mainZoneName); //SAVE ZONE TIME
UnityEngine.Debug.Log("[ZONE SERVER] - [SAVE] - "
+ "Saved Zone " + mainZoneName + "!");
}
// -------------------------------------------------------------------------------
// CheckSubZone
// @Server
// -------------------------------------------------------------------------------
void CheckSubZone()
{
if (DatabaseManager.singleton.CheckZoneTimeout(mainZoneName, GetSubZoneTimeoutInterval))
{
UnityEngine.Debug.Log("[ZONE SERVER] - [ZONE TIMEOUT] - "
+ "Zone number " + subZoneIndex + " - " + zoneConfig.subZones[subZoneIndex].scene.SceneName + "'s master zone " + mainZoneName + " has gone offline...shutting down!");
//TODO: Add a timer here and do a safe shutdown
Application.Quit();
}
}
// -------------------------------------------------------------------------------
// OnDestroy
// -------------------------------------------------------------------------------
void OnDestroy()
{
CancelInvoke();
}
}
}
| 41.161017 | 197 | 0.494462 | [
"MIT"
] | alka69/OpenMMO | Plugins/_ADDONS_/ServerSystems/ZoneSystem/ZoneManager/Scripts/Components/Components [Attach to NetworkManager]/ZoneManager.cs | 24,285 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrizeTicketUIState : State
{
public FadeUIElement fadeElement;
public float fadeDuration;
private PrizeTicketUI prizeTicketUI;
private Prize prize;
void Awake ()
{
prizeTicketUI = GetComponentInChildren<PrizeTicketUI> ();
}
void Start ()
{
gameObject.SetActive (false);
}
public void Init (Prize prize)
{
this.prize = prize;
}
public override void Enter ()
{
gameObject.SetActive (true);
prizeTicketUI.ShowUI (this.prize);
fadeElement.FadeFromTo (0, 1, fadeDuration, prizeTicketUI.ScreenShown);
}
public override void Execute ()
{
}
public override void Exit ()
{
gameObject.SetActive (false);
}
}
| 16.043478 | 73 | 0.726287 | [
"MIT"
] | IrenaMystic/unity-scratcher | Assets/Scripts/MonoBehaviours/States/PrizeTicketUIState.cs | 740 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using System.Xml.XPath;
namespace LaunchServer.Areas.HelpPage
{
/// <summary>
/// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file.
/// </summary>
public class XmlDocumentationProvider : IDocumentationProvider
{
private XPathNavigator _documentNavigator;
private const string TypeExpression = "/doc/members/member[@name='T:{0}']";
private const string MethodExpression = "/doc/members/member[@name='M:{0}']";
private const string ParameterExpression = "param[@name='{0}']";
/// <summary>
/// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
/// </summary>
/// <param name="documentPath">The physical path to XML document.</param>
public XmlDocumentationProvider(string documentPath)
{
if (documentPath == null)
{
throw new ArgumentNullException("documentPath");
}
XPathDocument xpath = new XPathDocument(documentPath);
_documentNavigator = xpath.CreateNavigator();
}
public string GetDocumentation(HttpControllerDescriptor controllerDescriptor)
{
XPathNavigator typeNode = GetTypeNode(controllerDescriptor);
return GetTagValue(typeNode, "summary");
}
public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "summary");
}
public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
{
ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;
if (reflectedParameterDescriptor != null)
{
XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);
if (methodNode != null)
{
string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;
XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));
if (parameterNode != null)
{
return parameterNode.Value.Trim();
}
}
}
return null;
}
public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)
{
XPathNavigator methodNode = GetMethodNode(actionDescriptor);
return GetTagValue(methodNode, "returns");
}
private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor)
{
ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;
if (reflectedActionDescriptor != null)
{
string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo));
return _documentNavigator.SelectSingleNode(selectExpression);
}
return null;
}
private static string GetMemberName(MethodInfo method)
{
string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", method.DeclaringType.FullName, method.Name);
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 0)
{
string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray();
name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames));
}
return name;
}
private static string GetTagValue(XPathNavigator parentNode, string tagName)
{
if (parentNode != null)
{
XPathNavigator node = parentNode.SelectSingleNode(tagName);
if (node != null)
{
return node.Value.Trim();
}
}
return null;
}
private static string GetTypeName(Type type)
{
if (type.IsGenericType)
{
// Format the generic type name to something like: Generic{System.Int32,System.String}
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string typeName = genericType.FullName;
// Trim the generic parameter counts from the name
typeName = typeName.Substring(0, typeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();
return String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", typeName, String.Join(",", argumentTypeNames));
}
return type.FullName;
}
private XPathNavigator GetTypeNode(HttpControllerDescriptor controllerDescriptor)
{
Type controllerType = controllerDescriptor.ControllerType;
string controllerTypeName = controllerType.FullName;
if (controllerType.IsNested)
{
// Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax.
controllerTypeName = controllerTypeName.Replace("+", ".");
}
string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName);
return _documentNavigator.SelectSingleNode(selectExpression);
}
}
}
| 42.152778 | 160 | 0.627348 | [
"Apache-2.0"
] | DonnotRain/WPFUpgradeTool | LaunchServer/Areas/HelpPage/XmlDocumentationProvider.cs | 6,070 | C# |
namespace Core4
{
using NServiceBus;
class JsonSerializerUsage
{
JsonSerializerUsage()
{
#region JsonSerialization
Configure.Serialization.Json();
#endregion
}
}
} | 14.555556 | 44 | 0.5 | [
"Apache-2.0"
] | foz1284/docs.particular.net | Snippets/Json/Core_4/JsonSerializerUsage.cs | 247 | C# |
using NewLife;
using NewLife.Log;
using NewLife.Net;
using NewLife.Reflection;
using NewLife.Remoting;
using NewLife.Serialization;
using NewLife.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using xLink.Common;
namespace xLink
{
/// <summary>物联客户端</summary>
[Api(null)]
public class LinkClient : ApiClient
{
#region 属性
/// <summary>用户名</summary>
public String UserName { get; set; }
/// <summary>密码</summary>
public String Password { get; set; }
/// <summary>动作前缀</summary>
public String ActionPrefix { get; set; }
/// <summary>已登录</summary>
public Boolean Logined { get; set; }
/// <summary>最后一次登录成功后的消息</summary>
public IDictionary<String, Object> Info { get; private set; }
/// <summary>请求到服务端并返回的延迟时间</summary>
public TimeSpan Delay { get; set; }
#endregion
#region 构造
/// <summary>实例化</summary>
/// <param name="uri"></param>
public LinkClient(String uri) : base(uri)
{
Log = XTrace.Log;
StatPeriod = 60;
ShowError = true;
#if DEBUG
EncoderLog = XTrace.Log;
StatPeriod = 10;
#endif
}
#endregion
#region 执行
/// <summary>异步调用</summary>
/// <param name="action"></param>
/// <param name="args"></param>
/// <returns></returns>
public override Task<TResult> InvokeAsync<TResult>(String action, Object args = null)
{
if (!ActionPrefix.IsNullOrEmpty() && !action.Contains("/")) action = ActionPrefix + "/" + action;
return base.InvokeAsync<TResult>(action, args);
}
#endregion
#region 登录
/// <summary>连接后自动登录</summary>
/// <param name="client">客户端</param>
/// <param name="force">强制登录</param>
protected override async Task<Object> OnLoginAsync(ISocketClient client, Boolean force)
{
if (Logined && !force) return null;
Logined = false;
var user = UserName;
var pass = Password;
//if (user.IsNullOrEmpty()) return null;
//if (user.IsNullOrEmpty()) throw new ArgumentNullException(nameof(user), "用户名不能为空!");
//if (pass.IsNullOrEmpty()) throw new ArgumentNullException(nameof(pass), "密码不能为空!");
if (!pass.IsNullOrEmpty()) pass = pass.MD5();
var arg = new
{
user,
pass,
};
// 克隆一份,避免修改原始数据
var dic = arg.ToDictionary();
dic.Merge(GetLoginInfo(), false);
var act = "Login";
if (!ActionPrefix.IsNullOrEmpty()) act = ActionPrefix + "/" + act;
var rs = await base.InvokeWithClientAsync<Object>(client, act, dic);
var inf = rs.ToJson();
XTrace.WriteLine("登录{0}成功!{1}", Servers.FirstOrDefault(), inf);
Logined = true;
Info = rs as IDictionary<String, Object>;
if (_timer == null) _timer = new TimerX(DoPing, null, 10_000, 30_000);
return rs;
}
/// <summary>获取登录附加信息</summary>
/// <returns></returns>
protected virtual Object GetLoginInfo()
{
var asm = AssemblyX.Entry;
var mcs = MachineHelper.GetMacs().Join(",", e => e.ToHex("-"));
var ip = NetHelper.MyIP();
var ext = new
{
asm.Version,
asm.Compile,
OSName = Environment.OSVersion.Platform + "",
OSVersion = Environment.OSVersion.VersionString,
Environment.MachineName,
Environment.UserName,
CPU = Environment.ProcessorCount,
Macs = mcs,
InstallPath = ".".GetFullPath(),
Runtime = Environment.Version + "",
LocalIP = ip + "",
Time = DateTime.Now,
};
return ext;
}
#endregion
#region 心跳
private TimerX _timer;
private void DoPing(Object state) => PingAsync().Wait();
/// <summary>心跳</summary>
/// <returns></returns>
public async Task<Object> PingAsync()
{
// 获取需要携带的心跳信息
var ext = GetPingInfo();
// 执行心跳
var rs = await InvokeAsync<Object>("Ping", ext).ConfigureAwait(false);
// 获取响应中的Time,乃请求时送过去的本地时间,用于计算延迟
if (rs is IDictionary<String, Object> dic && dic.TryGetValue("Time", out var obj))
{
var dt = obj.ToDateTime();
if (dt.Year > 2000)
{
// 计算延迟
Delay = DateTime.Now - dt;
}
}
return rs;
}
/// <summary>心跳前获取附加信息</summary>
/// <returns></returns>
protected virtual Object GetPingInfo()
{
var asm = AssemblyX.Entry;
var pcs = new List<Process>();
foreach (var item in Process.GetProcesses().OrderBy(e => e.SessionId).ThenBy(e => e.ProcessName))
{
var name = item.ProcessName;
if (name.EqualIgnoreCase("svchost", "dllhost", "conhost")) continue;
pcs.Add(item);
}
var mcs = MachineHelper.GetMacs().Join(",", e => e.ToHex("-"));
var ext = new
{
Macs = mcs,
Processes = pcs.Join(",", e => e.ProcessName),
Time = DateTime.Now,
Delay = (Int32)Delay.TotalMilliseconds,
};
return ext;
}
#endregion
#region 业务
#endregion
}
} | 28.166667 | 109 | 0.510566 | [
"MIT"
] | NewLifeX/XLink | xLink.Client/Services/LinkClient.cs | 6,263 | C# |
namespace Bitbucket.Net.Models.Core.Projects
{
public class Ref
{
public string Id { get; set; }
public string DisplayId { get; set; }
public string Type { get; set; }
}
} | 23.111111 | 45 | 0.586538 | [
"MIT"
] | ADHUI/Bitbucket.Net | src/Bitbucket.Net/Models/Core/Projects/Ref.cs | 210 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinFu.Delegates
{
public static class DelegateExtensions
{
public static TDelegate DefineDelegate<TDelegate>(this Func<object[], object> methodBody)
where TDelegate : class
{
var delegateType = typeof(TDelegate);
if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType))
throw new InvalidOperationException("TDelegate must derive from System.MulicastDelegate");
return DefineDelegate(methodBody, delegateType) as TDelegate;
}
public static MulticastDelegate DefineDelegate(this Func<object[], object> methodBody, Type delegateType)
{
return DelegateFactory.DefineDelegate(delegateType, methodBody);
}
}
}
| 32.444444 | 113 | 0.691781 | [
"MIT"
] | philiplaureano/LinFu.Delegates | LinFu.Delegates/DelegateExtensions.cs | 878 | C# |
using System;
using BattleTech;
using Harmony;
using UnityEngine;
namespace VehicleEvasivePipsGainiedAdditionalFix
{
[HarmonyPatch(typeof(Vehicle), "GetEvasivePipsResult", 0)]
public static class VehiclePatch
{
public static bool Prefix(float distMoved, bool isJump, bool isSprint, bool isMelee, Vehicle __instance, ref int __result, StatCollection ___statCollection)
{
int targetSpeedIndex = __instance.Combat.ToHit.GetTargetSpeedIndex(distMoved);
int num = (targetSpeedIndex <= -1) ? 0 : __instance.Combat.Constants.ToHit.EvasivePipsMovingTarget[targetSpeedIndex];
if (isJump)
{
num++;
}
if ((double)distMoved > 0.01)
{
num += ___statCollection.GetValue<int>("EvasivePipsGainedAdditional");
}
num = Mathf.Min(num, ___statCollection.GetValue<int>("MaxEvasivePips"));
__result = (int)((float)num * __instance.Combat.Constants.ResolutionConstants.VehicleEvasiveResultMultiplier);
return false;
}
}
}
| 32.057143 | 164 | 0.639037 | [
"Unlicense"
] | Arcananix/VehicleEvasivePipsGainiedAdditionalFix | VehicleEvasivePipsGainiedAdditionalFix/VehiclePatch.cs | 1,124 | C# |
using AutoMapper;
using JetBrains.Annotations;
using Lykke.Service.Credentials.Client.Models.Responses;
using MAVN.Service.CustomerManagement.Client.Models;
using MAVN.Service.CustomerManagement.Client.Models.Requests;
using MAVN.Service.CustomerManagement.Client.Models.Responses;
using MAVN.Service.CustomerManagement.Domain;
using MAVN.Service.CustomerManagement.Domain.Models;
using PasswordResetErrorResponse = Lykke.Service.Credentials.Client.Models.Responses.PasswordResetErrorResponse;
namespace MAVN.Service.CustomerManagement.AutoMapperProfiles
{
[UsedImplicitly(ImplicitUseTargetFlags.WithMembers)]
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<AuthResultModel, AuthenticateResponseModel>();
CreateMap<RegistrationResultModel, RegistrationResponseModel>();
CreateMap<ConfirmVerificationCodeResultModel, VerificationCodeConfirmationResponseModel>();
CreateMap<ChangePasswordResultModel, ChangePasswordResponseModel>();
CreateMap<PasswordResetResponseModel, PasswordResetError>()
.ForMember(x => x.Error, c => c.MapFrom(s => s.ErrorCode));
CreateMap<PasswordResetErrorResponse, PasswordResetError>();
CreateMap<PasswordResetError, Client.Models.PasswordResetErrorResponse>();
CreateMap<VerificationCodeResult, VerificationCodeResponseModel>();
CreateMap<ResetIdentifierValidationResponse, ValidateResetIdentifierModel>();
CreateMap<ValidateResetIdentifierModel, ValidateResetIdentifierResponse>();
CreateMap<BatchCustomerStatusesModel, BatchOfCustomerStatusesResponse>();
CreateMap<RegistrationRequestModel, RegistrationRequestDto>();
}
}
}
| 43.756098 | 112 | 0.763099 | [
"MIT"
] | IliyanIlievPH/MAVN.Service.CustomerManagement | src/MAVN.Service.CustomerManagement/AutoMapperProfiles/AutoMapperProfile.cs | 1,794 | C# |
using System.Linq;
using System.Text;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using RestMockCore.Interfaces;
using RestMockCore.Models;
namespace RestMockCore
{
public class HttpServer : IHttpServer
{
private IWebHost _host;
private readonly string _hostname;
private readonly int _port;
public IRequestBuilder Config { get; set; }
public HttpServer(int port = 5000, string hostname = "localhost")
{
_hostname = hostname;
_port = port;
Config = new RequestBuilder();
}
public void Run()
{
_host = WebHost.CreateDefaultBuilder()
.UseUrls($"http://{_hostname}:{_port}")
.Configure(app =>
{
app.Run(async context =>
{
var route = Config.RouteTable?.LastOrDefault(x => x.IsMatch(context.Request));
switch (route)
{
case null when context.Request.Path == @"/":
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("It Works!", Encoding.UTF8);
return;
case null:
context.Response.StatusCode = StatusCodes.Status404NotFound;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Page not found!", Encoding.UTF8);
return;
}
if (route.Response.Handler != null)
{
route.Response.Handler(context);
return;
}
var response = route.Response.Body;
context.Response.StatusCode = route.Response.StatusCode;
context.Response.Headers.AddRange(route.Response.Headers);
await context.Response.WriteAsync(response, Encoding.UTF8).ConfigureAwait(false);
});
}).Build();
_host.Start();
}
public void Dispose()
{
_host?.Dispose();
}
}
}
| 35.239437 | 105 | 0.478417 | [
"MIT"
] | benyblack/rest-mock-core | src/RestMockCore/HttpServer.cs | 2,504 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFDGameScriptInterface;
namespace SFD.Teletransportación.porBoton
{
public class TPButton
{
/*
* author: XHomie
* description: Teletransportation by Button
* version: v0.1
* license: Creative Commons
* authorized for any official use, update and share for new versions to: LennyShogy
*/
private readonly Boolean TPBUTTON_EFFECTS = true;
private readonly int AREA_RANGE = 8;
/// <summary>
/// Funcion que permite teletransportar "Players" usando como referencia:
/// 1 Boton, 1 ScriptTrigger
/// Boton: Sera el que apunte al ScriptTrigger para que aquel llame al metodo
/// ScriptTrigger: Sera el que llame al metodo y ademas sea usado como referencia donde teletransportara al personaje
/// </summary>
/// <param name="args">Trigger invocado con Objetos del que llama y el llamado</param>
public void TP_Button(TriggerArgs args)
{
if (args.Sender is IObject)
{
IObject ob = (IObject)args.Caller;
Vector2 ps1 = ((IObject)args.Sender).GetWorldPosition();
Vector2 ps2 = ob.GetWorldPosition();
Area a = new Area(ps1.Y + AREA_RANGE, ps1.X - AREA_RANGE, ps1.Y - AREA_RANGE, ps1.X + AREA_RANGE);
foreach (IObject obs in GameScriptInterface.Game.GetObjectsByArea(a))
{
if (obs is IPlayer)
{
TPEffect("S_P", ps1);
obs.SetWorldPosition(ps2);
TPEffect("TR_D", ps2);
}
}
}
}
public void TPEffect(String type, Vector2 ps)
{
if(TPBUTTON_EFFECTS)
GameScriptInterface.Game.PlayEffect(type, ps);
}
}
}
| 35.245614 | 125 | 0.571926 | [
"Apache-2.0"
] | HomieStart/SFD-TPButton | TPButton.cs | 2,010 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RFID.Controllers
{
using Models;
[Route("[controller]")]
public class RFIDController : Controller
{
private readonly RFIDContext context;
public RFIDController(RFIDContext context)
{
this.context = context;
}
// GET /rfid
[HttpGet]
public async Task<IEnumerable<Event>> List()
{
return await context.Events.ToListAsync();
}
// GET /rfid/latest
[HttpGet("latest")]
public async Task<Event> Latest()
{
return await context.Events
.OrderByDescending(e => e.Time)
.FirstOrDefaultAsync();
}
// POST /rfid
[HttpPost]
public async Task Create([FromBody] ViewModels.Event[] values)
{
var now = DateTime.Now;
var maxOffset = values.Max(v => v.Offset);
foreach (var value in values)
{
var time = now - TimeSpan.FromMilliseconds(maxOffset - value.Offset);
await context.Events.AddAsync(new Event
{
RFID = value.RFID,
State = value.State,
Time = time
});
}
await context.SaveChangesAsync();
}
}
}
| 25.931034 | 85 | 0.53391 | [
"MIT"
] | nikibobi/rfid-server | RFID/Controllers/RFIDController.cs | 1,506 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MaxMind.GeoIP2.Exceptions
{
/// <summary>
/// This exception is thrown when there is an authentication error.
/// </summary>
public class AuthenticationException : GeoIP2Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="AuthenticationException"/> class.
/// </summary>
/// <param name="message">A message explaining the cause of the error.</param>
public AuthenticationException(string message)
: base(message)
{
}
}
}
| 26.458333 | 90 | 0.637795 | [
"Apache-2.0"
] | Mailaender/GeoIP2-dotnet | GeoIP2/Exceptions/AuthenticationException.cs | 637 | C# |
//-----------------------------------------------------------------------------
// Filename: SIPHeader.cs
//
// Description: SIP Header.
//
// History:
// 17 Sep 2005 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson ([email protected]), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of SIP Sorcery PTY LTD.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using SIPSorcery.GB28181.Sys;
using log4net;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.GB28181.SIP
{
/// <bnf>
/// Via = ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm)
/// via-parm = sent-protocol LWS sent-by *( SEMI via-params )
/// via-params = via-ttl / via-maddr / via-received / via-branch / via-extension
/// via-ttl = "ttl" EQUAL ttl
/// via-maddr = "maddr" EQUAL host
/// via-received = "received" EQUAL (IPv4address / IPv6address)
/// via-branch = "branch" EQUAL token
/// via-extension = generic-param
/// sent-protocol = protocol-name SLASH protocol-version SLASH transport
/// protocol-name = "SIP" / token
/// protocol-version = token
/// transport = "UDP" / "TCP" / "TLS" / "SCTP" / other-transport
/// sent-by = host [ COLON port ]
/// ttl = 1*3DIGIT ; 0 to 255
/// generic-param = token [ EQUAL gen-value ]
/// gen-value = token / host / quoted-string
/// </bnf>
/// <remarks>
/// The Via header only has parameters, no headers. Parameters of from ...;name=value;name2=value2
/// Specific parameters: ttl, maddr, received, branch.
///
/// From page 179 of RFC3261:
/// "Even though this specification mandates that the branch parameter be
/// present in all requests, the BNF for the header field indicates that
/// it is optional."
///
/// The branch parameter on a Via therefore appears to be optionally mandatory?!
///
/// Any SIP application element that uses transactions depends on the branch parameter for transaction matching.
/// Only the top Via header branch is used for transactions though so if the request has made it to this stack
/// with missing branches then in theory it should be safe to proceed. It will be left up to the SIPTransaction
/// class to reject any SIP requests that are missing the necessary branch.
/// </remarks>
public class SIPViaHeader
{
private static ILog logger = AssemblyState.logger;
private static char m_paramDelimChar = ';';
private static char m_hostDelimChar = ':';
private static string m_receivedKey = SIPHeaderAncillary.SIP_HEADERANC_RECEIVED;
private static string m_rportKey = SIPHeaderAncillary.SIP_HEADERANC_RPORT;
private static string m_branchKey = SIPHeaderAncillary.SIP_HEADERANC_BRANCH;
public string Version;
public SIPProtocolsEnum Transport;
public string Host;
public int Port = 0;
public string Branch
{
get
{
if (ViaParameters != null && ViaParameters.Has(m_branchKey))
{
return ViaParameters.Get(m_branchKey);
}
else
{
return null;
}
}
set { ViaParameters.Set(m_branchKey, value); }
}
public string ReceivedFromIPAddress // IP Address contained in the recevied parameter.
{
get
{
if (ViaParameters != null && ViaParameters.Has(m_receivedKey))
{
return ViaParameters.Get(m_receivedKey);
}
else
{
return null;
}
}
set { ViaParameters.Set(m_receivedKey, value); }
}
public int ReceivedFromPort // Port contained in the rport parameter.
{
get
{
if (ViaParameters != null && ViaParameters.Has(m_rportKey))
{
return Convert.ToInt32(ViaParameters.Get(m_rportKey));
}
else
{
return 0;
}
}
set { ViaParameters.Set(m_rportKey, value.ToString()); }
}
public SIPParameters ViaParameters = new SIPParameters(null, m_paramDelimChar);
public string ContactAddress // This the address placed into the Via header by the User Agent.
{
get
{
if (Port != 0)
{
return Host + ":" + Port;
}
else
{
return Host;
}
}
}
public string ReceivedFromAddress // This is the socket the request was received on and is a combination of the Host and Received fields.
{
get
{
if (ReceivedFromIPAddress != null && ReceivedFromPort != 0)
{
return ReceivedFromIPAddress + ":" + ReceivedFromPort;
}
else if (ReceivedFromIPAddress != null && Port != 0)
{
return ReceivedFromIPAddress + ":" + Port;
}
else if (ReceivedFromIPAddress != null)
{
return ReceivedFromIPAddress;
}
else if (ReceivedFromPort != 0)
{
return Host + ":" + ReceivedFromPort;
}
else if (Port != 0)
{
return Host + ":" + Port;
}
else
{
return Host;
}
}
}
public SIPViaHeader()
{ }
public SIPViaHeader(string contactIPAddress, int contactPort, string branch, SIPProtocolsEnum protocol)
{
Version = SIPConstants.SIP_FULLVERSION_STRING;
Transport = protocol;
Host = contactIPAddress;
Port = contactPort;
Branch = branch;
ViaParameters.Set(m_rportKey, null);
}
public SIPViaHeader(string contactIPAddress, int contactPort, string branch) :
this(contactIPAddress, contactPort, branch, SIPProtocolsEnum.udp)
{ }
public SIPViaHeader(IPEndPoint contactEndPoint, string branch) :
this(contactEndPoint.Address.ToString(), contactEndPoint.Port, branch, SIPProtocolsEnum.udp)
{ }
public SIPViaHeader(SIPEndPoint localEndPoint, string branch) :
this(localEndPoint.Address.ToString(), localEndPoint.Port, branch, localEndPoint.Protocol)
{ }
public SIPViaHeader(string contactEndPoint, string branch) :
this(IPSocket.GetIPEndPoint(contactEndPoint).Address.ToString(), IPSocket.GetIPEndPoint(contactEndPoint).Port, branch, SIPProtocolsEnum.udp)
{ }
public SIPViaHeader(IPEndPoint contactEndPoint, string branch, SIPProtocolsEnum protocol) :
this(contactEndPoint.Address.ToString(), contactEndPoint.Port, branch, protocol)
{ }
public static SIPViaHeader[] ParseSIPViaHeader(string viaHeaderStr)
{
List<SIPViaHeader> viaHeadersList = new List<SIPViaHeader>();
if (!viaHeaderStr.IsNullOrBlank())
{
viaHeaderStr = viaHeaderStr.Trim();
// Multiple Via headers can be contained in a single line by separating them with a comma.
string[] viaHeaders = SIPParameters.GetKeyValuePairsFromQuoted(viaHeaderStr, ',');
foreach (string viaHeaderStrItem in viaHeaders)
{
if (viaHeaderStrItem == null || viaHeaderStrItem.Trim().Length == 0)
{
throw new SIPValidationException(SIPValidationFieldsEnum.ViaHeader, "No Contact address.");
}
else
{
SIPViaHeader viaHeader = new SIPViaHeader();
string header = viaHeaderStrItem.Trim();
int firstSpacePosn = header.IndexOf(" ");
if (firstSpacePosn == -1)
{
throw new SIPValidationException(SIPValidationFieldsEnum.ViaHeader, "No Contact address.");
}
else
{
string versionAndTransport = header.Substring(0, firstSpacePosn);
viaHeader.Version = versionAndTransport.Substring(0, versionAndTransport.LastIndexOf('/'));
viaHeader.Transport = SIPProtocolsType.GetProtocolType(versionAndTransport.Substring(versionAndTransport.LastIndexOf('/') + 1));
string nextField = header.Substring(firstSpacePosn, header.Length - firstSpacePosn).Trim();
int delimIndex = nextField.IndexOf(';');
string contactAddress = null;
// Some user agents include branch but have the semi-colon missing, that's easy to cope with by replacing "branch" with ";branch".
if (delimIndex == -1 && nextField.Contains(m_branchKey))
{
nextField = nextField.Replace(m_branchKey, ";" + m_branchKey);
delimIndex = nextField.IndexOf(';');
}
if (delimIndex == -1)
{
//logger.Warn("Via header missing semi-colon: " + header + ".");
//parserError = SIPValidationError.NoBranchOnVia;
//return null;
contactAddress = nextField.Trim();
}
else
{
contactAddress = nextField.Substring(0, delimIndex).Trim();
viaHeader.ViaParameters = new SIPParameters(nextField.Substring(delimIndex, nextField.Length - delimIndex), m_paramDelimChar);
}
if (contactAddress == null || contactAddress.Trim().Length == 0)
{
// Check that the branch parameter is present, without it the Via header is illegal.
//if (!viaHeader.ViaParameters.Has(m_branchKey))
//{
// logger.Warn("Via header missing branch: " + header + ".");
// parserError = SIPValidationError.NoBranchOnVia;
// return null;
//}
throw new SIPValidationException(SIPValidationFieldsEnum.ViaHeader, "No Contact address.");
}
// Parse the contact address.
int colonIndex = contactAddress.IndexOf(m_hostDelimChar);
if (colonIndex != -1)
{
viaHeader.Host = contactAddress.Substring(0, colonIndex);
if (!Int32.TryParse(contactAddress.Substring(colonIndex + 1), out viaHeader.Port))
{
throw new SIPValidationException(SIPValidationFieldsEnum.ViaHeader, "Non-numeric port for IP address.");
}
else if (viaHeader.Port > SIPConstants.MAX_SIP_PORT)
{
throw new SIPValidationException(SIPValidationFieldsEnum.ViaHeader, "The port specified in a Via header exceeded the maximum allowed.");
}
}
else
{
viaHeader.Host = contactAddress;
}
viaHeadersList.Add(viaHeader);
}
}
}
}
if (viaHeadersList.Count > 0)
{
return viaHeadersList.ToArray();
}
else
{
throw new SIPValidationException(SIPValidationFieldsEnum.ViaHeader, "Via list was empty."); ;
}
}
public new string ToString()
{
string sipViaHeader = SIPHeaders.SIP_HEADER_VIA + ": " + this.Version + "/" + this.Transport.ToString().ToUpper() + " " + ContactAddress;
sipViaHeader += (ViaParameters != null && ViaParameters.Count > 0) ? ViaParameters.ToString() : null;
return sipViaHeader;
}
}
/// <bnf>
/// From = ( "From" / "f" ) HCOLON from-spec
/// from-spec = ( name-addr / addr-spec ) *( SEMI from-param )
/// from-param = tag-param / generic-param
/// name-addr = [ display-name ] LAQUOT addr-spec RAQUOT
/// addr-spec = SIP-URI / SIPS-URI / absoluteURI
/// tag-param = "tag" EQUAL token
/// generic-param = token [ EQUAL gen-value ]
/// gen-value = token / host / quoted-string
/// </bnf>
/// <remarks>
/// The From header only has parameters, no headers. Parameters of from ...;name=value;name2=value2.
/// Specific parameters: tag.
/// </remarks>
public class SIPFromHeader
{
//public const string DEFAULT_FROM_NAME = SIPConstants.SIP_DEFAULT_USERNAME;
public const string DEFAULT_FROM_URI = SIPConstants.SIP_DEFAULT_FROMURI;
public const string PARAMETER_TAG = SIPHeaderAncillary.SIP_HEADERANC_TAG;
public string FromName
{
get { return m_userField.Name; }
set { m_userField.Name = value; }
}
public SIPURI FromURI
{
get { return m_userField.URI; }
set { m_userField.URI = value; }
}
public string FromTag
{
get { return FromParameters.Get(PARAMETER_TAG); }
set
{
if (value != null && value.Trim().Length > 0)
{
FromParameters.Set(PARAMETER_TAG, value);
}
else
{
if (FromParameters.Has(PARAMETER_TAG))
{
FromParameters.Remove(PARAMETER_TAG);
}
}
}
}
public SIPParameters FromParameters
{
get { return m_userField.Parameters; }
set { m_userField.Parameters = value; }
}
private SIPUserField m_userField = new SIPUserField();
public SIPUserField FromUserField
{
get { return m_userField; }
set { m_userField = value; }
}
private SIPFromHeader()
{ }
public SIPFromHeader(string fromName, SIPURI fromURI, string fromTag)
{
m_userField = new SIPUserField(fromName, fromURI, null);
FromTag = fromTag;
}
public static SIPFromHeader ParseFromHeader(string fromHeaderStr)
{
try
{
SIPFromHeader fromHeader = new SIPFromHeader();
fromHeader.m_userField = SIPUserField.ParseSIPUserField(fromHeaderStr);
return fromHeader;
}
catch (ArgumentException argExcp)
{
throw new SIPValidationException(SIPValidationFieldsEnum.FromHeader, argExcp.Message);
}
catch
{
throw new SIPValidationException(SIPValidationFieldsEnum.FromHeader, "The SIP From header was invalid.");
}
}
public override string ToString()
{
return m_userField.ToString();
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class SIPFromHeaderUnitTest
{
[TestFixtureSetUp]
public void Init()
{}
[TestFixtureTearDown]
public void Dispose()
{}
[Test]
public void ParseFromHeaderTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testFromHeader = "\"User\" <sip:[email protected]>;tag=abcdef";
SIPFromHeader sipFromHeader = SIPFromHeader.ParseFromHeader(testFromHeader);
Console.WriteLine("From header=" + sipFromHeader.ToString() + ".");
Assert.IsTrue(sipFromHeader.FromName == "User", "The From header name was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromURI.ToString() == "sip:[email protected]", "The From header URI was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromTag == "abcdef", "The From header Tag was not parsed correctly.");
Assert.IsTrue(sipFromHeader.ToString() == testFromHeader, "The From header ToString method did not produce the correct results.");
}
[Test]
public void ParseFromHeaderNoTagTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testFromHeader = "User <sip:[email protected]>";
SIPFromHeader sipFromHeader = SIPFromHeader.ParseFromHeader(testFromHeader);
Assert.IsTrue(sipFromHeader.FromName == "User", "The From header name was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromURI.ToString() == "sip:[email protected]", "The From header URI was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromTag == null, "The From header Tag was not parsed correctly.");
}
[Test]
public void ParseFromHeaderSocketDomainTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testFromHeader = "User <sip:[email protected]:5090>";
SIPFromHeader sipFromHeader = SIPFromHeader.ParseFromHeader(testFromHeader);
Assert.IsTrue(sipFromHeader.FromName == "User", "The From header name was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromURI.ToString() == "sip:[email protected]:5090", "The From header URI was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromTag == null, "The From header Tag was not parsed correctly.");
}
[Test]
public void ParseFromHeaderSocketDomainAndTagTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testFromHeader = "User <sip:[email protected]:5090>;tag=abcdef";
SIPFromHeader sipFromHeader = SIPFromHeader.ParseFromHeader(testFromHeader);
Assert.IsTrue(sipFromHeader.FromName == "User", "The From header name was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromURI.ToString() == "sip:[email protected]:5090", "The From header URI was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromTag == "abcdef", "The From header Tag was not parsed correctly.");
}
[Test]
public void ParseFromHeaderNoNameTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testFromHeader = "<sip:[email protected]>";
SIPFromHeader sipFromHeader = SIPFromHeader.ParseFromHeader(testFromHeader);
Assert.IsTrue(sipFromHeader.FromName == null, "The From header name was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromURI.ToString() == "sip:[email protected]", "The From header URI was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromTag == null, "The From header Tag was not parsed correctly.");
}
[Test]
public void ParseFromHeaderNoAngleBracketsTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testFromHeader = "sip:[email protected]";
SIPFromHeader sipFromHeader = SIPFromHeader.ParseFromHeader(testFromHeader);
Assert.IsTrue(sipFromHeader.FromName == null, "The From header name was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromURI.ToString() == "sip:[email protected]", "The From header URI was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromTag == null, "The From header Tag was not parsed correctly.");
}
[Test]
public void ParseFromHeaderNoSpaceTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testFromHeader = "UNAVAILABLE<sip:[email protected]:5060>;tag=abcd";
SIPFromHeader sipFromHeader = SIPFromHeader.ParseFromHeader(testFromHeader);
Assert.IsTrue(sipFromHeader.FromName == "UNAVAILABLE", "The From header name was not parsed correctly, name=" + sipFromHeader.FromName + ".");
Assert.IsTrue(sipFromHeader.FromURI.ToString() == "sip:[email protected]:5060", "The From header URI was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromTag == "abcd", "The From header Tag was not parsed correctly.");
}
[Test]
public void ParseFromHeaderNoUserTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testFromHeader = "<sip:sip.domain.com>;tag=as6900b876";
SIPFromHeader sipFromHeader = SIPFromHeader.ParseFromHeader(testFromHeader);
Assert.IsTrue(sipFromHeader.FromName == null, "The From header name was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromURI.ToString() == "sip:sip.domain.com", "The From header URI was not parsed correctly.");
Assert.IsTrue(sipFromHeader.FromTag == "as6900b876", "The From header Tag was not parsed correctly.");
}
}
#endif
#endregion
}
/// <bnf>
/// To = ( "To" / "t" ) HCOLON ( name-addr / addr-spec ) *( SEMI to-param )
/// to-param = tag-param / generic-param
/// name-addr = [ display-name ] LAQUOT addr-spec RAQUOT
/// addr-spec = SIP-URI / SIPS-URI / absoluteURI
/// tag-param = "tag" EQUAL token
/// generic-param = token [ EQUAL gen-value ]
/// gen-value = token / host / quoted-string
/// </bnf>
/// <remarks>
/// The To header only has parameters, no headers. Parameters of from ...;name=value;name2=value2.
/// Specific parameters: tag.
/// </remarks>
public class SIPToHeader
{
public const string PARAMETER_TAG = SIPHeaderAncillary.SIP_HEADERANC_TAG;
public string ToName
{
get { return m_userField.Name; }
set { m_userField.Name = value; }
}
public SIPURI ToURI
{
get { return m_userField.URI; }
set { m_userField.URI = value; }
}
public string ToTag
{
get { return ToParameters.Get(PARAMETER_TAG); }
set
{
if (value != null && value.Trim().Length > 0)
{
ToParameters.Set(PARAMETER_TAG, value);
}
else
{
if (ToParameters.Has(PARAMETER_TAG))
{
ToParameters.Remove(PARAMETER_TAG);
}
}
}
}
public SIPParameters ToParameters
{
get { return m_userField.Parameters; }
set { m_userField.Parameters = value; }
}
private SIPUserField m_userField;
public SIPUserField ToUserField
{
get { return m_userField; }
set { m_userField = value; }
}
private SIPToHeader()
{ }
public SIPToHeader(string toName, SIPURI toURI, string toTag)
{
m_userField = new SIPUserField(toName, toURI, null);
ToTag = toTag;
}
public static SIPToHeader ParseToHeader(string toHeaderStr)
{
try
{
SIPToHeader toHeader = new SIPToHeader();
toHeader.m_userField = SIPUserField.ParseSIPUserField(toHeaderStr);
return toHeader;
}
catch (ArgumentException argExcp)
{
throw new SIPValidationException(SIPValidationFieldsEnum.ToHeader, argExcp.Message);
}
catch
{
throw new SIPValidationException(SIPValidationFieldsEnum.ToHeader, "The SIP To header was invalid.");
}
}
public override string ToString()
{
return m_userField.ToString();
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class SIPToHeaderUnitTest
{
[TestFixtureSetUp]
public void Init()
{
}
[TestFixtureTearDown]
public void Dispose()
{
}
[Test]
public void ParseToHeaderTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testToHeader = "User <sip:[email protected]>;tag=abcdef";
SIPToHeader sipToHeader = SIPToHeader.ParseToHeader(testToHeader);
Assert.IsTrue(sipToHeader.ToName == "User", "The To header name was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToURI.ToString() == "sip:[email protected]", "The To header URI was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToTag == "abcdef", "The To header Tag was not parsed correctly.");
}
[Test]
public void ParseMSCToHeaderTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testToHeader = "sip:[email protected];tag=AZHf2-ZMfDX0";
SIPToHeader sipToHeader = SIPToHeader.ParseToHeader(testToHeader);
Console.WriteLine("To header: " + sipToHeader.ToString());
Assert.IsTrue(sipToHeader.ToName == null, "The To header name was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToURI.ToString() == "sip:[email protected]", "The To header URI was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToTag == "AZHf2-ZMfDX0", "The To header Tag was not parsed correctly.");
}
[Test]
public void ToStringToHeaderTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testToHeader = "User <sip:[email protected]>;tag=abcdef";
SIPToHeader sipToHeader = SIPToHeader.ParseToHeader(testToHeader);
Assert.IsTrue(sipToHeader.ToName == "User", "The To header name was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToURI.ToString() == "sip:[email protected]", "The To header URI was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToTag == "abcdef", "The To header Tag was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToString() == "\"User\" <sip:[email protected]>;tag=abcdef", "The To header was not put ToString correctly.");
}
/// <summary>
/// New requests should be received with no To header tag. It is up to the recevier to populate the To header tag.
/// This test makes sure that changing the tag works correctly.
/// </summary>
[Test]
public void ChangeTagToHeaderTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testToHeader = "User <sip:[email protected]>;tag=abcdef";
SIPToHeader sipToHeader = SIPToHeader.ParseToHeader(testToHeader);
string newTag = "123456";
sipToHeader.ToTag = newTag;
Console.WriteLine("To header with new tag: " + sipToHeader.ToString());
Assert.IsTrue(sipToHeader.ToName == "User", "The To header name was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToURI.ToString() == "sip:[email protected]", "The To header URI was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToTag == newTag, "The To header Tag was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToString() == "\"User\" <sip:[email protected]>;tag=123456", "The To header was not put ToString correctly.");
}
[Test]
public void ParseByeToHeader()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string testHeader = "\"Joe Bloggs\" <sip:[email protected]>;tag=0013c339acec34652d988c7e-4fddcdef";
SIPToHeader sipToHeader = SIPToHeader.ParseToHeader(testHeader);
Console.WriteLine("To header: " + sipToHeader.ToString());
Assert.IsTrue(sipToHeader.ToName == "Joe Bloggs", "The To header name was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToURI.ToString() == "sip:[email protected]", "The To header URI was not parsed correctly.");
Assert.IsTrue(sipToHeader.ToTag == "0013c339acec34652d988c7e-4fddcdef", "The To header Tag was not parsed correctly.");
}
}
#endif
#endregion
}
/// <bnf>
/// Contact = ("Contact" / "m" ) HCOLON ( STAR / (contact-param *(COMMA contact-param)))
/// contact-param = (name-addr / addr-spec) *(SEMI contact-params)
/// name-addr = [ display-name ] LAQUOT addr-spec RAQUOT
/// addr-spec = SIP-URI / SIPS-URI / absoluteURI
/// display-name = *(token LWS)/ quoted-string
///
/// contact-params = c-p-q / c-p-expires / contact-extension
/// c-p-q = "q" EQUAL qvalue
/// c-p-expires = "expires" EQUAL delta-seconds
/// contact-extension = generic-param
/// delta-seconds = 1*DIGIT
/// generic-param = token [ EQUAL gen-value ]
/// gen-value = token / host / quoted-string
/// </bnf>
/// <remarks>
/// The Contact header only has parameters, no headers. Parameters of from ...;name=value;name2=value2
/// Specific parameters: q, expires.
/// </remarks>
[DataContract]
public class SIPContactHeader
{
public const string EXPIRES_PARAMETER_KEY = "expires";
public const string QVALUE_PARAMETER_KEY = "q";
private static ILog logger = AssemblyState.logger;
//private static char[] m_nonStandardURIDelimChars = new char[] { '\n', '\r', ' ' }; // Characters that can delimit a SIP URI, supposed to be > but it is sometimes missing.
public string RawHeader;
public string ContactName
{
get { return m_userField.Name; }
set { m_userField.Name = value; }
}
public SIPURI ContactURI
{
get { return m_userField.URI; }
set { m_userField.URI = value; }
}
public SIPParameters ContactParameters
{
get { return m_userField.Parameters; }
set { m_userField.Parameters = value; }
}
// A value of -1 indicates the header did not contain an expires parameter setting.
public int Expires
{
get
{
int expires = -1;
if (ContactParameters.Has(EXPIRES_PARAMETER_KEY))
{
string expiresStr = ContactParameters.Get(EXPIRES_PARAMETER_KEY);
Int32.TryParse(expiresStr, out expires);
}
return expires;
}
set { ContactParameters.Set(EXPIRES_PARAMETER_KEY, value.ToString()); }
}
public string Q
{
get { return ContactParameters.Get(QVALUE_PARAMETER_KEY); }
set { ContactParameters.Set(QVALUE_PARAMETER_KEY, value); }
}
private SIPUserField m_userField;
private SIPContactHeader()
{ }
public SIPContactHeader(string contactName, SIPURI contactURI)
{
m_userField = new SIPUserField(contactName, contactURI, null);
}
public SIPContactHeader(SIPUserField contactUserField)
{
m_userField = contactUserField;
}
public static List<SIPContactHeader> ParseContactHeader(string contactHeaderStr)
{
try
{
if (contactHeaderStr == null || contactHeaderStr.Trim().Length == 0)
{
return null;
}
//string[] contactHeaders = null;
//// Broken User Agent fix (Aastra looking at you!)
//if (contactHeaderStr.IndexOf('<') != -1 && contactHeaderStr.IndexOf('>') == -1)
//{
// int nonStandardDelimPosn = contactHeaderStr.IndexOfAny(m_nonStandardURIDelimChars);
// if (nonStandardDelimPosn != -1)
// {
// // Add on the missing RQUOT and ignore whatever the rest of the header is.
// contactHeaders = new string[] { contactHeaderStr.Substring(0, nonStandardDelimPosn) + ">" };
// }
// else
// {
// // Can't work out what is going on with this header bomb out.
// throw new SIPValidationException(SIPValidationFieldsEnum.ContactHeader, "Contact header invalid.");
// }
//}
//else
//{
// contactHeaders = SIPParameters.GetKeyValuePairsFromQuoted(contactHeaderStr, ',');
//}
string[] contactHeaders = SIPParameters.GetKeyValuePairsFromQuoted(contactHeaderStr, ',');
List<SIPContactHeader> contactHeaderList = new List<SIPContactHeader>();
foreach (string contactHeaderItemStr in contactHeaders)
{
SIPContactHeader contactHeader = new SIPContactHeader();
contactHeader.RawHeader = contactHeaderStr;
contactHeader.m_userField = SIPUserField.ParseSIPUserField(contactHeaderItemStr);
contactHeaderList.Add(contactHeader);
}
return contactHeaderList;
}
catch (SIPValidationException sipValidationExcp)
{
throw sipValidationExcp;
}
catch (Exception excp)
{
logger.Error("Exception ParseContactHeader. " + excp.Message);
throw new SIPValidationException(SIPValidationFieldsEnum.ContactHeader, "Contact header invalid.");
}
}
public static List<SIPContactHeader> CreateSIPContactList(SIPURI sipURI)
{
List<SIPContactHeader> contactHeaderList = new List<SIPContactHeader>();
contactHeaderList.Add(new SIPContactHeader(null, sipURI));
return contactHeaderList;
}
/// <summary>
/// Compares two contact headers to determine contact address equality.
/// </summary>
public static bool AreEqual(SIPContactHeader contact1, SIPContactHeader contact2)
{
if (!SIPURI.AreEqual(contact1.ContactURI, contact2.ContactURI))
{
return false;
}
else
{
// Compare invaraiant parameters.
string[] contact1Keys = contact1.ContactParameters.GetKeys();
if (contact1Keys != null && contact1Keys.Length > 0)
{
foreach (string key in contact1Keys)
{
if (key == EXPIRES_PARAMETER_KEY || key == QVALUE_PARAMETER_KEY)
{
continue;
}
else if (contact1.ContactParameters.Get(key) != contact2.ContactParameters.Get(key))
{
return false;
}
}
}
// Need to do the reverse as well
string[] contact2Keys = contact2.ContactParameters.GetKeys();
if (contact2Keys != null && contact2Keys.Length > 0)
{
foreach (string key in contact2Keys)
{
if (key == EXPIRES_PARAMETER_KEY || key == QVALUE_PARAMETER_KEY)
{
continue;
}
else if (contact2.ContactParameters.Get(key) != contact1.ContactParameters.Get(key))
{
return false;
}
}
}
}
return true;
}
public override string ToString()
{
if (m_userField.URI.Host == SIPConstants.SIP_REGISTER_REMOVEALL)
{
return SIPConstants.SIP_REGISTER_REMOVEALL;
}
else
{
//if (m_userField.URI.Protocol == SIPProtocolsEnum.UDP)
//{
return m_userField.ToString();
//}
//else
//{
// return m_userField.ToContactString();
//}
}
}
public SIPContactHeader CopyOf()
{
SIPContactHeader copy = new SIPContactHeader();
copy.RawHeader = RawHeader;
copy.m_userField = m_userField.CopyOf();
return copy;
}
}
public class SIPAuthenticationHeader
{
public SIPAuthorisationDigest SIPDigest;
//public string Realm;
//public string Nonce;
//public string Username;
//public string URI;
//public string Response;
private SIPAuthenticationHeader()
{
SIPDigest = new SIPAuthorisationDigest();
}
public SIPAuthenticationHeader(SIPAuthorisationDigest sipDigest)
{
SIPDigest = sipDigest;
}
public SIPAuthenticationHeader(SIPAuthorisationHeadersEnum authorisationType, string realm, string nonce)
{
SIPDigest = new SIPAuthorisationDigest(authorisationType);
SIPDigest.Realm = realm;
SIPDigest.Nonce = nonce;
}
public static SIPAuthenticationHeader ParseSIPAuthenticationHeader(SIPAuthorisationHeadersEnum authorizationType, string headerValue)
{
try
{
SIPAuthenticationHeader authHeader = new SIPAuthenticationHeader();
authHeader.SIPDigest = SIPAuthorisationDigest.ParseAuthorisationDigest(authorizationType, headerValue);
return authHeader;
}
catch
{
throw new ApplicationException("Error parsing SIP authentication header request, " + headerValue);
}
}
public override string ToString()
{
if (SIPDigest != null)
{
string authHeader = null;
SIPAuthorisationHeadersEnum authorisationHeaderType = (SIPDigest.AuthorisationResponseType != SIPAuthorisationHeadersEnum.Unknown) ? SIPDigest.AuthorisationResponseType : SIPDigest.AuthorisationType;
if (authorisationHeaderType == SIPAuthorisationHeadersEnum.Authorize)
{
authHeader = SIPHeaders.SIP_HEADER_AUTHORIZATION + ": ";
}
else if (authorisationHeaderType == SIPAuthorisationHeadersEnum.ProxyAuthenticate)
{
authHeader = SIPHeaders.SIP_HEADER_PROXYAUTHENTICATION + ": ";
}
else if (authorisationHeaderType == SIPAuthorisationHeadersEnum.ProxyAuthorization)
{
authHeader = SIPHeaders.SIP_HEADER_PROXYAUTHORIZATION + ": ";
}
else if (authorisationHeaderType == SIPAuthorisationHeadersEnum.WWWAuthenticate)
{
authHeader = SIPHeaders.SIP_HEADER_WWWAUTHENTICATE + ": ";
}
else
{
authHeader = SIPHeaders.SIP_HEADER_AUTHORIZATION + ": ";
}
return authHeader + SIPDigest.ToString();
}
else
{
return null;
}
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class SIPAuthenticationHeaderUnitTest
{
[TestFixtureSetUp]
public void Init()
{}
[TestFixtureTearDown]
public void Dispose()
{}
[Test]
public void ParseAuthHeaderUnitTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
SIPAuthenticationHeader authHeader = SIPAuthenticationHeader.ParseSIPAuthenticationHeader(SIPAuthorisationHeadersEnum.ProxyAuthorization, "Digest realm=\"o-fone.com\",nonce=\"mv1keFTRX4yYVsHb/E+rviOflIurIw\",algorithm=MD5,qop=\"auth\",username=\"joe.bloggs\", response=\"1234\",uri=\"sip:o-fone.com\"");
Console.WriteLine("SIP Auth Header=" + authHeader.ToString() + ".");
Assert.AreEqual(authHeader.SIPDigest.Realm, "o-fone.com", "The SIP auth header realm was not parsed correctly.");
Assert.AreEqual(authHeader.SIPDigest.Nonce, "mv1keFTRX4yYVsHb/E+rviOflIurIw", "The SIP auth header nonce was not parsed correctly.");
Assert.AreEqual(authHeader.SIPDigest.URI, "sip:o-fone.com", "The SIP URI was not parsed correctly.");
Assert.AreEqual(authHeader.SIPDigest.Username, "joe.bloggs", "The SIP username was not parsed correctly.");
Assert.AreEqual(authHeader.SIPDigest.Response, "1234", "The SIP response was not parsed correctly.");
}
}
#endif
#endregion
}
/// <summary>
/// The SIPRoute class is used to represent both Route and Record-Route headers.
/// </summary>
/// <bnf>
/// Route = "Route" HCOLON route-param *(COMMA route-param)
/// route-param = name-addr *( SEMI rr-param )
///
/// Record-Route = "Record-Route" HCOLON rec-route *(COMMA rec-route)
/// rec-route = name-addr *( SEMI rr-param )
/// rr-param = generic-param
///
/// name-addr = [ display-name ] LAQUOT addr-spec RAQUOT
/// addr-spec = SIP-URI / SIPS-URI / absoluteURI
/// display-name = *(token LWS)/ quoted-string
/// generic-param = token [ EQUAL gen-value ]
/// gen-value = token / host / quoted-string
/// </bnf>
/// <remarks>
/// The Route and Record-Route headers only have parameters, no headers. Parameters of from ...;name=value;name2=value2
/// There are no specific parameters.
/// </remarks>
public class SIPRoute
{
private static string m_looseRouterParameter = SIPConstants.SIP_LOOSEROUTER_PARAMETER;
private static char[] m_angles = new char[] { '<', '>' };
private SIPUserField m_userField;
public string Host
{
get { return m_userField.URI.Host; }
set { m_userField.URI.Host = value; }
}
public SIPURI URI
{
get { return m_userField.URI; }
}
public bool IsStrictRouter
{
get { return !m_userField.URI.Parameters.Has(m_looseRouterParameter); }
set
{
if (value)
{
m_userField.URI.Parameters.Remove(m_looseRouterParameter);
}
else
{
m_userField.URI.Parameters.Set(m_looseRouterParameter, null);
}
}
}
private SIPRoute()
{ }
public SIPRoute(string host)
{
if (host.IsNullOrBlank())
{
throw new SIPValidationException(SIPValidationFieldsEnum.RouteHeader, "Cannot create a Route from an blank string.");
}
m_userField = SIPUserField.ParseSIPUserField(host);
}
public SIPRoute(string host, bool looseRouter)
{
if (host.IsNullOrBlank())
{
throw new SIPValidationException(SIPValidationFieldsEnum.RouteHeader, "Cannot create a Route from an blank string.");
}
m_userField = SIPUserField.ParseSIPUserField(host);
this.IsStrictRouter = !looseRouter;
}
public SIPRoute(SIPURI uri)
{
m_userField = new SIPUserField();
m_userField.URI = uri;
}
public SIPRoute(SIPURI uri, bool looseRouter)
{
m_userField = new SIPUserField();
m_userField.URI = uri;
this.IsStrictRouter = !looseRouter;
}
public static SIPRoute ParseSIPRoute(string route)
{
if (route.IsNullOrBlank())
{
throw new SIPValidationException(SIPValidationFieldsEnum.RouteHeader, "Cannot create a Route from an blank string.");
}
try
{
SIPRoute sipRoute = new SIPRoute();
sipRoute.m_userField = SIPUserField.ParseSIPUserField(route);
return sipRoute;
}
catch (Exception excp)
{
throw new SIPValidationException(SIPValidationFieldsEnum.RouteHeader, excp.Message);
}
}
public override string ToString()
{
//if (m_userField.URI.Protocol == SIPProtocolsEnum.UDP)
//{
return m_userField.ToString();
//}
//else
//{
//return m_userField.ToContactString();
//}
}
public SIPEndPoint ToSIPEndPoint()
{
return URI.ToSIPEndPoint();
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class SIPRouteHeaderUnitTest
{
[TestFixtureSetUp]
public void Init()
{}
[TestFixtureTearDown]
public void Dispose()
{}
[Test]
public void MissingBracketsRouteTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
SIPRoute newRoute = new SIPRoute("sip:127.0.0.1:5060");
Console.WriteLine(newRoute.ToString());
Assert.IsTrue(newRoute.URI.ToString() == "sip:127.0.0.1:5060", "The Route header URI was not correctly parsed.");
}
[Test]
public void ParseRouteTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
SIPRoute route = SIPRoute.ParseSIPRoute("<sip:127.0.0.1:5060;lr>");
Console.WriteLine("SIP Route=" + route.ToString() + ".");
Assert.AreEqual(route.Host, "127.0.0.1:5060", "The SIP route host was not parsed correctly.");
Assert.AreEqual(route.ToString(), "<sip:127.0.0.1:5060;lr>", "The SIP route string was not correct.");
Assert.IsFalse(route.IsStrictRouter, "Route was not correctly passed as a loose router.");
}
[Test]
public void SetLooseRouteTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
SIPRoute route = SIPRoute.ParseSIPRoute("<sip:127.0.0.1:5060>");
route.IsStrictRouter = false;
Console.WriteLine("SIP Route=" + route.ToString() + ".");
Assert.AreEqual(route.Host, "127.0.0.1:5060", "The SIP route host was not parsed correctly.");
Assert.AreEqual(route.ToString(), "<sip:127.0.0.1:5060;lr>", "The SIP route string was not correct.");
Assert.IsFalse(route.IsStrictRouter, "Route was not correctly settable as a loose router.");
}
[Test]
public void RemoveLooseRouterTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
SIPRoute route = SIPRoute.ParseSIPRoute("<sip:127.0.0.1:5060;lr>");
route.IsStrictRouter = true;
Console.WriteLine("SIP Route=" + route.ToString() + ".");
Assert.AreEqual(route.Host, "127.0.0.1:5060", "The SIP route host was not parsed correctly.");
Assert.AreEqual(route.ToString(), "<sip:127.0.0.1:5060>", "The SIP route string was not correct.");
Assert.IsTrue(route.IsStrictRouter, "Route was not correctly settable as a strict router.");
}
[Test]
public void ParseRouteWithDisplayNameTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
SIPRoute route = SIPRoute.ParseSIPRoute("12345656 <sip:127.0.0.1:5060;lr>");
Console.WriteLine("SIP Route=" + route.ToString() + ".");
Console.WriteLine("Route to SIPEndPoint=" + route.ToSIPEndPoint().ToString() + ".");
Assert.AreEqual(route.Host, "127.0.0.1:5060", "The SIP route host was not parsed correctly.");
Assert.AreEqual(route.ToString(), "\"12345656\" <sip:127.0.0.1:5060;lr>", "The SIP route string was not correct.");
Assert.IsFalse(route.IsStrictRouter, "Route was not correctly passed as a loose router.");
Assert.AreEqual(route.ToSIPEndPoint().ToString(), "udp:127.0.0.1:5060", "The SIP route did not produce the correct SIP End Point.");
}
[Test]
public void ParseRouteWithDoubleQuotedDisplayNameTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
SIPRoute route = SIPRoute.ParseSIPRoute("\"Joe Bloggs\" <sip:127.0.0.1:5060;lr>");
Console.WriteLine("SIP Route=" + route.ToString() + ".");
Assert.AreEqual(route.Host, "127.0.0.1:5060", "The SIP route host was not parsed correctly.");
Assert.AreEqual(route.ToString(), "\"Joe Bloggs\" <sip:127.0.0.1:5060;lr>", "The SIP route string was not correct.");
Assert.IsFalse(route.IsStrictRouter, "Route was not correctly passed as a loose router.");
}
[Test]
public void ParseRouteWithUserPortionTest() {
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string routeStr = "<sip:[email protected]:5060;lr;transport=udp>";
SIPRoute route = SIPRoute.ParseSIPRoute(routeStr);
Console.WriteLine("SIP Route=" + route.ToString() + ".");
Console.WriteLine("Route to SIPEndPoint=" + route.ToSIPEndPoint().ToString() + ".");
Assert.AreEqual(route.Host, "127.0.0.1:5060", "The SIP route host was not parsed correctly.");
Assert.AreEqual(route.ToString(), routeStr, "The SIP route string was not correct.");
Assert.IsFalse(route.IsStrictRouter, "Route was not correctly passed as a loose router.");
Assert.AreEqual(route.ToSIPEndPoint().ToString(), "udp:127.0.0.1:5060", "The SIP route did not produce the correct SIP End Point.");
}
}
#endif
#endregion
}
public class SIPRouteSet
{
private static ILog logger = AssemblyState.logger;
private List<SIPRoute> m_sipRoutes = new List<SIPRoute>();
public int Length
{
get { return m_sipRoutes.Count; }
}
public static SIPRouteSet ParseSIPRouteSet(string routeSet)
{
SIPRouteSet sipRouteSet = new SIPRouteSet();
string[] routes = SIPParameters.GetKeyValuePairsFromQuoted(routeSet, ',');
foreach (string route in routes)
{
SIPRoute sipRoute = SIPRoute.ParseSIPRoute(route);
sipRouteSet.AddBottomRoute(sipRoute);
}
return sipRouteSet;
}
public SIPRoute GetAt(int index)
{
return m_sipRoutes[index];
}
public void SetAt(int index, SIPRoute sipRoute)
{
m_sipRoutes[index] = sipRoute;
}
public SIPRoute TopRoute
{
get
{
if (m_sipRoutes != null && m_sipRoutes.Count > 0)
{
return m_sipRoutes[0];
}
else
{
return null;
}
}
}
public SIPRoute BottomRoute
{
get
{
if (m_sipRoutes != null && m_sipRoutes.Count > 0)
{
return m_sipRoutes[m_sipRoutes.Count - 1];
}
else
{
return null;
}
}
}
public void PushRoute(SIPRoute route)
{
m_sipRoutes.Insert(0, route);
}
public void PushRoute(string host)
{
m_sipRoutes.Insert(0, new SIPRoute(host, true));
}
public void PushRoute(IPEndPoint socket, SIPSchemesEnum scheme, SIPProtocolsEnum protcol)
{
m_sipRoutes.Insert(0, new SIPRoute(scheme + ":" + socket.ToString(), true));
}
public void AddBottomRoute(SIPRoute route)
{
m_sipRoutes.Insert(m_sipRoutes.Count, route);
}
public SIPRoute PopRoute()
{
SIPRoute route = null;
if (m_sipRoutes.Count > 0)
{
route = m_sipRoutes[0];
m_sipRoutes.RemoveAt(0);
}
return route;
}
public void RemoveBottomRoute()
{
if (m_sipRoutes.Count > 0)
{
m_sipRoutes.RemoveAt(m_sipRoutes.Count - 1);
};
}
public SIPRouteSet Reversed()
{
if (m_sipRoutes != null && m_sipRoutes.Count > 0)
{
SIPRouteSet reversedSet = new SIPRouteSet();
for (int index = 0; index < m_sipRoutes.Count; index++)
{
reversedSet.PushRoute(m_sipRoutes[index]);
}
return reversedSet;
}
else
{
return null;
}
}
/// <summary>
/// If a route set is travelling from the public side of a proxy to the private side it can be required that the Record-Route set is modified.
/// </summary>
/// <param name="origSocket">The socket string in the original route set that needs to be replace.</param>
/// <param name="replacementSocket">The socket string the original route is being replaced with.</param>
public void ReplaceRoute(string origSocket, string replacementSocket)
{
foreach (SIPRoute route in m_sipRoutes)
{
if (route.Host == origSocket)
{
route.Host = replacementSocket;
}
}
}
public new string ToString()
{
string routeStr = null;
if (m_sipRoutes != null && m_sipRoutes.Count > 0)
{
for (int routeIndex = 0; routeIndex < m_sipRoutes.Count; routeIndex++)
{
routeStr += (routeStr != null) ? "," + m_sipRoutes[routeIndex].ToString() : m_sipRoutes[routeIndex].ToString();
}
}
return routeStr;
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class RouteSetUnitTest
{
[Test]
public void SampleTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
}
[Test]
public void ParseSIPRouteSetTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string routeSetString = "<sip:127.0.0.1:5434;lr>,<sip:10.0.0.1>,<sip:192.168.0.1;ftag=12345;lr=on>";
SIPRouteSet routeSet = ParseSIPRouteSet(routeSetString);
Console.WriteLine(routeSet.ToString());
Assert.IsTrue(routeSet.Length == 3, "The parsed route set had an incorrect length.");
Assert.IsTrue(routeSet.ToString() == routeSetString, "The parsed route set did not produce the same string as the original parsed value.");
SIPRoute topRoute = routeSet.PopRoute();
Assert.IsTrue(topRoute.Host == "127.0.0.1:5434", "The first route host was not parsed correctly.");
Assert.IsFalse(topRoute.IsStrictRouter, "The first route host was not correctly recognised as a loose router.");
topRoute = routeSet.PopRoute();
Assert.IsTrue(topRoute.Host == "10.0.0.1", "The second route host was not parsed correctly.");
Assert.IsTrue(topRoute.IsStrictRouter, "The second route host was not correctly recognised as a strict router.");
topRoute = routeSet.PopRoute();
Assert.IsTrue(topRoute.Host == "192.168.0.1", "The third route host was not parsed correctly.");
Assert.IsFalse(topRoute.IsStrictRouter, "The third route host was not correctly recognised as a loose router.");
Assert.IsTrue(topRoute.URI.Parameters.Get("ftag") == "12345", "The ftag parameter on the third route was not correctly parsed.");
}
}
#endif
#endregion
}
public class SIPViaSet
{
private static string m_CRLF = SIPConstants.CRLF;
private List<SIPViaHeader> m_viaHeaders = new List<SIPViaHeader>();
public int Length
{
get { return m_viaHeaders.Count; }
}
public List<SIPViaHeader> Via
{
get
{
return m_viaHeaders;
}
set
{
m_viaHeaders = value;
}
}
public SIPViaHeader TopViaHeader
{
get
{
if (m_viaHeaders != null && m_viaHeaders.Count > 0)
{
return m_viaHeaders[0];
}
else
{
return null;
}
}
}
public SIPViaHeader BottomViaHeader
{
get
{
if (m_viaHeaders != null && m_viaHeaders.Count > 0)
{
return m_viaHeaders[m_viaHeaders.Count - 1];
}
else
{
return null;
}
}
}
/// <summary>
/// Pops top Via header off the array.
/// </summary>
public SIPViaHeader PopTopViaHeader()
{
SIPViaHeader topHeader = m_viaHeaders[0];
m_viaHeaders.RemoveAt(0);
return topHeader;
}
public void AddBottomViaHeader(SIPViaHeader viaHeader)
{
m_viaHeaders.Add(viaHeader);
}
/// <summary>
/// Updates the topmost Via header by setting the received and rport parameters to the IP address and port
/// the request came from.
/// </summary>
/// <remarks>The setting of the received parameter is documented in RFC3261 section 18.2.1 and in RFC3581
/// section 4. RFC3581 states that the received parameter value must be set even if it's the same as the
/// address in the sent from field. The setting of the rport parameter is documented in RFC3581 section 4.
/// An attempt was made to comply with the RFC3581 standard and only set the rport parameter if it was included
/// by the client user agent however in the wild there are too many user agents that are behind symmetric NATs
/// not setting an empty rport and if it's not added then they will not be able to communicate.
/// </remarks>
/// <param name="msgRcvdEndPoint">The remote endpoint the request was received from.</param>
public void UpateTopViaHeader(IPEndPoint msgRcvdEndPoint)
{
// Update the IP Address and port that this request was received on.
SIPViaHeader topViaHeader = this.TopViaHeader;
topViaHeader.ReceivedFromIPAddress = msgRcvdEndPoint.Address.ToString();
topViaHeader.ReceivedFromPort = msgRcvdEndPoint.Port;
}
/// <summary>
/// Pushes a new Via header onto the top of the array.
/// </summary>
public void PushViaHeader(SIPViaHeader viaHeader)
{
m_viaHeaders.Insert(0, viaHeader);
}
public new string ToString()
{
string viaStr = null;
if (m_viaHeaders != null && m_viaHeaders.Count > 0)
{
for (int viaIndex = 0; viaIndex < m_viaHeaders.Count; viaIndex++)
{
viaStr += (m_viaHeaders[viaIndex]).ToString() + m_CRLF;
}
}
return viaStr;
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class SIPViaSetUnitTest
{
[Test]
public void AdjustReceivedViaHeaderTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string xtenViaHeader = "SIP/2.0/UDP 192.168.1.2:5065;rport;branch=z9hG4bKFBB7EAC06934405182D13950BD51F001";
SIPViaHeader[] sipViaHeaders = SIPViaHeader.ParseSIPViaHeader(xtenViaHeader);
SIPViaSet viaSet = new SIPViaSet();
viaSet.PushViaHeader(sipViaHeaders[0]);
viaSet.UpateTopViaHeader(IPSocket.ParseSocketString("88.88.88.88:1234"));
Assert.IsTrue(viaSet.Length == 1, "Incorrect number of Via headers in set.");
Assert.IsTrue(viaSet.TopViaHeader.Host == "192.168.1.2", "Top Via Host was incorrect.");
Assert.IsTrue(viaSet.TopViaHeader.Port == 5065, "Top Via Port was incorrect.");
Assert.IsTrue(viaSet.TopViaHeader.ContactAddress == "192.168.1.2:5065", "Top Via ContactAddress was incorrect.");
Assert.IsTrue(viaSet.TopViaHeader.ReceivedFromIPAddress == "88.88.88.88", "Top Via received was incorrect.");
Assert.IsTrue(viaSet.TopViaHeader.ReceivedFromPort == 1234, "Top Via rport was incorrect.");
Console.WriteLine("---------------------------------------------------");
}
/// <summary>
/// Tests that when the sent from socket is the same as the socket received from that the received and rport
/// parameters are still updated.
/// </summary>
[Test]
public void AdjustReceivedCorrectAlreadyViaHeaderTest()
{
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
string xtenViaHeader = "SIP/2.0/UDP 192.168.1.2:5065;rport;branch=z9hG4bKFBB7EAC06934405182D13950BD51F001";
SIPViaHeader[] sipViaHeaders = SIPViaHeader.ParseSIPViaHeader(xtenViaHeader);
SIPViaSet viaSet = new SIPViaSet();
viaSet.PushViaHeader(sipViaHeaders[0]);
viaSet.UpateTopViaHeader(IPSocket.ParseSocketString("192.168.1.2:5065"));
Assert.IsTrue(viaSet.Length == 1, "Incorrect number of Via headers in set.");
Assert.IsTrue(viaSet.TopViaHeader.Host == "192.168.1.2", "Top Via Host was incorrect.");
Assert.IsTrue(viaSet.TopViaHeader.Port == 5065, "Top Via Port was incorrect.");
Assert.IsTrue(viaSet.TopViaHeader.ContactAddress == "192.168.1.2:5065", "Top Via ContactAddress was incorrect.");
Assert.IsTrue(viaSet.TopViaHeader.ReceivedFromIPAddress == "192.168.1.2", "Top Via received was incorrect.");
Assert.IsTrue(viaSet.TopViaHeader.ReceivedFromPort == 5065, "Top Via rport was incorrect.");
Console.WriteLine("---------------------------------------------------");
}
}
#endif
#endregion
}
/// <bnf>
/// header = "header-name" HCOLON header-value *(COMMA header-value)
/// field-name: field-value CRLF
/// </bnf>
public class SIPHeader
{
public const int DEFAULT_CSEQ = 100;
private static ILog logger = AssemblyState.logger;
private static string m_CRLF = SIPConstants.CRLF;
// RFC SIP headers.
public string Accept;
public string AcceptEncoding;
public string AcceptLanguage;
public string AlertInfo;
public string Allow;
public string AllowEvents; // RFC3265 SIP Events.
public string AuthenticationInfo;
public SIPAuthenticationHeader AuthenticationHeader;
public string CallId;
public string CallInfo;
public List<SIPContactHeader> Contact = new List<SIPContactHeader>();
public string ContentDisposition;
public string ContentEncoding;
public string ContentLanguage;
public string ContentType;
public int ContentLength = 0;
public int CSeq = -1;
public SIPMethodsEnum CSeqMethod;
public string Date;
public string ErrorInfo;
public string ETag; // added by Tilmann: look RFC3903
public string Event; // RFC3265 SIP Events.
public int Expires = -1;
public SIPFromHeader From;
public string InReplyTo;
public int MinExpires = -1;
public int MaxForwards = SIPConstants.DEFAULT_MAX_FORWARDS;
public string MIMEVersion;
public string Organization;
public string Priority;
public string ProxyRequire;
public string Reason;
public SIPRouteSet RecordRoutes = new SIPRouteSet();
public string ReferredBy; // RFC 3515 "The Session Initiation Protocol (SIP) Refer Method"
public string ReferSub; // RFC 4488 If set to false indicates the implict REFER subscription should not be created.
public string ReferTo; // RFC 3515 "The Session Initiation Protocol (SIP) Refer Method"
public string ReplyTo;
public string Require;
public string RetryAfter;
public SIPRouteSet Routes = new SIPRouteSet();
public string Server;
public string Subject;
public string SubscriptionState; // RFC3265 SIP Events.
public string Supported;
public string Timestamp;
public SIPToHeader To;
public string Unsupported;
public string UserAgent;
public SIPViaSet Vias = new SIPViaSet();
public string Warning;
// Non-core custom SIP headers used to allow a SIP Proxy to communicate network info to internal server agents.
public string ProxyReceivedOn; // The Proxy socket that the SIP message was received on.
public string ProxyReceivedFrom; // The remote socket that the Proxy received the SIP message on.
public string ProxySendFrom; // The Proxy socket that the SIP message should be transmitted from.
//public string ProxyOutboundProxy; // The remote socket that the Proxy should send the SIP request to.
// Non-core custom SIP headers for use with the SIP Sorcery switchboard.
public string SwitchboardOriginalCallID; // The original Call-ID header on the call that was forwarded to the switchboard.
//public string SwitchboardOriginalFrom; // The original From header on the call that was forwarded to the switchboard.
//public string SwitchboardOriginalTo; // The original To header on the call that was forwarded to the switchboard.
public string SwitchboardLineName; // An optional name for the line the call was received on.
public string SwitchboardOwner; // If a switchboard operator "grabs" a call then they will take exclusive ownership of it. This field records the owner.
public string SwitchboardTerminate; // Can be set on a BYE request to indicate whether the switchboard is requesting both, current or opposite dialogues to be hungup.
//public string SwitchboardFromContactURL;
//public int SwitchboardTokenRequest; // A user agent can request a token from a sipsorcery server and this value indicates the period the token is being requested for.
//public string SwitchboardToken; // If a token is issued this header will be used to hold it in the response.
// Non-core custom headers for CMR integration.
public string CRMPersonName; // The matching name from the CRM system for the caller.
public string CRMCompanyName; // The matching company name from the CRM system for the caller.
public string CRMPictureURL; // If available a URL for a picture for the person or company from the CRM system for the caller.
public List<string> UnknownHeaders = new List<string>(); // Holds any unrecognised headers.
public SIPHeader()
{ }
public SIPHeader(string fromHeader, string toHeader, int cseq, string callId)
{
SIPFromHeader from = SIPFromHeader.ParseFromHeader(fromHeader);
SIPToHeader to = SIPToHeader.ParseToHeader(toHeader);
Initialise(null, from, to, cseq, callId);
}
public SIPHeader(string fromHeader, string toHeader, string contactHeader, int cseq, string callId)
{
SIPFromHeader from = SIPFromHeader.ParseFromHeader(fromHeader);
SIPToHeader to = SIPToHeader.ParseToHeader(toHeader);
List<SIPContactHeader> contact = SIPContactHeader.ParseContactHeader(contactHeader);
Initialise(contact, from, to, cseq, callId);
}
public SIPHeader(SIPFromHeader from, SIPToHeader to, int cseq, string callId)
{
Initialise(null, from, to, cseq, callId);
}
public SIPHeader(SIPContactHeader contact, SIPFromHeader from, SIPToHeader to, int cseq, string callId)
{
List<SIPContactHeader> contactList = new List<SIPContactHeader>();
if (contact != null)
{
contactList.Add(contact);
}
Initialise(contactList, from, to, cseq, callId);
}
public SIPHeader(List<SIPContactHeader> contactList, SIPFromHeader from, SIPToHeader to, int cseq, string callId)
{
Initialise(contactList, from, to, cseq, callId);
}
private void Initialise(List<SIPContactHeader> contact, SIPFromHeader from, SIPToHeader to, int cseq, string callId)
{
if (from == null)
{
throw new ApplicationException("The From header cannot be empty when creating a new SIP header.");
}
if (to == null)
{
throw new ApplicationException("The To header cannot be empty when creating a new SIP header.");
}
if (callId == null || callId.Trim().Length == 0)
{
throw new ApplicationException("The CallId header cannot be empty when creating a new SIP header.");
}
From = from;
To = to;
Contact = contact;
CallId = callId;
if (cseq > 0 && cseq < Int32.MaxValue)
{
CSeq = cseq;
}
else
{
CSeq = DEFAULT_CSEQ;
}
}
public static string[] SplitHeaders(string message)
{
// SIP headers can be extended across lines if the first character of the next line is at least on whitespace character.
message = Regex.Replace(message, m_CRLF + @"\s+", " ", RegexOptions.Singleline);
// Some user agents couldn't get the \r\n bit right.
message = Regex.Replace(message, "\r ", m_CRLF, RegexOptions.Singleline);
return Regex.Split(message, m_CRLF);
}
public static SIPHeader ParseSIPHeaders(string[] headersCollection)
{
try
{
SIPHeader sipHeader = new SIPHeader();
sipHeader.MaxForwards = -1; // This allows detection of whether this header is present or not.
string lastHeader = null;
for (int lineIndex = 0; lineIndex < headersCollection.Length; lineIndex++)
{
string headerLine = headersCollection[lineIndex];
if (headerLine.IsNullOrBlank())
{
// No point processing blank headers.
continue;
}
string headerName = null;
string headerValue = null;
// If the first character of a line is whitespace it's a contiuation of the previous line.
if (headerLine.StartsWith(" "))
{
headerName = lastHeader;
headerValue = headerLine.Trim();
}
else
{
headerLine = headerLine.Trim();
int delimiterIndex = headerLine.IndexOf(SIPConstants.HEADER_DELIMITER_CHAR);
if (delimiterIndex == -1)
{
logger.Warn("Invalid SIP header, ignoring, " + headerLine + ".");
continue;
}
headerName = headerLine.Substring(0, delimiterIndex).Trim();
headerValue = headerLine.Substring(delimiterIndex + 1).Trim();
}
try
{
string headerNameLower = headerName.ToLower();
#region Via
if (headerNameLower == SIPHeaders.SIP_COMPACTHEADER_VIA ||
headerNameLower == SIPHeaders.SIP_HEADER_VIA.ToLower())
{
//sipHeader.RawVia += headerValue;
SIPViaHeader[] viaHeaders = SIPViaHeader.ParseSIPViaHeader(headerValue);
if (viaHeaders != null && viaHeaders.Length > 0)
{
foreach (SIPViaHeader viaHeader in viaHeaders)
{
sipHeader.Vias.AddBottomViaHeader(viaHeader);
}
}
}
#endregion
#region CallId
else if (headerNameLower == SIPHeaders.SIP_COMPACTHEADER_CALLID ||
headerNameLower == SIPHeaders.SIP_HEADER_CALLID.ToLower())
{
sipHeader.CallId = headerValue;
}
#endregion
#region CSeq
else if (headerNameLower == SIPHeaders.SIP_HEADER_CSEQ.ToLower())
{
//sipHeader.RawCSeq += headerValue;
string[] cseqFields = headerValue.Split(' ');
if (cseqFields == null || cseqFields.Length == 0)
{
logger.Warn("The " + SIPHeaders.SIP_HEADER_CSEQ + " was empty.");
}
else
{
if (!Int32.TryParse(cseqFields[0], out sipHeader.CSeq))
{
logger.Warn(SIPHeaders.SIP_HEADER_CSEQ + " did not contain a valid integer, " + headerLine + ".");
}
if (cseqFields != null && cseqFields.Length > 1)
{
sipHeader.CSeqMethod = SIPMethods.GetMethod(cseqFields[1]);
}
else
{
logger.Warn("There was no " + SIPHeaders.SIP_HEADER_CSEQ + " method, " + headerLine + ".");
}
}
}
#endregion
#region Expires
else if (headerNameLower == SIPHeaders.SIP_HEADER_EXPIRES.ToLower())
{
//sipHeader.RawExpires += headerValue;
if (!Int32.TryParse(headerValue, out sipHeader.Expires))
{
logger.Warn("The Expires value was not a valid integer, " + headerLine + ".");
}
}
#endregion
#region Min-Expires
else if (headerNameLower == SIPHeaders.SIP_HEADER_MINEXPIRES.ToLower())
{
if (!Int32.TryParse(headerValue, out sipHeader.MinExpires))
{
logger.Warn("The Min-Expires value was not a valid integer, " + headerLine + ".");
}
}
#endregion
#region Contact
else if (headerNameLower == SIPHeaders.SIP_COMPACTHEADER_CONTACT ||
headerNameLower == SIPHeaders.SIP_HEADER_CONTACT.ToLower())
{
List<SIPContactHeader> contacts = SIPContactHeader.ParseContactHeader(headerValue);
if (contacts != null && contacts.Count > 0)
{
sipHeader.Contact.AddRange(contacts);
}
}
#endregion
#region From
else if (headerNameLower == SIPHeaders.SIP_COMPACTHEADER_FROM ||
headerNameLower == SIPHeaders.SIP_HEADER_FROM.ToLower())
{
//sipHeader.RawFrom = headerValue;
sipHeader.From = SIPFromHeader.ParseFromHeader(headerValue);
}
#endregion
#region To
else if (headerNameLower == SIPHeaders.SIP_COMPACTHEADER_TO ||
headerNameLower == SIPHeaders.SIP_HEADER_TO.ToLower())
{
//sipHeader.RawTo = headerValue;
sipHeader.To = SIPToHeader.ParseToHeader(headerValue);
}
#endregion
#region WWWAuthenticate
else if (headerNameLower == SIPHeaders.SIP_HEADER_WWWAUTHENTICATE.ToLower())
{
//sipHeader.RawAuthentication = headerValue;
sipHeader.AuthenticationHeader = SIPAuthenticationHeader.ParseSIPAuthenticationHeader(SIPAuthorisationHeadersEnum.WWWAuthenticate, headerValue);
}
#endregion
#region Authorization
else if (headerNameLower == SIPHeaders.SIP_HEADER_AUTHORIZATION.ToLower())
{
//sipHeader.RawAuthentication = headerValue;
sipHeader.AuthenticationHeader = SIPAuthenticationHeader.ParseSIPAuthenticationHeader(SIPAuthorisationHeadersEnum.Authorize, headerValue);
}
#endregion
#region ProxyAuthentication
else if (headerNameLower == SIPHeaders.SIP_HEADER_PROXYAUTHENTICATION.ToLower())
{
//sipHeader.RawAuthentication = headerValue;
sipHeader.AuthenticationHeader = SIPAuthenticationHeader.ParseSIPAuthenticationHeader(SIPAuthorisationHeadersEnum.ProxyAuthenticate, headerValue);
}
#endregion
#region ProxyAuthorization
else if (headerNameLower == SIPHeaders.SIP_HEADER_PROXYAUTHORIZATION.ToLower())
{
sipHeader.AuthenticationHeader = SIPAuthenticationHeader.ParseSIPAuthenticationHeader(SIPAuthorisationHeadersEnum.ProxyAuthorization, headerValue);
}
#endregion
#region UserAgent
else if (headerNameLower == SIPHeaders.SIP_HEADER_USERAGENT.ToLower())
{
sipHeader.UserAgent = headerValue;
}
#endregion
#region MaxForwards
else if (headerNameLower == SIPHeaders.SIP_HEADER_MAXFORWARDS.ToLower())
{
if (!Int32.TryParse(headerValue, out sipHeader.MaxForwards))
{
logger.Warn("The " + SIPHeaders.SIP_HEADER_MAXFORWARDS + " could not be parsed as a valid integer, " + headerLine + ".");
}
}
#endregion
#region ContentLength
else if (headerNameLower == SIPHeaders.SIP_COMPACTHEADER_CONTENTLENGTH ||
headerNameLower == SIPHeaders.SIP_HEADER_CONTENTLENGTH.ToLower())
{
if (!Int32.TryParse(headerValue, out sipHeader.ContentLength))
{
logger.Warn("The " + SIPHeaders.SIP_HEADER_CONTENTLENGTH + " could not be parsed as a valid integer.");
}
}
#endregion
#region ContentType
else if (headerNameLower == SIPHeaders.SIP_COMPACTHEADER_CONTENTTYPE ||
headerNameLower == SIPHeaders.SIP_HEADER_CONTENTTYPE.ToLower())
{
sipHeader.ContentType = headerValue;
}
#endregion
#region Accept
else if (headerNameLower == SIPHeaders.SIP_HEADER_ACCEPT.ToLower())
{
sipHeader.Accept = headerValue;
}
#endregion
#region Route
else if (headerNameLower == SIPHeaders.SIP_HEADER_ROUTE.ToLower())
{
SIPRouteSet routeSet = SIPRouteSet.ParseSIPRouteSet(headerValue);
if (routeSet != null)
{
while (routeSet.Length > 0)
{
sipHeader.Routes.AddBottomRoute(routeSet.PopRoute());
}
}
}
#endregion
#region RecordRoute
else if (headerNameLower == SIPHeaders.SIP_HEADER_RECORDROUTE.ToLower())
{
SIPRouteSet recordRouteSet = SIPRouteSet.ParseSIPRouteSet(headerValue);
if (recordRouteSet != null)
{
while (recordRouteSet.Length > 0)
{
sipHeader.RecordRoutes.AddBottomRoute(recordRouteSet.PopRoute());
}
}
}
#endregion
#region Allow-Events
else if (headerNameLower == SIPHeaders.SIP_HEADER_ALLOW_EVENTS || headerNameLower == SIPHeaders.SIP_COMPACTHEADER_ALLOWEVENTS)
{
sipHeader.AllowEvents = headerValue;
}
#endregion
#region Event
else if (headerNameLower == SIPHeaders.SIP_HEADER_EVENT.ToLower() || headerNameLower == SIPHeaders.SIP_COMPACTHEADER_EVENT)
{
sipHeader.Event = headerValue;
}
#endregion
#region SubscriptionState.
else if (headerNameLower == SIPHeaders.SIP_HEADER_SUBSCRIPTION_STATE.ToLower())
{
sipHeader.SubscriptionState = headerValue;
}
#endregion
#region Timestamp.
else if (headerNameLower == SIPHeaders.SIP_HEADER_TIMESTAMP.ToLower())
{
sipHeader.Timestamp = headerValue;
}
#endregion
#region Date.
else if (headerNameLower == SIPHeaders.SIP_HEADER_DATE.ToLower())
{
sipHeader.Date = headerValue;
}
#endregion
#region Refer-Sub.
else if (headerNameLower == SIPHeaders.SIP_HEADER_REFERSUB.ToLower())
{
if (sipHeader.ReferSub == null)
{
sipHeader.ReferSub = headerValue;
}
else
{
throw new SIPValidationException(SIPValidationFieldsEnum.ReferToHeader, "Only a single Refer-Sub header is permitted.");
}
}
#endregion
#region Refer-To.
else if (headerNameLower == SIPHeaders.SIP_HEADER_REFERTO.ToLower() ||
headerNameLower == SIPHeaders.SIP_COMPACTHEADER_REFERTO)
{
if (sipHeader.ReferTo == null)
{
sipHeader.ReferTo = headerValue;
}
else
{
throw new SIPValidationException(SIPValidationFieldsEnum.ReferToHeader, "Only a single Refer-To header is permitted.");
}
}
#endregion
#region Referred-By.
else if (headerNameLower == SIPHeaders.SIP_HEADER_REFERREDBY.ToLower())
{
sipHeader.ReferredBy = headerValue;
}
#endregion
#region Require.
else if (headerNameLower == SIPHeaders.SIP_HEADER_REQUIRE.ToLower())
{
sipHeader.Require = headerValue;
}
#endregion
#region Reason.
else if (headerNameLower == SIPHeaders.SIP_HEADER_REASON.ToLower())
{
sipHeader.Reason = headerValue;
}
#endregion
#region Proxy-ReceivedFrom.
else if (headerNameLower == SIPHeaders.SIP_HEADER_PROXY_RECEIVEDFROM.ToLower())
{
sipHeader.ProxyReceivedFrom = headerValue;
}
#endregion
#region Proxy-ReceivedOn.
else if (headerNameLower == SIPHeaders.SIP_HEADER_PROXY_RECEIVEDON.ToLower())
{
sipHeader.ProxyReceivedOn = headerValue;
}
#endregion
#region Proxy-SendFrom.
else if (headerNameLower == SIPHeaders.SIP_HEADER_PROXY_SENDFROM.ToLower())
{
sipHeader.ProxySendFrom = headerValue;
}
#endregion
#region Supported
else if (headerNameLower == SIPHeaders.SIP_COMPACTHEADER_SUPPORTED ||
headerNameLower == SIPHeaders.SIP_HEADER_SUPPORTED.ToLower())
{
sipHeader.Supported = headerValue;
}
#endregion
#region Authentication-Info
else if (headerNameLower == SIPHeaders.SIP_HEADER_AUTHENTICATIONINFO.ToLower())
{
sipHeader.AuthenticationInfo = headerValue;
}
#endregion
#region Accept-Encoding
else if (headerNameLower == SIPHeaders.SIP_HEADER_ACCEPTENCODING.ToLower())
{
sipHeader.AcceptEncoding = headerValue;
}
#endregion
#region Accept-Language
else if (headerNameLower == SIPHeaders.SIP_HEADER_ACCEPTLANGUAGE.ToLower())
{
sipHeader.AcceptLanguage = headerValue;
}
#endregion
#region Alert-Info
else if (headerNameLower == SIPHeaders.SIP_HEADER_ALERTINFO.ToLower())
{
sipHeader.AlertInfo = headerValue;
}
#endregion
#region Allow
else if (headerNameLower == SIPHeaders.SIP_HEADER_ALLOW.ToLower())
{
sipHeader.Allow = headerValue;
}
#endregion
#region Call-Info
else if (headerNameLower == SIPHeaders.SIP_HEADER_CALLINFO.ToLower())
{
sipHeader.CallInfo = headerValue;
}
#endregion
#region Content-Disposition
else if (headerNameLower == SIPHeaders.SIP_HEADER_CONTENT_DISPOSITION.ToLower())
{
sipHeader.ContentDisposition = headerValue;
}
#endregion
#region Content-Encoding
else if (headerNameLower == SIPHeaders.SIP_HEADER_CONTENT_ENCODING.ToLower())
{
sipHeader.ContentEncoding = headerValue;
}
#endregion
#region Content-Language
else if (headerNameLower == SIPHeaders.SIP_HEADER_CONTENT_LANGUAGE.ToLower())
{
sipHeader.ContentLanguage = headerValue;
}
#endregion
#region Error-Info
else if (headerNameLower == SIPHeaders.SIP_HEADER_ERROR_INFO.ToLower())
{
sipHeader.ErrorInfo = headerValue;
}
#endregion
#region In-Reply-To
else if (headerNameLower == SIPHeaders.SIP_HEADER_IN_REPLY_TO.ToLower())
{
sipHeader.InReplyTo = headerValue;
}
#endregion
#region MIME-Version
else if (headerNameLower == SIPHeaders.SIP_HEADER_MIME_VERSION.ToLower())
{
sipHeader.MIMEVersion = headerValue;
}
#endregion
#region Organization
else if (headerNameLower == SIPHeaders.SIP_HEADER_ORGANIZATION.ToLower())
{
sipHeader.Organization = headerValue;
}
#endregion
#region Priority
else if (headerNameLower == SIPHeaders.SIP_HEADER_PRIORITY.ToLower())
{
sipHeader.Priority = headerValue;
}
#endregion
#region Proxy-Require
else if (headerNameLower == SIPHeaders.SIP_HEADER_PROXY_REQUIRE.ToLower())
{
sipHeader.ProxyRequire = headerValue;
}
#endregion
#region Reply-To
else if (headerNameLower == SIPHeaders.SIP_HEADER_REPLY_TO.ToLower())
{
sipHeader.ReplyTo = headerValue;
}
#endregion
#region Retry-After
else if (headerNameLower == SIPHeaders.SIP_HEADER_RETRY_AFTER.ToLower())
{
sipHeader.RetryAfter = headerValue;
}
#endregion
#region Subject
else if (headerNameLower == SIPHeaders.SIP_HEADER_SUBJECT.ToLower())
{
sipHeader.Subject = headerValue;
}
#endregion
#region Unsupported
else if (headerNameLower == SIPHeaders.SIP_HEADER_UNSUPPORTED.ToLower())
{
sipHeader.Unsupported = headerValue;
}
#endregion
#region Warning
else if (headerNameLower == SIPHeaders.SIP_HEADER_WARNING.ToLower())
{
sipHeader.Warning = headerValue;
}
#endregion
#region Switchboard-OriginalCallID.
else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_ORIGINAL_CALLID.ToLower())
{
sipHeader.SwitchboardOriginalCallID = headerValue;
}
#endregion
//#region Switchboard-OriginalTo.
//else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_ORIGINAL_TO.ToLower())
//{
// sipHeader.SwitchboardOriginalTo = headerValue;
//}
//#endregion
//#region Switchboard-CallerDescription.
//else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_CALLER_DESCRIPTION.ToLower())
//{
// sipHeader.SwitchboardCallerDescription = headerValue;
//}
//#endregion
#region Switchboard-LineName.
else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_LINE_NAME.ToLower())
{
sipHeader.SwitchboardLineName = headerValue;
}
#endregion
//#region Switchboard-OriginalFrom.
//else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_ORIGINAL_FROM.ToLower())
//{
// sipHeader.SwitchboardOriginalFrom = headerValue;
//}
//#endregion
//#region Switchboard-FromContactURL.
//else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_FROM_CONTACT_URL.ToLower())
//{
// sipHeader.SwitchboardFromContactURL = headerValue;
//}
//#endregion
#region Switchboard-Owner.
else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_OWNER.ToLower())
{
sipHeader.SwitchboardOwner = headerValue;
}
#endregion
#region Switchboard-Terminate.
else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_TERMINATE.ToLower())
{
sipHeader.SwitchboardTerminate = headerValue;
}
#endregion
//#region Switchboard-Token.
//else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_TOKEN.ToLower())
//{
// sipHeader.SwitchboardToken = headerValue;
//}
//#endregion
//#region Switchboard-TokenRequest.
//else if (headerNameLower == SIPHeaders.SIP_HEADER_SWITCHBOARD_TOKENREQUEST.ToLower())
//{
// Int32.TryParse(headerValue, out sipHeader.SwitchboardTokenRequest);
//}
//#endregion
#region CRM-PersonName.
else if (headerNameLower == SIPHeaders.SIP_HEADER_CRM_PERSON_NAME.ToLower())
{
sipHeader.CRMPersonName = headerValue;
}
#endregion
#region CRM-CompanyName.
else if (headerNameLower == SIPHeaders.SIP_HEADER_CRM_COMPANY_NAME.ToLower())
{
sipHeader.CRMCompanyName = headerValue;
}
#endregion
#region CRM-AvatarURL.
else if (headerNameLower == SIPHeaders.SIP_HEADER_CRM_PICTURE_URL.ToLower())
{
sipHeader.CRMPictureURL = headerValue;
}
#endregion
#region ETag
else if (headerNameLower == SIPHeaders.SIP_HEADER_ETAG.ToLower())
{
sipHeader.ETag = headerValue;
}
#endregion
else
{
sipHeader.UnknownHeaders.Add(headerLine);
}
lastHeader = headerName;
}
catch (SIPValidationException)
{
throw;
}
catch (Exception parseExcp)
{
logger.Error("Error parsing SIP header " + headerLine + ". " + parseExcp.Message);
throw new SIPValidationException(SIPValidationFieldsEnum.Headers, "Unknown error parsing Header.");
}
}
sipHeader.Validate();
return sipHeader;
}
catch (SIPValidationException)
{
throw;
}
catch (Exception excp)
{
logger.Error("Exception ParseSIPHeaders. " + excp.Message);
throw new SIPValidationException(SIPValidationFieldsEnum.Headers, "Unknown error parsing Headers.");
}
}
/// <summary>
/// Puts the SIP headers together into a string ready for transmission.
/// </summary>
/// <returns>String representing the SIP headers.</returns>
public new string ToString()
{
try
{
StringBuilder headersBuilder = new StringBuilder();
headersBuilder.Append(Vias.ToString());
string cseqField = null;
if (this.CSeq != 0)
{
cseqField = (this.CSeqMethod != SIPMethodsEnum.NONE) ? this.CSeq + " " + this.CSeqMethod.ToString() : this.CSeq.ToString();
}
headersBuilder.Append((To != null) ? SIPHeaders.SIP_HEADER_TO + ": " + this.To.ToString() + m_CRLF : null);
headersBuilder.Append((From != null) ? SIPHeaders.SIP_HEADER_FROM + ": " + this.From.ToString() + m_CRLF : null);
headersBuilder.Append((CallId != null) ? SIPHeaders.SIP_HEADER_CALLID + ": " + this.CallId + m_CRLF : null);
headersBuilder.Append((CSeq > 0) ? SIPHeaders.SIP_HEADER_CSEQ + ": " + cseqField + m_CRLF : null);
#region Appending Contact header.
if (Contact != null && Contact.Count == 1)
{
headersBuilder.Append(SIPHeaders.SIP_HEADER_CONTACT + ": " + Contact[0].ToString() + m_CRLF);
}
else if (Contact != null && Contact.Count > 1)
{
StringBuilder contactsBuilder = new StringBuilder();
contactsBuilder.Append(SIPHeaders.SIP_HEADER_CONTACT + ": ");
bool firstContact = true;
foreach (SIPContactHeader contactHeader in Contact)
{
if (firstContact)
{
contactsBuilder.Append(contactHeader.ToString());
}
else
{
contactsBuilder.Append("," + contactHeader.ToString());
}
firstContact = false;
}
headersBuilder.Append(contactsBuilder.ToString() + m_CRLF);
}
#endregion
headersBuilder.Append((MaxForwards >= 0) ? SIPHeaders.SIP_HEADER_MAXFORWARDS + ": " + this.MaxForwards + m_CRLF : null);
headersBuilder.Append((Routes != null && Routes.Length > 0) ? SIPHeaders.SIP_HEADER_ROUTE + ": " + Routes.ToString() + m_CRLF : null);
headersBuilder.Append((RecordRoutes != null && RecordRoutes.Length > 0) ? SIPHeaders.SIP_HEADER_RECORDROUTE + ": " + RecordRoutes.ToString() + m_CRLF : null);
headersBuilder.Append((UserAgent != null && UserAgent.Trim().Length != 0) ? SIPHeaders.SIP_HEADER_USERAGENT + ": " + this.UserAgent + m_CRLF : null);
headersBuilder.Append((Expires != -1) ? SIPHeaders.SIP_HEADER_EXPIRES + ": " + this.Expires + m_CRLF : null);
headersBuilder.Append((MinExpires != -1) ? SIPHeaders.SIP_HEADER_MINEXPIRES + ": " + this.MinExpires + m_CRLF : null);
headersBuilder.Append((Accept != null) ? SIPHeaders.SIP_HEADER_ACCEPT + ": " + this.Accept + m_CRLF : null);
headersBuilder.Append((AcceptEncoding != null) ? SIPHeaders.SIP_HEADER_ACCEPTENCODING + ": " + this.AcceptEncoding + m_CRLF : null);
headersBuilder.Append((AcceptLanguage != null) ? SIPHeaders.SIP_HEADER_ACCEPTLANGUAGE + ": " + this.AcceptLanguage + m_CRLF : null);
headersBuilder.Append((Allow != null) ? SIPHeaders.SIP_HEADER_ALLOW + ": " + this.Allow + m_CRLF : null);
headersBuilder.Append((AlertInfo != null) ? SIPHeaders.SIP_HEADER_ALERTINFO + ": " + this.AlertInfo + m_CRLF : null);
headersBuilder.Append((AuthenticationInfo != null) ? SIPHeaders.SIP_HEADER_AUTHENTICATIONINFO + ": " + this.AuthenticationInfo + m_CRLF : null);
headersBuilder.Append((AuthenticationHeader != null) ? AuthenticationHeader.ToString() + m_CRLF : null);
headersBuilder.Append((CallInfo != null) ? SIPHeaders.SIP_HEADER_CALLINFO + ": " + this.CallInfo + m_CRLF : null);
headersBuilder.Append((ContentDisposition != null) ? SIPHeaders.SIP_HEADER_CONTENT_DISPOSITION + ": " + this.ContentDisposition + m_CRLF : null);
headersBuilder.Append((ContentEncoding != null) ? SIPHeaders.SIP_HEADER_CONTENT_ENCODING + ": " + this.ContentEncoding + m_CRLF : null);
headersBuilder.Append((ContentLanguage != null) ? SIPHeaders.SIP_HEADER_CONTENT_LANGUAGE + ": " + this.ContentLanguage + m_CRLF : null);
headersBuilder.Append((Date != null) ? SIPHeaders.SIP_HEADER_DATE + ": " + Date + m_CRLF : null);
headersBuilder.Append((ErrorInfo != null) ? SIPHeaders.SIP_HEADER_ERROR_INFO + ": " + this.ErrorInfo + m_CRLF : null);
headersBuilder.Append((InReplyTo != null) ? SIPHeaders.SIP_HEADER_IN_REPLY_TO + ": " + this.InReplyTo + m_CRLF : null);
headersBuilder.Append((Organization != null) ? SIPHeaders.SIP_HEADER_ORGANIZATION + ": " + this.Organization + m_CRLF : null);
headersBuilder.Append((Priority != null) ? SIPHeaders.SIP_HEADER_PRIORITY + ": " + Priority + m_CRLF : null);
headersBuilder.Append((ProxyRequire != null) ? SIPHeaders.SIP_HEADER_PROXY_REQUIRE + ": " + this.ProxyRequire + m_CRLF : null);
headersBuilder.Append((ReplyTo != null) ? SIPHeaders.SIP_HEADER_REPLY_TO + ": " + this.ReplyTo + m_CRLF : null);
headersBuilder.Append((Require != null) ? SIPHeaders.SIP_HEADER_REQUIRE + ": " + Require + m_CRLF : null);
headersBuilder.Append((RetryAfter != null) ? SIPHeaders.SIP_HEADER_RETRY_AFTER + ": " + this.RetryAfter + m_CRLF : null);
headersBuilder.Append((Server != null && Server.Trim().Length != 0) ? SIPHeaders.SIP_HEADER_SERVER + ": " + this.Server + m_CRLF : null);
headersBuilder.Append((Subject != null) ? SIPHeaders.SIP_HEADER_SUBJECT + ": " + Subject + m_CRLF : null);
headersBuilder.Append((Supported != null) ? SIPHeaders.SIP_HEADER_SUPPORTED + ": " + Supported + m_CRLF : null);
headersBuilder.Append((Timestamp != null) ? SIPHeaders.SIP_HEADER_TIMESTAMP + ": " + Timestamp + m_CRLF : null);
headersBuilder.Append((Unsupported != null) ? SIPHeaders.SIP_HEADER_UNSUPPORTED + ": " + Unsupported + m_CRLF : null);
headersBuilder.Append((Warning != null) ? SIPHeaders.SIP_HEADER_WARNING + ": " + Warning + m_CRLF : null);
headersBuilder.Append((ETag != null) ? SIPHeaders.SIP_HEADER_ETAG + ": " + ETag + m_CRLF : null);
headersBuilder.Append(SIPHeaders.SIP_HEADER_CONTENTLENGTH + ": " + this.ContentLength + m_CRLF);
if (this.ContentType != null && this.ContentType.Trim().Length > 0)
{
headersBuilder.Append(SIPHeaders.SIP_HEADER_CONTENTTYPE + ": " + this.ContentType + m_CRLF);
}
// Non-core SIP headers.
headersBuilder.Append((AllowEvents != null) ? SIPHeaders.SIP_HEADER_ALLOW_EVENTS + ": " + AllowEvents + m_CRLF : null);
headersBuilder.Append((Event != null) ? SIPHeaders.SIP_HEADER_EVENT + ": " + Event + m_CRLF : null);
headersBuilder.Append((SubscriptionState != null) ? SIPHeaders.SIP_HEADER_SUBSCRIPTION_STATE + ": " + SubscriptionState + m_CRLF : null);
headersBuilder.Append((ReferSub != null) ? SIPHeaders.SIP_HEADER_REFERSUB + ": " + ReferSub + m_CRLF : null);
headersBuilder.Append((ReferTo != null) ? SIPHeaders.SIP_HEADER_REFERTO + ": " + ReferTo + m_CRLF : null);
headersBuilder.Append((ReferredBy != null) ? SIPHeaders.SIP_HEADER_REFERREDBY + ": " + ReferredBy + m_CRLF : null);
headersBuilder.Append((Reason != null) ? SIPHeaders.SIP_HEADER_REASON + ": " + Reason + m_CRLF : null);
// Custom SIP headers.
headersBuilder.Append((ProxyReceivedFrom != null) ? SIPHeaders.SIP_HEADER_PROXY_RECEIVEDFROM + ": " + ProxyReceivedFrom + m_CRLF : null);
headersBuilder.Append((ProxyReceivedOn != null) ? SIPHeaders.SIP_HEADER_PROXY_RECEIVEDON + ": " + ProxyReceivedOn + m_CRLF : null);
headersBuilder.Append((ProxySendFrom != null) ? SIPHeaders.SIP_HEADER_PROXY_SENDFROM + ": " + ProxySendFrom + m_CRLF : null);
headersBuilder.Append((SwitchboardOriginalCallID != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_ORIGINAL_CALLID + ": " + SwitchboardOriginalCallID + m_CRLF : null);
//headersBuilder.Append((SwitchboardOriginalTo != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_ORIGINAL_TO + ": " + SwitchboardOriginalTo + m_CRLF : null);
//headersBuilder.Append((SwitchboardCallerDescription != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_CALLER_DESCRIPTION + ": " + SwitchboardCallerDescription + m_CRLF : null);
headersBuilder.Append((SwitchboardLineName != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_LINE_NAME + ": " + SwitchboardLineName + m_CRLF : null);
//headersBuilder.Append((SwitchboardOriginalFrom != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_ORIGINAL_FROM + ": " + SwitchboardOriginalFrom + m_CRLF : null);
//headersBuilder.Append((SwitchboardFromContactURL != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_FROM_CONTACT_URL + ": " + SwitchboardFromContactURL + m_CRLF : null);
headersBuilder.Append((SwitchboardOwner != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_OWNER + ": " + SwitchboardOwner + m_CRLF : null);
headersBuilder.Append((SwitchboardTerminate != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_TERMINATE + ": " + SwitchboardTerminate + m_CRLF : null);
//headersBuilder.Append((SwitchboardToken != null) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_TOKEN + ": " + SwitchboardToken + m_CRLF : null);
//headersBuilder.Append((SwitchboardTokenRequest > 0) ? SIPHeaders.SIP_HEADER_SWITCHBOARD_TOKENREQUEST + ": " + SwitchboardTokenRequest + m_CRLF : null);
// CRM Headers.
headersBuilder.Append((CRMPersonName != null) ? SIPHeaders.SIP_HEADER_CRM_PERSON_NAME + ": " + CRMPersonName + m_CRLF : null);
headersBuilder.Append((CRMCompanyName != null) ? SIPHeaders.SIP_HEADER_CRM_COMPANY_NAME + ": " + CRMCompanyName + m_CRLF : null);
headersBuilder.Append((CRMPictureURL != null) ? SIPHeaders.SIP_HEADER_CRM_PICTURE_URL + ": " + CRMPictureURL + m_CRLF : null);
// Unknown SIP headers
foreach (string unknownHeader in UnknownHeaders)
{
headersBuilder.Append(unknownHeader + m_CRLF);
}
return headersBuilder.ToString();
}
catch (Exception excp)
{
logger.Error("Exception SIPHeader ToString. " + excp.Message);
return "";
//throw excp;
}
}
private void Validate()
{
if (Vias == null || Vias.Length == 0)
{
throw new SIPValidationException(SIPValidationFieldsEnum.ViaHeader, "Invalid header, no Via.");
}
}
public void SetDateHeader()
{
//Date = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ") + "GMT";
Date = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fff");
}
public SIPHeader Copy()
{
string headerString = this.ToString();
string[] sipHeaders = SIPHeader.SplitHeaders(headerString);
return ParseSIPHeaders(sipHeaders);
}
public string GetUnknownHeaderValue(string unknownHeaderName)
{
if (unknownHeaderName.IsNullOrBlank())
{
return null;
}
else if (UnknownHeaders == null || UnknownHeaders.Count == 0)
{
return null;
}
else
{
foreach (string unknonwHeader in UnknownHeaders)
{
string trimmedHeader = unknonwHeader.Trim();
int delimiterIndex = trimmedHeader.IndexOf(SIPConstants.HEADER_DELIMITER_CHAR);
if (delimiterIndex == -1)
{
logger.Warn("Invalid SIP header, ignoring, " + unknonwHeader + ".");
continue;
}
string headerName = trimmedHeader.Substring(0, delimiterIndex).Trim();
if (headerName.ToLower() == unknownHeaderName.ToLower())
{
return trimmedHeader.Substring(delimiterIndex + 1).Trim();
}
}
return null;
}
}
}
}
| 43.30167 | 319 | 0.535245 | [
"MIT"
] | chenmuyong/Gb28181_Platform2016_Test | SIPSorcery.28181/SIP.Core/SIP/SIPHeader.cs | 116,698 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using HotChocolate.Execution;
namespace HotChocolate
{
internal class Error
: IError
{
private const string _code = "code";
private OrderedDictionary<string, object> _extensions =
new OrderedDictionary<string, object>();
private bool _needsCopy;
private string _message;
public Error()
{
Locations = ImmutableList<Location>.Empty;
}
public string Message
{
get => _message;
internal set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(
"The message mustn't be null or empty.",
nameof(value));
}
_message = value;
}
}
public string Code
{
get
{
if (_extensions.TryGetValue(_code, out object code) &&
code is string s)
{
return s;
}
return null;
}
internal set
{
CopyExtensions();
if (value == null)
{
_extensions.Remove(_code);
}
else
{
_extensions[_code] = value;
}
}
}
public IReadOnlyList<object> Path { get; set; }
IReadOnlyList<Location> IError.Locations =>
Locations.Count == 0 ? null : Locations;
public IImmutableList<Location> Locations { get; set; }
public Exception Exception { get; set; }
IReadOnlyDictionary<string, object> IError.Extensions =>
_extensions.Count == 0 ? null : _extensions;
public OrderedDictionary<string, object> Extensions
{
get
{
CopyExtensions();
return _extensions;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_needsCopy = false;
_extensions = value;
}
}
private void CopyExtensions()
{
if (_needsCopy)
{
_extensions = _extensions.Clone();
_needsCopy = false;
}
}
public IError WithCode(string code)
{
Error error = Copy();
error.Code = code;
return error;
}
public IError WithException(Exception exception)
{
Error error = Copy();
error.Exception = exception;
return error;
}
public IError WithExtensions(
IReadOnlyDictionary<string, object> extensions)
{
Error error = Copy();
error.Extensions =
new OrderedDictionary<string, object>(extensions);
return error;
}
public IError AddExtension(string key, object value)
{
Error error = Copy();
error.Extensions.Add(key, value);
return error;
}
public IError RemoveExtension(string key)
{
Error error = Copy();
error.Extensions.Remove(key);
return error;
}
public IError WithLocations(IReadOnlyList<Location> locations)
{
Error error = Copy();
error.Locations = ImmutableList.CreateRange(locations);
return error;
}
public IError WithMessage(string message)
{
if (string.IsNullOrEmpty(message))
{
throw new ArgumentException(
"The message mustn't be null or empty.",
nameof(message));
}
Error error = Copy();
error.Message = message;
return error;
}
public IError WithPath(Path path)
{
Error error = Copy();
error.Path = path.ToCollection();
return error;
}
public IError WithPath(IReadOnlyList<object> path)
{
Error error = Copy();
error.Path = path;
return error;
}
internal Error Copy()
{
return new Error
{
Message = Message,
_extensions = _extensions,
_needsCopy = true,
Path = Path,
Locations = Locations,
Exception = Exception
};
}
}
}
| 25.478947 | 70 | 0.459203 | [
"MIT"
] | leighmetzroth/hotchocolate | src/Core/Abstractions/Error.cs | 4,841 | C# |
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.0.1
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using BungieNetPlatform.BungieNetPlatform.Api;
using BungieNetPlatform.BungieNetPlatform.Model;
using BungieNetPlatform.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace BungieNetPlatform.Test
{
/// <summary>
/// Class for testing InlineResponse20018
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class InlineResponse20018Tests
{
// TODO uncomment below to declare an instance variable for InlineResponse20018
//private InlineResponse20018 instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of InlineResponse20018
//instance = new InlineResponse20018();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of InlineResponse20018
/// </summary>
[Test]
public void InlineResponse20018InstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" InlineResponse20018
//Assert.IsInstanceOfType<InlineResponse20018> (instance, "variable 'instance' is a InlineResponse20018");
}
/// <summary>
/// Test the property 'Response'
/// </summary>
[Test]
public void ResponseTest()
{
// TODO unit test for the property 'Response'
}
/// <summary>
/// Test the property 'ErrorCode'
/// </summary>
[Test]
public void ErrorCodeTest()
{
// TODO unit test for the property 'ErrorCode'
}
/// <summary>
/// Test the property 'ThrottleSeconds'
/// </summary>
[Test]
public void ThrottleSecondsTest()
{
// TODO unit test for the property 'ThrottleSeconds'
}
/// <summary>
/// Test the property 'ErrorStatus'
/// </summary>
[Test]
public void ErrorStatusTest()
{
// TODO unit test for the property 'ErrorStatus'
}
/// <summary>
/// Test the property 'Message'
/// </summary>
[Test]
public void MessageTest()
{
// TODO unit test for the property 'Message'
}
/// <summary>
/// Test the property 'MessageData'
/// </summary>
[Test]
public void MessageDataTest()
{
// TODO unit test for the property 'MessageData'
}
}
}
| 27.123967 | 194 | 0.57922 | [
"MIT"
] | xlxCLUxlx/BungieNetPlatform | src/BungieNetPlatform.Test/BungieNetPlatform.Model/InlineResponse20018Tests.cs | 3,282 | C# |
// © 2020 VOID-INTELLIGENCE ALL RIGHTS RESERVED
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nomad.Core;
namespace NomadTest.Core
{
[TestClass]
public class ShapeTest
{
[TestMethod]
public void Shape()
{
var mat = new Matrix(10, 10);
mat.InRandomize(-0.5,0.5);
mat = mat.Flatten();
mat = mat.Widen(10, 10);
mat.InFlatten();
mat.InWiden(10, 10);
mat = mat.Reshape(100, 1);
mat.InReshape(10, 10);
mat = mat.Merge(mat, out var mergepoint);
mat.InMerge(mat, out mergepoint);
mat.Split(mergepoint);
mat = new Matrix(10, 5);
mat.InRandomize(-0.5, 0.5);
mat.InReshape(5, 10);
}
}
}
| 25.25 | 53 | 0.518564 | [
"Apache-2.0"
] | void-intelligence/Nomad | src/Nomad-Tests/Core/ShapeTest.cs | 811 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace WordWrap.Test
{
[TestClass]
public class UnitTest1
{
WordWrapper wordWrapper;
[TestInitialize]
public void Setup()
{
wordWrapper = new WordWrapper();
}
[TestMethod]
public void 공백이나_0값을_입력하면_wrap할필요가없다()
{
string output = wordWrapper.DoWrap("", 0);
Assert.AreEqual("", output);
}
[DataRow("word", "word", 4)]
[DataRow("word", "word", 5)]
[DataTestMethod]
[TestMethod]
public void 랩할것이없다(string Expected, string Actual, int col)
{
string output = wordWrapper.DoWrap(Actual, col);
Assert.AreEqual(Expected, output);
}
[DataRow("w--ord", "word", 1)]
[DataRow("wo--rd", "word", 2)]
[DataRow("wor--d", "word", 3)]
[DataTestMethod]
[TestMethod]
public void 한단어_랩(string Expected, string Actual, int col)
{
string output = wordWrapper.DoWrap(Actual, col);
Assert.AreEqual(Expected, output);
}
[DataRow("word--word", "word word", 4)]
[DataRow("word--word", "word word", 5)]
[DataTestMethod]
[TestMethod]
public void 두단어_랩(string Expected, string Actual, int col)
{
string output = wordWrapper.DoWrap(Actual, col);
Assert.AreEqual(Expected, output);
}
[DataRow("word--word", "word word", 6)]
[DataTestMethod]
[TestMethod]
public void 가능하면_단어를자르지않고_랩한다(string Expected, string Actual, int col)
{
string output = wordWrapper.DoWrap(Actual, col);
Assert.AreEqual(Expected, output);
}
}
}
| 26.202899 | 78 | 0.547566 | [
"MIT"
] | cjhnim/daily-kata | WordWrap/day_6/WordWrap/WordWrap.Test/UnitTest1.cs | 1,900 | C# |
using System.Windows.Input;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using RibbonApp.Constants;
using RibbonApp.Contracts.Services;
namespace RibbonApp.ViewModels
{
public class ShellViewModel : BindableBase
{
private readonly IRegionManager _regionManager;
private readonly IRightPaneService _rightPaneService;
private IRegionNavigationService _navigationService;
private ICommand _loadedCommand;
private ICommand _unloadedCommand;
public ICommand LoadedCommand => _loadedCommand ?? (_loadedCommand = new DelegateCommand(OnLoaded));
public ICommand UnloadedCommand => _unloadedCommand ?? (_unloadedCommand = new DelegateCommand(OnUnloaded));
public ShellViewModel(IRegionManager regionManager, IRightPaneService rightPaneService)
{
_regionManager = regionManager;
_rightPaneService = rightPaneService;
}
private void OnLoaded()
{
_navigationService = _regionManager.Regions[Regions.Main].NavigationService;
_navigationService.RequestNavigate(PageKeys.Main);
}
private void OnUnloaded()
{
_regionManager.Regions.Remove(Regions.Main);
_rightPaneService.CleanUp();
}
}
}
| 30.465116 | 116 | 0.699237 | [
"MIT"
] | mvegaca/WTS.WPF.Prism.GeneratedApps | RibbonApp/RibbonApp/ViewModels/ShellViewModel.cs | 1,312 | C# |
using static SampleService.Services.ApiClient;
namespace SampleService.Services
{
public interface IApiClient
{
CoinsInfo ConnectToApi(string currency);
}
} | 19.777778 | 49 | 0.735955 | [
"Apache-2.0"
] | mohamadlawand087/v23-MicroService | SampleService/Services/IApiClient.cs | 178 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2015 Ingo Herbote
* http://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Types.EventProxies
{
#region Using
using System.Web.Security;
using YAF.Types.Interfaces;
#endregion
/// <summary>
/// The new user registered event.
/// </summary>
public class NewUserRegisteredEvent : IAmEvent
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="NewUserRegisteredEvent"/> class.
/// </summary>
/// <param name="user">
/// The user.
/// </param>
/// <param name="userId">
/// The user id.
/// </param>
public NewUserRegisteredEvent([NotNull] MembershipUser user, int userId)
{
CodeContracts.VerifyNotNull(user, "user");
this.User = user;
this.UserId = userId;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets User.
/// </summary>
public MembershipUser User { get; set; }
/// <summary>
/// Gets or sets UserId.
/// </summary>
public int UserId { get; set; }
#endregion
}
} | 27.972973 | 86 | 0.648792 | [
"Apache-2.0"
] | TristanTong/bbsWirelessTag | yafsrc/YAF.Types/EventProxies/NewUserRegisteredEvent.cs | 1,998 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using backend.Data;
#nullable disable
namespace backend.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("backend.Models.Address", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Info")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Addresses");
});
modelBuilder.Entity("backend.Models.Card", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CardType")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<int>("LastFourDigit")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Cards");
});
modelBuilder.Entity("backend.Models.Category", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Categories");
});
modelBuilder.Entity("backend.Models.Contact", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<string>("Number")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Contacts");
});
modelBuilder.Entity("backend.Models.Coupon", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Discount")
.HasColumnType("integer");
b.Property<DateTime>("EndDate")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<DateTime>("StartDate")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("Coupons");
});
modelBuilder.Entity("backend.Models.Gallery", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<Guid>("ProductId")
.HasColumnType("uuid");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Url")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ProductId");
b.ToTable("Gallery");
});
modelBuilder.Entity("backend.Models.Order", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AddressId")
.HasColumnType("uuid");
b.Property<Guid>("CardId")
.HasColumnType("uuid");
b.Property<Guid>("ContactId")
.HasColumnType("uuid");
b.Property<Guid?>("CouponId")
.HasColumnType("uuid");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("TotalPrice")
.HasColumnType("double precision");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("AddressId");
b.HasIndex("CardId");
b.HasIndex("ContactId");
b.HasIndex("CouponId");
b.HasIndex("UserId");
b.ToTable("Orders");
});
modelBuilder.Entity("backend.Models.OrderDetail", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<Guid>("OrderId")
.HasColumnType("uuid");
b.Property<Guid>("ProductId")
.HasColumnType("uuid");
b.Property<int>("Quantity")
.HasColumnType("integer");
b.Property<double>("SalePrice")
.HasColumnType("double precision");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("OrderId");
b.HasIndex("ProductId");
b.ToTable("OrderDetails");
});
modelBuilder.Entity("backend.Models.Product", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("CategoryId")
.HasColumnType("uuid");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<int>("DiscountInPercent")
.HasColumnType("integer");
b.Property<string>("Image")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsDeleted")
.HasColumnType("boolean");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<int>("ProductQuantity")
.HasColumnType("integer");
b.Property<double>("SalePrice")
.HasColumnType("double precision");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Unit")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("Products");
});
modelBuilder.Entity("backend.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("ContactNumber")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("CreateAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("text");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<DateTime>("UpdateAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("Roles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("RoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("UserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("UserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("UserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("UserTokens", (string)null);
});
modelBuilder.Entity("backend.Models.Address", b =>
{
b.HasOne("backend.Models.User", null)
.WithMany("Addresses")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("backend.Models.Card", b =>
{
b.HasOne("backend.Models.User", null)
.WithMany("Cards")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("backend.Models.Contact", b =>
{
b.HasOne("backend.Models.User", null)
.WithMany("Contacts")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("backend.Models.Gallery", b =>
{
b.HasOne("backend.Models.Product", null)
.WithMany("Gallery")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("backend.Models.Order", b =>
{
b.HasOne("backend.Models.Address", "Address")
.WithMany()
.HasForeignKey("AddressId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("backend.Models.Card", "Card")
.WithMany()
.HasForeignKey("CardId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("backend.Models.Contact", "Contact")
.WithMany()
.HasForeignKey("ContactId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("backend.Models.Coupon", "Coupon")
.WithMany()
.HasForeignKey("CouponId");
b.HasOne("backend.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Address");
b.Navigation("Card");
b.Navigation("Contact");
b.Navigation("Coupon");
b.Navigation("User");
});
modelBuilder.Entity("backend.Models.OrderDetail", b =>
{
b.HasOne("backend.Models.Order", null)
.WithMany("OrderDetails")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("backend.Models.Product", "Product")
.WithMany()
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
});
modelBuilder.Entity("backend.Models.Product", b =>
{
b.HasOne("backend.Models.Category", "Category")
.WithMany("Products")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("backend.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("backend.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole<System.Guid>", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("backend.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("backend.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("backend.Models.Category", b =>
{
b.Navigation("Products");
});
modelBuilder.Entity("backend.Models.Order", b =>
{
b.Navigation("OrderDetails");
});
modelBuilder.Entity("backend.Models.Product", b =>
{
b.Navigation("Gallery");
});
modelBuilder.Entity("backend.Models.User", b =>
{
b.Navigation("Addresses");
b.Navigation("Cards");
b.Navigation("Contacts");
});
#pragma warning restore 612, 618
}
}
}
| 34.692308 | 102 | 0.42423 | [
"MIT"
] | onggieoi/ecommerce | backend/Migrations/ApplicationDbContextModelSnapshot.cs | 26,160 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SEDC.Adv10.FileSystemDatabase.Entities
{
public abstract class BaseEntity
{
public int Id { get; set; }
public abstract string Info();
}
}
| 17.307692 | 48 | 0.751111 | [
"MIT"
] | sedc-codecademy/skwd8-06-csharpadv | g7/Class-10/SEDC.Adv10/SEDC.Adv10.FileSystemDatabase/Entities/BaseEntity.cs | 227 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.CertificateManager")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Certificate Manager. AWS Certificate Manager (ACM) is an AWS service that makes it easier for you to deploy secure SSL based websites and applications on the AWS platform.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Certificate Manager. AWS Certificate Manager (ACM) is an AWS service that makes it easier for you to deploy secure SSL based websites and applications on the AWS platform.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - AWS Certificate Manager. AWS Certificate Manager (ACM) is an AWS service that makes it easier for you to deploy secure SSL based websites and applications on the AWS platform.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Certificate Manager. AWS Certificate Manager (ACM) is an AWS service that makes it easier for you to deploy secure SSL based websites and applications on the AWS platform.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Certificate Manager. AWS Certificate Manager (ACM) is an AWS service that makes it easier for you to deploy secure SSL based websites and applications on the AWS platform.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.5.0.34")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 55.150943 | 267 | 0.772494 | [
"Apache-2.0"
] | altso/aws-sdk-net | sdk/src/Services/CertificateManager/Properties/AssemblyInfo.cs | 2,923 | C# |
using System;
using AspectCore.DynamicProxy;
namespace Butterfly.Client.Logging
{
public interface ILogger
{
void Info(string message);
void Error(string message, Exception exception);
}
}
| 16.923077 | 56 | 0.690909 | [
"MIT"
] | ButterflyAPM/butterfly-csharp | src/Butterfly.Client/Common/ILogger.cs | 222 | C# |
namespace SecondMonitor.Telemetry.TelemetryApplication.AggregatedCharts.Histogram.Providers
{
using System;
using System.Collections.Generic;
using Controllers.Settings;
using DataModel.BasicProperties;
using Extractors;
using Filter;
using SecondMonitor.ViewModels.Factory;
using Settings.DTO.CarProperties;
using TelemetryManagement.DTO;
using ViewModels.AggregatedCharts.Histogram;
using ViewModels.LoadedLapCache;
public class SuspensionVelocityHistogramProvider : AbstractWheelHistogramProvider<SuspensionVelocityWheelsChartViewModel, SuspensionVelocityHistogramChartViewModel>
{
private readonly SuspensionVelocityHistogramDataExtractor _suspensionVelocityHistogramDataExtractor;
private readonly SuspensionVelocityFilter _suspensionVelocityFilter;
private readonly ISettingsController _settingsController;
private CarPropertiesDto _carProperties;
public SuspensionVelocityHistogramProvider(SuspensionVelocityHistogramDataExtractor suspensionVelocityHistogramDataExtractor, ILoadedLapsCache loadedLapsCache, IViewModelFactory viewModelFactory, SuspensionVelocityFilter suspensionVelocityFilter, ISettingsController settingsController)
: base(suspensionVelocityHistogramDataExtractor, loadedLapsCache, viewModelFactory, new []{suspensionVelocityFilter} )
{
_suspensionVelocityHistogramDataExtractor = suspensionVelocityHistogramDataExtractor;
_suspensionVelocityFilter = suspensionVelocityFilter;
_settingsController = settingsController;
}
public override string ChartName => "Suspension Velocity Histogram";
public override AggregatedChartKind Kind => AggregatedChartKind.Histogram;
protected override bool ResetCommandVisible => true;
protected override void OnNewViewModel(SuspensionVelocityWheelsChartViewModel newViewModel)
{
_carProperties = _settingsController.GetCarPropertiesForCurrentCar();
newViewModel.BandSize = _carProperties.ChartsProperties.SuspensionVelocityHistogram.BandSize.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
newViewModel.Maximum = _carProperties.ChartsProperties.SuspensionVelocityHistogram.Maximum.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
newViewModel.Minimum = _carProperties.ChartsProperties.SuspensionVelocityHistogram.Minimum.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.FrontLeftChartViewModel).BumpTransition = _carProperties.FrontLeftTyre.BumpTransition.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.FrontLeftChartViewModel).ReboundTransition = _carProperties.FrontLeftTyre.ReboundTransition.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.FrontLeftChartViewModel).Unit = Velocity.GetUnitSymbol(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.FrontRightChartViewModel).BumpTransition = _carProperties.FrontRightTyre.BumpTransition.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.FrontRightChartViewModel).ReboundTransition = _carProperties.FrontRightTyre.ReboundTransition.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.FrontRightChartViewModel).Unit = Velocity.GetUnitSymbol(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.RearLeftChartViewModel).BumpTransition = _carProperties.RearLeftTyre.BumpTransition.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.RearLeftChartViewModel).ReboundTransition = _carProperties.RearLeftTyre.ReboundTransition.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.RearLeftChartViewModel).Unit = Velocity.GetUnitSymbol(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.RearRightChartViewModel).BumpTransition = _carProperties.RearRightTyre.BumpTransition.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.RearRightChartViewModel).ReboundTransition = _carProperties.RearRightTyre.ReboundTransition.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
((SuspensionVelocityHistogramChartViewModel)newViewModel.RearRightChartViewModel).Unit = Velocity.GetUnitSymbol(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
newViewModel.BandSize = _carProperties.ChartsProperties.SuspensionVelocityHistogram.BandSize.GetValueInUnits(_suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
}
protected override void ResetHistogramParameters(IReadOnlyCollection<LapTelemetryDto> loadedLaps, double bandSize, SuspensionVelocityWheelsChartViewModel wheelsChart)
{
_carProperties = _settingsController.ResetAndGetCarPropertiesForCurrentCar();
OnNewViewModel(wheelsChart);
base.ResetHistogramParameters(loadedLaps, bandSize, wheelsChart);
}
protected override void ApplyHistogramLimits(Histogram flHistogram, Histogram frHistogram, Histogram rlHistogram, Histogram rrHistogram, SuspensionVelocityWheelsChartViewModel viewModel)
{
double maxY = Math.Max(flHistogram.MaximumY, Math.Max(frHistogram.MaximumY, Math.Max(rlHistogram.MaximumY, rrHistogram.MaximumY)));
flHistogram.MaximumY = maxY;
frHistogram.MaximumY = maxY;
rlHistogram.MaximumY = maxY;
rrHistogram.MaximumY = maxY;
flHistogram.MinimumX = viewModel.Minimum;
frHistogram.MinimumX = viewModel.Minimum;
rlHistogram.MinimumX = viewModel.Minimum;
rrHistogram.MinimumX = viewModel.Minimum;
flHistogram.MaximumX = viewModel.Maximum;
frHistogram.MaximumX = viewModel.Maximum;
rlHistogram.MaximumX = viewModel.Maximum;
rrHistogram.MaximumX = viewModel.Maximum;
}
protected override void RefreshHistogram(IReadOnlyCollection<LapTelemetryDto> loadedLaps, double bandSize, SuspensionVelocityWheelsChartViewModel wheelsChart)
{
_carProperties.ChartsProperties.SuspensionVelocityHistogram.BandSize = Velocity.FromUnits(wheelsChart.BandSize, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.ChartsProperties.SuspensionVelocityHistogram.Minimum = Velocity.FromUnits(wheelsChart.Minimum, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.ChartsProperties.SuspensionVelocityHistogram.Maximum = Velocity.FromUnits(wheelsChart.Maximum, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.FrontLeftTyre.BumpTransition = Velocity.FromUnits(((SuspensionVelocityHistogramChartViewModel) wheelsChart.FrontLeftChartViewModel).BumpTransition, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.FrontLeftTyre.ReboundTransition = Velocity.FromUnits(((SuspensionVelocityHistogramChartViewModel) wheelsChart.FrontLeftChartViewModel).ReboundTransition, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.FrontRightTyre.BumpTransition = Velocity.FromUnits(((SuspensionVelocityHistogramChartViewModel)wheelsChart.FrontRightChartViewModel).BumpTransition, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.FrontRightTyre.ReboundTransition = Velocity.FromUnits(((SuspensionVelocityHistogramChartViewModel)wheelsChart.FrontRightChartViewModel).ReboundTransition, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.RearLeftTyre.BumpTransition = Velocity.FromUnits(((SuspensionVelocityHistogramChartViewModel)wheelsChart.RearLeftChartViewModel).BumpTransition, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.RearLeftTyre.ReboundTransition = Velocity.FromUnits(((SuspensionVelocityHistogramChartViewModel)wheelsChart.RearLeftChartViewModel).ReboundTransition, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.RearRightTyre.BumpTransition = Velocity.FromUnits(((SuspensionVelocityHistogramChartViewModel)wheelsChart.RearRightChartViewModel).BumpTransition, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
_carProperties.RearRightTyre.ReboundTransition = Velocity.FromUnits(((SuspensionVelocityHistogramChartViewModel)wheelsChart.RearRightChartViewModel).ReboundTransition, _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall);
base.RefreshHistogram(loadedLaps, bandSize, wheelsChart);
}
protected override Histogram ExtractFlHistogram(IReadOnlyCollection<LapTelemetryDto> loadedLaps, double bandSize, SuspensionVelocityWheelsChartViewModel wheelsChart)
{
Filters.ForEach(x => x.FilterFrontLeft());
_suspensionVelocityHistogramDataExtractor.BumpTransition = ((SuspensionVelocityHistogramChartViewModel)wheelsChart.FrontLeftChartViewModel).BumpTransition;
_suspensionVelocityHistogramDataExtractor.ReboundTransition = ((SuspensionVelocityHistogramChartViewModel)wheelsChart.FrontLeftChartViewModel).ReboundTransition;
return _suspensionVelocityHistogramDataExtractor.ExtractHistogramFrontLeft(loadedLaps, bandSize, Filters);
}
protected override Histogram ExtractFrHistogram(IReadOnlyCollection<LapTelemetryDto> loadedLaps, double bandSize, SuspensionVelocityWheelsChartViewModel wheelsChart)
{
Filters.ForEach(x => x.FilterFrontRight());
_suspensionVelocityHistogramDataExtractor.BumpTransition = ((SuspensionVelocityHistogramChartViewModel)wheelsChart.FrontRightChartViewModel).BumpTransition;
_suspensionVelocityHistogramDataExtractor.ReboundTransition = ((SuspensionVelocityHistogramChartViewModel)wheelsChart.FrontRightChartViewModel).ReboundTransition;
return _suspensionVelocityHistogramDataExtractor.ExtractHistogramFrontRight(loadedLaps, bandSize, Filters);
}
protected override Histogram ExtractRlHistogram(IReadOnlyCollection<LapTelemetryDto> loadedLaps, double bandSize, SuspensionVelocityWheelsChartViewModel wheelsChart)
{
Filters.ForEach(x => x.FilterRearLeft());
_suspensionVelocityHistogramDataExtractor.BumpTransition = ((SuspensionVelocityHistogramChartViewModel)wheelsChart.RearLeftChartViewModel).BumpTransition;
_suspensionVelocityHistogramDataExtractor.ReboundTransition = ((SuspensionVelocityHistogramChartViewModel)wheelsChart.RearLeftChartViewModel).ReboundTransition;
return _suspensionVelocityHistogramDataExtractor.ExtractHistogramRearLeft(loadedLaps, bandSize, Filters);
}
protected override Histogram ExtractRrHistogram(IReadOnlyCollection<LapTelemetryDto> loadedLaps, double bandSize, SuspensionVelocityWheelsChartViewModel wheelsChart)
{
Filters.ForEach(x => x.FilterRearRight());
_suspensionVelocityHistogramDataExtractor.BumpTransition = ((SuspensionVelocityHistogramChartViewModel)wheelsChart.RearRightChartViewModel).BumpTransition;
_suspensionVelocityHistogramDataExtractor.ReboundTransition = ((SuspensionVelocityHistogramChartViewModel)wheelsChart.RearRightChartViewModel).ReboundTransition;
return _suspensionVelocityHistogramDataExtractor.ExtractHistogramRearRight(loadedLaps, bandSize, Filters);
}
protected override void BeforeHistogramFilling(SuspensionVelocityWheelsChartViewModel wheelsChart)
{
_suspensionVelocityFilter.MinimumVelocity = wheelsChart.Minimum;
_suspensionVelocityFilter.MaximumVelocity = wheelsChart.Maximum;
_suspensionVelocityFilter.VelocityUnits = _suspensionVelocityHistogramDataExtractor.VelocityUnitsSmall;
base.BeforeHistogramFilling(wheelsChart);
}
}
} | 87.621622 | 295 | 0.808297 | [
"MIT"
] | plkumar/SecondMonitor | Telemetry/TelemetryApplication/AggregatedCharts/Histogram/Providers/SuspensionVelocityHistogramProvider.cs | 12,970 | C# |
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
#nullable disable
namespace T0002.Models
{
public partial class CmdAgvpositionCodeDetail
{
/// <summary>
/// 主键
/// </summary>
public string Id { get; set; }
/// <summary>
/// AGV任务单编号
/// </summary>
public string Taskid { get; set; }
/// <summary>
/// 位置类型 00 表示:位置编号 01 表示:物料批次号 02 表示:策略编号(含多个区域) 如:第一个区域放不下, 可以放第二个区域 03 表示:货架编号,通过货架编号找到货架所在位置 04 表示:区域编号,在区域中查找可用位置
/// </summary>
public string Type { get; set; }
/// <summary>
/// 位置路径:AGV 关键路径位置集合,与任务类型中模板配置的位置路径一一对应。待现场地图部署、配置完成后可获取;
/// </summary>
public string Positioncodepath { get; set; }
/// <summary>
/// 位置路径顺序,任务模板中如果2个位置点,将根据任务点的先后顺序默认为起点和终点。相同任务单顺序号不可重复。1开始 2结束
/// </summary>
public int Codepathorder { get; set; }
/// <summary>
/// 任务生成者
/// </summary>
public string CreateOwner { get; set; }
/// <summary>
/// 创建日期
/// </summary>
public DateTime Createtime { get; set; }
}
} | 31.65 | 127 | 0.543444 | [
"MIT"
] | twoutlook/BlazorServerDbContextExample | BlazorServerEFCoreSample/T0002/Models/CmdAgvpositionCodeDetail.cs | 1,696 | C# |
using Adaptive.ReactiveTrader.Contract;
using System;
using System.Reactive.Subjects;
using System.Threading;
namespace Adaptive.ReactiveTrader.Server.Pricing
{
public abstract class BaseWalkPriceGenerator : IDisposable
{
protected static readonly ThreadLocal<Random> Random = new ThreadLocal<Random>(() => new Random());
protected readonly Subject<SpotPriceDto> _priceChanges = new Subject<SpotPriceDto>();
protected readonly object _lock = new object();
protected readonly int _precision;
protected decimal _initial;
protected decimal _previousMid;
protected BaseWalkPriceGenerator(CurrencyPair currencyPair, decimal initial, int precision)
{
CurrencyPair = currencyPair;
_initial = _previousMid = initial;
_precision = precision;
EffectiveDate = new DateTime(2019, 1, 1);
SourceName = PriceSource.HardCodedSourceName;
}
public CurrencyPair CurrencyPair { get; }
public DateTime EffectiveDate { get; private set; }
public string SourceName { get; private set; }
public decimal SampleRate => _previousMid;
public void Dispose()
{
_priceChanges.Dispose();
}
public void UpdateInitialValue(decimal newValue, DateTime effectiveDate, string sourceName)
{
lock (_lock)
{
_initial = _previousMid = newValue;
EffectiveDate = effectiveDate;
SourceName = sourceName;
}
UpdateWalkPrice();
}
public abstract void UpdateWalkPrice();
public IObservable<SpotPriceDto> PriceChanges => _priceChanges;
public override string ToString() => $"{CurrencyPair.Symbol}|{EffectiveDate}|{_initial}|{SourceName}";
}
}
| 29.578947 | 106 | 0.709964 | [
"Apache-2.0"
] | AdaptiveConsulting/ReactiveTraderCloud | src/server/dotNet/Adaptive.ReactiveTrader.Server.Pricing/BaseWalkPriceGenerator.cs | 1,686 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NiconicoToolkit.UWP.Test.Tests
{
[TestClass]
public class ExtractContenntIdTest
{
void CheckExtractIdResult(NiconicoIdType expectedType, NiconicoId? id)
{
Assert.IsNotNull(id);
Assert.AreEqual(expectedType, id.Value.IdType, $"not equal NiconicoIdType expected: {expectedType} actual:{id.Value.IdType}");
}
[TestMethod]
[DataRow("https://www.nicovideo.jp/watch/so31520197?ref=videotop_recommend_tag")]
[DataRow("https://www.nicovideo.jp/watch/sm38908270?ref=videocate_newarrival")]
[DataRow("sm38903015")]
public void ExtractVideoContentId(string urlOrId)
{
if (Uri.TryCreate(urlOrId, UriKind.Absolute, out var uri))
{
var id = NiconicoUrls.ExtractNicoContentId(uri);
Assert.IsNotNull(id);
Assert.IsTrue(id.Value.IdType is NiconicoIdType.Video or NiconicoIdType.Video);
}
else
{
Assert.IsTrue(NiconicoId.TryCreate(urlOrId, out var id));
Assert.IsTrue(id.IdType is NiconicoIdType.Video or NiconicoIdType.Video);
}
}
[TestMethod]
[DataRow("https://live.nicovideo.jp/watch/lv332360112?ref=top_pickup")]
[DataRow("lv332360112")]
public void ExtractLiveContentId(string urlOrId)
{
if (Uri.TryCreate(urlOrId, UriKind.Absolute, out var uri))
{
CheckExtractIdResult(NiconicoIdType.Live, NiconicoUrls.ExtractNicoContentId(uri));
}
else
{
CheckExtractIdResult(NiconicoIdType.Live, new NiconicoId(urlOrId));
}
}
[TestMethod]
[DataRow("https://ch.nicovideo.jp/channel/ch2646373")]
[DataRow("https://ch.nicovideo.jp/higurashianime_202010")]
[DataRow("https://ch.nicovideo.jp/ch2642363")]
[DataRow("ch2646373")]
public void ExtractChannelContentId(string urlOrId)
{
if (Uri.TryCreate(urlOrId, UriKind.Absolute, out var uri))
{
CheckExtractIdResult(NiconicoIdType.Channel, NiconicoUrls.ExtractNicoContentId(uri));
}
else
{
CheckExtractIdResult(NiconicoIdType.Channel, new NiconicoId(urlOrId));
}
}
[TestMethod]
[DataRow("https://com.nicovideo.jp/community/co358573")]
[DataRow("co358573")]
public void ExtractCommunityContentId(string urlOrId)
{
if (Uri.TryCreate(urlOrId, UriKind.Absolute, out var uri))
{
CheckExtractIdResult(NiconicoIdType.Community, NiconicoUrls.ExtractNicoContentId(uri));
}
else
{
CheckExtractIdResult(NiconicoIdType.Community, new NiconicoId(urlOrId));
}
}
[TestMethod]
[DataRow("https://www.nicovideo.jp/user/500600/mylist/61896980?ref=pc_userpage_mylist")]
public void ExtractMylistContentId(string urlOrId)
{
if (Uri.TryCreate(urlOrId, UriKind.Absolute, out var uri))
{
CheckExtractIdResult(NiconicoIdType.Mylist, NiconicoUrls.ExtractNicoContentId(uri));
}
else
{
CheckExtractIdResult(NiconicoIdType.Mylist, new NiconicoId(urlOrId));
}
}
[TestMethod]
[DataRow("https://www.nicovideo.jp/series/230847?ref=pc_watch_description_series")]
public void ExtractSeriesContentId(string urlOrId)
{
if (Uri.TryCreate(urlOrId, UriKind.Absolute, out var uri))
{
CheckExtractIdResult(NiconicoIdType.Series, NiconicoUrls.ExtractNicoContentId(uri));
}
else
{
CheckExtractIdResult(NiconicoIdType.Series, new NiconicoId(urlOrId));
}
}
}
}
| 35.025641 | 138 | 0.586628 | [
"MIT"
] | tor4kichi/NiconicoToolkit | Test/NiconicoToolkit.Shared.Test/ExtractContenntIdTest.cs | 4,100 | C# |
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes.Jobs;
using Prometheus;
using Prometheus.Advanced;
namespace Benchmark
{
[ClrJob]
[MemoryDiagnoser]
public class LabelBenchmarks
{
// Metric -> Variant -> Label values
private static readonly string[][][] _labelValueRows;
private const int _metricCount = 10;
private const int _variantCount = 10;
private const int _labelCount = 5;
static LabelBenchmarks()
{
_labelValueRows = new string[_metricCount][][];
for (var metricIndex = 0; metricIndex < _metricCount; metricIndex++)
{
var variants = new string[_variantCount][];
_labelValueRows[metricIndex] = variants;
for (var variantIndex = 0; variantIndex < _variantCount; variantIndex++)
{
var values = new string[_labelCount];
_labelValueRows[metricIndex][variantIndex] = values;
for (var labelIndex = 0; labelIndex < _labelCount; labelIndex++)
values[labelIndex] = $"metric{metricIndex:D2}_label{labelIndex:D2}_variant{variantIndex:D2}";
}
}
}
private readonly DefaultCollectorRegistry _registry = new DefaultCollectorRegistry();
private readonly Counter[] _metrics;
public LabelBenchmarks()
{
_metrics = new Counter[_metricCount];
var factory = Metrics.WithCustomRegistry(_registry);
// Just use 1st variant for the keys (all we care about are that there is some name-like value in there).
for (var metricIndex = 0; metricIndex < _metricCount; metricIndex++)
_metrics[metricIndex] = factory.CreateCounter($"metric{metricIndex:D2}", "", _labelValueRows[metricIndex][0]);
}
/// <summary>
/// Increments an unlabelled Collector instance for a single metric.
/// </summary>
[Benchmark]
public void WithoutLabels_OneMetric_OneSeries()
{
_metrics[0].Inc();
}
/// <summary>
/// Increments unlabelled Collector instances for a multiple metrics.
/// </summary>
[Benchmark]
public void WithoutLabels_ManyMetrics_OneSeries()
{
for (var metricIndex = 0; metricIndex < _metricCount; metricIndex++)
_metrics[metricIndex].Inc();
}
/// <summary>
/// Increments a labelled Collector.Child instance for a single metric.
/// </summary>
[Benchmark]
public void WithLabels_OneMetric_OneSeries()
{
_metrics[0].Labels(_labelValueRows[0][0]).Inc();
}
/// <summary>
/// Increments labelled Collector.Child instances for one metric with multiple different sets of labels.
/// </summary>
[Benchmark]
public void WithLabels_OneMetric_ManySeries()
{
for (var variantIndex = 0; variantIndex < _variantCount; variantIndex++)
_metrics[0].Labels(_labelValueRows[0][variantIndex]).Inc();
}
/// <summary>
/// Increments a labelled Collector.Child instance for multiple metrics.
/// </summary>
[Benchmark]
public void WithLabels_ManyMetrics_OneSeries()
{
for (var metricIndex = 0; metricIndex < _metricCount; metricIndex++)
_metrics[metricIndex].Labels(_labelValueRows[metricIndex][0]).Inc();
}
/// <summary>
/// Increments labelled Collector.Child instances for multiple metrics with multiple different sets of labels.
/// </summary>
[Benchmark]
public void WithLabels_ManyMetrics_ManySeries()
{
for (var metricIndex = 0; metricIndex < _metricCount; metricIndex++)
for (var variantIndex = 0; variantIndex < _variantCount; variantIndex++)
_metrics[metricIndex].Labels(_labelValueRows[metricIndex][variantIndex]).Inc();
}
}
}
| 36.424779 | 126 | 0.598882 | [
"MIT"
] | FloMaetschke/prometheus-net | Benchmark.NetFramework/LabelBenchmarks.cs | 4,118 | C# |
using Credfeto.Notification.Bot.Database.Twitch;
using Microsoft.Extensions.DependencyInjection;
namespace Credfeto.Notification.Bot.Database;
public static class DatabaseSetup
{
/// <summary>
/// Configures database.
/// </summary>
/// <param name="services">The DI Container to register services in.</param>
public static IServiceCollection AddApplicationDatabase(this IServiceCollection services)
{
return services.AddTwitch();
}
} | 29.75 | 93 | 0.731092 | [
"MIT"
] | credfeto/notification-bot | src/Credfeto.Notification.Bot.Database/DatabaseSetup.cs | 476 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Emc.Documentum.Rest.Net;
using System.Runtime.InteropServices;
namespace Emc.Documentum.Rest.DataModel
{
/// <summary>
/// Link model
/// </summary>
[DataContract(Name = "link", Namespace = "http://identifiers.emc.com/vocab/documentum")]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class Link
{
[DataMember(Name = "rel")]
public string Rel { get; set; }
[DataMember(Name = "href")]
public string Href { get; set; }
[DataMember(Name = "hreftemplate")]
public string Hreftemplate { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "type")]
public string Type { get; set; }
public override string ToString()
{
JsonDotnetJsonSerializer serializer = new JsonDotnetJsonSerializer();
return serializer.Serialize(this);
}
}
}
| 26.142857 | 92 | 0.63388 | [
"Apache-2.0"
] | DEV-MC01/documentum-rest-client-dotnet | MonoReST/RestClient/DataModel/Base/Link.cs | 1,100 | C# |
using Microsoft.UI.Xaml.Controls;
namespace WinUISample.Maps.World
{
public sealed partial class View : UserControl
{
public View()
{
InitializeComponent();
}
}
}
| 16.384615 | 50 | 0.586854 | [
"MIT"
] | Diademics-Pty-Ltd/LiveCharts2 | samples/WinUISample/WinUI/WinUI/Maps/World/View.xaml.cs | 215 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V3109</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V3109 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="PRSC_MT040101UK08.GpPerson", Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute("PRSC_MT040101UK08.GpPerson", Namespace="urn:hl7-org:v3")]
public partial class PRSC_MT040101UK08GpPerson {
private PN nameField;
private string typeField;
private string classCodeField;
private string determinerCodeField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public PRSC_MT040101UK08GpPerson() {
this.typeField = "Person";
this.classCodeField = "PSN";
this.determinerCodeField = "INSTANCE";
}
public PN name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string classCode {
get {
return this.classCodeField;
}
set {
this.classCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string determinerCode {
get {
return this.determinerCodeField;
}
set {
this.determinerCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(PRSC_MT040101UK08GpPerson));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current PRSC_MT040101UK08GpPerson object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an PRSC_MT040101UK08GpPerson object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output PRSC_MT040101UK08GpPerson object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out PRSC_MT040101UK08GpPerson obj, out System.Exception exception) {
exception = null;
obj = default(PRSC_MT040101UK08GpPerson);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out PRSC_MT040101UK08GpPerson obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static PRSC_MT040101UK08GpPerson Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((PRSC_MT040101UK08GpPerson)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current PRSC_MT040101UK08GpPerson object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an PRSC_MT040101UK08GpPerson object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output PRSC_MT040101UK08GpPerson object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out PRSC_MT040101UK08GpPerson obj, out System.Exception exception) {
exception = null;
obj = default(PRSC_MT040101UK08GpPerson);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out PRSC_MT040101UK08GpPerson obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static PRSC_MT040101UK08GpPerson LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this PRSC_MT040101UK08GpPerson object
/// </summary>
public virtual PRSC_MT040101UK08GpPerson Clone() {
return ((PRSC_MT040101UK08GpPerson)(this.MemberwiseClone()));
}
#endregion
}
}
| 40.437276 | 1,358 | 0.567807 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V3109/Generated/PRSC_MT040101UK08GpPerson.cs | 11,282 | C# |
using DecisionTree.Decisions;
using System;
using System.Linq.Expressions;
using DecisionTree.Builders.Interface.Action;
using DecisionTree.Decisions.DecisionsBase;
namespace DecisionTree.Builders
{
public sealed class DecisionActionBuilder<T>
: IActionTitle<T>, IAction<T>, IActionPath<T>, IActionBuild<T>
{
private string _title;
private Expression<Func<T, T>> _action;
private IDecision<T> _path;
private DecisionActionBuilder() { }
public static IActionTitle<T> Create() => new DecisionActionBuilder<T>();
public IAction<T> AddTitle(string title)
{
_title = title;
return this;
}
public IActionPath<T> AddAction(Expression<Func<T, T>> action)
{
_action = action;
return this;
}
public IActionBuild<T> AddPath(IDecision<T> path)
{
_path = path;
return this;
}
public IDecisionAction<T> Build() =>
new DecisionAction<T>(_title, _action, _path);
}
}
| 25.833333 | 81 | 0.607373 | [
"MIT"
] | Smrecz/DecisionTree | DecisionTree/Builders/DecisionActionBuilder.cs | 1,087 | C# |
using Abp.AutoMapper;
using Abp.Modules;
using Abp.Reflection.Extensions;
using MyLife.Authorization;
namespace MyLife
{
[DependsOn(
typeof(MyLifeCoreModule),
typeof(AbpAutoMapperModule))]
public class MyLifeApplicationModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Authorization.Providers.Add<MyLifeAuthorizationProvider>();
}
public override void Initialize()
{
var thisAssembly = typeof(MyLifeApplicationModule).GetAssembly();
IocManager.RegisterAssemblyByConvention(thisAssembly);
Configuration.Modules.AbpAutoMapper().Configurators.Add(
// Scan the assembly for classes which inherit from AutoMapper.Profile
cfg => cfg.AddProfiles(thisAssembly)
);
}
}
}
| 27.870968 | 86 | 0.652778 | [
"MIT"
] | xiaocaoweizui/MyLife | aspnet-core/src/MyLife.Application/MyLifeApplicationModule.cs | 866 | C# |
using System;
using Ding.Offices.Excels.Imports;
namespace Ding.Offices.Excels.Npoi.Imports
{
/// <summary>
/// 导入器工厂
/// </summary>
public class ImportFactory:IImportFactory
{
/// <summary>
/// 文件绝对路径
/// </summary>
private readonly string _path;
/// <summary>
/// 工作表名称
/// </summary>
private readonly string _sheetName;
/// <summary>
/// 初始化一个<see cref="ImportFactory"/>类型的实例
/// </summary>
/// <param name="path">导入文件路径,绝对路径</param>
/// <param name="sheetName">工作表名称</param>
public ImportFactory(string path, string sheetName = "")
{
_path = path;
_sheetName = sheetName;
}
/// <summary>
/// 创建导入器
/// </summary>
/// <param name="version">Excel格式</param>
/// <returns></returns>
public IImport Create(ExcelVersion version)
{
switch (version)
{
case ExcelVersion.Xlsx:
return new Excel2003Import(_path,_sheetName);
case ExcelVersion.Xls:
return new Excel2007Import(_path, _sheetName);
}
throw new NotImplementedException();
}
/// <summary>
/// 创建 Excel 2003 导入器
/// </summary>
/// <param name="path">导入文件路径,绝对路径</param>
/// <param name="sheetName">工作表名称</param>
/// <returns></returns>
public static IImport CreateExcel2003Import(string path, string sheetName = "")
{
return new ImportFactory(path, sheetName).Create(ExcelVersion.Xls);
}
/// <summary>
/// 创建 Excel 2007 导入器
/// </summary>
/// <param name="path">导入文件路径,绝对路径</param>
/// <param name="sheetName">工作表名称</param>
/// <returns></returns>
public static IImport CreateExcel2007Import(string path, string sheetName = "")
{
return new ImportFactory(path,sheetName).Create(ExcelVersion.Xlsx);
}
}
}
| 29.055556 | 87 | 0.526291 | [
"MIT"
] | EnhWeb/DC.Framework | src/Ding.Offices.Excels.Npoi/Imports/ImportFactory.cs | 2,276 | C# |
using System.Collections.Generic;
using System.Linq;
using Redzen.Random;
using Redzen.Sorting;
using Redzen.Structures;
using SharpNeat.Neat.Genome;
using SharpNeat.Graphs;
using Xunit;
using static SharpNeat.Neat.Genome.Tests.NestGenomeTestUtils;
namespace SharpNeat.Neat.Reproduction.Asexual.Strategy.Tests
{
public class AddNodeStrategyTests
{
#region Public Methods
/// <summary>
/// Apply 'add node' mutations to the same initial genome multiple times.
/// Note. The mutations are random, therefore this tests different mutations on each loop.
/// </summary>
[Fact]
public void AddNode1()
{
var pop = CreateNeatPopulation();
var generationSeq = new Int32Sequence();
var genomeBuilder = NeatGenomeBuilderFactory<double>.Create(pop.MetaNeatGenome);
var genome = pop.GenomeList[0];
var strategy = new AddNodeStrategy<double>(
pop.MetaNeatGenome, genomeBuilder,
pop.GenomeIdSeq, pop.InnovationIdSeq, generationSeq,
pop.AddedNodeBuffer);
IRandomSource rng = RandomDefaults.CreateRandomSource();
for(int i=0; i < 10_000; i++) {
CreateAndTestChildGenome(genome, strategy, rng);
}
}
/// <summary>
/// Apply cumulative 'add node' mutations.
/// This explores more complex genome structures as the mutations accumulate.
/// </summary>
[Fact]
public void AddNode2()
{
var pop = CreateNeatPopulation();
var generationSeq = new Int32Sequence();
var genomeBuilder = NeatGenomeBuilderFactory<double>.Create(pop.MetaNeatGenome);
var genome = pop.GenomeList[0];
var strategy = new AddNodeStrategy<double>(
pop.MetaNeatGenome, genomeBuilder,
pop.GenomeIdSeq, pop.InnovationIdSeq, generationSeq,
pop.AddedNodeBuffer);
IRandomSource rng = RandomDefaults.CreateRandomSource();
for(int i=0; i < 2000; i++)
{
NeatGenome<double> childGenome = CreateAndTestChildGenome(genome, strategy, rng);
// Make the child genome the parent in the next iteration. I.e. accumulate add node mutations.
genome = childGenome;
}
}
/// <summary>
/// Apply cumulative 'add node' mutations to 10 genomes, rather than the single genome in TestAddNode2().
/// This results in some mutations occurring that have already occurred on one of the other genomes,
/// and therefore this tests the code paths that handle re-using innovation IDs obtain from the innovation buffers.
/// </summary>
[Fact]
public void AddNode3()
{
var pop = CreateNeatPopulation();
var generationSeq = new Int32Sequence();
var genomeBuilder = NeatGenomeBuilderFactory<double>.Create(pop.MetaNeatGenome);
var genome = pop.GenomeList[0];
var strategy = new AddNodeStrategy<double>(
pop.MetaNeatGenome, genomeBuilder,
pop.GenomeIdSeq, pop.InnovationIdSeq, generationSeq,
pop.AddedNodeBuffer);
IRandomSource rng = RandomDefaults.CreateRandomSource();
CircularBuffer<NeatGenome<double>> genomeRing = new CircularBuffer<NeatGenome<double>>(10);
genomeRing.Enqueue(genome);
for(int i=0; i < 5000; i++)
{
NeatGenome<double> childGenome = CreateAndTestChildGenome(genome, strategy, rng);
// Add the new child genome to the ring.
genomeRing.Enqueue(childGenome);
// Take the genome at the tail of the ring for the next parent.
genome = genomeRing[0];
}
}
#endregion
#region Private Static Methods
private static NeatGenome<double> CreateAndTestChildGenome(
NeatGenome<double> parentGenome,
AddNodeStrategy<double> strategy,
IRandomSource rng)
{
var nodeIdSet = GetNodeIdSet(parentGenome);
var connSet = GetDirectedConnectionSet(parentGenome);
var childGenome = strategy.CreateChildGenome(parentGenome, rng);
// The connection genes should be sorted.
Assert.True(SortUtils.IsSortedAscending(childGenome.ConnectionGenes._connArr));
// The child genome should have one more connection than parent.
Assert.Equal(parentGenome.ConnectionGenes.Length + 1, childGenome.ConnectionGenes.Length);
// The child genome should have one more node ID than the parent.
var childNodeIdSet = GetNodeIdSet(childGenome);
var newNodeIdList = new List<int>(childNodeIdSet.Except(nodeIdSet));
Assert.Single(newNodeIdList);
int newNodeId = newNodeIdList[0];
// The child genome's new connections should not be a duplicate of any of the existing/parent connections.
var childConnSet = GetDirectedConnectionSet(childGenome);
var newConnList = new List<DirectedConnection>(childConnSet.Except(connSet));
Assert.Equal(2, newConnList.Count);
// The parent should have one connection that the child does not, i.e. the connection that was replaced.
var removedConnList = new List<DirectedConnection>(connSet.Except(childConnSet));
Assert.Single(removedConnList);
// The two new connections should connect to the new node ID.
var connRemoved = removedConnList[0];
var connA = newConnList[0];
var connB = newConnList[1];
Assert.True(
(connA.SourceId == connRemoved.SourceId && connA.TargetId == newNodeId && connB.SourceId == newNodeId && connB.TargetId == connRemoved.TargetId)
|| (connB.SourceId == connRemoved.SourceId && connB.TargetId == newNodeId && connA.SourceId == newNodeId && connA.TargetId == connRemoved.TargetId));
return childGenome;
}
#endregion
}
}
| 40.836601 | 166 | 0.62388 | [
"MIT"
] | neobepmat/sharpneat-refactor | src/Tests/SharpNeat.Tests/Neat/Reproduction/Asexual/Strategy/AddNodeStrategyTests.cs | 6,250 | C# |
namespace SharpIMClient
{
public enum BuddyStatus
{
Online,
Offline,
Away,
Busy
}
}
| 11.636364 | 27 | 0.5 | [
"MIT"
] | zachhowe/sharpim | ClientLibrary/Constants.cs | 128 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Microsoft.UI.Xaml.Controls;
using Uno.Disposables;
using Uno.Extensions;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace NupkgExplorer.Views.Extensions
{
public static class TabViewExtensions
{
/* ResetSelectionWith: resets the TabView selection (to first item) or sets the TabViewItem IsSelected to true when the binding is updated to non-null value
* ResetSelectionWithItemVisibility: resets the TabView selection (to first visible item) whenever any TabViewItem visibility changes
* - ResetSelectionWithItemVisibilitySubscription: [private] IDisposable for managing ResetSelectionWithItemVisibility subscription
* HideHeaderToolTip: hide mouse over tooltip on TabViewItem */
#region DependencyProperty: ResetSelectionWith
public static DependencyProperty ResetSelectionWithProperty { get; } = DependencyProperty.RegisterAttached(
"ResetSelectionWith",
typeof(object),
typeof(TabViewExtensions),
new PropertyMetadata(default(object), OnResetSelectionWithChanged));
public static object GetResetSelectionWith(FrameworkElement obj) => (object)obj.GetValue(ResetSelectionWithProperty);
public static void SetResetSelectionWith(FrameworkElement obj, object value) => obj.SetValue(ResetSelectionWithProperty, value);
#endregion
#region DependencyProperty: ResetSelectionWithItemVisibility
public static DependencyProperty ResetSelectionWithItemVisibilityProperty { get; } = DependencyProperty.RegisterAttached(
"ResetSelectionWithItemVisibility",
typeof(bool),
typeof(TabViewExtensions),
new PropertyMetadata(default(bool), (d, e) => d.Maybe<TabView>(control => OnResetSelectionWithItemVisibilityChanged(control, e))));
public static bool GetResetSelectionWithItemVisibility(TabView obj) => (bool)obj.GetValue(ResetSelectionWithItemVisibilityProperty);
public static void SetResetSelectionWithItemVisibility(TabView obj, bool value) => obj.SetValue(ResetSelectionWithItemVisibilityProperty, value);
#endregion
#region DependencyProperty: ResetSelectionWithItemVisibilitySubscription
private static DependencyProperty ResetSelectionWithItemVisibilitySubscriptionProperty { get; } = DependencyProperty.RegisterAttached(
"ResetSelectionWithItemVisibilitySubscription",
typeof(IDisposable),
typeof(TabViewExtensions),
new PropertyMetadata(default(IDisposable)));
private static IDisposable GetResetSelectionWithItemVisibilitySubscription(TabView obj) => (IDisposable)obj.GetValue(ResetSelectionWithItemVisibilitySubscriptionProperty);
private static void SetResetSelectionWithItemVisibilitySubscription(TabView obj, IDisposable? value) => obj.SetValue(ResetSelectionWithItemVisibilitySubscriptionProperty, value);
#endregion
#region DependencyProperty: HideHeaderToolTip
public static DependencyProperty HideHeaderToolTipProperty { get; } = DependencyProperty.RegisterAttached(
"HideHeaderToolTip",
typeof(bool),
typeof(TabViewExtensions),
new PropertyMetadata(default(bool), (d, e) => d.Maybe<TabViewItem>(control => OnHideHeaderToolTipChanged(control, e))));
public static bool GetHideHeaderToolTip(TabViewItem obj) => (bool)obj.GetValue(HideHeaderToolTipProperty);
public static void SetHideHeaderToolTip(TabViewItem obj, bool value) => obj.SetValue(HideHeaderToolTipProperty, value);
#endregion
private static void OnResetSelectionWithChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
if (sender is TabView tv) CoreImpl(tv, x => x.TabItems
.OfType<TabViewItem>()
.FirstOrDefault()
?.Apply(y => y.IsSelected = true));
if (sender is TabViewItem tvi) CoreImpl(tvi, x => x.IsSelected = true);
void CoreImpl<T>(T control, Action<T> action) where T : FrameworkElement
{
if (GetResetSelectionWith(control) is not null)
{
action(control);
}
}
}
[SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "managed via ResetSelectionWithItemVisibilitySubscription")]
private static void OnResetSelectionWithItemVisibilityChanged(TabView control, DependencyPropertyChangedEventArgs e)
{
GetResetSelectionWithItemVisibilitySubscription(control)?.Dispose();
SetResetSelectionWithItemVisibilitySubscription(control, null);
if ((bool)e.NewValue)
{
// for simplicity, we assume the TabItems wont changes
var subscriptions = new CompositeDisposable();
foreach (var tvi in control.TabItems.OfType<TabViewItem>())
{
var token = tvi.RegisterPropertyChangedCallback(UIElement.VisibilityProperty, SelectFirstVisibleTabItem);
subscriptions.Add(() => tvi.UnregisterPropertyChangedCallback(UIElement.VisibilityProperty, token));
}
SetResetSelectionWithItemVisibilitySubscription(control, subscriptions);
}
void SelectFirstVisibleTabItem(DependencyObject sender, DependencyProperty dp)
{
control.TabItems
.OfType<TabViewItem>()
.FirstOrDefault(x => x.Visibility == Visibility.Visible)
?.Apply(x => x.IsSelected = true);
}
}
private static void OnHideHeaderToolTipChanged(TabViewItem control, DependencyPropertyChangedEventArgs e)
{
if (ToolTipService.GetToolTip(control) is ToolTip tooltip)
{
tooltip.Opened += (s, e) => tooltip.IsOpen = false;
}
}
}
}
| 47.868217 | 186 | 0.693765 | [
"MIT"
] | MarcelWolf1983/NuGetPackageExplorer | Uno/NugetPackageExplorer.Legacy/Views/Extensions/TabViewExtensions.cs | 6,177 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MinimalKatana
{
using AppFunc = Func<IDictionary<string, object>, Task>;
public class Startup
{
public AppFunc Configuration() {
return async env => {
var writer = new StreamWriter((Stream)env["owin.ResponseBody"]);
await writer.WriteAsync("Hello World!");
await writer.FlushAsync();
};
}
}
} | 25.2 | 80 | 0.599206 | [
"MIT"
] | eocampo/LearningOwin | MinimalKatana/Startup.cs | 506 | C# |
using NLog;
using NLog.Config;
using NLog.Targets;
namespace EligibleService.Common
{
public class Logging
{
public Logging()
{
var config = new LoggingConfiguration();
var fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
fileTarget.FileName = "${basedir}/Logs/EligibleLog.log";
fileTarget.ArchiveEvery = FileArchivePeriod.Day;
fileTarget.MaxArchiveFiles = 10;
fileTarget.Footer = "${newline}";
fileTarget.ConcurrentWrites = true;
fileTarget.KeepFileOpen = false;
fileTarget.ArchiveFileName = "${basedir}/Logs/Archives/EligibleLog.{#}.log";
fileTarget.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
fileTarget.ArchiveDateFormat = "yyyy-MM-dd";
fileTarget.Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} ${logger} ${level}: ${message}";
var fileRule = new LoggingRule("*", LogLevel.Info, fileTarget);
config.LoggingRules.Add(fileRule);
var consoleTarget = new ColoredConsoleTarget();
config.AddTarget("console", consoleTarget);
consoleTarget.Footer = "${newline}";
consoleTarget.Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} ${logger} ${level}: ${message}";
var consoleRule = new LoggingRule("*", LogLevel.Info, consoleTarget);
config.LoggingRules.Add(consoleRule);
DebugTarget = new DebugTarget();
DebugTarget.Layout = @"${message}";
var debugRule = new LoggingRule("*", LogLevel.Error, DebugTarget);
config.LoggingRules.Add(debugRule);
LogManager.Configuration = config;
}
public static DebugTarget DebugTarget { get; set; }
public static string GetLastMessage()
{
return DebugTarget.LastMessage;
}
}
}
| 36.333333 | 106 | 0.59735 | [
"MIT"
] | balu-eligible/eligible-CSharp | Eligible.NET/src/EligibleService.Common/Logging.cs | 1,964 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SharpLearning.InputOutput.Csv;
using System.IO;
using System.Linq;
using SharpLearning.GradientBoost.Test.Properties;
using SharpLearning.Metrics.Classification;
using SharpLearning.Containers;
using System.Collections.Generic;
using System.Diagnostics;
using SharpLearning.GradientBoost.Models;
using SharpLearning.GradientBoost.Learners;
using SharpLearning.GradientBoost.Loss;
namespace SharpLearning.GradientBoost.Test.Models
{
[TestClass]
public class ClassificationGradientBoostModelTest
{
[TestMethod]
public void ClassificationGradientBoostModel_Predict_Single()
{
var parser = new CsvParser(() => new StringReader(Resources.AptitudeData));
var observations = parser.EnumerateRows(v => v != "Pass").ToF64Matrix();
var targets = parser.EnumerateRows("Pass").ToF64Vector();
var rows = targets.Length;
var learner = new ClassificationGradientBoostLearner(100, 0.1, 3, 1, 1e-6, 1, 0, new GradientBoostBinomialLoss(), false);
var sut = learner.Learn(observations, targets);
var predictions = new double[rows];
for (int i = 0; i < rows; i++)
{
predictions[i] = sut.Predict(observations.Row(i));
}
var evaluator = new TotalErrorClassificationMetric<double>();
var error = evaluator.Error(targets, predictions);
Assert.AreEqual(0.038461538461538464, error, 0.0000001);
}
[TestMethod]
public void ClassificationGradientBoostModel_Predict_Multiple()
{
var parser = new CsvParser(() => new StringReader(Resources.AptitudeData));
var observations = parser.EnumerateRows(v => v != "Pass").ToF64Matrix();
var targets = parser.EnumerateRows("Pass").ToF64Vector();
var rows = targets.Length;
var learner = new ClassificationGradientBoostLearner(100, 0.1, 3, 1, 1e-6, 1, 0, new GradientBoostBinomialLoss(), false);
var sut = learner.Learn(observations, targets);
var predictions = sut.Predict(observations);
var evaluator = new TotalErrorClassificationMetric<double>();
var error = evaluator.Error(targets, predictions);
Assert.AreEqual(0.038461538461538464, error, 0.0000001);
}
[TestMethod]
public void ClassificationGradientBoostModel_PredictProbability_Single()
{
var parser = new CsvParser(() => new StringReader(Resources.AptitudeData));
var observations = parser.EnumerateRows(v => v != "Pass").ToF64Matrix();
var targets = parser.EnumerateRows("Pass").ToF64Vector();
var rows = targets.Length;
var learner = new ClassificationGradientBoostLearner(100, 0.1, 3, 1, 1e-6, 1, 0, new GradientBoostBinomialLoss(), false);
var sut = learner.Learn(observations, targets);
var actual = new ProbabilityPrediction[rows];
for (int i = 0; i < rows; i++)
{
actual[i] = sut.PredictProbability(observations.Row(i));
}
var evaluator = new TotalErrorClassificationMetric<double>();
var error = evaluator.Error(targets, actual.Select(p => p.Prediction).ToArray());
Assert.AreEqual(0.038461538461538464, error, 0.0000001);
var expected = new ProbabilityPrediction[] { new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00153419685769873 }, { 0, 0.998465803142301 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.497135615200052 }, { 0, 0.502864384799948 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00674291737944022 }, { 0, 0.99325708262056 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00153419685769873 }, { 0, 0.998465803142301 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.497135615200052 }, { 0, 0.502864384799948 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00428497228545111 }, { 0, 0.995715027714549 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.987907185249206 }, { 0, 0.0120928147507945 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.982783250692275 }, { 0, 0.0172167493077254 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00262490179961228 }, { 0, 0.997375098200388 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.996417847055106 }, { 0, 0.00358215294489364 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.995341658753364 }, { 0, 0.00465834124663571 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00674291737944022 }, { 0, 0.99325708262056 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.0118633115475969 }, { 0, 0.988136688452403 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00048646805791186 }, { 0, 0.999513531942088 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.999891769651047 }, { 0, 0.000108230348952856 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00334655581934884 }, { 0, 0.996653444180651 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00428497228545111 }, { 0, 0.995715027714549 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.0118633115475969 }, { 0, 0.988136688452403 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.996417847055106 }, { 0, 0.00358215294489362 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.993419876193791 }, { 0, 0.00658012380620933 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00262490179961228 }, { 0, 0.997375098200388 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.996417847055106 }, { 0, 0.00358215294489362 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.988568859753437 }, { 0, 0.0114311402465632 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00334655581934884 }, { 0, 0.996653444180651 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00428497228545111 }, { 0, 0.995715027714549 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00262490179961228 }, { 0, 0.997375098200388 }, }), };
CollectionAssert.AreEqual(expected, actual);
}
[TestMethod]
public void ClassificationGradientBoostModel_PredictProbability_Multiple()
{
var parser = new CsvParser(() => new StringReader(Resources.AptitudeData));
var observations = parser.EnumerateRows(v => v != "Pass").ToF64Matrix();
var targets = parser.EnumerateRows("Pass").ToF64Vector();
var rows = targets.Length;
var learner = new ClassificationGradientBoostLearner(100, 0.1, 3, 1, 1e-6, 1, 0, new GradientBoostBinomialLoss(), false);
var sut = learner.Learn(observations, targets);
var actual = sut.PredictProbability(observations);
var evaluator = new TotalErrorClassificationMetric<double>();
var error = evaluator.Error(targets, actual.Select(p => p.Prediction).ToArray());
Assert.AreEqual(0.038461538461538464, error, 0.0000001);
var expected = new ProbabilityPrediction[] { new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00153419685769873 }, { 0, 0.998465803142301 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.497135615200052 }, { 0, 0.502864384799948 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00674291737944022 }, { 0, 0.99325708262056 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00153419685769873 }, { 0, 0.998465803142301 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.497135615200052 }, { 0, 0.502864384799948 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00428497228545111 }, { 0, 0.995715027714549 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.987907185249206 }, { 0, 0.0120928147507945 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.982783250692275 }, { 0, 0.0172167493077254 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00262490179961228 }, { 0, 0.997375098200388 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.996417847055106 }, { 0, 0.00358215294489364 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.995341658753364 }, { 0, 0.00465834124663571 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00674291737944022 }, { 0, 0.99325708262056 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.0118633115475969 }, { 0, 0.988136688452403 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00048646805791186 }, { 0, 0.999513531942088 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.999891769651047 }, { 0, 0.000108230348952856 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00334655581934884 }, { 0, 0.996653444180651 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00428497228545111 }, { 0, 0.995715027714549 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.0118633115475969 }, { 0, 0.988136688452403 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.996417847055106 }, { 0, 0.00358215294489362 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.993419876193791 }, { 0, 0.00658012380620933 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00262490179961228 }, { 0, 0.997375098200388 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.996417847055106 }, { 0, 0.00358215294489362 }, }), new ProbabilityPrediction(1, new Dictionary<double, double> { { 1, 0.988568859753437 }, { 0, 0.0114311402465632 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00334655581934884 }, { 0, 0.996653444180651 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00428497228545111 }, { 0, 0.995715027714549 }, }), new ProbabilityPrediction(0, new Dictionary<double, double> { { 1, 0.00262490179961228 }, { 0, 0.997375098200388 }, }), };
CollectionAssert.AreEqual(expected, actual);
}
[TestMethod]
public void ClassificationGradientBoostModel_GetVariableImportance()
{
var parser = new CsvParser(() => new StringReader(Resources.AptitudeData));
var observations = parser.EnumerateRows(v => v != "Pass").ToF64Matrix();
var targets = parser.EnumerateRows("Pass").ToF64Vector();
var featureNameToIndex = new Dictionary<string, int> { { "AptitudeTestScore", 0 },
{ "PreviousExperience_month", 1 } };
var learner = new ClassificationGradientBoostLearner(100, 0.1, 3, 1, 1e-6, 1, 0, new GradientBoostBinomialLoss(), false);
var sut = learner.Learn(observations, targets);
var actual = sut.GetVariableImportance(featureNameToIndex);
var expected = new Dictionary<string, double> { {"PreviousExperience_month", 100},
{"AptitudeTestScore", 56.81853305612 } };
Assert.AreEqual(expected.Count, actual.Count);
var zip = expected.Zip(actual, (e, a) => new { Expected = e, Actual = a });
foreach (var item in zip)
{
Assert.AreEqual(item.Expected.Key, item.Actual.Key);
Assert.AreEqual(item.Expected.Value, item.Actual.Value, 0.01);
}
}
[TestMethod]
public void ClassificationGradientBoostModel_GetRawVariableImportance()
{
var parser = new CsvParser(() => new StringReader(Resources.AptitudeData));
var observations = parser.EnumerateRows(v => v != "Pass").ToF64Matrix();
var targets = parser.EnumerateRows("Pass").ToF64Vector();
var learner = new ClassificationGradientBoostLearner(100, 0.1, 3, 1, 1e-6, 1, 0, new GradientBoostBinomialLoss(), false);
var sut = learner.Learn(observations, targets);
var actual = sut.GetRawVariableImportance();
var expected = new double[] { 26.287331114005394, 46.265416757664667 };
Assert.AreEqual(expected.Length, actual.Length);
for (int i = 0; i < expected.Length; i++)
{
Assert.AreEqual(expected[i], actual[i], 0.001);
}
}
[TestMethod]
public void ClassificationGradientBoostModel_Save()
{
var parser = new CsvParser(() => new StringReader(Resources.AptitudeData));
var observations = parser.EnumerateRows(v => v != "Pass").ToF64Matrix();
var targets = parser.EnumerateRows("Pass").ToF64Vector();
var learner = new ClassificationGradientBoostLearner(5);
var sut = learner.Learn(observations, targets);
// save model.
var writer = new StringWriter();
sut.Save(() => writer);
// load model and assert prediction results.
sut = ClassificationGradientBoostModel.Load(() => new StringReader(writer.ToString()));
var predictions = sut.Predict(observations);
var evaluator = new TotalErrorClassificationMetric<double>();
var actual = evaluator.Error(targets, predictions);
Assert.AreEqual(0.15384615384615385, actual, 0.0000001);
}
[TestMethod]
public void ClassificationGradientBoostModel_Load()
{
var parser = new CsvParser(() => new StringReader(Resources.AptitudeData));
var observations = parser.EnumerateRows(v => v != "Pass").ToF64Matrix();
var targets = parser.EnumerateRows("Pass").ToF64Vector();
var reader = new StringReader(ClassificationGradientBoostModelString);
var sut = ClassificationGradientBoostModel.Load(() => reader);
var predictions = sut.Predict(observations);
var evaluator = new TotalErrorClassificationMetric<double>();
var error = evaluator.Error(targets, predictions);
Assert.AreEqual(0.15384615384615385, error, 0.0000001);
}
void Write(ProbabilityPrediction[] predictions)
{
var value = "new ProbabilityPrediction[] {";
foreach (var item in predictions)
{
value += "new ProbabilityPrediction(" + item.Prediction + ", new Dictionary<double, double> {";
foreach (var prob in item.Probabilities)
{
value += "{" + prob.Key + ", " + prob.Value + "}, ";
}
value += "}),";
}
value += "};";
Trace.WriteLine(value);
}
readonly string ClassificationGradientBoostModelString =
"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<ClassificationGradientBoostModel xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" z:Id=\"1\" xmlns:z=\"http://schemas.microsoft.com/2003/10/Serialization/\" xmlns=\"http://schemas.datacontract.org/2004/07/SharpLearning.GradientBoost.Models\">\r\n <FeatureCount>2</FeatureCount>\r\n <InitialLoss>-0.47000362924573558</InitialLoss>\r\n <LearningRate>0.1</LearningRate>\r\n <TargetNames xmlns:d2p1=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" z:Id=\"2\" z:Size=\"2\">\r\n <d2p1:double>0</d2p1:double>\r\n <d2p1:double>1</d2p1:double>\r\n </TargetNames>\r\n <Trees xmlns:d2p1=\"http://schemas.datacontract.org/2004/07/SharpLearning.GradientBoost.GBMDecisionTree\" z:Id=\"3\" z:Size=\"1\">\r\n <d2p1:ArrayOfGBMTree z:Id=\"4\" z:Size=\"5\">\r\n <d2p1:GBMTree z:Id=\"5\">\r\n <d2p1:Nodes z:Id=\"6\" z:Size=\"5\">\r\n <d2p1:GBMNode z:Id=\"7\">\r\n <d2p1:Depth>0</d2p1:Depth>\r\n <d2p1:FeatureIndex>-1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>0.9749999999999992</d2p1:LeftConstant>\r\n <d2p1:LeftError>6.1538461538461577</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.9749999999999992</d2p1:RightConstant>\r\n <d2p1:RightError>6.1538461538461577</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>-1</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"8\">\r\n <d2p1:Depth>1</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.4477272727272721</d2p1:LeftConstant>\r\n <d2p1:LeftError>4.3636363636363686</d2p1:LeftError>\r\n <d2p1:LeftIndex>2</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.625000000000002</d2p1:RightConstant>\r\n <d2p1:RightError>-1.5543122344752192E-15</d2p1:RightError>\r\n <d2p1:RightIndex>3</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>20</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"9\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-1.625</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>1.5940476190476185</d2p1:RightConstant>\r\n <d2p1:RightError>3.8095238095238142</d2p1:RightError>\r\n <d2p1:RightIndex>4</d2p1:RightIndex>\r\n <d2p1:SampleCount>22</d2p1:SampleCount>\r\n <d2p1:SplitValue>2.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"10\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-1.625</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.6250000000000027</d2p1:RightConstant>\r\n <d2p1:RightError>-1.609823385706477E-15</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>4</d2p1:SampleCount>\r\n <d2p1:SplitValue>23</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"11\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>2.0366666666666666</d2p1:LeftConstant>\r\n <d2p1:LeftError>1.7333333333333374</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.4874999999999996</d2p1:RightConstant>\r\n <d2p1:RightError>1.5</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>21</d2p1:SampleCount>\r\n <d2p1:SplitValue>13.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n </d2p1:Nodes>\r\n </d2p1:GBMTree>\r\n <d2p1:GBMTree z:Id=\"12\">\r\n <d2p1:Nodes z:Id=\"13\" z:Size=\"6\">\r\n <d2p1:GBMNode z:Id=\"14\">\r\n <d2p1:Depth>0</d2p1:Depth>\r\n <d2p1:FeatureIndex>-1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>0.86059480408450362</d2p1:LeftConstant>\r\n <d2p1:LeftError>5.596711778030242</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.86059480408450362</d2p1:RightConstant>\r\n <d2p1:RightError>5.596711778030242</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>-1</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"15\">\r\n <d2p1:Depth>1</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.266063090014917</d2p1:LeftConstant>\r\n <d2p1:LeftError>4.1463589231846409</d2p1:LeftError>\r\n <d2p1:LeftIndex>2</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.5312600563908738</d2p1:RightConstant>\r\n <d2p1:RightError>-1.27675647831893E-15</d2p1:RightError>\r\n <d2p1:RightIndex>3</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>20</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"16\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-0.2989037549136308</d2p1:LeftConstant>\r\n <d2p1:LeftError>0.6137878335116782</d2p1:LeftError>\r\n <d2p1:LeftIndex>4</d2p1:LeftIndex>\r\n <d2p1:RightConstant>1.5087703239250865</d2p1:RightConstant>\r\n <d2p1:RightError>3.0331204175116282</d2p1:RightError>\r\n <d2p1:RightIndex>5</d2p1:RightIndex>\r\n <d2p1:SampleCount>22</d2p1:SampleCount>\r\n <d2p1:SplitValue>4.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"17\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-1.5312600563908738</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.5312600563908738</d2p1:RightConstant>\r\n <d2p1:RightError>-1.27675647831893E-15</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>4</d2p1:SampleCount>\r\n <d2p1:SplitValue>23</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"18\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>0</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>2.3051747796578996</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.6534579988148759</d2p1:RightConstant>\r\n <d2p1:RightError>0.0037726356416253326</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>3</d2p1:SampleCount>\r\n <d2p1:SplitValue>4</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"19\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.9919935727839668</d2p1:LeftConstant>\r\n <d2p1:LeftError>0.92307692307692335</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.43382354239469473</d2p1:RightConstant>\r\n <d2p1:RightError>1.4999999999999982</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>19</d2p1:SampleCount>\r\n <d2p1:SplitValue>13.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n </d2p1:Nodes>\r\n </d2p1:GBMTree>\r\n <d2p1:GBMTree z:Id=\"20\">\r\n <d2p1:Nodes z:Id=\"21\" z:Size=\"6\">\r\n <d2p1:GBMNode z:Id=\"22\">\r\n <d2p1:Depth>0</d2p1:Depth>\r\n <d2p1:FeatureIndex>-1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>0.772024071047949</d2p1:LeftConstant>\r\n <d2p1:LeftError>4.9956325710355829</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.772024071047949</d2p1:RightConstant>\r\n <d2p1:RightError>4.9956325710355829</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>-1</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"23\">\r\n <d2p1:Depth>1</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.1271620452174398</d2p1:LeftConstant>\r\n <d2p1:LeftError>3.81901068866107</d2p1:LeftError>\r\n <d2p1:LeftIndex>2</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.4558326033028339</d2p1:RightConstant>\r\n <d2p1:RightError>-5.5511151231257827E-17</d2p1:RightError>\r\n <d2p1:RightIndex>3</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>20</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"24\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-0.27786210243575493</d2p1:LeftConstant>\r\n <d2p1:LeftError>0.49774616548974571</d2p1:LeftError>\r\n <d2p1:LeftIndex>4</d2p1:LeftIndex>\r\n <d2p1:RightConstant>1.3374975310021555</d2p1:RightConstant>\r\n <d2p1:RightError>2.9159510952504579</d2p1:RightError>\r\n <d2p1:RightIndex>5</d2p1:RightIndex>\r\n <d2p1:SampleCount>22</d2p1:SampleCount>\r\n <d2p1:SplitValue>4.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"25\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>0</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-1.4558326033028344</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.4558326033028339</d2p1:RightConstant>\r\n <d2p1:RightError>-1.1102230246251565E-16</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>4</d2p1:SampleCount>\r\n <d2p1:SplitValue>2.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"26\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>0</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>2.0364687310490139</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.5552695523522238</d2p1:RightConstant>\r\n <d2p1:RightError>0.0034643522773981916</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>3</d2p1:SampleCount>\r\n <d2p1:SplitValue>4</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"27\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.7614034635323572</d2p1:LeftConstant>\r\n <d2p1:LeftError>0.923076923076926</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.38692819292266051</d2p1:RightConstant>\r\n <d2p1:RightError>1.4999999999999982</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>19</d2p1:SampleCount>\r\n <d2p1:SplitValue>13.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n </d2p1:Nodes>\r\n </d2p1:GBMTree>\r\n <d2p1:GBMTree z:Id=\"28\">\r\n <d2p1:Nodes z:Id=\"29\" z:Size=\"6\">\r\n <d2p1:GBMNode z:Id=\"30\">\r\n <d2p1:Depth>0</d2p1:Depth>\r\n <d2p1:FeatureIndex>-1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>0.70169938484575745</d2p1:LeftConstant>\r\n <d2p1:LeftError>4.51195943689269</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.70169938484575745</d2p1:RightConstant>\r\n <d2p1:RightError>4.51195943689269</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>-1</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"31\">\r\n <d2p1:Depth>1</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.0178497808241769</d2p1:LeftConstant>\r\n <d2p1:LeftError>3.5560561124147441</d2p1:LeftError>\r\n <d2p1:LeftIndex>2</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.3940754481637947</d2p1:RightConstant>\r\n <d2p1:RightError>5.5511151231257827E-16</d2p1:RightError>\r\n <d2p1:RightIndex>3</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>20</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"32\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-0.26129981339727465</d2p1:LeftConstant>\r\n <d2p1:LeftError>0.40445472313087061</d2p1:LeftError>\r\n <d2p1:LeftIndex>4</d2p1:LeftIndex>\r\n <d2p1:RightConstant>1.2026374881990321</d2p1:RightConstant>\r\n <d2p1:RightError>2.8223468437614274</d2p1:RightError>\r\n <d2p1:RightIndex>5</d2p1:RightIndex>\r\n <d2p1:SampleCount>22</d2p1:SampleCount>\r\n <d2p1:SplitValue>4.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"33\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-1.3940754481637925</d2p1:LeftConstant>\r\n <d2p1:LeftError>-8.3266726846886741E-17</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.3940754481638016</d2p1:RightConstant>\r\n <d2p1:RightError>5.6898930012039273E-16</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>4</d2p1:SampleCount>\r\n <d2p1:SplitValue>25</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"34\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>0</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.8454997650794467</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.476363101919945</d2p1:RightConstant>\r\n <d2p1:RightError>0.003125954915934176</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>3</d2p1:SampleCount>\r\n <d2p1:SplitValue>4</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"35\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.5881207774717288</d2p1:LeftConstant>\r\n <d2p1:LeftError>0.92307692307692246</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.34571926201171</d2p1:RightConstant>\r\n <d2p1:RightError>1.5000000000000016</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>19</d2p1:SampleCount>\r\n <d2p1:SplitValue>13.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n </d2p1:Nodes>\r\n </d2p1:GBMTree>\r\n <d2p1:GBMTree z:Id=\"36\">\r\n <d2p1:Nodes z:Id=\"37\" z:Size=\"6\">\r\n <d2p1:GBMNode z:Id=\"38\">\r\n <d2p1:Depth>0</d2p1:Depth>\r\n <d2p1:FeatureIndex>-1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>0.6437998722965409</d2p1:LeftConstant>\r\n <d2p1:LeftError>4.1213084097097727</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.6437998722965409</d2p1:RightConstant>\r\n <d2p1:RightError>4.1213084097097727</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>-1</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"39\">\r\n <d2p1:Depth>1</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>0.92847183796929378</d2p1:LeftConstant>\r\n <d2p1:LeftError>3.3439173220730334</d2p1:LeftError>\r\n <d2p1:LeftIndex>2</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.342795767209559</d2p1:RightConstant>\r\n <d2p1:RightError>-3.3306690738754696E-16</d2p1:RightError>\r\n <d2p1:RightIndex>3</d2p1:RightIndex>\r\n <d2p1:SampleCount>26</d2p1:SampleCount>\r\n <d2p1:SplitValue>20</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"40\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-0.24798179549281313</d2p1:LeftConstant>\r\n <d2p1:LeftError>0.32911873867457769</d2p1:LeftError>\r\n <d2p1:LeftIndex>4</d2p1:LeftIndex>\r\n <d2p1:RightConstant>1.09231706285825</d2p1:RightConstant>\r\n <d2p1:RightError>2.7471226162746536</d2p1:RightError>\r\n <d2p1:RightIndex>5</d2p1:RightIndex>\r\n <d2p1:SampleCount>22</d2p1:SampleCount>\r\n <d2p1:SplitValue>4.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"41\">\r\n <d2p1:Depth>2</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>-1.3427957672095576</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.3427957672095594</d2p1:RightConstant>\r\n <d2p1:RightError>-3.3306690738754696E-16</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>4</d2p1:SampleCount>\r\n <d2p1:SplitValue>23</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"42\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>0</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.7030147787421894</d2p1:LeftConstant>\r\n <d2p1:LeftError>0</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>-1.411809703520875</d2p1:RightConstant>\r\n <d2p1:RightError>0.0027812379638359475</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>3</d2p1:SampleCount>\r\n <d2p1:SplitValue>4</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n <d2p1:GBMNode z:Id=\"43\">\r\n <d2p1:Depth>3</d2p1:Depth>\r\n <d2p1:FeatureIndex>1</d2p1:FeatureIndex>\r\n <d2p1:LeftConstant>1.4518067863692972</d2p1:LeftConstant>\r\n <d2p1:LeftError>0.92307692307692313</d2p1:LeftError>\r\n <d2p1:LeftIndex>-1</d2p1:LeftIndex>\r\n <d2p1:RightConstant>0.309338924177296</d2p1:RightConstant>\r\n <d2p1:RightError>1.4999999999999996</d2p1:RightError>\r\n <d2p1:RightIndex>-1</d2p1:RightIndex>\r\n <d2p1:SampleCount>19</d2p1:SampleCount>\r\n <d2p1:SplitValue>13.5</d2p1:SplitValue>\r\n </d2p1:GBMNode>\r\n </d2p1:Nodes>\r\n </d2p1:GBMTree>\r\n </d2p1:ArrayOfGBMTree>\r\n </Trees>\r\n</ClassificationGradientBoostModel>";
}
}
| 164.35 | 20,683 | 0.631109 | [
"MIT"
] | GaGa2015/SharpLearning | src/SharpLearning.GradientBoost.Test/Models/ClassificationGradientBoostModelTest.cs | 36,159 | C# |
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Marionet.UI.ViewModels;
using System;
namespace Marionet.UI
{
public class ViewLocator : IDataTemplate
{
public bool SupportsRecycling => false;
public IControl Build(object data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
var name = data!.GetType().FullName!.Replace("ViewModel", "View", StringComparison.InvariantCulture);
var type = Type.GetType(name);
if (type != null)
{
return (Control)Activator.CreateInstance(type)!;
}
else
{
return new TextBlock { Text = "Not Found: " + name };
}
}
public bool Match(object data)
{
return data is ViewModelBase;
}
}
} | 24.837838 | 113 | 0.5321 | [
"MPL-2.0"
] | CptWesley/Marionet | Marionet.UI/ViewLocator.cs | 919 | C# |
//--------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: LimitedConcurrencyTaskScheduler.cs
//
//--------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
namespace System.Threading.Tasks.Schedulers
{
/// <summary>
/// Provides a task scheduler that ensures a maximum concurrency level while
/// running on top of the ThreadPool.
/// </summary>
public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler
{
/// <summary>Whether the current thread is processing work items.</summary>
[ThreadStatic]
private static bool _currentThreadIsProcessingItems;
/// <summary>The list of tasks to be executed.</summary>
private readonly LinkedList<Task> _tasks = new LinkedList<Task>(); // protected by lock(_tasks)
/// <summary>The maximum concurrency level allowed by this scheduler.</summary>
private readonly int _maxDegreeOfParallelism;
/// <summary>Whether the scheduler is currently processing work items.</summary>
private int _delegatesQueuedOrRunning = 0; // protected by lock(_tasks)
/// <summary>
/// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the
/// specified degree of parallelism.
/// </summary>
/// <param name="maxDegreeOfParallelism">The maximum degree of parallelism provided by this scheduler.</param>
public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism)
{
if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism");
_maxDegreeOfParallelism = maxDegreeOfParallelism;
}
/// <summary>Queues a task to the scheduler.</summary>
/// <param name="task">The task to be queued.</param>
protected sealed override void QueueTask(Task task)
{
// Add the task to the list of tasks to be processed. If there aren't enough
// delegates currently queued or running to process tasks, schedule another.
lock (_tasks)
{
_tasks.AddLast(task);
if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
{
++_delegatesQueuedOrRunning;
NotifyThreadPoolOfPendingWork();
}
}
}
/// <summary>
/// Informs the ThreadPool that there's work to be executed for this scheduler.
/// </summary>
private void NotifyThreadPoolOfPendingWork()
{
ThreadPool.UnsafeQueueUserWorkItem(_ =>
{
// Note that the current thread is now processing work items.
// This is necessary to enable inlining of tasks into this thread.
_currentThreadIsProcessingItems = true;
try
{
// Process all available items in the queue.
while (true)
{
Task item;
lock (_tasks)
{
// When there are no more items to be processed,
// note that we're done processing, and get out.
if (_tasks.Count == 0)
{
--_delegatesQueuedOrRunning;
break;
}
// Get the next item from the queue
item = _tasks.First.Value;
_tasks.RemoveFirst();
}
// Execute the task we pulled out of the queue
base.TryExecuteTask(item);
}
}
// We're done processing items on the current thread
finally { _currentThreadIsProcessingItems = false; }
}, null);
}
/// <summary>Attempts to execute the specified task on the current thread.</summary>
/// <param name="task">The task to be executed.</param>
/// <param name="taskWasPreviouslyQueued"></param>
/// <returns>Whether the task could be executed on the current thread.</returns>
protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
// If this thread isn't already processing a task, we don't support inlining
if (!_currentThreadIsProcessingItems) return false;
// If the task was previously queued, remove it from the queue
if (taskWasPreviouslyQueued) TryDequeue(task);
// Try to run the task.
return base.TryExecuteTask(task);
}
/// <summary>Attempts to remove a previously scheduled task from the scheduler.</summary>
/// <param name="task">The task to be removed.</param>
/// <returns>Whether the task could be found and removed.</returns>
protected sealed override bool TryDequeue(Task task)
{
lock (_tasks) return _tasks.Remove(task);
}
/// <summary>Gets the maximum concurrency level supported by this scheduler.</summary>
public sealed override int MaximumConcurrencyLevel { get { return _maxDegreeOfParallelism; } }
/// <summary>Gets an enumerable of the tasks currently scheduled on this scheduler.</summary>
/// <returns>An enumerable of the tasks currently scheduled.</returns>
protected sealed override IEnumerable<Task> GetScheduledTasks()
{
bool lockTaken = false;
try
{
Monitor.TryEnter(_tasks, ref lockTaken);
if (lockTaken) return _tasks.ToArray();
else throw new NotSupportedException();
}
finally
{
if (lockTaken) Monitor.Exit(_tasks);
}
}
}
} | 43.330986 | 118 | 0.560702 | [
"MIT"
] | NeverMorewd/nevermore | nevermore.core/Task/LimitedConcurrencyLevelTaskScheduler.cs | 6,155 | C# |
using UnityEngine;
public class ControlsMenu : MonoBehaviour
{
public GameObject info_A;
public GameObject info_B;
private ControllerLayout controllerLayout;
void Start()
{
controllerLayout = GameObject.Find("ControllerLayout").GetComponent<ControllerLayout>();
ChangeControllersInfo();
}
public void ChangeControllersInfo()
{
if(controllerLayout.layout == ControllerLayout.layoutEnum.normal)
{
info_A.SetActive(true);
info_B.SetActive(false);
}
else
{
info_A.SetActive(false);
info_B.SetActive(true);
}
}
}
| 18.333333 | 90 | 0.741818 | [
"MIT"
] | signeus/vrnd-rube-goldberg-game-by-kevin-menendez-soto | Assets/RubeGoldberg/Scripts/ControlsMenu.cs | 552 | 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 Microsoft.ML.Data.DataLoadSave;
using Microsoft.ML.Runtime;
namespace Microsoft.ML.Data
{
/// <summary>
/// This is a shim class to present the legacy <see cref="IDataTransform"/> interface as an <see cref="ITransformer"/>.
/// Note that there are some important differences in usages that make this shimming somewhat non-seemless, so the goal
/// would be gradual removal of this as we do away with <see cref="IDataTransform"/> based code.
/// </summary>
[BestFriend]
internal sealed class TransformWrapper : ITransformer
{
internal const string LoaderSignature = "TransformWrapper";
private readonly IHost _host;
private readonly IDataView _xf;
public TransformWrapper(IHostEnvironment env, IDataView xf)
{
Contracts.CheckValue(env, nameof(env));
Contracts.Check(xf is IDataTransform);
_host = env.Register(nameof(TransformWrapper));
_host.CheckValue(xf, nameof(xf));
_xf = xf;
}
public DataViewSchema GetOutputSchema(DataViewSchema inputSchema)
{
_host.CheckValue(inputSchema, nameof(inputSchema));
var dv = new EmptyDataView(_host, inputSchema);
var output = ApplyTransformUtils.ApplyTransformToData(_host, (IDataTransform)_xf, dv);
return output.Schema;
}
void ICanSaveModel.Save(ModelSaveContext ctx) => throw _host.Except("Saving is not permitted.");
public IDataView Transform(IDataView input) => ApplyTransformUtils.ApplyTransformToData(_host, (IDataTransform)_xf, input);
bool ITransformer.IsRowToRowMapper => _xf is IRowToRowMapper;
IRowToRowMapper ITransformer.GetRowToRowMapper(DataViewSchema inputSchema)
{
_host.CheckValue(inputSchema, nameof(inputSchema));
var transform = ApplyTransformUtils.ApplyTransformToData(_host, (IDataTransform)_xf, new EmptyDataView(_host, inputSchema)) as IRowToRowMapper;
_host.Check(transform is IRowToRowMapper);
return new CompositeRowToRowMapper(inputSchema, new[] { transform });
}
}
/// <summary>
/// Estimator for trained wrapped transformers.
/// </summary>
internal abstract class TrainedWrapperEstimatorBase : IEstimator<TransformWrapper>
{
[BestFriend]
private protected readonly IHost Host;
[BestFriend]
private protected TrainedWrapperEstimatorBase(IHost host)
{
Contracts.CheckValue(host, nameof(host));
Host = host;
}
public abstract TransformWrapper Fit(IDataView input);
public SchemaShape GetOutputSchema(SchemaShape inputSchema)
{
Host.CheckValue(inputSchema, nameof(inputSchema));
var fakeSchema = FakeSchemaFactory.Create(inputSchema);
var transformer = Fit(new EmptyDataView(Host, fakeSchema));
return SchemaShape.Create(transformer.GetOutputSchema(fakeSchema));
}
}
}
| 37.813953 | 155 | 0.676507 | [
"MIT"
] | AhmedsafwatEwida/machinelearning | src/Microsoft.ML.Data/DataLoadSave/TransformWrapper.cs | 3,254 | C# |
using System;
namespace RandomchaosMGSkySphere
{
#if WINDOWS || LINUX
/// <summary>
/// The main class.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
using (var game = new Game1())
game.Run();
}
}
#endif
}
| 18.391304 | 53 | 0.49409 | [
"MIT"
] | Lajbert/Randomchaos-MonoGame-Samples | Sandboxs/XNA Blog Ports/RandomchaosMGSkySphere/Program.cs | 425 | C# |
using log4net.Core;
namespace log4net.Util.PatternStringConverters
{
/// <summary>
/// Writes a newline to the output
/// </summary>
/// <remarks>
/// <para>
/// Writes the system dependent line terminator to the output.
/// This behavior can be overridden by setting the <see cref="P:log4net.Util.PatternConverter.Option" />:
/// </para>
/// <list type="definition">
/// <listheader>
/// <term>Option Value</term>
/// <description>Output</description>
/// </listheader>
/// <item>
/// <term>DOS</term>
/// <description>DOS or Windows line terminator <c>"\r\n"</c></description>
/// </item>
/// <item>
/// <term>UNIX</term>
/// <description>UNIX line terminator <c>"\n"</c></description>
/// </item>
/// </list>
/// </remarks>
/// <author>Nicko Cadell</author>
internal sealed class NewLinePatternConverter : LiteralPatternConverter, IOptionHandler
{
/// <summary>
/// Initialize the converter
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="T:log4net.Core.IOptionHandler" /> delayed object
/// activation scheme. The <see cref="M:log4net.Util.PatternStringConverters.NewLinePatternConverter.ActivateOptions" /> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="M:log4net.Util.PatternStringConverters.NewLinePatternConverter.ActivateOptions" /> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="M:log4net.Util.PatternStringConverters.NewLinePatternConverter.ActivateOptions" /> must be called again.
/// </para>
/// </remarks>
public void ActivateOptions()
{
if (SystemInfo.EqualsIgnoringCase(Option, "DOS"))
{
Option = "\r\n";
}
else if (SystemInfo.EqualsIgnoringCase(Option, "UNIX"))
{
Option = "\n";
}
else
{
Option = SystemInfo.NewLine;
}
}
}
}
| 31.3125 | 135 | 0.651697 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | bzmework/log4net | Project/Util/PatternStringConverters/NewLinePatternConverter.cs | 2,004 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Feature.Navigation.Extensions;
using Foundation.BlazorExtensions.Extensions;
using Foundation.BlazorExtensions.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SitecoreBlazorHosted.Shared;
using System.Net.Http;
namespace SitecoreBlazorHosted.Server
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// HttpContextAccessor
services.AddHttpContextAccessor();
services.AddScoped<HttpContextAccessor>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<HttpClient>((s) => new HttpClient());
services.AddScoped<IRestService, RestService>();
services.AddForFoundationBlazorExtensions();
services.AddForFeatureNavigation();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
| 32.588235 | 143 | 0.63583 | [
"MIT"
] | thild/SitecoreBlazor | SitecoreBlazorHosted.Server/Startup.cs | 2,218 | C# |
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
namespace Lucene.Net.Analysis.Standard
{
/*
* 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.
*/
/// <summary>
/// Normalizes tokens extracted with <see cref="ClassicTokenizer"/>. </summary>
public class ClassicFilter : TokenFilter
{
/// <summary>
/// Construct filtering <paramref name="in"/>. </summary>
public ClassicFilter(TokenStream @in)
: base(@in)
{
typeAtt = AddAttribute<ITypeAttribute>();
termAtt = AddAttribute<ICharTermAttribute>();
}
private static readonly string APOSTROPHE_TYPE = ClassicTokenizer.TOKEN_TYPES[ClassicTokenizer.APOSTROPHE];
private static readonly string ACRONYM_TYPE = ClassicTokenizer.TOKEN_TYPES[ClassicTokenizer.ACRONYM];
// this filters uses attribute type
private readonly ITypeAttribute typeAtt;
private readonly ICharTermAttribute termAtt;
/// <summary>
/// Returns the next token in the stream, or null at EOS.
/// <para>Removes <c>'s</c> from the end of words.
/// </para>
/// <para>Removes dots from acronyms.
/// </para>
/// </summary>
public override sealed bool IncrementToken()
{
if (!m_input.IncrementToken())
{
return false;
}
char[] buffer = termAtt.Buffer;
int bufferLength = termAtt.Length;
string type = typeAtt.Type;
if (type == APOSTROPHE_TYPE && bufferLength >= 2 && buffer[bufferLength - 2] == '\'' && (buffer[bufferLength - 1] == 's' || buffer[bufferLength - 1] == 'S')) // remove 's
{
// Strip last 2 characters off
termAtt.Length = bufferLength - 2;
} // remove dots
else if (type == ACRONYM_TYPE)
{
int upto = 0;
for (int i = 0; i < bufferLength; i++)
{
char c = buffer[i];
if (c != '.')
{
buffer[upto++] = c;
}
}
termAtt.Length = upto;
}
return true;
}
}
} | 37.674699 | 182 | 0.570515 | [
"Apache-2.0"
] | 10088/lucenenet | src/Lucene.Net.Analysis.Common/Analysis/Standard/ClassicFilter.cs | 3,127 | 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.Tke.V20180525.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DisableVpcCniNetworkTypeResponse : AbstractModel
{
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.454545 | 81 | 0.666418 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Tke/V20180525/Models/DisableVpcCniNetworkTypeResponse.cs | 1,398 | C# |
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using Pro.Utils;
using Pro.Dal;
using Platinium.Entidade;
using Negocio;
namespace Platinium.Negocio
{
public class ManterTipoMovimento : IManter
{
#region Variáveis e Propriedades
private TipoMovimento oTipoMovimento;
private Dao oDao;
#endregion
#region Construtores
public ManterTipoMovimento()
{
oDao = new Dao();
}
public ManterTipoMovimento(string connectionString, DataBaseTypes dataBaseType)
{
oDao = new Dao(connectionString, dataBaseType);
}
#endregion
#region Métodos
public DataTable Consultar(Dictionary<string, object> filtros, string direcao, string colunaSort)
{
Dictionary<string, string> dicionario = ClassFunctions.GetMap(typeof(TipoMovimento));
dicionario.Add("FLG_TIPO_MOVIMENTO", "DscTipo");
dicionario.Add("FLG_ATIVO", "DscAtivo");
List<Parameter> lstParametros = new List<Parameter>();
foreach (KeyValuePair<string, object> item in filtros)
{
if (item.Value != null)
{
if (item.Value.GetType() == typeof(Int32))
lstParametros.Add(new Parameter(item.Key, item.Value, OperationTypes.EqualsTo));
else
lstParametros.Add(new Parameter(item.Key, item.Value, OperationTypes.Like));
}
}
lstParametros.Add(new Parameter(colunaSort, null, OperationTypes.Null, direcao));
return this.oDao.Select(lstParametros, "platinium", "VI_TIPO_MOVIMENTO_TIMO", dicionario);
}
public DataTable Consultar(Dictionary<string, object> filtros, string direcao)
{
Dictionary<string, string> dicionario = ClassFunctions.GetMap(typeof(TipoMovimento));
dicionario.Add("FLG_TIPO_MOVIMENTO", "DscTipo");
dicionario.Add("FLG_ATIVO", "DscAtivo");
List<Parameter> lstParametros = new List<Parameter>();
foreach (KeyValuePair<string, object> item in filtros)
{
if (item.Value != null)
{
if (item.Value.GetType() == typeof(Int32))
lstParametros.Add(new Parameter(item.Key, item.Value, OperationTypes.EqualsTo));
else
lstParametros.Add(new Parameter(item.Key, item.Value, OperationTypes.Like));
}
}
return this.oDao.Select(lstParametros, "platinium", "VI_TIPO_MOVIMENTO_TIMO", dicionario);
}
public void PrepararInclusao()
{
oTipoMovimento = new TipoMovimento(oDao);
}
public Dictionary<string, object> Selecionar(int id)
{
oTipoMovimento = new TipoMovimento(id, oDao);
return ClassFunctions.GetProperties(oTipoMovimento);
}
public CrudActionTypes Salvar(Dictionary<string, object> valores)
{
ClassFunctions.SetProperties(oTipoMovimento, valores);
return oTipoMovimento.Salvar();
}
public CrudActionTypes Excluir()
{
return oTipoMovimento.Excluir();
}
#endregion
}
}
| 31.785047 | 105 | 0.589532 | [
"MIT"
] | CesarRabelo/eGovernos.Corporativo | src/Negocio/Controladoras/ManterTipoMovimento.cs | 3,405 | C# |
namespace MyBackEnd
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
} | 21.153846 | 69 | 0.592727 | [
"MIT"
] | lover299/LearnDapr | Source/DaprMultiContainer/MyBackEnd/WeatherForecast.cs | 275 | 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 MaterialSkinExample.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.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;
}
}
}
}
| 39.777778 | 151 | 0.58473 | [
"MIT"
] | 3dsoft/MaterialSkin | MaterialSkinExample/Properties/Settings.Designer.cs | 1,076 | C# |
using System;
using System.IO;
using K4os.Compression.LZ4.Internal;
using Xunit;
namespace K4os.Compression.LZ4.Streams.Test.Internal
{
public class Tools
{
public static readonly string[] CorpusNames = {
"dickens", "mozilla", "mr", "nci",
"ooffice", "osdb", "reymont", "samba",
"sao", "webster", "x-ray", "xml"
};
public static unsafe uint Adler32(byte* data, int length)
{
const uint modAdler = 65521;
uint a = 1, b = 0;
for (var index = 0; index < length; ++index)
{
a = (a + data[index]) % modAdler;
b = (b + a) % modAdler;
}
return (b << 16) | a;
}
public static uint Adler32(byte[] data, int index = 0, int length = -1)
{
const uint modAdler = 65521;
if (length < 0)
length = data.Length - index;
uint a = 1, b = 0;
for (; index < length; ++index)
{
a = (a + data[index]) % modAdler;
b = (b + a) % modAdler;
}
return (b << 16) | a;
}
public static byte[] LoadChunk(string filename, int index, int length)
{
using (var file = File.OpenRead(filename))
{
length = length < 0 ? (int) (file.Length - index) : length;
var src = new byte[length];
file.Seek(index, SeekOrigin.Begin);
file.Read(src, 0, length);
return src;
}
}
public static string FindFile(string filename) =>
Path.Combine(FindRoot(), filename);
private static string FindRoot(string path = ".")
{
bool IsRoot(string p) =>
Path.GetFullPath(p) == Path.GetFullPath(Path.Combine(p, ".."));
while (true)
{
if (Directory.Exists(Path.Combine(path, "./.git"))) return path;
if (IsRoot(path)) return null;
path = Path.Combine(path, "..");
}
}
public static void SameBytes(byte[] source, byte[] target)
{
if (source.Length != target.Length)
throw new ArgumentException(
$"Arrays are not same length: {source.Length} vs {target.Length}");
var length = source.Length;
for (var i = 0; i < length; i++)
{
if (source[i] != target[i])
throw new ArgumentException(
$"Arrays differ at index {i}: {source[i]} vs {target[i]}");
}
}
public static void SameBytes(byte[] source, byte[] target, int length)
{
if (source.Length < length)
throw new ArgumentException($"Source array is too small: {source.Length}");
if (target.Length < length)
throw new ArgumentException($"Target array is too small: {target.Length}");
for (var i = 0; i < length; i++)
{
if (source[i] != target[i])
throw new ArgumentException(
$"Arrays differ at index {i}: {source[i]} vs {target[i]}");
}
}
public static void SameFiles(string original, string decoded)
{
using (var streamA = File.OpenRead(original))
using (var streamB = File.OpenRead(decoded))
{
Assert.Equal(streamA.Length, streamB.Length);
var bufferA = new byte[4096];
var bufferB = new byte[4096];
while (true)
{
var readA = streamA.Read(bufferA, 0, bufferA.Length);
var readB = streamB.Read(bufferB, 0, bufferB.Length);
Assert.Equal(readA, readB);
if (readA == 0)
break;
SameBytes(bufferA, bufferB, readA);
}
}
}
public static LZ4Settings ParseSettings(string options)
{
var result = new LZ4Settings();
foreach (var option in options.Split(' '))
{
switch (option)
{
case "-1":
result.Level = LZ4Level.L00_FAST;
break;
case "-9":
result.Level = LZ4Level.L09_HC;
break;
case "-11":
result.Level = LZ4Level.L11_OPT;
break;
case "-12":
result.Level = LZ4Level.L12_MAX;
break;
case "-BD":
result.Chaining = true;
break;
case "-BX":
// ignored to be implemented
break;
case "-B4":
result.BlockSize = Mem.K64;
break;
case "-B5":
result.BlockSize = Mem.K256;
break;
case "-B6":
result.BlockSize = Mem.M1;
break;
case "-B7":
result.BlockSize = Mem.M4;
break;
default:
throw new NotImplementedException($"Option '{option}' not recognized");
}
}
return result;
}
public static void WriteRandom(string filename, int length, int seed = 0)
{
var random = new Random(seed);
var buffer = new byte[0x10000];
using (var file = File.Create(filename))
{
while (length > 0)
{
random.NextBytes(buffer);
var chunkSize = Math.Min(length, buffer.Length);
file.Write(buffer, 0, chunkSize);
length -= chunkSize;
}
}
}
}
}
| 23.279793 | 79 | 0.594925 | [
"MIT"
] | warrenfalk/K4os.Compression.LZ4 | src/K4os.Compression.LZ4.Streams.Test/Internal/Tools.cs | 4,495 | C# |
using NServiceBus;
public class TheHandler :
IHandleMessages<StartHandler>
{
ManualResetEvent resetEvent;
public TheHandler(ManualResetEvent resetEvent)
{
this.resetEvent = resetEvent;
}
public Task Handle(StartHandler message, IMessageHandlerContext context)
{
context.LogInformation("Hello from {@Handler}.");
resetEvent.Set();
return Task.CompletedTask;
}
} | 22.526316 | 76 | 0.684579 | [
"MIT"
] | NServiceBusExtensions/NServiceBus.Serilog | src/Tests/Handler/TheHandler.cs | 430 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Playnite;
using System.Windows;
using System.Windows.Markup;
using System.Text.RegularExpressions;
using Playnite.Settings;
using Playnite.Common;
using Playnite.SDK;
using System.IO.Compression;
namespace Playnite
{
public class ThemeDescription
{
public string Name { get; set; }
public string Author { get; set; }
public string Website { get; set; }
public string Version { get; set; }
public ApplicationMode Mode { get; set; }
public string ThemeApiVersion { get; set; } = ThemeManager.ThemeApiVersion.ToString(3);
public string DirectoryPath { get; set; }
public string DirectoryName { get; set; }
public static ThemeDescription FromFile(string path)
{
var theme = Serialization.FromYaml<ThemeDescription>(File.ReadAllText(path));
theme.DirectoryPath = Path.GetDirectoryName(path);
theme.DirectoryName = Path.GetFileNameWithoutExtension(theme.DirectoryPath);
return theme;
}
}
public class ThemeManager
{
private static ILogger logger = LogManager.GetLogger();
public const string ThemeManifestFileName = "theme.yaml";
public const string PackedThemeFileExtention = ".pthm";
public static System.Version ThemeApiVersion => new System.Version("1.1.0");
public static ThemeDescription CurrentTheme { get; private set; }
public static ThemeDescription DefaultTheme { get; private set; }
public static string GetThemeRootDir(ApplicationMode mode)
{
return mode == ApplicationMode.Desktop ? "Desktop" : "Fullscreen";
}
public static void SetCurrentTheme(ThemeDescription theme)
{
CurrentTheme = theme;
}
public static void SetDefaultTheme(ThemeDescription theme)
{
DefaultTheme = theme;
}
public static void ApplyFullscreenButtonPrompts(Application app, FullscreenButtonPrompts prompts)
{
if (prompts == FullscreenSettings.DefaultButtonPrompts)
{
var defaultXaml = $"{FullscreenSettings.DefaultButtonPrompts.ToString()}.xaml";
foreach (var dir in PlayniteApplication.CurrentNative.Resources.MergedDictionaries.ToList())
{
if (dir.Source == null)
{
continue;
}
if (dir.Source.OriginalString.Contains("ButtonPrompts") &&
!dir.Source.OriginalString.EndsWith(defaultXaml))
{
PlayniteApplication.CurrentNative.Resources.MergedDictionaries.Remove(dir);
}
}
}
else
{
var promptsPath = Path.Combine(ThemeManager.DefaultTheme.DirectoryPath, "Images", "ButtonPrompts");
foreach (var dir in Directory.GetDirectories(promptsPath))
{
var dirInfo = new DirectoryInfo(dir);
var promptXaml = Path.Combine(dir, $"{dirInfo.Name}.xaml");
if (File.Exists(promptXaml) && dirInfo.Name == prompts.ToString())
{
var xaml = Xaml.FromFile(promptXaml);
if (xaml is ResourceDictionary xamlDir)
{
xamlDir.Source = new Uri(promptXaml, UriKind.Absolute);
PlayniteApplication.CurrentNative.Resources.MergedDictionaries.Add(xamlDir);
}
}
}
}
}
public static bool ApplyTheme(Application app, ThemeDescription theme, ApplicationMode mode)
{
if ((new System.Version(theme.ThemeApiVersion).Major != ThemeApiVersion.Major))
{
logger.Error($"Failed to apply {theme.Name} theme, unsupported API version {theme.ThemeApiVersion}.");
return false;
}
var allLoaded = true;
var loadedXamls = new List<ResourceDictionary>();
var acceptableXamls = new List<string>();
var defaultRoot = $"Themes/{mode.GetDescription()}/{DefaultTheme.DirectoryName}/";
foreach (var dict in app.Resources.MergedDictionaries)
{
if (dict.Source.OriginalString.StartsWith("Themes") && dict.Source.OriginalString.EndsWith("xaml"))
{
acceptableXamls.Add(dict.Source.OriginalString.Replace(defaultRoot, "").Replace('/', '\\'));
}
}
foreach (var accXaml in acceptableXamls)
{
var xamlPath = Path.Combine(theme.DirectoryPath, accXaml);
if (!File.Exists(xamlPath))
{
continue;
}
try
{
var xaml = Xaml.FromFile(xamlPath);
if (xaml is ResourceDictionary xamlDir)
{
xamlDir.Source = new Uri(xamlPath, UriKind.Absolute);
loadedXamls.Add(xamlDir as ResourceDictionary);
}
else
{
logger.Error($"Skipping theme file {xamlPath}, it's not resource dictionary.");
}
}
catch (Exception e) when (!PlayniteEnvironment.ThrowAllErrors)
{
logger.Error(e, $"Failed to load xaml {xamlPath}");
allLoaded = false;
break;
}
}
if (allLoaded)
{
loadedXamls.ForEach(a => app.Resources.MergedDictionaries.Add(a));
return true;
}
return false;
}
public static List<ThemeDescription> GetAvailableThemes(ApplicationMode mode)
{
var modeDir = GetThemeRootDir(mode);
var added = new List<string>();
var themes = new List<ThemeDescription>();
var userPath = Path.Combine(PlaynitePaths.ThemesUserDataPath, modeDir);
if (!PlayniteSettings.IsPortable && Directory.Exists(userPath))
{
foreach (var dir in Directory.GetDirectories(userPath))
{
var descriptorPath = Path.Combine(dir, ThemeManifestFileName);
if (File.Exists(descriptorPath))
{
var info = new FileInfo(descriptorPath);
added.Add(info.Directory.Name);
themes.Add(ThemeDescription.FromFile(descriptorPath));
}
}
}
var programPath = Path.Combine(PlaynitePaths.ThemesProgramPath, modeDir);
if (Directory.Exists(programPath))
{
foreach (var dir in Directory.GetDirectories(programPath))
{
var descriptorPath = Path.Combine(dir, ThemeManifestFileName);
if (File.Exists(descriptorPath))
{
var info = new FileInfo(descriptorPath);
if (!added.Contains(info.Directory.Name))
{
themes.Add(ThemeDescription.FromFile(descriptorPath));
}
}
}
}
return themes;
}
public static ThemeDescription GetDescriptionFromPackedFile(string path)
{
using (var zip = ZipFile.OpenRead(path))
{
var manifest = zip.GetEntry(ThemeManifestFileName);
using (var logStream = manifest.Open())
{
using (TextReader tr = new StreamReader(logStream))
{
return Serialization.FromYaml<ThemeDescription>(tr.ReadToEnd());
}
}
}
}
public static void InstallFromPackedFile(string path)
{
var desc = GetDescriptionFromPackedFile(path);
var installDir = Paths.GetSafeFilename(desc.Name).Replace(" ", string.Empty)+ "_" + (desc.Name + desc.Author).MD5();
var targetDir = PlayniteSettings.IsPortable ? PlaynitePaths.ThemesProgramPath : PlaynitePaths.ThemesUserDataPath;
targetDir = Path.Combine(targetDir, desc.Mode.GetDescription(), installDir);
FileSystem.CreateDirectory(targetDir, true);
ZipFile.ExtractToDirectory(path, targetDir);
}
}
}
| 40.325991 | 129 | 0.528512 | [
"MIT"
] | Donkeyfumbler/Playnite | source/Playnite/Themes.cs | 9,156 | 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("Api.Events")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Api.Events")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1ab25608-3b33-494e-be9d-07aa3a294058")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.743001 | [
"MIT"
] | austinejei/sidekick | Api.Events/Properties/AssemblyInfo.cs | 1,396 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace SimpleStorageEngine.Persistance.Exceptions {
[Serializable]
public class PersistanceException : Exception {
public PersistanceException(string message)
: base(message) {
}
public PersistanceException(string message, Exception innerException)
: base(message, innerException) {
}
protected PersistanceException(SerializationInfo info, StreamingContext context)
: base(info, context) {
}
}
}
| 26.217391 | 88 | 0.68325 | [
"BSD-3-Clause"
] | SamSaffron/simplestorageengine | SimpleStorageEngine/Persistance/Exceptions/PersistanceException.cs | 605 | C# |
using lm.Comol.Core.FileRepository.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lm.Comol.Core.BaseModules.FileRepository.Presentation
{
public interface IViewFolderSelector : lm.Comol.Core.DomainModel.Common.iDomainView
{
Boolean AutoPostBack { get; set; }
Boolean AlsoSelectedQuota { get; set; }
long IdSelectedFolder { get; }
RepositoryType RepositoryType { get; set; }
Int32 RepositoryIdCommunity { get; set; }
void InitializeControl(long idFolder, String folderName,List<dtoNodeFolderItem> folders );
void InitializeControl(RepositoryType type, Int32 idCommunity, long idFolder, String folderName, List<dtoNodeFolderItem> folders);
void InitializeControl(RepositoryType type, Int32 idCommunity);
}
} | 40.095238 | 138 | 0.739905 | [
"MIT"
] | EdutechSRL/Adevico | 3-Business/3-Modules/lm.Comol.Core.BaseModules/FileRepository/Presentation/Repository/IView/UC/IViewFolderSelector.cs | 844 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.OsConfig.V1.Snippets
{
using Google.Api.Gax;
using Google.Cloud.OsConfig.V1;
using System;
public sealed partial class GeneratedOsConfigServiceClientStandaloneSnippets
{
/// <summary>Snippet for ListPatchDeployments</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ListPatchDeployments()
{
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedEnumerable<ListPatchDeploymentsResponse, PatchDeployment> response = osConfigServiceClient.ListPatchDeployments(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchDeployment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchDeploymentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchDeployment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
}
| 41.109589 | 137 | 0.629124 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/osconfig/v1/google-cloud-osconfig-v1-csharp/Google.Cloud.OsConfig.V1.StandaloneSnippets/OsConfigServiceClient.ListPatchDeploymentsSnippet.g.cs | 3,001 | C# |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Plant_A_Plant.Data.Common.Repositories;
using Plant_A_Plant.Data.Models;
namespace Plant_A_Plant.Web.Views.ViewComponents
{
public class FeedbackInfoViewComponent : ViewComponent
{
private readonly IRepository<FeedbackInfo> _feedbackRepository;
public FeedbackInfoViewComponent(IRepository<FeedbackInfo> feedbackRepository)
{
_feedbackRepository = feedbackRepository;
}
public async Task<IViewComponentResult> InvokeAsync()
{
return View(await _feedbackRepository.All().OrderByDescending(x => x.SendOn).ToListAsync());
}
}
} | 31 | 104 | 0.733871 | [
"MIT"
] | goofy5752/Plant-A-Plant | Web/Plant-A-Plant.Web/Views/ViewComponents/FeedbackInfoViewComponent.cs | 746 | C# |
using App.Common.Data;
using System.Linq;
using WebFramework.Data.Domain;
namespace Service
{
public class LogService : ILogService
{
private IRepository<Logs,long> _logsRepository;
public LogService(IRepository<Logs, long> logsRepository)
{
_logsRepository = logsRepository;
}
public IQueryable<Logs> Query()
{
return _logsRepository.Query;
}
public Logs GetLogById(long id)
{
if (id == default(long))
return null;
var log = _logsRepository.GetById(id);
return log;
}
}
}
| 20.903226 | 65 | 0.567901 | [
"MIT"
] | zsu/WebFrameworkMVC | WebFramework.Service/LogService.cs | 650 | C# |
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SimpleFeedReader.Services;
namespace SimpleFeedReader
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<NewsService>();
services.AddAutoMapper();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseMvc();
}
}
}
| 27 | 89 | 0.597761 | [
"MIT"
] | mbanks850/simple-feed-reader | SimpleFeedReader/Startup.cs | 1,163 | C# |
namespace GTCapture
{
partial class ToastMessageForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ToastMessageForm));
this.pictureBox = new System.Windows.Forms.PictureBox();
this.label = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.SuspendLayout();
//
// pictureBox
//
this.pictureBox.Cursor = System.Windows.Forms.Cursors.Hand;
resources.ApplyResources(this.pictureBox, "pictureBox");
this.pictureBox.Name = "pictureBox";
this.pictureBox.TabStop = false;
this.pictureBox.Click += new System.EventHandler(this.pictureBox_Click);
this.pictureBox.MouseEnter += new System.EventHandler(this.pictureBox_MouseEnter);
this.pictureBox.MouseLeave += new System.EventHandler(this.pictureBox_MouseLeave);
//
// label
//
resources.ApplyResources(this.label, "label");
this.label.Name = "label";
this.label.Click += new System.EventHandler(this.label_Click);
//
// ToastMessageForm
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.label);
this.Controls.Add(this.pictureBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ToastMessageForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.TopMost = true;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ToastMessageForm_FormClosing);
this.Load += new System.EventHandler(this.ToastMessageForm_Load);
this.Shown += new System.EventHandler(this.ToastMessageForm_Shown);
this.Click += new System.EventHandler(this.ToastMessageForm_Click);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ToastMessageForm_KeyDown);
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBox;
private System.Windows.Forms.Label label;
}
} | 41.843373 | 148 | 0.608984 | [
"MIT"
] | vip00112/GTLauncher | src/GTCapture/Control/ToastMessageForm.Designer.cs | 3,475 | C# |
using System.Web.Http;
using System.Web.Mvc;
using NLog.Targets;
using SFA.DAS.NLog.Logger;
using Microsoft.ApplicationInsights.Extensibility;
using System.Configuration;
namespace SFA.DAS.Commitments.Api
{
public class WebApiApplication : System.Web.HttpApplication
{
private static ILog Logger = new NLogLogger();
#pragma warning disable 0169
private static RedisTarget _redisTarget; // Required to ensure assembly is copied to output.
#pragma warning disable 0169
protected void Application_Start()
{
Logger.Info("Starting Commitments Api Application");
FilterConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
TelemetryConfiguration.Active.InstrumentationKey = ConfigurationManager.AppSettings["APPINSIGHTS_INSTRUMENTATIONKEY"] ?? "";
}
protected void Application_End()
{
Logger.Info("Stopping Commitments Api Application");
}
protected void Application_Error()
{
var ex = Server.GetLastError().GetBaseException();
Logger.Error(ex, "Unhandled exception");
}
}
}
| 31.05 | 136 | 0.687601 | [
"MIT"
] | SkillsFundingAgency/das-commitments | src/SFA.DAS.Commitments.Api/Global.asax.cs | 1,244 | C# |
using System;
using JetBrains.Application;
using JetBrains.Application.Settings;
using JetBrains.Application.Settings.Implementation;
using JetBrains.ReSharper.Psi.CSharp.Naming2;
using JetBrains.ReSharper.Psi.Naming.Elements;
using JetBrains.ReSharper.Psi.Naming.Settings;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.Naming.Elements
{
// Defining an element kind isn't enough, we also need to set up a rule that uses it. This is a different process
// for CLR and non-CLR languages. The rules come from a per-language instance of INamingPolicyProvider, which gets
// its values from settings. For non-CLR languages, this is simply a map from element kind name to NamingPolicy,
// which is a list of NamingRules and a flag for inspections. If the rule isn't set up, the default NamingRule comes
// from IElementKind.GetDefaultRule.
// CLR languages have a more flexible (but also more confusing) system. There are two sets of rules, predefined and
// user. The predefined rules are a map of enum to NamingPolicy, with hardcoded defaults. The NamingPolicy can be
// modified, but the rule cannot be deleted. The user rules are more flexible, with a set of element kinds, flags
// for static and instance modifiers, plus the NamingPolicy. These have to be set in defaults, and can be both
// modified and deleted.
// I'm not really sure why there is this split. AFAICT, the predefined rules could all be handled with user rules,
// if a "do not delete" flag was added. One thing these rules provide is a set of fallbacks, so that there is no
// need to provide default rules for all possible element kinds. For example, the XAML namespace naming rule can
// fallback to the TypesAndNamespaces predefined type if XamlNamedElements.NAMESPACE_ALIAS doesn't have a rule.
// Whatever, this class adds a default user rule for our Unity element kinds
[ShellComponent]
public class UnityNamingRuleDefaultSettings : HaveDefaultSettings
{
public static readonly Guid SerializedFieldRuleGuid = new Guid("5F0FDB63-C892-4D2C-9324-15C80B22A7EF");
public UnityNamingRuleDefaultSettings(ILogger logger, ISettingsSchema settingsSchema)
: base(logger, settingsSchema)
{
}
public override void InitDefaultSettings(ISettingsStorageMountPoint mountPoint)
{
SetIndexedValue(mountPoint, (CSharpNamingSettings key) => key.UserRules, SerializedFieldRuleGuid,
GetUnitySerializedFieldRule());
}
public static ClrUserDefinedNamingRule GetUnitySerializedFieldRule()
{
var lowerCaseNamingPolicy = new NamingPolicy(new NamingRule {NamingStyleKind = NamingStyleKinds.aaBb});
return new ClrUserDefinedNamingRule(
new ClrNamedElementDescriptor(
AccessRightKinds.Any,
StaticnessKinds.Instance,
new ElementKindSet(UnityNamedElement.SERIALISED_FIELD),
"Unity serialized field"),
lowerCaseNamingPolicy
);
}
public override string Name => "Unity default naming rules";
}
}
| 54.610169 | 120 | 0.720981 | [
"Apache-2.0"
] | 20chan/resharper-unity | resharper/resharper-unity/src/CSharp/Psi/Naming/Elements/UnityNamingRuleDefaultSettings.cs | 3,222 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.ExcelApi
{
/// <summary>
/// DispatchInterface FormatCondition
/// SupportByVersion Excel, 9,10,11,12,14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196650.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
[TypeId("00024425-0000-0000-C000-000000000046")]
public interface FormatCondition : ICOMObject
{
#region Properties
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197842.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
NetOffice.ExcelApi.Application Application { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff840744.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
NetOffice.ExcelApi.Enums.XlCreator Creator { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193291.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16), ProxyResult]
object Parent { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff840778.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
Int32 Type { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836182.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
Int32 Operator { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff841065.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
string Formula1 { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195641.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
string Formula2 { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196979.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
NetOffice.ExcelApi.Interior Interior { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196030.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
NetOffice.ExcelApi.Borders Borders { get; }
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193040.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
NetOffice.ExcelApi.Font Font { get; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194461.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
string Text { get; set; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197985.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
NetOffice.ExcelApi.Enums.XlContainsOperator TextOperator { get; set; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff821022.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
NetOffice.ExcelApi.Enums.XlTimePeriods DateOperator { get; set; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff820867.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
object NumberFormat { get; set; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195509.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
Int32 Priority { get; set; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838861.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
bool StopIfTrue { get; set; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff839719.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
NetOffice.ExcelApi.Range AppliesTo { get; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195159.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
bool PTCondition { get; }
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193933.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
NetOffice.ExcelApi.Enums.XlPivotConditionScope ScopeType { get; set; }
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837106.aspx </remarks>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
/// <param name="_operator">optional object operator</param>
/// <param name="formula1">optional object formula1</param>
/// <param name="formula2">optional object formula2</param>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
void Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type, object _operator, object formula1, object formula2);
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837106.aspx </remarks>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
/// <param name="_operator">optional object operator</param>
/// <param name="formula1">optional object formula1</param>
/// <param name="formula2">optional object formula2</param>
/// <param name="_string">optional object string</param>
/// <param name="operator2">optional object operator2</param>
[SupportByVersion("Excel", 12,14,15,16)]
void Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type, object _operator, object formula1, object formula2, object _string, object operator2);
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837106.aspx </remarks>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
[CustomMethod]
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
void Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type);
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837106.aspx </remarks>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
/// <param name="_operator">optional object operator</param>
[CustomMethod]
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
void Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type, object _operator);
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837106.aspx </remarks>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
/// <param name="_operator">optional object operator</param>
/// <param name="formula1">optional object formula1</param>
[CustomMethod]
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
void Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type, object _operator, object formula1);
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837106.aspx </remarks>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
/// <param name="_operator">optional object operator</param>
/// <param name="formula1">optional object formula1</param>
/// <param name="formula2">optional object formula2</param>
/// <param name="_string">optional object string</param>
[CustomMethod]
[SupportByVersion("Excel", 12,14,15,16)]
void Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type, object _operator, object formula1, object formula2, object _string);
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196592.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
void Delete();
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
/// <param name="_operator">optional object operator</param>
/// <param name="formula1">optional object formula1</param>
/// <param name="formula2">optional object formula2</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersion("Excel", 12,14,15,16)]
void _Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type, object _operator, object formula1, object formula2);
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[CustomMethod]
[SupportByVersion("Excel", 12,14,15,16)]
void _Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type);
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
/// <param name="_operator">optional object operator</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[CustomMethod]
[SupportByVersion("Excel", 12,14,15,16)]
void _Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type, object _operator);
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <param name="type">NetOffice.ExcelApi.Enums.XlFormatConditionType type</param>
/// <param name="_operator">optional object operator</param>
/// <param name="formula1">optional object formula1</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[CustomMethod]
[SupportByVersion("Excel", 12,14,15,16)]
void _Modify(NetOffice.ExcelApi.Enums.XlFormatConditionType type, object _operator, object formula1);
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837422.aspx </remarks>
/// <param name="range">NetOffice.ExcelApi.Range range</param>
[SupportByVersion("Excel", 12,14,15,16)]
void ModifyAppliesToRange(NetOffice.ExcelApi.Range range);
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff820833.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
void SetFirstPriority();
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff841221.aspx </remarks>
[SupportByVersion("Excel", 12,14,15,16)]
void SetLastPriority();
#endregion
}
}
| 40.488959 | 153 | 0.68469 | [
"MIT"
] | igoreksiz/NetOffice | Source/Excel/DispatchInterfaces/FormatCondition.cs | 12,837 | C# |
using System.Threading.Tasks;
using MiniCover.CommandLine.Options;
using MiniCover.Reports;
using MiniCover.Utils;
namespace MiniCover.CommandLine.Commands
{
class NCoverReportCommand : BaseCommand
{
private const string _name = "xmlreport";
private const string _description = "Write an NCover-formatted XML report to file";
private readonly CoverageLoadedFileOption _coverageLoadedFileOption;
private readonly NCoverOutputOption _nCoverOutputOption;
private readonly ThresholdOption _thresholdOption;
public NCoverReportCommand(
WorkingDirectoryOption workingDirectoryOption,
CoverageLoadedFileOption coverageLoadedFileOption,
NCoverOutputOption nCoverOutputOption,
ThresholdOption thresholdOption)
: base(_name, _description)
{
_coverageLoadedFileOption = coverageLoadedFileOption;
_thresholdOption = thresholdOption;
_nCoverOutputOption = nCoverOutputOption;
Options = new IOption[]
{
workingDirectoryOption,
_coverageLoadedFileOption,
_thresholdOption,
_nCoverOutputOption
};
}
protected override Task<int> Execute()
{
XmlReport.Execute(_coverageLoadedFileOption.Result, _nCoverOutputOption.Value, _thresholdOption.Value);
var result = CalcUtils.IsHigherThanThreshold(_coverageLoadedFileOption.Result, _thresholdOption.Value);
return Task.FromResult(result);
}
}
}
| 35.644444 | 115 | 0.679551 | [
"MIT"
] | haytam1988/NuGet | src/MiniCover/CommandLine/Commands/NCoverReportCommand.cs | 1,606 | C# |
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace Contoso.Branding.SetThemeToSite
{
class Program
{
static void Main(string[] args)
{
// Request Office365 site from the user
string siteUrl = GetSite();
/* Prompt for Credentials */
Console.WriteLine("Enter Credentials for {0}", siteUrl);
string userName = GetUserName();
SecureString pwd = GetPassword();
/* End Program if no Credentials */
if (string.IsNullOrEmpty(userName) || (pwd == null))
return;
ClientContext cc = new ClientContext(siteUrl);
cc.AuthenticationMode = ClientAuthenticationMode.Default;
cc.Credentials = new SharePointOnlineCredentials(userName, pwd);
try
{
// Let's ensure that the theme is available in root web
new ThemeManager().DeployContosoThemeToWeb(cc, cc.Web, "Garage",
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DeploymentFiles/Garage/garage.spcolor"),
string.Empty,
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DeploymentFiles/Garage/garagebg.jpg"),
"seattle.master");
// Setting the theme to web - can be sub site or root site
new ThemeManager().SetThemeBasedOnName(cc, cc.Web, "Garage");
Console.WriteLine("Theme applied to the provided site successfully.");
Console.WriteLine("Press any key to continue.");
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Exception while applying the theme with exception details as {0}."), ex.ToString());
Console.WriteLine("Press any key to continue.");
Console.Read();
throw;
}
}
static SecureString GetPassword()
{
SecureString sStrPwd = new SecureString();
try
{
Console.Write("SharePoint Password : ");
for (ConsoleKeyInfo keyInfo = Console.ReadKey(true); keyInfo.Key != ConsoleKey.Enter; keyInfo = Console.ReadKey(true))
{
if (keyInfo.Key == ConsoleKey.Backspace)
{
if (sStrPwd.Length > 0)
{
sStrPwd.RemoveAt(sStrPwd.Length - 1);
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.Write(" ");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}
}
else if (keyInfo.Key != ConsoleKey.Enter)
{
Console.Write("*");
sStrPwd.AppendChar(keyInfo.KeyChar);
}
}
Console.WriteLine("");
}
catch (Exception e)
{
sStrPwd = null;
Console.WriteLine(e.Message);
}
return sStrPwd;
}
static string GetUserName()
{
string strUserName = string.Empty;
try
{
Console.Write("SharePoint Username : ");
strUserName = Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
strUserName = string.Empty;
}
return strUserName;
}
static string GetSite()
{
string siteUrl = string.Empty;
try
{
Console.Write("Give Office365 site URL: ");
siteUrl = Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
siteUrl = string.Empty;
}
return siteUrl;
}
private static string URLCombine(string baseUrl, string relativeUrl)
{
if (baseUrl.Length == 0)
return relativeUrl;
if (relativeUrl.Length == 0)
return baseUrl;
return string.Format("{0}/{1}", baseUrl.TrimEnd(new char[] { '/', '\\' }), relativeUrl.TrimStart(new char[] { '/', '\\' }));
}
}
}
| 34.158273 | 136 | 0.491575 | [
"Apache-2.0"
] | AKrasheninnikov/PnP | Samples/Branding.SetThemeToSite/Branding.SetThemeToSite.Console/Program.cs | 4,750 | C# |
/*
* Original author: Nick Shulman <nicksh .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2012 University of Washington - Seattle, WA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using pwiz.Common.SystemUtil;
using pwiz.Skyline.Model.Results;
using ZedGraph;
using pwiz.Skyline.Model;
using pwiz.Skyline.Model.DocSettings;
using pwiz.Skyline.Model.Lib;
using pwiz.Skyline.Model.RetentionTimes;
using pwiz.Skyline.Properties;
using pwiz.Skyline.Util;
namespace pwiz.Skyline.Controls.Graphs
{
public partial class AlignmentForm : FormEx
{
private readonly BindingList<DataRow> _dataRows = new BindingList<DataRow>
{
AllowEdit = false,
AllowNew = false,
AllowRemove = false,
};
private readonly QueueWorker<Action> _rowUpdateQueue = new QueueWorker<Action>(null, (a, i) => a());
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public AlignmentForm(SkylineWindow skylineWindow)
{
InitializeComponent();
SkylineWindow = skylineWindow;
Icon = Resources.Skyline;
bindingSource.DataSource = _dataRows;
colIntercept.CellTemplate.Style.Format = @"0.0000";
colSlope.CellTemplate.Style.Format = @"0.0000";
colCorrelationCoefficient.CellTemplate.Style.Format = @"0.0000";
colUnrefinedSlope.CellTemplate.Style.Format = @"0.0000";
colUnrefinedIntercept.CellTemplate.Style.Format = @"0.0000";
colUnrefinedCorrelationCoefficient.CellTemplate.Style.Format = @"0.0000";
zedGraphControl.GraphPane.IsFontsScaled = false;
zedGraphControl.GraphPane.YAxisList[0].MajorTic.IsOpposite = false;
zedGraphControl.GraphPane.YAxisList[0].MinorTic.IsOpposite = false;
zedGraphControl.GraphPane.XAxis.MajorTic.IsOpposite = false;
zedGraphControl.GraphPane.XAxis.MinorTic.IsOpposite = false;
zedGraphControl.GraphPane.Chart.Border.IsVisible = false;
_rowUpdateQueue.RunAsync(ParallelEx.GetThreadCount(), @"Alignment Rows");
}
private PlotTypeRT _plotType;
public SkylineWindow SkylineWindow { get; private set; }
public SrmDocument Document
{
get { return SkylineWindow.DocumentUI; }
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
if (SkylineWindow != null)
{
SkylineWindow.DocumentUIChangedEvent += SkylineWindowOnDocumentUIChangedEvent;
}
UpdateAll();
}
protected override void OnClosing(CancelEventArgs e)
{
_cancellationTokenSource.Cancel();
base.OnClosing(e);
}
protected override void OnHandleDestroyed(EventArgs e)
{
if (SkylineWindow != null)
{
SkylineWindow.DocumentUIChangedEvent -= SkylineWindowOnDocumentUIChangedEvent;
}
_rowUpdateQueue.Dispose();
base.OnHandleDestroyed(e);
}
private void SkylineWindowOnDocumentUIChangedEvent(object sender, DocumentChangedEventArgs documentChangedEventArgs)
{
UpdateAll();
}
public void UpdateAll()
{
UpdateCombo();
}
public void UpdateGraph()
{
zedGraphControl.IsEnableVPan = zedGraphControl.IsEnableVZoom = PlotType == PlotTypeRT.residuals;
zedGraphControl.GraphPane.CurveList.Clear();
zedGraphControl.GraphPane.GraphObjList.Clear();
zedGraphControl.IsZoomOnMouseCenter = true;
if (!(bindingSource.Current is DataRow))
{
return;
}
var currentRow = (DataRow) bindingSource.Current;
var alignedFile = currentRow.AlignedRetentionTimes;
if (alignedFile == null)
{
zedGraphControl.GraphPane.Title.Text = Resources.AlignmentForm_UpdateGraph_Waiting_for_retention_time_alignment;
return;
}
var points = new PointPairList();
var outliers = new PointPairList();
var peptideTimes = alignedFile.Regression.PeptideTimes;
for (int i = 0; i < peptideTimes.Count; i++)
{
var peptideTime = peptideTimes[i];
var xTime = alignedFile.OriginalTimes[peptideTime.PeptideSequence];
var yTime = peptideTime.RetentionTime;
if (PlotType == PlotTypeRT.residuals)
yTime = (double) (alignedFile.Regression.GetRetentionTime(xTime, true) - yTime);
var point = new PointPair(xTime, yTime, peptideTime.PeptideSequence.Sequence);
if (alignedFile.OutlierIndexes.Contains(i))
{
outliers.Add(point);
}
else
{
points.Add(point);
}
}
var goodPointsLineItem = new LineItem(@"Peptides", points, Color.Black, SymbolType.Diamond) // CONSIDER: localize?
{
Symbol = {Size = 8f},
Line = {IsVisible = false}
};
goodPointsLineItem.Symbol.Border.IsVisible = false;
goodPointsLineItem.Symbol.Fill = new Fill(RTLinearRegressionGraphPane.COLOR_REFINED);
if (outliers.Count > 0)
{
var outlierLineItem = zedGraphControl.GraphPane.AddCurve(Resources.AlignmentForm_UpdateGraph_Outliers, outliers, Color.Black,
SymbolType.Diamond);
outlierLineItem.Symbol.Size = 8f;
outlierLineItem.Line.IsVisible = false;
outlierLineItem.Symbol.Border.IsVisible = false;
outlierLineItem.Symbol.Fill = new Fill(RTLinearRegressionGraphPane.COLOR_OUTLIERS);
goodPointsLineItem.Label.Text = Resources.AlignmentForm_UpdateGraph_Peptides_Refined;
}
zedGraphControl.GraphPane.CurveList.Add(goodPointsLineItem);
if (points.Count > 0 && PlotType == PlotTypeRT.correlation)
{
double xMin = points.Select(p => p.X).Min();
double xMax = points.Select(p => p.X).Max();
var regression = alignedFile.RegressionRefined ?? alignedFile.Regression;
var regressionLine = zedGraphControl.GraphPane
.AddCurve(Resources.AlignmentForm_UpdateGraph_Regression_line, new[] { xMin, xMax },
new[] { regression.Conversion.GetY(xMin), regression.Conversion.GetY(xMax) },
Color.Black);
regressionLine.Symbol.IsVisible = false;
}
zedGraphControl.GraphPane.Title.Text = string.Format(Resources.AlignmentForm_UpdateGraph_Alignment_of__0__to__1_,
currentRow.DataFile, currentRow.Target.Name);
zedGraphControl.GraphPane.XAxis.Title.Text = string.Format(Resources.AlignmentForm_UpdateGraph_Time_from__0__,
currentRow.DataFile);
zedGraphControl.GraphPane.YAxis.Title.Text = PlotType == PlotTypeRT.correlation
? Resources.AlignmentForm_UpdateGraph_Aligned_Time
: Resources.AlignmentForm_UpdateGraph_Time_from_Regression;
zedGraphControl.GraphPane.AxisChange();
zedGraphControl.Invalidate();
}
private void AlignDataRow(int index, CancellationToken cancellationToken)
{
var dataRow = _dataRows[index];
if (dataRow.TargetTimes == null || dataRow.SourceTimes == null)
{
return;
}
_rowUpdateQueue.Add(() => AlignDataRowAsync(dataRow, index, cancellationToken));
}
private void AlignDataRowAsync(DataRow dataRow, int index, CancellationToken cancellationToken)
{
try
{
var alignedTimes = AlignedRetentionTimes.AlignLibraryRetentionTimes(
dataRow.TargetTimes, dataRow.SourceTimes,
DocumentRetentionTimes.REFINEMENT_THRESHHOLD,
RegressionMethodRT.linear,
cancellationToken);
if (!cancellationToken.IsCancellationRequested)
{
RunUI(() => UpdateDataRow(index, alignedTimes, cancellationToken));
}
}
catch (OperationCanceledException operationCanceledException)
{
throw new OperationCanceledException(operationCanceledException.Message, operationCanceledException, cancellationToken);
}
}
private void RunUI(Action action)
{
Invoke(action);
}
private void UpdateDataRow(int iRow, AlignedRetentionTimes alignedTimes, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var dataRow = _dataRows[iRow];
dataRow.AlignedRetentionTimes = alignedTimes;
_dataRows[iRow] = dataRow;
}
public void UpdateRows()
{
var newRows = GetRows();
if (newRows.SequenceEqual(_dataRows))
{
return;
}
_cancellationTokenSource.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
_dataRows.RaiseListChangedEvents = false;
_dataRows.Clear();
foreach (var row in newRows)
{
_dataRows.Add(row);
}
bool allSameLibrary = true;
if (newRows.Count > 0)
{
var firstLibrary = newRows[0].Library;
allSameLibrary = newRows.Skip(1).All(row => Equals(row.Library, firstLibrary));
}
colLibrary.Visible = !allSameLibrary;
_dataRows.RaiseListChangedEvents = true;
_dataRows.ResetBindings();
for (int i = 0; i < _dataRows.Count; i++ )
{
AlignDataRow(i, _cancellationTokenSource.Token);
}
UpdateGraph();
}
private void UpdateCombo()
{
var documentRetentionTimes = Document.Settings.DocumentRetentionTimes;
var newItems = documentRetentionTimes.RetentionTimeSources.Values.Select(retentionTimeSource=>new DataFileKey(retentionTimeSource)).ToArray();
if (newItems.SequenceEqual(comboAlignAgainst.Items.Cast<DataFileKey>()))
{
return;
}
var selectedIndex = comboAlignAgainst.SelectedIndex;
comboAlignAgainst.Items.Clear();
comboAlignAgainst.Items.AddRange(newItems.Cast<object>().ToArray());
ComboHelper.AutoSizeDropDown(comboAlignAgainst);
bool updateRows = true;
if (comboAlignAgainst.Items.Count > 0)
{
if (selectedIndex < 0)
{
if (SkylineWindow.SelectedResultsIndex >= 0 && Document.Settings.HasResults)
{
var chromatogramSet =
Document.Settings.MeasuredResults.Chromatograms[SkylineWindow.SelectedResultsIndex];
foreach (var msDataFileInfo in chromatogramSet.MSDataFileInfos)
{
var retentionTimeSource = documentRetentionTimes.RetentionTimeSources.Find(msDataFileInfo);
if (retentionTimeSource == null)
{
continue;
}
selectedIndex =
newItems.IndexOf(
dataFileKey => Equals(retentionTimeSource, dataFileKey.RetentionTimeSource));
break;
}
}
}
selectedIndex = Math.Min(comboAlignAgainst.Items.Count - 1,
Math.Max(0, selectedIndex));
if (comboAlignAgainst.SelectedIndex != selectedIndex)
{
comboAlignAgainst.SelectedIndex = selectedIndex;
updateRows = false; // because the selection change will cause an update
}
}
if (updateRows)
UpdateRows();
}
private IList<DataRow> GetRows()
{
var targetKey = comboAlignAgainst.SelectedItem as DataFileKey?;
if (!targetKey.HasValue)
{
return new DataRow[0];
}
var documentRetentionTimes = Document.Settings.DocumentRetentionTimes;
var dataRows = new List<DataRow>();
foreach (var retentionTimeSource in documentRetentionTimes.RetentionTimeSources.Values)
{
if (targetKey.Value.RetentionTimeSource.Name == retentionTimeSource.Name)
{
continue;
}
dataRows.Add(new DataRow(Document.Settings, targetKey.Value.RetentionTimeSource, retentionTimeSource));
}
return dataRows;
}
internal struct DataRow
{
public DataRow(SrmSettings settings, RetentionTimeSource target, RetentionTimeSource timesToAlign) : this()
{
DocumentRetentionTimes = settings.DocumentRetentionTimes;
Target = target;
Source = timesToAlign;
Assume.IsNotNull(target, @"target");
Assume.IsNotNull(DocumentRetentionTimes.FileAlignments, @"DocumentRetentionTimes.FileAlignments");
var fileAlignment = DocumentRetentionTimes.FileAlignments.Find(target.Name);
if (fileAlignment != null)
{
Assume.IsNotNull(fileAlignment.RetentionTimeAlignments, @"fileAlignment.RetentionTimeAlignments");
Assume.IsNotNull(Source, @"Source");
Alignment = fileAlignment.RetentionTimeAlignments.Find(Source.Name);
}
TargetTimes = GetFirstRetentionTimes(settings, target);
SourceTimes = GetFirstRetentionTimes(settings, timesToAlign);
}
internal DocumentRetentionTimes DocumentRetentionTimes { get; private set; }
internal RetentionTimeSource Target { get; private set; }
internal RetentionTimeSource Source { get; private set; }
internal RetentionTimeAlignment Alignment { get; private set; }
internal IDictionary<Target, double> TargetTimes { get; private set; }
internal IDictionary<Target, double> SourceTimes { get; private set; }
public AlignedRetentionTimes AlignedRetentionTimes { get; set; }
public String DataFile { get { return Source.Name; } }
public string Library { get { return Source.Library; } }
public RegressionLine RegressionLine
{
get
{
if (AlignedRetentionTimes != null)
{
var regression = AlignedRetentionTimes.RegressionRefined ?? AlignedRetentionTimes.Regression;
if (regression != null)
{
var regressionLine = regression.Conversion as RegressionLineElement;
if(regressionLine != null)
return new RegressionLine(regressionLine.Slope, regressionLine.Intercept);
}
}
if (Alignment != null)
{
return Alignment.RegressionLine;
}
return null;
}
}
public double? Slope
{
get
{
var regressionLine = RegressionLine;
if (regressionLine != null)
{
return regressionLine.Slope;
}
return null;
}
}
public double? Intercept
{
get
{
var regressionLine = RegressionLine;
if (regressionLine != null)
{
return regressionLine.Intercept;
}
return null;
}
}
public double? CorrelationCoefficient
{
get
{
if (AlignedRetentionTimes == null)
{
return null;
}
return AlignedRetentionTimes.RegressionRefinedStatistics.R;
}
}
public int? OutlierCount
{
get
{
if (AlignedRetentionTimes == null)
{
return null;
}
return AlignedRetentionTimes.OutlierIndexes.Count;
}
}
public double? UnrefinedSlope
{
get
{
if (AlignedRetentionTimes == null)
{
return null;
}
var regressionLine = AlignedRetentionTimes.Regression.Conversion as RegressionLineElement;
return regressionLine != null ? regressionLine.Slope : null as double?;
}
}
public double? UnrefinedIntercept
{
get
{
if (AlignedRetentionTimes == null)
{
return null;
}
var regressionLine = AlignedRetentionTimes.Regression.Conversion as RegressionLineElement;
return regressionLine != null ? regressionLine.Intercept: null as double?;
}
}
public double? UnrefinedCorrelationCoefficient
{
get
{
if (AlignedRetentionTimes == null)
{
return null;
}
return AlignedRetentionTimes.RegressionStatistics.R;
}
}
public int? PointCount
{
get
{
if (AlignedRetentionTimes == null)
{
return null;
}
return AlignedRetentionTimes.RegressionStatistics.Peptides.Count;
}
}
private static IDictionary<Target, double> GetFirstRetentionTimes(
SrmSettings settings, RetentionTimeSource retentionTimeSource)
{
var libraryRetentionTimes = settings.PeptideSettings.Libraries.IsLoaded ?
settings.GetRetentionTimes(MsDataFileUri.Parse(retentionTimeSource.Name)) : null;
if (null == libraryRetentionTimes)
{
return new Dictionary<Target, double>();
}
return libraryRetentionTimes.GetFirstRetentionTimes();
}
}
internal struct DataFileKey
{
public DataFileKey(RetentionTimeSource retentionTimeSource) : this()
{
RetentionTimeSource = retentionTimeSource;
}
public RetentionTimeSource RetentionTimeSource { get; private set; }
public override string ToString()
{
return RetentionTimeSource.Name;
}
}
private void comboAlignAgainst_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateRows();
}
private void bindingSource_CurrentItemChanged(object sender, EventArgs e)
{
UpdateGraph();
}
private void zedGraphControl_ContextMenuBuilder(ZedGraphControl sender, ContextMenuStrip menuStrip, Point mousePt, ZedGraphControl.ContextMenuObjectState objState)
{
ZedGraphHelper.BuildContextMenu(sender, menuStrip, true);
int iInsert = 0;
menuStrip.Items.Insert(iInsert++, timePlotContextMenuItem);
if (timePlotContextMenuItem.DropDownItems.Count == 0)
{
timePlotContextMenuItem.DropDownItems.AddRange(new ToolStripItem[]
{
timeCorrelationContextMenuItem,
timeResidualsContextMenuItem
});
}
timeCorrelationContextMenuItem.Checked = PlotType == PlotTypeRT.correlation;
timeResidualsContextMenuItem.Checked = PlotType == PlotTypeRT.residuals;
menuStrip.Items.Insert(iInsert, new ToolStripSeparator());
}
private void timeCorrelationContextMenuItem_Click(object sender, EventArgs e)
{
PlotType = PlotTypeRT.correlation;
}
private void timeResidualsContextMenuItem_Click(object sender, EventArgs e)
{
PlotType = PlotTypeRT.residuals;
}
public PlotTypeRT PlotType
{
get { return _plotType; }
set
{
if (_plotType != value)
{
_plotType = value;
zedGraphControl.ZoomOutAll(zedGraphControl.GraphPane);
UpdateGraph();
}
}
}
#region Functional test support
public ComboBox ComboAlignAgainst { get { return comboAlignAgainst; } }
public DataGridView DataGridView { get { return dataGridView1; } }
public ZedGraphControl RegressionGraph { get { return zedGraphControl; } }
public SplitContainer Splitter { get { return splitContainer1; } }
#endregion
}
}
| 42.008696 | 172 | 0.535376 | [
"Apache-2.0"
] | vagisha/pwiz | pwiz_tools/Skyline/Controls/Graphs/AlignmentForm.cs | 24,157 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Ashirvad.Repo.Model
{
using System;
using System.Collections.Generic;
public partial class BATCH_MASTER
{
public long batch_id { get; set; }
public long branch_id { get; set; }
public long std_id { get; set; }
public int batch_time { get; set; }
public string mon_fri_batch_time { get; set; }
public string sat_batch_time { get; set; }
public string sun_batch_time { get; set; }
public int row_sta_cd { get; set; }
public long trans_id { get; set; }
public virtual TRANSACTION_MASTER TRANSACTION_MASTER { get; set; }
public virtual BRANCH_MASTER BRANCH_MASTER { get; set; }
public virtual STD_MASTER STD_MASTER { get; set; }
}
}
| 37.15625 | 85 | 0.560976 | [
"MIT"
] | ShailUniqtech/Ashirvad | Ashirvad-main/Ashirvad.Repo/Model/BATCH_MASTER.cs | 1,189 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Services;
using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;
using NadekoBot.Extensions;
using NadekoBot.Modules.Administration;
namespace NadekoBot.Modules.Gambling.Services
{
public class ShopService : IShopService, INService
{
private readonly DbService _db;
public ShopService(DbService db)
{
_db = db;
}
private IndexedCollection<ShopEntry> GetEntriesInternal(NadekoContext uow, ulong guildId) =>
uow.GuildConfigsForId(
guildId,
set => set.Include(x => x.ShopEntries).ThenInclude(x => x.Items)
)
.ShopEntries
.ToIndexed();
public async Task<bool> ChangeEntryPriceAsync(ulong guildId, int index, int newPrice)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (newPrice <= 0)
throw new ArgumentOutOfRangeException(nameof(newPrice));
using var uow = _db.GetDbContext();
var entries = GetEntriesInternal(uow, guildId);
if (index >= entries.Count)
return false;
entries[index].Price = newPrice;
await uow.SaveChangesAsync();
return true;
}
public async Task<bool> ChangeEntryNameAsync(ulong guildId, int index, string newName)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (string.IsNullOrWhiteSpace(newName))
throw new ArgumentNullException(nameof(newName));
using var uow = _db.GetDbContext();
var entries = GetEntriesInternal(uow, guildId);
if (index >= entries.Count)
return false;
entries[index].Name = newName.TrimTo(100);
await uow.SaveChangesAsync();
return true;
}
public async Task<bool> SwapEntriesAsync(ulong guildId, int index1, int index2)
{
if (index1 < 0)
throw new ArgumentOutOfRangeException(nameof(index1));
if (index2 < 0)
throw new ArgumentOutOfRangeException(nameof(index2));
using var uow = _db.GetDbContext();
var entries = GetEntriesInternal(uow, guildId);
if (index1 >= entries.Count || index2 >= entries.Count || index1 == index2)
return false;
entries[index1].Index = index2;
entries[index2].Index = index1;
await uow.SaveChangesAsync();
return true;
}
public async Task<bool> MoveEntryAsync(ulong guildId, int fromIndex, int toIndex)
{
if (fromIndex < 0)
throw new ArgumentOutOfRangeException(nameof(fromIndex));
if (toIndex < 0)
throw new ArgumentOutOfRangeException(nameof(toIndex));
using var uow = _db.GetDbContext();
var entries = GetEntriesInternal(uow, guildId);
if (fromIndex >= entries.Count || toIndex >= entries.Count || fromIndex == toIndex)
return false;
var entry = entries[fromIndex];
entries.RemoveAt(fromIndex);
entries.Insert(toIndex, entry);
await uow.SaveChangesAsync();
return true;
}
}
} | 33 | 100 | 0.585578 | [
"MIT"
] | AnotherFoxGuy/NadekoBot | src/NadekoBot/Modules/Gambling/Services/Impl/ShopService.cs | 3,566 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Amw.Identity.Server
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 24.6 | 76 | 0.694309 | [
"MIT"
] | amwitx/Amw.Core | Identity/Amw.Identity.Server/Program.cs | 617 | C# |
using System.Collections.Generic;
using System.Data.SqlClient;
using System;
namespace BandTracker
{
public class Band
{
private int _id;
private string _name;
public Band(string Name, int Id = 0)
{
_id = Id;
_name = Name;
}
public override bool Equals(System.Object otherBand)
{
if (!(otherBand is Band))
{
return false;
}
else {
Band newBand = (Band) otherBand;
bool idEquality = this.GetId() == newBand.GetId();
bool nameEquality = this.GetName() == newBand.GetName();
return (idEquality && nameEquality);
}
}
public int GetId()
{
return _id;
}
public string GetName()
{
return _name;
}
public static List<Band> GetAll()
{
List<Band> AllBands = new List<Band>{};
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM bands;", conn);
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
int bandId = rdr.GetInt32(0);
string bandName = rdr.GetString(1);
Band newBand = new Band(bandName, bandId);
AllBands.Add(newBand);
}
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
return AllBands;
}
public void Save()
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO bands (name) OUTPUT INSERTED.id VALUES (@BandName);", conn);
SqlParameter nameParameter = new SqlParameter();
nameParameter.ParameterName = "@BandName";
nameParameter.Value = this.GetName();
cmd.Parameters.Add(nameParameter);
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
this._id = rdr.GetInt32(0);
}
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
public static Band Find(int id)
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM bands WHERE id = @BandId;", conn);
SqlParameter bandIdParameter = new SqlParameter();
bandIdParameter.ParameterName = "@BandId";
bandIdParameter.Value = id.ToString();
cmd.Parameters.Add(bandIdParameter);
SqlDataReader rdr = cmd.ExecuteReader();
int foundBandId = 0;
string foundBandName = null;
while(rdr.Read())
{
foundBandId = rdr.GetInt32(0);
foundBandName = rdr.GetString(1);
}
Band foundBand = new Band(foundBandName, foundBandId);
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
return foundBand;
}
public void AddVenue(Venue newVenue)
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO bands_venues (venue_id, band_id) VALUES (@VenueId, @BandId);", conn);
SqlParameter venueIdParameter = new SqlParameter();
venueIdParameter.ParameterName = "@VenueId";
venueIdParameter.Value = newVenue.GetId();
cmd.Parameters.Add(venueIdParameter);
SqlParameter bandIdParameter = new SqlParameter();
bandIdParameter.ParameterName = "@BandId";
bandIdParameter.Value = this.GetId();
cmd.Parameters.Add(bandIdParameter);
cmd.ExecuteNonQuery();
if (conn != null)
{
conn.Close();
}
}
public List<Venue> GetVenues()
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT venue_id FROM bands_venues WHERE band_id = @BandId;", conn);
SqlParameter bandIdParameter = new SqlParameter();
bandIdParameter.ParameterName = "@BandId";
bandIdParameter.Value = this.GetId();
cmd.Parameters.Add(bandIdParameter);
SqlDataReader rdr = cmd.ExecuteReader();
List<int> venueIds = new List<int> {};
while (rdr.Read())
{
int venueId = rdr.GetInt32(0);
venueIds.Add(venueId);
}
if (rdr != null)
{
rdr.Close();
}
List<Venue> venues = new List<Venue> {};
foreach (int venueId in venueIds)
{
SqlCommand venueQuery = new SqlCommand("SELECT * FROM venues WHERE id = @VenueId;", conn);
SqlParameter venueIdParameter = new SqlParameter();
venueIdParameter.ParameterName = "@VenueId";
venueIdParameter.Value = venueId;
venueQuery.Parameters.Add(venueIdParameter);
SqlDataReader queryReader = venueQuery.ExecuteReader();
while (queryReader.Read())
{
int thisVenueId = queryReader.GetInt32(0);
string venueName = queryReader.GetString(1);
Venue foundVenue = new Venue(venueName, thisVenueId);
venues.Add(foundVenue);
}
if (queryReader != null)
{
queryReader.Close();
}
}
if (conn != null)
{
conn.Close();
}
return venues;
}
public void Delete()
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM bands WHERE id = @BandId; DELETE FROM bands_venues WHERE band_id = @BandId;", conn);
SqlParameter bandIdParameter = new SqlParameter();
bandIdParameter.ParameterName = "@BandId";
bandIdParameter.Value = this.GetId();
cmd.Parameters.Add(bandIdParameter);
cmd.ExecuteNonQuery();
if (conn != null)
{
conn.Close();
}
}
public static void DeleteAll()
{
SqlConnection conn = DB.Connection();
conn.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM bands;", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
| 28.934694 | 139 | 0.48808 | [
"MIT"
] | cassiemusolf/Band-Tracker | Objects/Band.cs | 7,089 | C# |
using System;
using MongoDB.Bson.Serialization.Attributes;
using Common.Data;
using System.Collections.Generic;
namespace KT.Data.Models
{
public class FormFieldChoice
{
public object Value { get; set; }
public Dictionary<string, string> Labels { get; set; }
}
public class FormField
{
public string Id { get; set; }
public string ControlType { get; set; }
public string ParentId { get; set; }
public int Order { get; set; }
[BsonIgnoreIfNull]
public Dictionary<string, string> Labels { get; set; }
[BsonIgnoreIfNull]
public int? ColumnCount { get; set; }
[BsonIgnoreIfNull]
public bool? IsRequired { get; set; }
[BsonIgnoreIfNull]
public List<FormFieldChoice> Choices { get; set; }
[BsonIgnoreIfNull]
public int? MaxLength { get; set; }
[BsonIgnoreIfNull]
public bool? UseCurrentDateAsDefaultValue { get; set; }
[BsonIgnoreIfNull]
public string MinValue { get; set; }
[BsonIgnoreIfNull]
public string MaxValue { get; set; }
[BsonIgnoreIfNull]
public int? HeaderLevel { get; set; }
}
public class FormTemplate : IModel<Guid>
{
public FormTemplate()
{
Id = Guid.NewGuid();
Fields = new List<FormField>();
}
[BsonId]
public Guid Id { get; set; }
public string Name { get; set; }
public List<FormField> Fields { get; set; }
public bool IsArchived { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
}
}
| 24.507246 | 63 | 0.583678 | [
"MIT"
] | bourbest/keeptrack | api/KT.Data/Models/FormTemplate.cs | 1,691 | 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.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Tag.Transform;
using Aliyun.Acs.Tag.Transform.V20180828;
namespace Aliyun.Acs.Tag.Model.V20180828
{
public class TagResourcesRequest : RpcAcsRequest<TagResourcesResponse>
{
public TagResourcesRequest()
: base("Tag", "2018-08-28", "TagResources", "tag", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
}
private long? resourceOwnerId;
private List<string> resourceARNs = new List<string>(){ };
private string resourceOwnerAccount;
private string ownerAccount;
private long? ownerId;
private string tags;
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public List<string> ResourceARNs
{
get
{
return resourceARNs;
}
set
{
resourceARNs = value;
for (int i = 0; i < resourceARNs.Count; i++)
{
DictionaryUtil.Add(QueryParameters,"ResourceARN." + (i + 1) , resourceARNs[i]);
}
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string OwnerAccount
{
get
{
return ownerAccount;
}
set
{
ownerAccount = value;
DictionaryUtil.Add(QueryParameters, "OwnerAccount", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string Tags
{
get
{
return tags;
}
set
{
tags = value;
DictionaryUtil.Add(QueryParameters, "Tags", value);
}
}
public override TagResourcesResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return TagResourcesResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 24.161972 | 134 | 0.651997 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-tag/Tag/Model/V20180828/TagResourcesRequest.cs | 3,431 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CellularAutomaton.src.Rules;
namespace CellularAutomaton.Tests.src.Rules
{
[TestClass]
public class WolframCodeTests
{
[TestMethod]
public void InstantiationByteTest()
{
const byte rule = 90;
const byte initialState = 1;
const byte Expected = initialState;
WolframCode code = new WolframCode(rule, initialState);
byte result = code.GetState();
Assert.AreEqual(Expected, result);
}
[TestMethod]
public void InstantiationStringTest()
{
const string rule = "10101010";
const byte initialState = 1;
const byte Expected = initialState;
WolframCode code = new WolframCode(rule, initialState);
byte result = code.GetState();
Assert.AreEqual(Expected, result);
}
[TestMethod]
public void RuleTest()
{
const string rule = "10101010";
string[] neighbors = new string[] {"111", "110", "101", "100", "011", "010", "001", "000", };
const byte initialState = 0;
WolframCode code = new WolframCode(rule, initialState);
for (int i = 0; i < neighbors.Length; i++)
{
code.Update(neighbors[i]);
byte result = code.GetState();
Assert.AreEqual(int.Parse(new string (rule[i], 1)), result);
}
}
}
}
| 22.070175 | 96 | 0.677266 | [
"MIT"
] | Natehhggh/CellularAutomaton | CellularAutomaton.Tests/src/Rules/WolframCodeTests.cs | 1,260 | C# |
using System.Collections.Generic;
namespace Havit.Data.EntityFrameworkCore.Patterns.UnitOfWorks.EntityValidation
{
/// <summary>
/// Factory poskytující entity validátory.
/// </summary>
/// <remarks>
/// Revize použití s ohledem na https://github.com/volosoft/castle-windsor-ms-adapter/issues/32:
/// Implementované služby musí být bezstavové.
/// Pokud budou registrované jako transient nebo singleton (což budou), pak se této factory popsaná issue netýká.
/// </remarks>
public interface IEntityValidatorsFactory
{
/// <summary>
/// Poskytuje entity validátory pro daný typ.
/// </summary>
/// <remarks>
/// Implementace pomocí Castle Windsor nedává případné registrace pro předky entity.
/// </remarks>
IEnumerable<IEntityValidator<TEntity>> Create<TEntity>()
where TEntity : class;
/// <summary>
/// Uvolňuje vytvořené validátory.
/// </summary>
void Release<TEntity>(IEnumerable<IEntityValidator<TEntity>> validators)
where TEntity : class;
}
}
| 32.064516 | 114 | 0.725352 | [
"MIT"
] | havit/HavitFramework | Havit.Data.EntityFrameworkCore.Patterns/UnitOfWorks/EntityValidation/IEntityValidatorsFactory.cs | 1,025 | C# |
using Store.Core.Domain.Entities.Default;
using Store.Core.Domain.Interfaces.Infrastructures.Data.Contexts;
using Store.Core.Domain.Interfaces.Services.Default.Samples;
using Store.Core.Domain.Resources;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Store.Core.Application.Default.Samples.Commands.DeleteSample
{
public class DeleteSampleCommandHandler : ApplicationRequestHandler<Sample, DeleteSampleCommand, DeleteSampleCommandResponse>
{
private IStringLocalizer MessagesLocalizer { get; set; }
private IStringLocalizer EntitiesDefaultLocalizer { get; set; }
public IDefaultDbContext Context { get; set; }
private IDeleteSampleService DeleteService { get; set; }
public DeleteSampleCommandHandler(
IStringLocalizer<Messages> messagesLocalizer,
IStringLocalizer<EntitiesDefault> entitiesDefaultLocalizer,
IDefaultDbContext context,
IDeleteSampleService deleteService)
{
MessagesLocalizer = messagesLocalizer;
EntitiesDefaultLocalizer = entitiesDefaultLocalizer;
Context = context;
DeleteService = deleteService;
}
public override async Task<DeleteSampleCommandResponse> Handle(DeleteSampleCommand request, CancellationToken cancellationToken)
{
var id = request.Project(x => x.Id);
var data = await Context.Samples.SingleOrDefaultAsync(x => x.Id == id);
if (data == null)
{
throw new Exception(string.Format(MessagesLocalizer["{0} not found!"], EntitiesDefaultLocalizer[nameof(Sample)]));
}
await DeleteService.Run(data);
await Context.SaveChangesAsync();
return new DeleteSampleCommandResponse(request, data, MessagesLocalizer["Successful operation!"], 1);
}
}
}
| 40.44898 | 136 | 0.702321 | [
"MIT"
] | isilveira/ModelWrapper | samples/Store/Store.Core.Application/Default/Samples/Commands/DeleteSample/DeleteSampleCommandHandler.cs | 1,982 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_1._0
{
class Program
{
static void Main(string[] args)
{
string word = Console.ReadLine();
List<int> numbers = new List<int>();
int lastOne = 0;
int count = 0;
int num = 0;
while (word != "stop")
{
try
{
num = int.Parse(word);
count++;
numbers.Add(num);
if (numbers.Count > 1)
{
for (int i = numbers.Count - 1; i >= 1; i--)
{
int solv = 0;
solv = numbers[i];
numbers[i] = numbers[i - 1];
numbers[i - 1] = solv;
}
}
}
catch (Exception)
{
if (word == "bang")
{
count--;
if (count >= 0)
{
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] <= AverageList(numbers))
{
Console.WriteLine($"shot {numbers[i]}"); // махам елемент
lastOne = numbers[i];
numbers.Remove(numbers[i]);
for (int j = 0; j < numbers.Count; j++) // намалям всички останали с 1
{
numbers[j]--;
}
break;
}
}
}
else
{
Console.WriteLine($"nobody left to shoot! last one was {lastOne}");
break;
}
}
}
word = Console.ReadLine();
}
if (count == 0)
{
Console.WriteLine($"you shot them all. last one was {lastOne}");
}
else if (count > 0)
{
Console.WriteLine($"survivors: {String.Join(" ", numbers)}");
}
}
static int AverageList(List<int> numbers)
{
int sum = 0;
for (int i = 0; i < numbers.Count; i++)
{
sum = sum + numbers[i];
}
return sum / numbers.Count;
}
}
}
| 29.530612 | 106 | 0.299585 | [
"MIT"
] | danielstaikov/List-and-others | test 1.0/Shoot List Elements.cs | 2,930 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Blazored.LocalStorage;
using Blazored.SessionStorage;
using Count4U.Model.Count4U;
using Count4U.Model.SelectionParams;
using Count4U.Service.Shared;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Monitor.Service.Model;
using Monitor.Service.Shared;
using Monitor.Service.Urls;
using Count4U.Admin.Client.Blazor.Component;
using Count4U.Admin.Client.Blazor.I18nText;
using System.Net.Http;
using BlazorInputFile;
using Microsoft.JSInterop;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using BlazorMonacoXml;
using Microsoft.AspNetCore.Components.Forms;
using Monitor.Service.Shared.MapperExpandoObject;
using Count4U.Service.Format;
using Microsoft.AspNetCore.SignalR.Client;
using Count4U.Model.Common;
namespace Count4U.Admin.Client.Blazor.Page
{
public class CustomerProfileAndUserAddBase : ComponentBase
{
protected ProfileFile _profileFile { get; set; }
public ProfileAndUserModel _profileAndUserModel { get; set; }
public ProfileAndUrerResult _profileAndUserResult { get; set; }
protected string _code { get; set; } = "";
public string PingServer { get; set; }
public string SessionStorageMode { get; set; }
public bool Ping { get; set; }
public bool PingMonitor { get; set; }
public bool PingSignalRHub { get; set; }
public string StorageMonitorWebApiUrl { get; set; }
public string StorageSignalRHubUrl { get; set; }
public bool IsSubmit { get; set; } = false;
[Inject]
protected ISessionStorageService _sessionStorage { get; set; }
[Inject]
protected ILocalStorageService _localStorage { get; set; }
[Inject]
protected NavigationManager _navigationManager { get; set; }
[Inject]
protected IProfileFileService _profileFileService { get; set; }
[Inject]
protected IFileDefaultService _fileDefaultService { get; set; }
[Inject]
protected IClaimService _claimService { get; set; }
[Inject]
protected Toolbelt.Blazor.I18nText.I18nText I18nText { get; set; }
protected GetResources LocalizationResources { get; set; }
[Inject]
protected IAuthService _authService { get; set; }
[Inject]
protected IAdminService _adminService { get; set; }
[Inject]
protected HttpClient Http { get; set; }
[Inject]
protected IJSRuntime _jsRuntime { get; set; }
[Inject]
protected IHubCommandSignalRRepository _hubCommandSignalRRepository { get; set; }
protected IFileListEntry _selectedFile { get; set; }
public CustomerProfileAndUserAddBase()
{
this._profileAndUserModel = new ProfileAndUserModel(new RegisterModel(), new ProfileFile());
this._profileAndUserResult = new ProfileAndUrerResult();
this._profileAndUserResult.RegisterResult = null;
this._selectedFile = null;
}
protected async Task RegistrationAsync()
{
IsSubmit = true;
this._profileAndUserResult.RegisterResult = new RegisterResult();
this._profileAndUserResult.RegisterResult.Successful = SuccessfulEnum.Waiting;
this._profileAndUserModel.ProfileFile.Successful = SuccessfulEnum.Waiting;
this._profileFileService.RunUpdateFtpAndDbProfiles = null;
StateHasChanged();
Console.WriteLine();
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.RegistrationAsync() : start");
//this._showErrors = null;
//this._showSuccessful = null;
//this._profileAndUserResult.RegisterResult = null;
if (this._authService == null)
{
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.RegistrationAsync() : _authService is null");
}
else
{
try
{
UserViewModel editUser = new UserViewModel() { Email = this._profileAndUserModel.RegisterModel.Email };
editUser = await this._authService.GetUser(editUser);
Console.WriteLine($"Client.CustomerProfileAndUserEditBase.RegistrationAsync() : editUser 1 : {editUser.Successful}");
Console.WriteLine($"Client.CustomerProfileAndUserEditBase.RegistrationAsync() : error 1 : {editUser.Error}");
if (editUser != null && this._profileAndUserResult.RegisterResult.Successful != SuccessfulEnum.UserNotFound)
{
this._profileAndUserResult.RegisterResult.Successful = editUser.Successful;
this._profileAndUserResult.RegisterResult.Error = editUser.Error;
StateHasChanged();
if (editUser.Successful == SuccessfulEnum.Successful)
{
this._profileAndUserModel.RegisterModel = this._profileAndUserModel.RegisterModel.RefreshRegisterModel(editUser);
}
else
{
Console.WriteLine($"{editUser.Error}");
}
}
if (this._profileAndUserResult.RegisterResult.Successful == SuccessfulEnum.UserNotFound)
{
this._profileAndUserResult.RegisterResult = await this._authService.RegisterAsync(this._profileAndUserModel.RegisterModel);
Console.WriteLine($"Client.CustomerProfileAndUserEditBase.RegistrationAsync() : editUser 2 : {this._profileAndUserResult.RegisterResult.Successful}");
Console.WriteLine($"Client.CustomerProfileAndUserEditBase.RegistrationAsync() : error 2 : {this._profileAndUserResult.RegisterResult.Error}");
StateHasChanged();
if (this._profileAndUserResult != null)
{
if (this._profileAndUserResult.RegisterResult != null)
{
if (this._profileAndUserResult.RegisterResult.Successful == SuccessfulEnum.Successful)
{
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.RegistrationAsync() : Successful2");
//this._showSuccessful = true;
// this._navigationManager.NavigateTo("/customergrid");
}
else
{
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.RegistrationAsync() : Errors2");
Console.WriteLine($"{this._profileAndUserResult.RegisterResult.Error}");
//this._errors.Add(result.Error);
//this._showErrors = true;
}
}
}
}
if (editUser == null)
{
this._profileAndUserResult.RegisterResult.Successful = SuccessfulEnum.NotSuccessful;
this._profileAndUserResult.RegisterResult.Error = "editUser == null";
StateHasChanged();
}
}
catch (Exception ecx)
{
Console.WriteLine("Client.CustomerProfileAndUserAddBase.RegistrationAsync() Exception : ");
Console.WriteLine(ecx.Message);
}
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.RegistrationAsync() : end");
}
if (this._profileAndUserResult.RegisterResult.Successful == SuccessfulEnum.Successful)
{
if (this._profileFileService != null)
{
try
{
if (string.IsNullOrWhiteSpace(this._profileAndUserModel.RegisterModel.CustomerCode) == false)
{
Console.WriteLine($"Client.InventorProfileGridBase.GetProfileFiles() : start Register");
this._profileAndUserModel.ProfileFile.Code = this._profileAndUserModel.RegisterModel.CustomerCode;
this._profileAndUserModel.ProfileFile.CustomerCode = this._profileAndUserModel.RegisterModel.CustomerCode;
this._profileAndUserModel.ProfileFile.Name = this._profileAndUserModel.ProfileFile.CustomerName;
this._profileAndUserModel.ProfileFile.SubFolder = this._profileAndUserModel.RegisterModel.CustomerCode;
this._profileAndUserModel.ProfileFile.CurrentPath = @"Customer\" + this._profileAndUserModel.RegisterModel.CustomerCode;
this._profileAndUserModel.ProfileFile.DomainObject = "Customer";
//Console.WriteLine($"Client.InventorProfileGridBase.GetProfileFiles() : this._profileAndUserModel.ProfileFile.CustomerName :{this._profileAndUserModel.ProfileFile.CustomerName}");
//this._profileAndUserModel.ProfileFile.CustomerName = this._profileAndUserModel.ProfileFile.CustomerName;
//Console.WriteLine($"Client.InventorProfileGridBase.GetProfileFiles() : this._profileAndUserModel.RegisterModel.CustomerDescription :{this._profileAndUserModel.ProfileFile.CustomerDescription}");
//this._profileAndUserModel.ProfileFile.CustomerDescription = this._profileAndUserModel.ProfileFile.CustomerDescription;
this._profileAndUserModel.ProfileFile.Email = this._profileAndUserModel.RegisterModel.Email;
//await this._localStorage.SetItemAsync(SessionStorageKey.filterCustomer, FilterCustomerSelectParam.Code);
//await this._localStorage.SetItemAsync(SessionStorageKey.filterValueCustomer, this._profileAndUserModel.RegisterModel.CustomerCode);
Console.WriteLine($"Client.InventorProfileGridBase.GetProfileFiles() : 1 Register");
if (_profileAndUserModel.RegisterModel.InheritProfile == @InheritProfileString.Exist)
{
ProfileFile customerProfileFile = await this._profileFileService.GetProfileFileFromFtp(this._profileAndUserModel.ProfileFile, @"http://localhost:12389");
if(string.IsNullOrWhiteSpace(customerProfileFile.ProfileXml) == false)
{
this._profileAndUserModel.ProfileFile.ProfileXml = customerProfileFile.ProfileXml;
this._profileAndUserModel.ProfileFile.Successful = customerProfileFile.Successful;
this._profileAndUserModel.ProfileFile.Error = customerProfileFile.Error;
}
else
{
ProfileFile defaultProfileFile = await this._fileDefaultService.GetDefaultProfileFile(@"http://localhost:12389");
this._profileAndUserModel.ProfileFile.ProfileXml = defaultProfileFile.ProfileXml;
this._profileAndUserModel.ProfileFile.Successful = defaultProfileFile.Successful;
this._profileAndUserModel.ProfileFile.Error = defaultProfileFile.Error;
}
}
else if (_profileAndUserModel.RegisterModel.InheritProfile == @InheritProfileString.Default)
{
if (_fileDefaultService != null)
{
Console.WriteLine($"Client.InventorProfileGridBase.GetProfileFiles() : 2 Register");
ProfileFile defaultProfileFile = await this._fileDefaultService.GetDefaultProfileFile(@"http://localhost:12389");
//Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() defaultProfileFile.ProfileXml : {defaultProfileFile.ProfileXml}");
this._profileAndUserModel.ProfileFile.ProfileXml = defaultProfileFile.ProfileXml;
this._profileAndUserModel.ProfileFile.Successful = defaultProfileFile.Successful;
this._profileAndUserModel.ProfileFile.Error = defaultProfileFile.Error;
}
}
else if (_profileAndUserModel.RegisterModel.InheritProfile == @InheritProfileString.File)
{
if (this._selectedFile != null && this._selectedFile.Data != null)
{
try
{
using (var reader = new StreamReader(this._selectedFile.Data))
{
this._profileAndUserModel.ProfileFile.ProfileXml = await reader.ReadToEndAsync();
this._profileAndUserModel.ProfileFile.Successful = SuccessfulEnum.Successful;
}
}
catch (Exception ecx)
{
this._profileAndUserModel.ProfileFile.Successful = SuccessfulEnum.NotSuccessful;
this._profileAndUserModel.ProfileFile.Error = ecx.Message;
}
}
else
{
ProfileFile defaultProfileFile = await this._fileDefaultService.GetDefaultProfileFile(@"http://localhost:12389");
this._profileAndUserModel.ProfileFile.ProfileXml = defaultProfileFile.ProfileXml;
this._profileAndUserModel.ProfileFile.Successful = defaultProfileFile.Successful;
this._profileAndUserModel.ProfileFile.Error = defaultProfileFile.Error;
}
}
else if (_profileAndUserModel.RegisterModel.InheritProfile == @InheritProfileString.Customer)
{
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() Customer 1");
if (_profileAndUserModel.RegisterModel.CustomerProfileCodesFromDB != null)
{
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() Customer 2");
if (string.IsNullOrWhiteSpace(_profileAndUserModel.RegisterModel.CustomerProfileCodesFromDB.SelectByCustomerProfile) == false)
{
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() Customer 3");
ProfileFile customerProfileFile = await this._profileFileService.GetProfileFileByCode(
_profileAndUserModel.RegisterModel.CustomerProfileCodesFromDB.SelectByCustomerProfile, @"http://localhost:12389");
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() Customer 4");
if (customerProfileFile != null)
{
this._profileAndUserModel.ProfileFile.ProfileXml = customerProfileFile.ProfileXml;
this._profileAndUserModel.ProfileFile.Successful = customerProfileFile.Successful;
this._profileAndUserModel.ProfileFile.Error = customerProfileFile.Error;
}
else
{
ProfileFile defaultProfileFile = await this._fileDefaultService.GetDefaultProfileFile(@"http://localhost:12389");
this._profileAndUserModel.ProfileFile.ProfileXml = defaultProfileFile.ProfileXml;
this._profileAndUserModel.ProfileFile.Successful = defaultProfileFile.Successful;
this._profileAndUserModel.ProfileFile.Error = defaultProfileFile.Error;
}
}
else
{
ProfileFile defaultProfileFile = await this._fileDefaultService.GetDefaultProfileFile(@"http://localhost:12389");
this._profileAndUserModel.ProfileFile.ProfileXml = defaultProfileFile.ProfileXml;
this._profileAndUserModel.ProfileFile.Successful = defaultProfileFile.Successful;
this._profileAndUserModel.ProfileFile.Error = defaultProfileFile.Error;
}
}
else
{
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() CustomerProfileCodesFromDB is null");
this._profileAndUserModel.ProfileFile.Successful = SuccessfulEnum.NotSuccessful;
this._profileAndUserModel.ProfileFile.Error = "CustomerProfileCodesFromDB is null";
}
}
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() 3 Register");
// StateHasChanged();
//while(this._profileAndUserModel.ProfileFile.Successful != SuccessfulEnum.Successful)
//{
// await Task.Delay(1000);
// Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() Waiting {this._profileAndUserModel.ProfileFile.Successful}");
//}
this._profileFileService.RunUpdateFtpAndDbProfiles = await this._profileFileService.AddToQueueUpdateFtpAndDbRun(this._profileAndUserModel.ProfileFile, @"http://localhost:12389");
////this._profileAndUserModel.ProfileFile = await this._profileFileService.SaveOrUpdateProfileFileOnFtpAndDB(this._profileAndUserModel.ProfileFile, @"http://localhost:12389");
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() 4 Register");
//if (this._profileAndUserModel.ProfileFile != null)
//{
// if (this._profileAndUserModel.ProfileFile.Successful == SuccessfulEnum.Successful)
// {
// Console.WriteLine($"Client.CustomerProfileAndUserAddBase.RegistrationAsync SaveOrUpdateProfileFileOnFtpAndDB() : Successful");
// }
// else
// {
// Console.WriteLine($"Client.CustomerProfileAndUserAddBase.RegistrationAsync() SaveOrUpdateProfileFileOnFtpAndDB : Errors");
// Console.WriteLine($"{this._profileAndUserModel.ProfileFile.Error}");
// }
//}
}
else
{
this._profileAndUserModel.ProfileFile.Successful = SuccessfulEnum.NotSuccessful;
this._profileAndUserModel.ProfileFile.Error = "Customer Code is empty";
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.RegistrationAsync() Error : Customer Code is empty");
}
}
catch (Exception exc)
{
this._profileAndUserModel.ProfileFile.Successful = SuccessfulEnum.NotSuccessful;
this._profileAndUserModel.ProfileFile.Error = exc.Message;
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() Exception :");
Console.WriteLine(exc.Message);
}
}
else
{
this._profileAndUserModel.ProfileFile.Successful = SuccessfulEnum.NotSuccessful;
this._profileAndUserModel.ProfileFile.Error = " _profileFileService is null";
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() : _profileFileService is null");
Console.WriteLine($"Client.InventorProfileGridBase.RegistrationAsync() : end");
}
}
//IsSubmit = false;
StateHasChanged();
}
public async Task OnClearAsync()
{
this._profileFile = null;
this._profileAndUserModel = new ProfileAndUserModel(new RegisterModel(), new ProfileFile());
this._profileAndUserResult = new ProfileAndUrerResult();
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.OnClearAsync() : start");
//await CreateNewCustomer();
}
public async Task ToCustomers()
{
this._navigationManager.NavigateTo("/customergrid");
}
protected async Task GetProfileFiles()
{
Console.WriteLine();
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.GetProfileFiles() : start");
if (this._profileFileService != null)
{
try
{
Console.WriteLine($"Client.CustomerProfileGridBase.GetProfileFiles() 1");
var profileFiles = await this._profileFileService.GetCustomerCodeListFromDb(@"http://localhost:12389");
Console.WriteLine($"Client.CustomerProfileGridBase.GetProfileFiles() 2");
foreach (var profileFile in profileFiles)
{
if (profileFile == null) continue; // такого не должно быть
this._profileAndUserModel.RegisterModel.CustomerProfileCodesFromDB.CodeDictionary[profileFile.Code] = $"[{profileFile.Code}] {profileFile.Name}";
}
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.GetProfileFiles() 3");
}
catch (Exception exc)
{
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.GetProfileFiles() Exception :");
Console.WriteLine(exc.Message);
}
}
else
{
Console.WriteLine($"Client.CustomerProfileAndUserAddBase.GetProfileFiles() : end");
}
}
public async Task GetRegisterModel()
{
this._profileAndUserModel.RegisterModel = new RegisterModel();
this._profileAndUserResult.RegisterResult = null;
}
protected override async Task OnInitializedAsync()
{
Console.WriteLine();
Console.WriteLine($"Client.CustomerProfileBase.OnInitializedAsync() : start");
this.StorageMonitorWebApiUrl = "";
this.StorageSignalRHubUrl = "";
this.Ping = false;
this.PingMonitor = false;
this.PingSignalRHub = false;
if (this._profileFileService != null)
{
this._profileFileService.RunUpdateFtpAndDbProfiles = null;
}
else
{
Console.WriteLine($"Client.ObjectProfileXmlFileEditBase.OnInitializedAsync() : _profileFileService is null");
}
try
{
this.LocalizationResources = await this.I18nText.GetTextTableAsync<GetResources>(this);
if (this._localStorage != null)
{
//await this._localStorage.SetItemAsync(SessionStorageKey.filterCustomer, FilterCustomerSelectParam.Code);
//await this._localStorage.SetItemAsync(SessionStorageKey.filterValueCustomer, "");
//if (this._profileAndUserModel.RegisterModel != null)
//{
// if (string.IsNullOrWhiteSpace(this._profileAndUserModel.RegisterModel.CustomerCode) == false)
// {
// await this._localStorage.SetItemAsync(SessionStorageKey.filterValueCustomer, this._profileAndUserModel.RegisterModel.CustomerCode);
// }
//}
this.StorageMonitorWebApiUrl = await this._localStorage.GetItemAsync<string>(SessionStorageKey.monitorWebapiUrl);
this.StorageSignalRHubUrl = await this._localStorage.GetItemAsync<string>(SessionStorageKey.signalRHubUrl);
if (string.IsNullOrWhiteSpace(this.StorageMonitorWebApiUrl) == false)
{
string result = await this._claimService.PingWebApiMonitorAsync();
if (result == PingOpetarion.Pong)
{ this.PingMonitor = true; }
}
if (string.IsNullOrWhiteSpace(this.StorageSignalRHubUrl) == false)
{
string result = await this._claimService.PingSignalRHubAsync();
if (result == PingOpetarion.Pong)
{ this.PingSignalRHub = true; }
}
}
if (this._sessionStorage == null)
{
Console.WriteLine($"Client.ObjectProfileXmlFileEditBase.OnInitializedAsync() : _sessionStorage is null");
}
else
{
// string tokenFromStorage = await this._sessionStorage.GetItemAsync<string>(SessionStorageKey.authToken);
// Console.WriteLine($"Client.InventorProfileFileEditBase.OnInitializedAsync() : got Token");
}
await GetRegisterModel();
await GetProfileFiles();
}
catch (Exception exc)
{
Console.WriteLine($"Client.CustomerProfileBase.OnInitializedAsync() Exception :");
Console.WriteLine(exc.Message);
}
Console.WriteLine($"Client.CustomerProfileBase.OnInitializedAsync() : end");
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
try
{
this._hubCommandSignalRRepository.HubCommandConnection.On<ProfileFile>(SignalRHubPublishFunction.ReceiveProfileFile, (result) =>
{
Console.WriteLine($"Client.ObjectProfileXmlFileEditBase.OnAfterRenderAsync() Start On<ProfileFile> {result.Code}");
Console.WriteLine($"Client.ObjectProfileXmlFileEditBase.OnAfterRenderAsync() result.Step {result.Step}");
Console.WriteLine($"Client.ObjectProfileXmlFileEditBase.OnAfterRenderAsync() result.Successful {result.Successful}");
//this._importFromPdaService.FileItemsInData = this._importFromPdaService.FileItemsInData.UpdateCommandResultInFileItems(
// this._importFromPdaService.FileItemsInData, result);
// this._importFromPdaService.RunImportCommandResults.UpdateCommandResulByOperationCode(result);
this._profileFileService.RunUpdateFtpAndDbProfiles.UpdateProfileFileByOperationCode(result);
// this._profileFileService.RunUpdateFtpAndDbProfiles.UpdateProfileFileByOperationCode(result);
//SaveOrUpdatOnFtp = 5,
//UpdateOrInsertInventorFromFtpToDb = 6,
//GetByInventorCodeFromFtp = 7,
if (result.Step == ProfiFileStepEnum.SaveOrUpdatOnFtp)
{
if (result.Successful == SuccessfulEnum.Successful)
{
Console.WriteLine($"{ProfiFileStepEnum.SaveOrUpdatOnFtp.ToString()} : {SuccessfulEnum.Successful.ToString()}");
}
}
else if (result.Step == ProfiFileStepEnum.UpdateOrInsertObjectFromFtpToDb)
{
if (result.Successful == SuccessfulEnum.Successful)
{
Console.WriteLine($"{ProfiFileStepEnum.UpdateOrInsertObjectFromFtpToDb.ToString()} : {SuccessfulEnum.Successful.ToString()}");
IsSubmit = false;
Console.WriteLine($"{ProfiFileStepEnum.UpdateOrInsertObjectFromFtpToDb.ToString()} Wait end with Successful");
}
if (result.Successful == SuccessfulEnum.NotSuccessful)
{
IsSubmit = false;
Console.WriteLine($"{ProfiFileStepEnum.UpdateOrInsertObjectFromFtpToDb.ToString()} Wait end with NotSuccessful");
}
this.StateHasChanged();
}
//else if (result.Step == ProfiFileStepEnum.GetByCodeFromFtp)
//{
// if (result.Successful == SuccessfulEnum.Successful)
// {
// Console.WriteLine($"{ProfiFileStepEnum.SaveOrUpdatOnFtp.ToString()} : {SuccessfulEnum.Successful.ToString()}");
// }
//}
this.StateHasChanged();
});
Console.WriteLine($"Client.ObjectProfileXmlFileEditBase.OnAfterRenderAsync() : GetProfileFile");
}
catch (Exception exc)
{
Console.WriteLine($"Client.ObjectProfileXmlFileEditBase.OnAfterRenderAsync() Exception :");
Console.WriteLine(exc.Message);
}
}
}
public async void OnButtonClick(string elementID)
{
await _jsRuntime.InvokeAsync<string>("BlazorInputFile.wrapInput", elementID);
}
public async Task HandleSelection(IFileListEntry[] files)
{
foreach (var file in files)
{
this._selectedFile = file;
Console.WriteLine("file.Name : " + file.Name);
StateHasChanged();
}
}
//private async Task OnCodeChanged(string value)
//{
// //_profileAndUserModel.RegisterModel.CustomerCode
// //Contact.Name = value;
//}
}
}
| 41.163025 | 204 | 0.728646 | [
"MIT"
] | parad74/Count4U.Service.5 | src/Count4U.Admin.Client.Blazor/Page/FtpFile/CustomerProfileAndUserAdd.razor.cs | 24,512 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace OpenApi.Dtos
{
/// <summary>
/// Parameters of an error detail object
/// </summary>
[DataContract(Name = "ErrorDetail")]
public class ErrorDetailDto
{
/// <summary>
/// The error detail message.
/// </summary>
[Required]
[StringLength(255)]
[DataMember(Name = "message")]
public string Message { get; set; }
/// <summary>
/// List of fields.
/// </summary>
[DataMember(Name = "fields", EmitDefaultValue = false)]
public IReadOnlyList<string> Fields { get; set; }
}
}
| 25.714286 | 63 | 0.590278 | [
"MIT"
] | AKomyshan/FunctionMonkey | Samples/Scratch/OpenApi/Dtos/ErrorDetailDto.cs | 722 | C# |
namespace loginForm
{
partial class InsertPick
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(103, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(74, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Adaugare: ";
this.label1.Click += new System.EventHandler(this.label1_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(21, 166);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(241, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Sala Proceduri";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(21, 120);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(106, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Procedura";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(21, 72);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(106, 23);
this.button3.TabIndex = 3;
this.button3.Text = "Client";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(156, 72);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(106, 23);
this.button4.TabIndex = 4;
this.button4.Text = "Cosmetician";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button5
//
this.button5.Location = new System.Drawing.Point(156, 120);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(106, 23);
this.button5.TabIndex = 5;
this.button5.Text = "Programare";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// InsertPick
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label1);
this.Name = "InsertPick";
this.Text = "InsertPicks";
this.Load += new System.EventHandler(this.InsertPick_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
}
} | 42.5625 | 169 | 0.553965 | [
"Apache-2.0"
] | SabrinaDanoiu/Baza-de-date-Salon-Cosmetica | loginForm/loginForm/InsertPick.Designer.cs | 5,450 | 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 codeguruprofiler-2019-07-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CodeGuruProfiler.Model
{
/// <summary>
/// The server encountered an internal error and is unable to complete the request.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class InternalServerException : AmazonCodeGuruProfilerException
{
private RetryableDetails _retryableDetails = new RetryableDetails(false);
/// <summary>
/// Constructs a new InternalServerException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InternalServerException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InternalServerException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InternalServerException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InternalServerException
/// </summary>
/// <param name="innerException"></param>
public InternalServerException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InternalServerException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InternalServerException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InternalServerException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InternalServerException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the InternalServerException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InternalServerException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
/// <summary>
/// Flag indicating if the exception is retryable and the associated retry
/// details. A null value indicates that the exception is not retryable.
/// </summary>
public override RetryableDetails Retryable
{
get
{
return _retryableDetails;
}
}
}
} | 46.10219 | 178 | 0.673686 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CodeGuruProfiler/Generated/Model/InternalServerException.cs | 6,316 | C# |
namespace test.sacs
{
/// <date>Jun 20, 2005</date>
public class BoundsCheck10 : Test.Framework.TestCase
{
private BoundsCheckEntities bce;
public BoundsCheck10(BoundsCheckEntities bce) :
base("sacs_boundsCheck_tc10", "sacs_boundsCheck", "init",
"Initialize some more test entities",
"test entities are initialized successfully", null)
{
this.bce = bce;
}
public override Test.Framework.TestResult Run()
{
DDS.TopicQos tQos = null;
DDS.DataWriterQos dwQos = null;
DDS.ReturnCode rc;
string expResult = "Initialization success";
Test.Framework.TestResult result = new Test.Framework.TestResult(
expResult,
string.Empty,
Test.Framework.TestVerdict.Pass,
Test.Framework.TestVerdict.Fail);
bce.typeSupport2 = new mod.embeddedStructTypeTypeSupport();
rc = bce.typeSupport2.RegisterType(bce.participant, "embeddedStructType");
if (rc != DDS.ReturnCode.Ok)
{
result.Result = "Typesupport could not be registered.";
return result;
}
rc = bce.participant.GetDefaultTopicQos(ref tQos);
if (rc != DDS.ReturnCode.Ok)
{
result.Result = "Default TopicQos could not be resolved.";
return result;
}
bce.topic2 = bce.participant.CreateTopic("embeddedStruct", "embeddedStructType", tQos);
if (bce.topic2 == null)
{
result.Result = "Topic could not be created.";
return result;
}
rc = bce.publisher.GetDefaultDataWriterQos(ref dwQos);
if (rc != DDS.ReturnCode.Ok)
{
result.Result = "Default DataWriterQos could not be resolved.";
return result;
}
bce.datawriter2 = (mod.embeddedStructTypeDataWriter)bce.publisher.CreateDataWriter(bce.topic2, dwQos);
if (bce.datawriter2 == null)
{
result.Result = "DataWriter could not be created.";
return result;
}
result.Result = expResult;
result.Verdict = Test.Framework.TestVerdict.Pass;
return result;
}
}
}
| 30.742424 | 105 | 0.656974 | [
"Apache-2.0"
] | ADLINK-IST/opensplice | testsuite/dbt/api/dcps/sacs/boundsCheck/code/test/sacs/BoundsCheck10.cs | 2,029 | C# |
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
namespace Mayfly.Attributes
{
public class RequireVoiceAttribute : PreconditionAttribute
{
public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
if (context.User is not IGuildUser user || user.VoiceChannel == null)
{
return PreconditionResult.FromError("User not in voice channel.");
}
ChannelPermissions perms = (await context.Guild.GetCurrentUserAsync()).GetPermissions(user.VoiceChannel);
if (perms is { Connect: false } or { Speak: false } or { ViewChannel: false })
{
return PreconditionResult.FromError("Don't have permission to connect to that voice channel.");
}
return PreconditionResult.FromSuccess();
}
}
} | 30.962963 | 143 | 0.754785 | [
"MIT"
] | Kerillian/Mayfly | Mayfly/Attributes/RequireVoiceAttribute.cs | 838 | C# |
Subsets and Splits