content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// KoubeiMarketingCampaignCrowdBatchqueryResponse.
/// </summary>
public class KoubeiMarketingCampaignCrowdBatchqueryResponse : AlipayResponse
{
/// <summary>
/// 人群组的基本信息,id表示人群分组的ID,name表示人群分组的名称,status表示人群分组的状态,目前只有status=ENABLE有效状态才返回,已经删除的为DISABLE的不返回
/// </summary>
[JsonPropertyName("crowd_group_sets")]
public string CrowdGroupSets { get; set; }
/// <summary>
/// 返回接记录的总条数
/// </summary>
[JsonPropertyName("total_number")]
public string TotalNumber { get; set; }
}
}
| 29.652174 | 105 | 0.655425 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/KoubeiMarketingCampaignCrowdBatchqueryResponse.cs | 820 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.AspNetCore.Razor.Language.Syntax.InternalSyntax;
using Xunit;
namespace Microsoft.AspNetCore.Razor.Language.Legacy;
public abstract class TokenizerTestBase
{
internal abstract object IgnoreRemaining { get; }
internal abstract object CreateTokenizer(ITextDocument source);
internal void TestTokenizer(string input, params SyntaxToken[] expectedSymbols)
{
// Arrange
var success = true;
var output = new StringBuilder();
using (var source = new SeekableTextReader(input, filePath: null))
{
var tokenizer = (Tokenizer)CreateTokenizer(source);
var counter = 0;
SyntaxToken current = null;
while ((current = tokenizer.NextToken()) != null)
{
if (counter >= expectedSymbols.Length)
{
output.AppendLine(string.Format(CultureInfo.InvariantCulture, "F: Expected: << Nothing >>; Actual: {0}", current));
success = false;
}
else if (ReferenceEquals(expectedSymbols[counter], IgnoreRemaining))
{
output.AppendLine(string.Format(CultureInfo.InvariantCulture, "P: Ignored |{0}|", current));
}
else
{
if (!expectedSymbols[counter].IsEquivalentTo(current))
{
output.AppendLine(string.Format(CultureInfo.InvariantCulture, "F: Expected: {0}; Actual: {1}", expectedSymbols[counter], current));
success = false;
}
else
{
output.AppendLine(string.Format(CultureInfo.InvariantCulture, "P: Expected: {0}", expectedSymbols[counter]));
}
counter++;
}
}
if (counter < expectedSymbols.Length && !ReferenceEquals(expectedSymbols[counter], IgnoreRemaining))
{
success = false;
for (; counter < expectedSymbols.Length; counter++)
{
output.AppendLine(string.Format(CultureInfo.InvariantCulture, "F: Expected: {0}; Actual: << None >>", expectedSymbols[counter]));
}
}
}
Assert.True(success, Environment.NewLine + output.ToString());
WriteTraceLine(output.Replace("{", "{{").Replace("}", "}}").ToString());
}
[Conditional("PARSER_TRACE")]
private static void WriteTraceLine(string format, params object[] args)
{
Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, format, args));
}
}
| 39.72973 | 155 | 0.57619 | [
"MIT"
] | dotnet/razor-compiler | src/Microsoft.AspNetCore.Razor.Language/test/Legacy/TokenizerTestBase.cs | 2,940 | C# |
// © XIV-Tools.
// Licensed under the MIT license.
namespace XivToolsWpf.Converters
{
using System;
using System.Globalization;
using System.Windows.Data;
[ValueConversion(typeof(bool), typeof(bool))]
public class BoolInversionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool v = (bool)value;
return !v;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool v = (bool)value;
return !v;
}
}
}
| 21.461538 | 97 | 0.724014 | [
"MIT"
] | 0x0ade/XivToolsWpf | Converters/BoolInversionConverter.cs | 561 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.MachineLearningServices.V20200301.Inputs
{
/// <summary>
/// A Machine Learning compute based on AKS.
/// </summary>
public sealed class AKSArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Location for the underlying compute
/// </summary>
[Input("computeLocation")]
public Input<string>? ComputeLocation { get; set; }
/// <summary>
/// The type of compute
/// Expected value is 'AKS'.
/// </summary>
[Input("computeType", required: true)]
public Input<string> ComputeType { get; set; } = null!;
/// <summary>
/// The description of the Machine Learning compute.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// AKS properties
/// </summary>
[Input("properties")]
public Input<Inputs.AKSPropertiesArgs>? Properties { get; set; }
/// <summary>
/// ARM resource id of the underlying compute
/// </summary>
[Input("resourceId")]
public Input<string>? ResourceId { get; set; }
public AKSArgs()
{
}
}
}
| 28.537037 | 81 | 0.585334 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/MachineLearningServices/V20200301/Inputs/AKSArgs.cs | 1,541 | C# |
using System.Collections.Generic;
namespace Notion.Client
{
public class PagesCreateParameters : IPagesCreateBodyParameters, IPagesCreateQueryParameters
{
public IPageParentInput Parent { get; set; }
public IDictionary<string, PropertyValue> Properties { get; set; }
public IList<Block> Children { get; set; }
public IPageIcon Icon { get; set; }
public FileObject Cover { get; set; }
}
}
| 31.571429 | 96 | 0.68552 | [
"MIT"
] | hognevevle/notion-sdk-net | Src/Notion.Client/Api/Pages/RequestParams/PagesCreateParameters/PagesCreateParameters.cs | 444 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace proyectv.Models
{
public class Carrito
{
public int id { get; set; }
public int codigo_producto_carrito { get; set; }
public int cantidad_producto { get; set; }
public int id_comprador { get; set; }
public string nombre_producto { get; set; }
public string imagen_producto { get; set; }
public double precio_producto { get; set; }
}
}
| 27.894737 | 57 | 0.630189 | [
"MIT"
] | DanielClavijoGonzalez/tienda-el-vecino-aspnc | proyectv/Models/Carrito.cs | 532 | C# |
using System.Collections.Generic;
using System;
using Addresses.Models;
namespace Streets.Models
{
public class Street
{
private string _line1;
private string _line2;
private string _city;
private string _state;
private int _zipCode;
private int _streetId;
private int _addressId;
private List<Street> _currentAddress = new List<Street>{};
public Street(string line1, string line2, string city, string state, int zip, int addressId)
{
_line1 = line1;
_line2 = line2;
_city = city;
_state = state;
_zipCode = zip;
_streetId = _currentAddress.Count;
_addressId = addressId;
}
}
}
| 23.8 | 98 | 0.630252 | [
"Unlicense"
] | LeeMellon/Review5 | Models/Streets.cs | 714 | C# |
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using Piedone.Facebook.Suite.Models;
namespace Piedone.Facebook.Suite.Drivers
{
public class FacebookSuiteSettingsPartDriver : ContentPartDriver<FacebookSuiteSettingsPart>
{
protected override string Prefix
{
get { return "FacebookSuite"; }
}
// GET
protected override DriverResult Editor(FacebookSuiteSettingsPart part, dynamic shapeHelper)
{
return ContentShape("Parts_FacebookSuiteSettings_SiteSettings",
() => shapeHelper.EditorTemplate(
TemplateName: "Parts.FacebookSuiteSettings.SiteSettings",
Model: part,
Prefix: Prefix))
.OnGroup("FacebookSuiteSettings");
}
// POST
protected override DriverResult Editor(FacebookSuiteSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
{
updater.TryUpdateModel(part, Prefix, null, null);
return Editor(part, shapeHelper);
}
}
} | 35.636364 | 122 | 0.630952 | [
"BSD-3-Clause"
] | Lombiq/Orchard-Facebook-Suite | Drivers/FacebookSuiteSettingsPartDriver.cs | 1,178 | C# |
using ImageCircle.Forms.Plugin.Abstractions;
using Xamarin.Forms;
namespace TicketToTalk
{
/// <summary>
/// Invitation cell.
/// </summary>
public class InvitationCell : ViewCell
{
CircleImage personProfileImage;
Label nameLabel;
Label relation;
public InvitationCell()
{
personProfileImage = new CircleImage
{
BorderColor = ProjectResource.color_blue,
BorderThickness = 2,
HeightRequest = 75,
WidthRequest = 75,
Aspect = Aspect.AspectFill,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
};
personProfileImage.SetBinding(Image.SourceProperty, "imageSource");
nameLabel = new Label
{
};
nameLabel.SetSubHeaderStyle();
nameLabel.VerticalOptions = LayoutOptions.Start;
nameLabel.SetBinding(Label.TextProperty, "person_name");
relation = new Label
{
};
relation.SetBodyStyle();
relation.VerticalOptions = LayoutOptions.Start;
relation.TextColor = ProjectResource.color_red;
relation.SetBinding(Label.TextProperty, new Binding("name", stringFormat: "Invited by {0}"));
var detailsStack = new StackLayout
{
Padding = new Thickness(10, 0, 0, 0),
Spacing = 2,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
Children =
{
nameLabel,
relation
}
};
var cellLayout = new StackLayout
{
Spacing = 0,
Padding = new Thickness(10, 5, 10, 5),
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.FillAndExpand,
Children =
{
personProfileImage,
detailsStack
}
};
this.View = cellLayout;
}
}
}
| 22.519481 | 96 | 0.672434 | [
"BSD-3-Clause"
] | digitalinteraction/ticket-to-talk-client | TicketToTalk/ViewModels/InvitationCell.cs | 1,736 | C# |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace SharpNeat.Utility
{
/// <summary>
/// General purpose static utility methods.
/// </summary>
public static class Utilities
{
/// <summary>
/// Randomly shuffles items within a list.
/// </summary>
/// <param name="list">The list to shuffle.</param>
/// <param name="rng">Random number generator.</param>
public static void Shuffle<T>(IList<T> list, FastRandom rng)
{
// This approach was suggested by Jon Skeet in a dotNet newsgroup post and
// is also the technique used by the OpenJDK. The use of rnd.Next(i+1) introduces
// the possibility of swapping an item with itself, I suspect the reasoning behind this
// has to do with ensuring the probability of each possible permutation is approximately equal.
for (int i=list.Count-1; i>0; i--)
{
int swapIndex = rng.Next(i+1);
T tmp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = tmp;
}
}
/// <summary>
/// Rounds up or down to a whole number by using the fractional part of the input value
/// as the probability that the value will be rounded up.
///
/// This is useful if we wish to round values and then sum them without generating a rounding bias.
/// For monetary rounding this problem is solved with rounding to e.g. the nearest even number which
/// then causes a bias towards even numbers.
///
/// This solution is more appropriate for certain types of scientific values.
/// </summary>
public static double ProbabilisticRound(double val, FastRandom rng)
{
double integerPart = Math.Floor(val);
double fractionalPart = val - integerPart;
return rng.NextDouble() < fractionalPart ? integerPart + 1.0 : integerPart;
}
/// <summary>
/// Calculates the median value in a list of sorted values.
/// </summary>
public static double CalculateMedian(IList<double> valueList)
{
Debug.Assert(valueList.Count != 0 && IsSorted(valueList), "CalculateMedian() requires non-zero length sorted list of values.");
if(valueList.Count == 1) {
return valueList[0];
}
if(valueList.Count % 2 == 0)
{ // Even number of values. The values are already sorted so we simply take the
// mean of the two central values.
int idx = valueList.Count / 2;
return (valueList[idx-1] + valueList[idx]) / 2.0;
}
// Odd number of values. Return the middle value.
// (integer division truncates fractional part of result).
return valueList[valueList.Count/2];
}
/// <summary>
/// Indicates if a list of doubles is sorted into ascending order.
/// </summary>
public static bool IsSorted(IList<double> valueList)
{
if(0 == valueList.Count) {
return true;
}
double prev = valueList[0];
int count = valueList.Count;
for(int i=1; i<count; i++)
{
if(valueList[i] < prev) {
return false;
}
prev = valueList[i];
}
return true;
}
/// <summary>
/// Calculate a frequency distribution for the provided array of values.
/// 1) The minimum and maximum values are found.
/// 2) The resulting value range is divided into equal sized sub-ranges (categoryCount).
/// 3) The number of values that fall into each category is determined.
/// </summary>
public static FrequencyDistributionData CalculateDistribution(double[] valArr, int categoryCount)
{
// Determine min/max.
double min = valArr[0];
double max = min;
for(int i=1; i<valArr.Length; i++)
{
double val = valArr[i];
if(val < min) {
min = val;
}
else if(val > max) {
max = val;
}
}
double range = max - min;
// Handle special case where the data series contains a single value.
if(0.0 == range) {
return new FrequencyDistributionData(min, max, 0.0, new int[]{valArr.Length});
}
// Loop values and for each one increment the relevant category's frequency count.
double incr = range / (categoryCount-1);
int[] frequencyArr = new int[categoryCount];
for(int i=0; i<valArr.Length; i++)
{
frequencyArr[(int)((valArr[i]-min)/incr)]++;
}
return new FrequencyDistributionData(min, max, incr, frequencyArr);
}
public static double MagnifyFitnessRange(double x, double metricThreshold, double metricMax, double fitnessThreshold, double fitnessMax)
{
if(x < 0.0) {
x = 0.0;
}
else if (x > metricMax) {
x = metricMax;
}
if(x > metricThreshold)
{
return ((x - metricThreshold) / (metricMax - metricThreshold) * (fitnessMax - fitnessThreshold)) + fitnessThreshold;
}
// else
return (x / metricThreshold) * fitnessThreshold;
}
}
}
| 37.885057 | 144 | 0.557342 | [
"MIT"
] | FrozenSonar/Fencing3DNEAT | Assets/UnitySharpNEAT/SharpNEAT/Utility/Utilities.cs | 6,592 | C# |
#region Copyright
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Phoenix Contact GmbH & Co KG
// This software is licensed under Apache-2.0
//
///////////////////////////////////////////////////////////////////////////////
#endregion
using System;
namespace PlcNext.Common.Tools.UI
{
public interface IProgressNotifier : IDisposable
{
void TickIncrement(double addedProgress = 1.0, string message = "");
void Tick(double totalProgress, string message = "");
IProgressNotifier Spawn(double maxTicks, string startMessage = "");
IDisposable SpawnInfiniteProgress(string startMessage);
}
}
| 28.6 | 80 | 0.516084 | [
"Apache-2.0"
] | PLCnext/PLCnext_CLI | src/PlcNext.Common/Tools/UI/IProgressNotifier.cs | 717 | C# |
// ReSharper disable All
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using MixERP.Net.Core.Modules.HRM.Data;
using MixERP.Net.EntityParser;
using PetaPoco;
using CustomField = PetaPoco.CustomField;
namespace MixERP.Net.Api.HRM.Fakes
{
public class ResignationScrudViewRepository : IResignationScrudViewRepository
{
public long Count()
{
return 1;
}
public IEnumerable<MixERP.Net.Entities.HRM.ResignationScrudView> Get()
{
return Enumerable.Repeat(new MixERP.Net.Entities.HRM.ResignationScrudView(), 1);
}
public IEnumerable<MixERP.Net.Entities.HRM.ResignationScrudView> GetPaginatedResult()
{
return Enumerable.Repeat(new MixERP.Net.Entities.HRM.ResignationScrudView(), 1);
}
public IEnumerable<MixERP.Net.Entities.HRM.ResignationScrudView> GetPaginatedResult(long pageNumber)
{
return Enumerable.Repeat(new MixERP.Net.Entities.HRM.ResignationScrudView(), 1);
}
public IEnumerable<DisplayField> GetDisplayFields()
{
return Enumerable.Repeat(new DisplayField(), 1);
}
public long CountWhere(List<EntityParser.Filter> filters)
{
return 1;
}
public IEnumerable<MixERP.Net.Entities.HRM.ResignationScrudView> GetWhere(long pageNumber, List<EntityParser.Filter> filters)
{
return Enumerable.Repeat(new MixERP.Net.Entities.HRM.ResignationScrudView(), 1);
}
public List<EntityParser.Filter> GetFilters(string catalog, string filterName)
{
return Enumerable.Repeat(new EntityParser.Filter(), 1).ToList();
}
public long CountFiltered(string filterName)
{
return 1;
}
public IEnumerable<MixERP.Net.Entities.HRM.ResignationScrudView> GetFiltered(long pageNumber, string filterName)
{
return Enumerable.Repeat(new MixERP.Net.Entities.HRM.ResignationScrudView(), 1);
}
}
} | 31.149254 | 133 | 0.662674 | [
"MPL-2.0"
] | asine/mixerp | src/FrontEnd/Modules/HRM.API/Fakes/ResignationScrudViewRepository.cs | 2,087 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace Lab03
{
public partial class Persona : Form
{
SqlConnection conn;
public Persona(SqlConnection conn)
{
this.conn = conn;
InitializeComponent();
}
private void Persona_Load(object sender, EventArgs e)
{
}
private void btnListar_Click(object sender, EventArgs e)
{
if (conn.State == ConnectionState.Open)
{
String sql = "SELECT * FROM Person";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
dgvListado.DataSource = dt;
dgvListado.Refresh();
}
else
{
MessageBox.Show("La conexion esta Cerrada");
}
}
private void btnBuscar_Click(object sender, EventArgs e)
{
if (conn.State == ConnectionState.Open)
{
String FirstName = txtNombre.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "BuscarPersonaNombre";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
SqlParameter param = new SqlParameter();
param.ParameterName = "FirstName";
param.SqlDbType = SqlDbType.NVarChar;
param.Value = FirstName;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
dgvListado.DataSource = dt;
dgvListado.Refresh();
}
else
{
MessageBox.Show("La conexion es cerrada");
}
}
}
}
| 27.708861 | 64 | 0.531293 | [
"MIT"
] | Michael-C914/DAEA-2021-2-A | lab04/Persona.cs | 2,191 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BufferTests.cs" company="Email Hippo Ltd">
// © Email Hippo Ltd
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Furysoft.Queuing.AzureStorage.Tests.Integration.Buffer
{
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Entities.Configuration;
using Logic;
using Mocks;
using NUnit.Framework;
using Serializers;
using Serializers.Entities;
using TestHelpers;
using Versioning;
using Buffer = Logic.Pump.Buffer;
/// <summary>
/// The Buffer Tests
/// </summary>
[TestFixture]
public sealed class BufferTests : TestBase
{
/// <summary>
/// Processes the buffer asynchronous when messages on buffer expect sent to queue.
/// </summary>
/// <returns>The <see cref="Task"/></returns>
[Test]
public async Task ProcessBufferAsync_WhenMessagesOnBuffer_ExpectSentToQueue()
{
// Arrange
const SerializerType SerializerType = SerializerType.Json;
var queueWrapper = new MockQueueWrapper();
var batchSettings = new BatchSettings { MaxQueueMessagesPerSchedule = 10, MaxMessagesPerQueueMessage = 10 };
var serializerSettings = new SerializerSettings { SerializerType = SerializerType };
var messageSerializer = new MessageSerializer(serializerSettings);
var queueMessageSerializer = new QueueMessageSerializer(batchSettings, messageSerializer);
var buffer = new Buffer(this.LoggerFactory, queueWrapper, queueMessageSerializer);
// Act
var stopwatch = Stopwatch.StartNew();
buffer.AddMessage(new TestEntity { Data = "d1" });
buffer.AddMessage(new TestEntity { Data = "d2" });
buffer.AddMessage(new TestEntity { Data = "d3" });
await buffer.ProcessBufferAsync(CancellationToken.None).ConfigureAwait(false);
stopwatch.Stop();
// Assert
this.WriteTimeElapsed(stopwatch);
var cloudQueueMessage = queueWrapper.Get();
Assert.That(cloudQueueMessage, Is.Not.Null);
var asString = cloudQueueMessage.AsString;
var batchedVersionedMessage = asString.Deserialize<BatchedVersionedMessage>(SerializerType);
Assert.That(batchedVersionedMessage, Is.Not.Null);
var messages = batchedVersionedMessage.Messages.ToList();
Assert.That(messages.Count, Is.EqualTo(3));
Assert.That(messages.All(r => r.Version == new DtoVersion(typeof(TestEntity), 1, 0, 0)), Is.True);
}
}
} | 36.607595 | 120 | 0.595436 | [
"MIT"
] | Furysoft/Queuing-AuzreStorage | src/Tests/Furysoft.Queuing.AzureStorage.Tests/Integration/Buffer/BufferTests.cs | 2,895 | C# |
/*
* Copyright 2020 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 kafka-2018-11-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Kafka.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Kafka.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for TooManyRequestsException Object
/// </summary>
public class TooManyRequestsExceptionUnmarshaller : IErrorResponseUnmarshaller<TooManyRequestsException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public TooManyRequestsException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public TooManyRequestsException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse)
{
context.Read();
TooManyRequestsException unmarshalledObject = new TooManyRequestsException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("invalidParameter", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.InvalidParameter = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static TooManyRequestsExceptionUnmarshaller _instance = new TooManyRequestsExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static TooManyRequestsExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.802198 | 139 | 0.657152 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Kafka/Generated/Model/Internal/MarshallTransformations/TooManyRequestsExceptionUnmarshaller.cs | 3,258 | C# |
// Copyright © 2020 Dmitry Sikorsky. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using ExtCore.Infrastructure;
using Microsoft.AspNetCore.Http;
namespace Platformus.Core.Backend.Metadata.Providers
{
public class DefaultStyleSheetsProvider : IStyleSheetsProvider
{
public IEnumerable<StyleSheet> GetStyleSheets(HttpContext httpContext)
{
return ExtensionManager.GetInstances<IMetadata>()
.SelectMany(m => m.GetStyleSheets(httpContext))
.OrderBy(ss => ss.Position);
}
}
} | 32.7 | 111 | 0.75841 | [
"Apache-2.0"
] | Platformus/Platformus | src/Platformus.Core.Backend/Metadata/Providers/DefaultStyleSheetsProvider.cs | 657 | C# |
using System;
namespace Amns.GreyFox.People
{
/// <summary>
/// Summary description for AddressParser.
/// </summary>
public class AddressParser
{
string _fullAddress;
public AddressParser()
{
//
// TODO: Add constructor logic here
//
}
public void Parse(string address)
{
bool caps = true; // Capitalize this character
bool holdCaps = false; // Capitalize next character
bool wordBreak = false; // Wordbreak
char c;
char[] chars = address.ToCharArray();
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
string word;
System.Text.StringBuilder output = new System.Text.StringBuilder();
string[,] dic = new string[,]
{
{"Mc^", "Mc"},
{"#rd", "rd"},
{"#th", "th"},
{"#st", "st"},
{"ne", "NE"},
{"nw", "NW"},
{"se", "SE"},
{"sw", "SW"},
};
for(int index = 0; index <= chars.GetUpperBound(0); index++)
{
c = chars[index];
wordBreak =
char.IsWhiteSpace(c) |
char.IsSeparator(c);
holdCaps =
wordBreak |
char.IsPunctuation(c);
char.IsNumber(c);
if(!wordBreak)
{
if(caps)
{
c = char.ToUpper(c);
}
buffer.Append(c);
}
else
{
word = buffer.ToString();
for(int x = 0; x < dic.GetUpperBound(0); x++)
{
if(dic[x,0].EndsWith("^"))
{
if(word == dic[x,0].Substring(0, dic[x,0].Length - 1))
{
holdCaps = true;
word = dic[x,1];
break;
}
}
if(dic[x,0].StartsWith("#"))
{
if(word == dic[x,0].Substring(1))
{
word = dic[x,1];
break;
}
}
if(dic[x,0].StartsWith("."))
{
if(word.Replace(".", "") == dic[x,0].Substring(1))
{
word = dic[x,1];
break;
}
}
}
output.Append(word);
output.Append(c);
buffer.Length = 0;
}
caps = holdCaps;
}
_fullAddress = output.ToString();
}
}
} | 18.354545 | 70 | 0.497276 | [
"MIT"
] | rahodges/Amns | Amns.GreyFox/People/AddressParser.cs | 2,019 | C# |
using System;
class MethodArray
{
static void Main()
{
int[] arry1 = new int[5];
int[] arry2 = new int[5];
int[] arry3 = new int[5];
int[,] matriz = { { 11, 22, 00, 44, 55 }, { 66, 77, 88, 99, 00 } };
// método Random sorteamos 5 valores entre 1 e 60 e preenchemos o arry1
Random random = new Random();
for (int i = 0; i < arry1.Length; i++)
{
arry1[i] = random.Next(1, 60); // metodo random eu posso escolher o valor minimo ou maximo
}
foreach (int elements in arry1)
{
Console.WriteLine(elements);
}
//pesquisar valor dentro de um array: public static int BinarySearch(array,valor);
Console.WriteLine("BinarySearch");
int SearchValue = 33;
int indice = Array.BinarySearch(arry1, SearchValue);
Console.WriteLine("O valor {0} está na posição {1}", SearchValue, indice);
Console.WriteLine("----------------------------------------------");
// copiando uma array com Copy
Console.WriteLine("Copy");
Array.Copy(arry1, arry2, arry1.Length);
foreach (int items in arry2)
{
Console.WriteLine(items);
}
Console.WriteLine("----------------------------------------------");
// Copiando um array a partir do vetor com Copyto
Console.WriteLine("Copyto");
arry1.CopyTo(arry3, 0);
foreach (int items in arry3)
{
Console.WriteLine(items);
}
Console.WriteLine("----------------------------------------------");
// GetLongLenght retorna a dimensão do array0
Console.WriteLine("GetLongLenght");
long qtdeElementosVetor = arry1.GetLongLength(0);
Console.WriteLine("Quantidade de elementos {0}", qtdeElementosVetor);
Console.WriteLine("----------------------------------------------");
// GetlowerBound retorna o menor indice de um array ou matriz no caso de array o parâmetro é zero e matriz é necessário indicar a dimensão.
Console.WriteLine("GetLowerBound");
int LowIndice = arry1.GetLowerBound(0);
int lowIndiceMatriz_d1 = matriz.GetLowerBound(1);
Console.WriteLine("Menor indice do arry1 {0}", LowIndice);
Console.WriteLine("Menor indice da matriz {0}", lowIndiceMatriz_d1);
Console.WriteLine("----------------------------------------------");
// GetUpperBound retorna o maior inice nas mesmas regras do método anterior
// GetValue retorna um valor através de um indice, nesse caso se trata de um object é necessário converterlo com catch
Console.WriteLine("GetValue");
int v1 = (int)arry1.GetValue(3);
Console.WriteLine("Valor na posição 3 do arry1 {0}", v1);
Console.WriteLine("----------------------------------------------");
// Indexof retorna o indice através de um valor indicador, no caso de elementos repetido ele retorna apenas o valor da primeira incidência
Console.WriteLine("IndexOf");
int indice1 = Array.IndexOf(arry1, 3);
Console.WriteLine("Indice do primeiro valor 3: {0}", indice1);
Console.WriteLine("----------------------------------------------");
// LastIndexOp retora a oposição do indice do ultimo valor
Console.WriteLine("LastIndexOf");
int indice2 = Array.LastIndexOf(arry1, 3);
Console.WriteLine("Indice do ultimo valor 3: {0}", indice2);
Console.WriteLine("----------------------------------------------");
// Reverse inverte a ordem dos elementos
Console.WriteLine("Reverse");
Array.Reverse(arry1);
foreach (int items in arry1)
{
Console.WriteLine(items);
}
Console.WriteLine("----------------------------------------------");
// SetValue Defini um valor em uma posição no array
Console.WriteLine("SetValue");
arry2.SetValue(99, 0); //inserimos o valor 99 na posição zero do segundo array
for (int i = 0; i < arry2.Length; i++)
{
arry2.SetValue(0, i);
}
Console.WriteLine("Vetor 2");
foreach (int items in arry2)
{
Console.WriteLine(items);
}
Console.WriteLine("----------------------------------------------");
// Sort ordena o valor em ordem crescente do array
Console.WriteLine("Sort");
Array.Sort(arry1);
Array.Sort(arry2);
Array.Sort(arry3);
Console.WriteLine("Arry1");
foreach (int items in arry1)
{
Console.WriteLine(items);
}
Console.WriteLine("Arry2");
foreach (int items in arry2)
{
Console.WriteLine(items);
}
Console.WriteLine("Arry3");
foreach (int items in arry3)
{
Console.WriteLine(items);
}
}
} | 38.609375 | 147 | 0.534197 | [
"MIT"
] | AlamoVinicius/cSharp-pratice | pratices/14-metodos/MethodArray.cs | 4,966 | C# |
namespace FocLauncher
{
public enum ApplicationType
{
Stable,
Beta,
//Alpha,
Test
}
} | 13 | 31 | 0.492308 | [
"MIT"
] | AnakinSklavenwalker/FoC-Mod-Launcher | src/FocLauncher.Core/Information/ApplicationType.cs | 132 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Discord.Net.Audio")]
[assembly: AssemblyDescription("A Discord.Net extension adding voice support.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("RogueException")]
[assembly: AssemblyProduct("Discord.Net.Modules")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("76ea00e6-ea24-41e1-acb2-639c0313fa80")]
[assembly: AssemblyVersion("0.9.2.0")]
[assembly: AssemblyFileVersion("0.9.2.0")]
| 32.421053 | 80 | 0.766234 | [
"MIT"
] | Asian-Demon-Blast/KitDiscord | src/Discord.Net.Audio.Net45/Properties/AssemblyInfo.cs | 619 | C# |
//---------------------------------------------------------------------------
//
// <copyright file="CollectionSynchronizationCallback.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Delegate used to synchronize access to multi-threaded collections.
//
// See spec at http://sharepoint/sites/WPF/Specs/Shared%20Documents/v4.5/Cross-thread%20Collections.docx
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
namespace System.Windows.Data
{
///<summary>
/// An application that wishes to allow WPF to participate in synchronized
/// (multi-threaded) access to a collection can register a callback matching
/// the CollectionSynchronizationCallback delegate. WPF will then invoke
/// the callback to access the collection.
///</summary>
///<param name="collection"> The collection that the caller intends to access. </param>
///<param name="context"> An object supplied by the application at registration
/// time. See BindingOperations.EnableCollectionSynchronization. </param>
///<param name="accessMethod"> The method that performs the caller's desired access. </param>
///<param name="writeAccess"/> True if the caller needs write access to the collection,
/// false if the caller needs only read access. </param>
///<notes>
/// The method supplied by the application should do the following steps:
/// 1. Determine the synchronization mechanism used by the application
/// to govern access to the given collection. The context object
/// can be used to help with this step.
/// 2. Ensure the desired access to the collection. This is read-access
/// or write-access, depending on the value of writeAccess.
/// 3. Invoke the access method.
/// 4. Release the access to the collection, if appropriate.
///</notes>
public delegate void CollectionSynchronizationCallback(
IEnumerable collection,
object context,
Action accessMethod,
bool writeAccess
);
}
| 46.020833 | 104 | 0.63694 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/wpf/src/Framework/System/Windows/Data/CollectionSynchronizationCallback.cs | 2,209 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using ASPEntityCore_05_Movie.Models;
using SPEntityCore_05_Movie.Models;
namespace ASPEntityCore_05_Movie.Pages.Models
{
public class DeleteModel : PageModel
{
private readonly ASPEntityCore_05_Movie.Models.ASPEntityCore_05_MovieContext _context;
public DeleteModel(ASPEntityCore_05_Movie.Models.ASPEntityCore_05_MovieContext context)
{
_context = context;
}
[BindProperty]
public Movie Movie { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
Movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
if (Movie == null)
{
return NotFound();
}
return Page();
}
public async Task<IActionResult> OnPostAsync(int? id)
{
if (id == null)
{
return NotFound();
}
Movie = await _context.Movie.FindAsync(id);
if (Movie != null)
{
_context.Movie.Remove(Movie);
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
}
}
| 25.116667 | 95 | 0.572661 | [
"MIT"
] | philanderson888/c-sharp | ASP_Core_Movie_05/Pages/Models/Delete.cshtml.cs | 1,509 | C# |
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_FairyGUI_ColliderHitTest : LuaObject {
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetArea(IntPtr l) {
try {
FairyGUI.ColliderHitTest self=(FairyGUI.ColliderHitTest)checkSelf(l);
System.Single a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
System.Single a3;
checkType(l,4,out a3);
System.Single a4;
checkType(l,5,out a4);
self.SetArea(a1,a2,a3,a4);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetEnabled(IntPtr l) {
try {
FairyGUI.ColliderHitTest self=(FairyGUI.ColliderHitTest)checkSelf(l);
System.Boolean a1;
checkType(l,2,out a1);
self.SetEnabled(a1);
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int HitTest(IntPtr l) {
try {
FairyGUI.ColliderHitTest self=(FairyGUI.ColliderHitTest)checkSelf(l);
FairyGUI.Container a1;
checkType(l,2,out a1);
UnityEngine.Vector2 a2;
checkType(l,3,out a2);
var ret=self.HitTest(a1,ref a2);
pushValue(l,true);
pushValue(l,ret);
pushValue(l,a2);
return 3;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_collider(IntPtr l) {
try {
FairyGUI.ColliderHitTest self=(FairyGUI.ColliderHitTest)checkSelf(l);
pushValue(l,true);
pushValue(l,self.collider);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int set_collider(IntPtr l) {
try {
FairyGUI.ColliderHitTest self=(FairyGUI.ColliderHitTest)checkSelf(l);
UnityEngine.Collider v;
checkType(l,2,out v);
self.collider=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
static public void reg(IntPtr l) {
getTypeTable(l,"FairyGUI.ColliderHitTest");
addMember(l,SetArea);
addMember(l,SetEnabled);
addMember(l,HitTest);
addMember(l,"collider",get_collider,set_collider,true);
createTypeMetatable(l,null, typeof(FairyGUI.ColliderHitTest));
}
}
| 25.16129 | 72 | 0.708547 | [
"MIT"
] | zhangjie0072/FairyGUILearn | Assets/Slua/LuaObject/Custom/Lua_FairyGUI_ColliderHitTest.cs | 2,342 | C# |
namespace YuGiOhCollectionSupporter
{
partial class CardForm
{
/// <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.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.label6 = new System.Windows.Forms.Label();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.略号 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.パック名 = new System.Windows.Forms.DataGridViewLinkColumn();
this.レアリティ = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.所持 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.flowLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Font = new System.Drawing.Font("MS UI Gothic", 20F);
this.linkLabel1.Location = new System.Drawing.Point(10, 10);
this.linkLabel1.Margin = new System.Windows.Forms.Padding(10, 10, 3, 0);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(125, 27);
this.linkLabel1.TabIndex = 0;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "linkLabel1";
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(10, 47);
this.label1.Margin = new System.Windows.Forms.Padding(10, 10, 3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 12);
this.label1.TabIndex = 1;
this.label1.Text = "label1";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(10, 69);
this.label2.Margin = new System.Windows.Forms.Padding(10, 10, 3, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 12);
this.label2.TabIndex = 2;
this.label2.Text = "label2";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("MS UI Gothic", 15F);
this.label3.Location = new System.Drawing.Point(10, 91);
this.label3.Margin = new System.Windows.Forms.Padding(10, 10, 3, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(0, 20);
this.label3.TabIndex = 3;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("MS UI Gothic", 9F);
this.label4.Location = new System.Drawing.Point(10, 156);
this.label4.Margin = new System.Windows.Forms.Padding(10, 15, 3, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(84, 12);
this.label4.TabIndex = 4;
this.label4.Text = "ペンデュラム効果";
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Right;
this.textBox1.Location = new System.Drawing.Point(10, 173);
this.textBox1.Margin = new System.Windows.Forms.Padding(10, 5, 3, 3);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(637, 60);
this.textBox1.TabIndex = 5;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("MS UI Gothic", 9F);
this.label5.Location = new System.Drawing.Point(10, 251);
this.label5.Margin = new System.Windows.Forms.Padding(10, 15, 3, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(69, 12);
this.label5.TabIndex = 6;
this.label5.Text = "カードテキスト";
//
// textBox2
//
this.textBox2.Dock = System.Windows.Forms.DockStyle.Right;
this.textBox2.Location = new System.Drawing.Point(10, 268);
this.textBox2.Margin = new System.Windows.Forms.Padding(10, 5, 3, 3);
this.textBox2.Multiline = true;
this.textBox2.Name = "textBox2";
this.textBox2.ReadOnly = true;
this.textBox2.Size = new System.Drawing.Size(637, 60);
this.textBox2.TabIndex = 7;
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.略号,
this.パック名,
this.レアリティ,
this.所持});
this.dataGridView1.Location = new System.Drawing.Point(10, 341);
this.dataGridView1.Margin = new System.Windows.Forms.Padding(10, 10, 3, 3);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.RowTemplate.Height = 21;
this.dataGridView1.RowTemplate.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridView1.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal;
this.dataGridView1.Size = new System.Drawing.Size(637, 97);
this.dataGridView1.TabIndex = 8;
this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
this.dataGridView1.CurrentCellDirtyStateChanged += new System.EventHandler(this.dataGridView1_CurrentCellDirtyStateChanged);
this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("MS UI Gothic", 15F);
this.label6.Location = new System.Drawing.Point(10, 121);
this.label6.Margin = new System.Windows.Forms.Padding(10, 10, 3, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(57, 20);
this.label6.TabIndex = 9;
this.label6.Text = "label6";
//
// checkBox1
//
this.checkBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.checkBox1.AutoSize = true;
this.checkBox1.Checked = true;
this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox1.Location = new System.Drawing.Point(491, 48);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(155, 16);
this.checkBox1.TabIndex = 10;
this.checkBox1.Text = "このカードを一覧に表示する";
this.checkBox1.UseVisualStyleBackColor = true;
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.flowLayoutPanel1.Controls.Add(this.linkLabel1);
this.flowLayoutPanel1.Controls.Add(this.label1);
this.flowLayoutPanel1.Controls.Add(this.label2);
this.flowLayoutPanel1.Controls.Add(this.label3);
this.flowLayoutPanel1.Controls.Add(this.label6);
this.flowLayoutPanel1.Controls.Add(this.label4);
this.flowLayoutPanel1.Controls.Add(this.textBox1);
this.flowLayoutPanel1.Controls.Add(this.label5);
this.flowLayoutPanel1.Controls.Add(this.textBox2);
this.flowLayoutPanel1.Controls.Add(this.dataGridView1);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(658, 450);
this.flowLayoutPanel1.TabIndex = 11;
//
// 略号
//
this.略号.HeaderText = "略号";
this.略号.Name = "略号";
this.略号.ReadOnly = true;
this.略号.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.略号.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// パック名
//
this.パック名.HeaderText = "パック名";
this.パック名.Name = "パック名";
this.パック名.ReadOnly = true;
this.パック名.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.パック名.Width = 300;
//
// レアリティ
//
this.レアリティ.HeaderText = "レアリティ";
this.レアリティ.Name = "レアリティ";
this.レアリティ.ReadOnly = true;
this.レアリティ.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// 所持
//
this.所持.HeaderText = "所持";
this.所持.Name = "所持";
this.所持.Width = 50;
//
// CardForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ClientSize = new System.Drawing.Size(658, 450);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.flowLayoutPanel1);
this.Name = "CardForm";
this.Text = "カード情報";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.flowLayoutPanel1.ResumeLayout(false);
this.flowLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.DataGridViewTextBoxColumn 略号;
private System.Windows.Forms.DataGridViewLinkColumn パック名;
private System.Windows.Forms.DataGridViewTextBoxColumn レアリティ;
private System.Windows.Forms.DataGridViewCheckBoxColumn 所持;
}
} | 48.956204 | 159 | 0.600194 | [
"MIT"
] | SorabaneSAI/YuGiOhCollectionSupporter | YuGiOhCollectionSupporter/YuGiOhCollectionSupporter/UI/CardForm.Designer.cs | 13,750 | C# |
using System;
namespace ExternalA
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Hello {0}!", typeof(Microsoft.CodeAnalysis.SyntaxNode));
}
}
}
| 14.846154 | 79 | 0.683938 | [
"MIT"
] | kzu/UltimateNuGetRestore | External/ExternalA/ExternalA/Program.cs | 195 | C# |
namespace Neuralm.Services.Common.Patterns
{
/// <summary>
/// Represents the <see cref="IFactory{TResult}"/> interface for the Factory pattern.
/// </summary>
/// <typeparam name="TResult">Factory output result.</typeparam>
public interface IFactory<out TResult>
{
/// <summary>
/// Creates a new instance of <see cref="TResult"/>.
/// </summary>
/// <returns>Returns a new instance of <see cref="TResult"/>.</returns>
TResult Create();
}
/// <summary>
/// Represents the <see cref="IFactory{TResult, TParameter}"/> interface for the Factory pattern with an argument.
/// </summary>
/// <typeparam name="TResult">Factory output result.</typeparam>
/// <typeparam name="TParameter">Factory argument.</typeparam>
public interface IFactory<out TResult, in TParameter>
{
/// <summary>
/// Creates a new instance of <see cref="TResult"/>.
/// </summary>
/// <param name="parameter">The parameter.</param>
/// <returns>Returns a new instance of <see cref="TResult"/>.</returns>
TResult Create(TParameter parameter);
}
/// <summary>
/// Represents the <see cref="IFactory{TResult, TParameter1, TParameter2}"/> interface for the Factory pattern with two arguments.
/// </summary>
/// <typeparam name="TResult">Factory output result.</typeparam>
/// <typeparam name="TParameter1">Factory argument 1.</typeparam>
/// <typeparam name="TParameter2">Factory argument 2.</typeparam>
public interface IFactory<out TResult, in TParameter1, in TParameter2>
{
/// <summary>
/// Creates a new instance of <see cref="TResult"/>.
/// </summary>
/// <param name="parameter1">The parameter 1.</param>
/// <param name="parameter2">The parameter 2.</param>
/// <returns>Returns a new instance of <see cref="TResult"/>.</returns>
TResult Create(TParameter1 parameter1, TParameter2 parameter2);
}
}
| 42 | 134 | 0.626488 | [
"MIT"
] | neuralm/Neuralm-Server | src/Neuralm.Services/Neuralm.Services.Common/Patterns/IFactory.cs | 2,018 | C# |
using Ao.SavableConfig.Binder;
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace Ao.SavableConfig.Benchmark
{
[MemoryDiagnoser]
public class ConfigBind
{
private IConfiguration config;
[GlobalSetup]
public void Init()
{
var builder = new ConfigurationBuilder();
var map = new Dictionary<string, string>
{
["Name0"] = "1",
["Name1"] = "2",
["Name2"] = "3",
["Name3"] = "4",
["Name4"] = "5",
["Name:0"] = "1",
["Name:1"] = "1",
["Name:2"] = "1",
["Name:3"] = "1",
["Name:4"] = "1",
};
for (int i = 1; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
map[$"Student" + i + ":" + "Student" + j] = (i * j + j).ToString();
}
}
builder.AddInMemoryCollection(map);
config = builder.Build();
GetToType();
FastGetToType();
}
[Params(1,1000)]
public int Count { get; set; }
[Benchmark]
public void GetToType()
{
var names = new Names();
for (int i = 0; i < Count; i++)
{
ConfigurationBinder.Bind(config, names);
}
}
[Benchmark]
public void FastGetToType()
{
var names = new Names();
for (int i = 0; i < Count; i++)
{
FastConfigurationBinder.FastBind(config, names);
}
}
[Benchmark]
public void GetToList()
{
for (int i = 0; i < Count; i++)
{
ConfigurationBinder.GetValue<string[]>(config, "Name");
}
}
[Benchmark]
public void FastGetToList()
{
for (int i = 0; i < Count; i++)
{
FastConfigurationBinder.FastGetValue<string[]>(config, "Name");
}
}
}
}
| 26.518072 | 87 | 0.410268 | [
"Apache-2.0"
] | Cricle/Ao.SavableConfig | test/Ao.SavableConfig.Benchmark/ConfigBind.cs | 2,203 | C# |
namespace AspNetCoreTemplate.Web.Areas.Identity.Pages.Account
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using AspNetCoreTemplate.Data.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
[AllowAnonymous]
#pragma warning disable SA1649 // File name should match first type name
public class LoginWithRecoveryCodeModel : PageModel
#pragma warning restore SA1649 // File name should match first type name
{
private readonly SignInManager<ApplicationUser> signInManager;
private readonly ILogger<LoginWithRecoveryCodeModel> logger;
public LoginWithRecoveryCodeModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginWithRecoveryCodeModel> logger)
{
this.signInManager = signInManager;
this.logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public async Task<IActionResult> OnGetAsync(string returnUrl = null)
{
// Ensure the user has gone through the username & password screen first
var user = await this.signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException($"Unable to load two-factor authentication user.");
}
this.ReturnUrl = returnUrl;
return this.Page();
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
if (!this.ModelState.IsValid)
{
return this.Page();
}
var user = await this.signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException($"Unable to load two-factor authentication user.");
}
var recoveryCode = this.Input.RecoveryCode.Replace(" ", string.Empty);
var result = await this.signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
if (result.Succeeded)
{
this.logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", user.Id);
return this.LocalRedirect(returnUrl ?? this.Url.Content("~/"));
}
if (result.IsLockedOut)
{
this.logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);
return this.RedirectToPage("./Lockout");
}
else
{
this.logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", user.Id);
this.ModelState.AddModelError(string.Empty, "Invalid recovery code entered.");
return this.Page();
}
}
public class InputModel
{
[BindProperty]
[Required]
[DataType(DataType.Text)]
[Display(Name = "Recovery Code")]
public string RecoveryCode { get; set; }
}
}
}
| 35.042553 | 131 | 0.611111 | [
"MIT"
] | Abhinavchamallamudi/ASP.NET-MVC-Template | ASP.NET Core/Web/AspNetCoreTemplate.Web/Areas/Identity/Pages/Account/LoginWithRecoveryCode.cshtml.cs | 3,296 | C# |
using System;
using System.Data.SqlClient;
using CommonFiles;
namespace Add_Minion
{
public class StartUp
{
public static void Main()
{
var minionTokens = Console.ReadLine().Split();
var villainName = Console.ReadLine().Split()[1];
var minionName = minionTokens[1];
var age = int.Parse(minionTokens[2]);
var town = minionTokens[3];
using (var connection = new SqlConnection(Configuration.connectionParams))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
try
{
var townId = ExecuteScalar(string.Format(Statments.getTown, town), connection);
if (townId is null)
{
ExecuteNonQuerry(string.Format(Statments.insertTown, town), connection);
Print($"Town {town} was added to the database.");
townId = ExecuteScalar(string.Format(Statments.getTown, town), connection);
}
var villainId = ExecuteScalar(string.Format(Statments.getVillain, villainName), connection);
if (villainId is null)
{
ExecuteNonQuerry(string.Format(Statments.insertVillain, villainName), connection);
villainId = ExecuteScalar(string.Format(Statments.getVillain, villainName), connection);
Print($"Villain {villainName} was added to the database.");
}
ExecuteNonQuerry(string.Format(Statments.insertMinion, minionName, age, townId), connection);
var minionId = ExecuteScalar(string.Format(Statments.getMinion, minionName), connection);
ExecuteNonQuerry(string.Format(Statments.insertMinionAndVillain, minionId, villainId), connection);
Print($"Successfully added {minionName} to be minion of {villainName}.");
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
}
}
static void Print(string text) => Console.WriteLine(text);
static object ExecuteScalar(string query, SqlConnection connection)
{
return new SqlCommand(query, connection).ExecuteScalar();
}
static int ExecuteNonQuerry(string query, SqlConnection connection)
{
return new SqlCommand(query, connection).ExecuteNonQuery();
}
}
} | 38.884058 | 119 | 0.559448 | [
"MIT"
] | DimoDD/Databases | Entity-Framework/01.Fetching Results With AdoNet/04.Add Minion/StartUp.cs | 2,685 | C# |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
namespace Subtext.Framework.Email
{
public interface ITextTemplate
{
string Format(object data);
}
} | 32.791667 | 99 | 0.545108 | [
"MIT",
"BSD-3-Clause"
] | Dashboard-X/SubText-2.5.2.0.src | Subtext.Framework/Services/Email/ITextTemplate.cs | 787 | C# |
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Core.Access.Identity.DB.EntitySets
{
public class ClientTokenRequest : IEntity
{
[Key]
public long Id { get; set; }
public string ClientId { get; set; }
[ForeignKey("ClientId")]
public Client Client { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public IdentityUser User { get; set; }
public string AccessToken { get; set; }
public string RefreshToken { get; set; }
public bool IsActive { get; set; }
}
}
| 23.551724 | 51 | 0.633968 | [
"MIT"
] | GitAyanC/SecurityTokenService | Core.Access/Identity/DB/EntitySets/ClientTokenRequest.cs | 685 | C# |
using System.Reflection;
using Abp.Localization.Dictionaries;
using Abp.Localization.Dictionaries.Xml;
using Abp.Modules;
using Abp.Zero;
using Abp.Zero.Configuration;
using Demo.Authorization;
using Demo.Authorization.Roles;
using Demo.Authorization.Users;
using Demo.Configuration;
using Demo.MultiTenancy;
namespace Demo
{
[DependsOn(typeof(AbpZeroCoreModule))]
public class DemoCoreModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Auditing.IsEnabledForAnonymousUsers = true;
//Declare entity types
Configuration.Modules.Zero().EntityTypes.Tenant = typeof(Tenant);
Configuration.Modules.Zero().EntityTypes.Role = typeof(Role);
Configuration.Modules.Zero().EntityTypes.User = typeof(User);
//Remove the following line to disable multi-tenancy.
Configuration.MultiTenancy.IsEnabled = DemoConsts.MultiTenancyEnabled;
//Add/remove localization sources here
Configuration.Localization.Sources.Add(
new DictionaryBasedLocalizationSource(
DemoConsts.LocalizationSourceName,
new XmlEmbeddedFileLocalizationDictionaryProvider(
Assembly.GetExecutingAssembly(),
"Demo.Localization.Source"
)
)
);
AppRoleConfig.Configure(Configuration.Modules.Zero().RoleManagement);
Configuration.Authorization.Providers.Add<DemoAuthorizationProvider>();
Configuration.Settings.Providers.Add<AppSettingProvider>();
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
}
| 33.814815 | 85 | 0.654984 | [
"MIT"
] | vinhtuanpham/ivs | src/Demo.Core/DemoCoreModule.cs | 1,828 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using VkNet.Enums;
using VkNet.Model;
using VkNet.Tests.Infrastructure;
using VkNet.Utils;
namespace VkNet.Tests
{
[TestFixture]
public class VkApiTest : BaseTest
{
[Test]
public void AuthorizeByToken()
{
Api.Authorize(new ApiAuthParams
{
AccessToken = "token",
UserId = 1
});
Assert.That(Api.UserId, Is.EqualTo(1));
}
[Test]
public async Task Call_NotMoreThen3CallsPerSecond()
{
Url = "https://api.vk.com/method/friends.getRequests";
ReadJsonFile(nameof(VkApi), nameof(Call_NotMoreThen3CallsPerSecond));
const int callsCount = 3;
Api.RequestsPerSecond = callsCount;
var taskList = new List<Task>();
var calls = 0;
for (var i = 0; i < callsCount + 1; i++)
{
taskList.Add(Api.CallAsync("friends.getRequests", VkParameters.Empty, true).ContinueWith((_) => calls++));
}
await Task.Delay(1000);
Assert.LessOrEqual(calls, callsCount);
}
[Test]
public void CallAndConvertToType()
{
Url = "https://api.vk.com/method/friends.getRequests";
ReadJsonFile(nameof(VkApi), nameof(CallAndConvertToType));
var result = Api.Call<FriendsGetRequestsResult>("friends.getRequests", VkParameters.Empty);
Assert.NotNull(result);
Assert.That(result.UserId, Is.EqualTo(221634238));
Assert.That(result.Message, Is.EqualTo("text"));
Assert.IsNotEmpty(result.Mutual);
}
[Test]
public void DefaultLanguageValue()
{
var lang = Api.GetLanguage();
Assert.IsNull(lang);
}
[Test]
public void DisposeTest()
{
Api.Dispose();
}
[Test]
public void EnglishLanguageValue()
{
Api.SetLanguage(Language.En);
var lang = Api.GetLanguage();
Assert.AreEqual(lang, Language.En);
}
[Test]
public void Invoke_DictionaryParams()
{
Url = "https://api.vk.com/method/example.get";
ReadJsonFile(JsonPaths.EmptyArray);
var parameters = new Dictionary<string, string>
{
{ "count", "23" }
};
var json = Api.Invoke("example.get", parameters, true);
StringAssert.AreEqualIgnoringCase(json, Json);
}
[Test]
public void Invoke_VkParams()
{
Url = "https://api.vk.com/method/example.get";
ReadJsonFile(JsonPaths.EmptyArray);
var parameters = new VkParameters
{
{ "count", 23 }
};
var json = Api.Invoke("example.get", parameters, true);
StringAssert.AreEqualIgnoringCase(json, Json);
}
[Test]
public void Validate()
{
var uri = new Uri("https://m.vk.com/activation?act=validate&api_hash=f2fed5f22ebadc301e&hash=c8acf371111c938417");
Api.Validate(uri.ToString());
}
[Test]
public void VkApi_Constructor_SetDefaultMethodCategories()
{
Assert.That(Api.Users, Is.Not.Null);
Assert.That(Api.Friends, Is.Not.Null);
Assert.That(Api.Status, Is.Not.Null);
Assert.That(Api.Messages, Is.Not.Null);
Assert.That(Api.Groups, Is.Not.Null);
Assert.That(Api.Audio, Is.Not.Null);
Assert.That(Api.Wall, Is.Not.Null);
Assert.That(Api.Database, Is.Not.Null);
Assert.That(Api.Utils, Is.Not.Null);
Assert.That(Api.Fave, Is.Not.Null);
Assert.That(Api.Video, Is.Not.Null);
Assert.That(Api.Account, Is.Not.Null);
Assert.That(Api.Photo, Is.Not.Null);
Assert.That(Api.Docs, Is.Not.Null);
Assert.That(Api.Likes, Is.Not.Null);
Assert.That(Api.Pages, Is.Not.Null);
Assert.That(Api.Gifts, Is.Not.Null);
Assert.That(Api.Apps, Is.Not.Null);
Assert.That(Api.NewsFeed, Is.Not.Null);
Assert.That(Api.Stats, Is.Not.Null);
Assert.That(Api.Auth, Is.Not.Null);
Assert.That(Api.Markets, Is.Not.Null);
Assert.That(Api.Ads, Is.Not.Null);
}
[Test]
public void VkCallShouldBePublic()
{
// arrange
var myType = typeof(VkApi);
var myArrayMethodInfo = myType.GetMethods();
// act
var callMethod = myArrayMethodInfo.FirstOrDefault(x => x.Name.Contains("Call"));
// Assert
Assert.IsNotNull(callMethod);
Assert.IsTrue(callMethod.IsPublic);
}
[Test]
public void VersionShouldBeenChanged()
{
Api.VkApiVersion.SetVersion(999, 0);
Assert.AreEqual("999.0", Api.VkApiVersion.Version);
}
[Test]
public void Logout()
{
Api.LogOut();
Assert.IsEmpty(Api.Token);
}
}
} | 23.434066 | 117 | 0.680188 | [
"MIT"
] | f0xeri/vk | VkNet.Tests/VkApiTest.cs | 4,265 | C# |
// <auto-generated />
using BooklistApp.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace BooklistApp.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20200316210301_AddBookToDb")]
partial class AddBookToDb
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.2")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("BooklistApp.Model.Book", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Author")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Book");
});
#pragma warning restore 612, 618
}
}
}
| 35.088889 | 125 | 0.60608 | [
"Unlicense"
] | Ivan-Marquez/net-core | BooklistApp/Migrations/20200316210301_AddBookToDb.Designer.cs | 1,581 | C# |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using SharpDX.Mathematics.Interop;
namespace SharpDX.XInput
{
internal class XInput14 : IXInput
{
public int XInputSetState(int dwUserIndex, Vibration vibrationRef)
{
return XInput.XInputSetState(dwUserIndex, ref vibrationRef);
}
public int XInputGetState(int dwUserIndex, out State stateRef)
{
return XInput.XInputGetState(dwUserIndex, out stateRef);
}
public int XInputGetAudioDeviceIds(int dwUserIndex, IntPtr renderDeviceIdRef, IntPtr renderCountRef, IntPtr captureDeviceIdRef, IntPtr captureCountRef)
{
return XInput.XInputGetAudioDeviceIds(dwUserIndex, renderDeviceIdRef, renderCountRef, captureDeviceIdRef, captureCountRef);
}
public void XInputEnable(RawBool enable)
{
XInput.XInputEnable(enable);
}
public int XInputGetBatteryInformation(int dwUserIndex, BatteryDeviceType devType, out BatteryInformation batteryInformationRef)
{
return XInput.XInputGetBatteryInformation(dwUserIndex, devType, out batteryInformationRef);
}
public int XInputGetKeystroke(int dwUserIndex, int dwReserved, out Keystroke keystrokeRef)
{
return XInput.XInputGetKeystroke(dwUserIndex, dwReserved, out keystrokeRef);
}
public int XInputGetCapabilities(int dwUserIndex, DeviceQueryType dwFlags, out Capabilities capabilitiesRef)
{
return XInput.XInputGetCapabilities(dwUserIndex, dwFlags, out capabilitiesRef);
}
}
} | 43.142857 | 159 | 0.727005 | [
"MIT"
] | Altair7610/SharpDX | Source/SharpDX.XInput/XInput14.cs | 2,718 | C# |
// Copyright © 2017 - 2021 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, 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
//
// 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 chocolatey.infrastructure.services
{
using System;
using events;
/// <summary>
/// Interface for EventSubscriptionManagerService
/// </summary>
public interface IEventSubscriptionManagerService
{
/// <summary>
/// Publishes the specified event message.
/// </summary>
/// <typeparam name="Event">The type of the event.</typeparam>
/// <param name="eventMessage">The message to publish.</param>
void publish<Event>(Event eventMessage) where Event : class, IMessage;
/// <summary>
/// Subscribes to the specified event.
/// </summary>
/// <typeparam name="Event">The type of the event.</typeparam>
/// <param name="handleEvent">The message handler.</param>
/// <param name="handleError">The error handler.</param>
/// <param name="filter">The message filter.</param>
/// <returns>The subscription as Disposable</returns>
IDisposable subscribe<Event>(Action<Event> handleEvent, Action<Exception> handleError, Func<Event, bool> filter) where Event : class, IMessage;
}
}
| 41.177778 | 152 | 0.656233 | [
"Apache-2.0"
] | AdmiringWorm/choco | src/chocolatey/infrastructure/services/IEventSubscriptionManagerService.cs | 1,857 | C# |
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using System.ComponentModel.Composition;
using System.Windows.Forms;
using Sce.Atf;
using Sce.Atf.Dom;
using Sce.Atf.Adaptation;
using LevelEditorCore;
namespace LevelEditor.PickFilters
{
/// <summary>
/// PickFilter that Only allow
/// locator-type to be picked.</summary>
[Export(typeof (IPickFilter))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class LocatorPickFilter : IPickFilter
{
#region IPickFilter Members
public string Name
{
get { return "Locators"; }
}
public object Filter(object obj,MouseEventArgs e)
{
Path<object> path = obj as Path<object>;
DomNode node = path != null ? path.Last.As<DomNode>() : Adapters.As<DomNode>(obj);
return node == null || Schema.locatorType.Type.IsAssignableFrom(node.Type) ? obj : null;
}
#endregion
}
/// <summary>
/// PickFilter that only allow basic shapes
/// to be picked.</summary>
[Export(typeof(IPickFilter))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class BasicShapePickFilter : IPickFilter
{
#region IPickFilter Members
public string Name
{
get { return "Basic Shapes"; }
}
public object Filter(object obj, MouseEventArgs e)
{
Path<object> path = obj as Path<object>;
DomNode node = path != null ? path.Last.As<DomNode>() : Adapters.As<DomNode>(obj);
return node == null || Schema.shapeTestType.Type.IsAssignableFrom(node.Type) ? obj : null;
}
#endregion
}
/// <summary>
/// PickFilter that only allow basic shapes
/// to be picked.</summary>
[Export(typeof(IPickFilter))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class NoCubePickFilter : IPickFilter
{
#region IPickFilter Members
public string Name
{
get { return "No Cubes"; }
}
public object Filter(object obj, MouseEventArgs e)
{
Path<object> path = obj as Path<object>;
DomNode node = path != null ? path.Last.As<DomNode>() : Adapters.As<DomNode>(obj);
return (node == null || !Schema.cubeTestType.Type.IsAssignableFrom(node.Type)) ? obj : null;
}
#endregion
}
}
| 29.386364 | 113 | 0.570379 | [
"Apache-2.0"
] | T-rvw/LevelEditor | LevelEditor/PickFilters/GobPickFilter.cs | 2,500 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using QuidMind.CloRoFeel.RoboardService;
namespace QuidMind.CloRoFeel.RobotServiceModule
{
class ServoMotorDriver
{
const int PwmPulseRightForwardMax = 1400;
const int PwmPulseRightStop = 1510;
const int PwmPulseRightBackward = 1720;
const int PwmPulseLeftForwardMax = 1720;
const int PwmPulseLeftStop = 1510;
const int PwmPulseLeftBackward = 1400;
Thread thServoSpeed = null;
int currentLeftSpeed = 0;
int currentRightSpeed = 0;
IRoboardHardware _hardwareService;
public ServoMotorDriver(IRoboardHardware hardwareService)
{
_hardwareService = hardwareService;
thServoSpeed = new Thread(new ThreadStart(DoServoSpeedManagement));
//InitRoboard();
thServoSpeed.Start();
}
public void Terminate()
{
}
void DoServoSpeedManagement()
{
uint pwmDuty, pwmPeriod, pwmCount;
int lastLeftSpeed = currentLeftSpeed;
int lastRightSpeed = currentRightSpeed;
Console.WriteLine("ServoMotorDriver: Thread speed management started");
while (true)
{
Thread.Sleep(200);
try
{
//Console.WriteLine("Thred Speed / Iteration.");
if (lastLeftSpeed == 0 && currentLeftSpeed == lastLeftSpeed &&
lastRightSpeed == 0 && currentRightSpeed == lastRightSpeed)
continue; // on etait a zero et on ne change pas de vitesse -> on ne touche pas au servo.
//Console.WriteLine(" Setting speed");
lastLeftSpeed = currentLeftSpeed;
lastRightSpeed = currentRightSpeed;
#region Right Speed Management
if (currentRightSpeed == 0) // on stop
{
pwmDuty = PwmPulseRightStop;
pwmPeriod = 20000 + pwmDuty;
pwmCount = 1;
}
else if (currentRightSpeed > 0) // on avance
{
pwmDuty = Convert.ToUInt32(
PwmPulseRightStop - (PwmPulseRightStop - PwmPulseRightForwardMax) * (currentRightSpeed / 10.0)
);
pwmPeriod = 20000 + pwmDuty;
pwmCount = 20;
}
else // on recule
{
pwmDuty = Convert.ToUInt32(
PwmPulseRightStop + (PwmPulseRightBackward - PwmPulseRightStop) * (-currentRightSpeed / 10.0)
);
pwmPeriod = 20000 + pwmDuty;
pwmCount = 20;
}
//RoBoIO.rcservo_SendPWMPulses(0, pwmPeriod, pwmDuty, pwmCount);
_hardwareService.SetServo(0, pwmDuty, pwmCount);
//RoBoIO.rcservo_SendPWMPulses(1, pwmPeriod, pwmDuty, pwmCount);
_hardwareService.SetServo(1, pwmDuty, pwmCount);
//Console.WriteLine(" right = " + pwmDuty);
#endregion
#region Left Speed Management
if (currentLeftSpeed == 0) // on stop
{
pwmDuty = PwmPulseLeftStop;
pwmPeriod = 20000 + pwmDuty;
pwmCount = 1;
}
else if (currentLeftSpeed > 0) // on avance
{
pwmDuty = Convert.ToUInt32(
PwmPulseLeftStop + (PwmPulseLeftForwardMax - PwmPulseLeftStop) * (currentLeftSpeed / 10.0)
);
pwmPeriod = 20000 + pwmDuty;
pwmCount = 10;
}
else // on recule
{
pwmDuty = Convert.ToUInt32(
PwmPulseLeftStop - (PwmPulseLeftStop - PwmPulseLeftBackward) * (-currentLeftSpeed / 10.0)
);
pwmPeriod = 20000 + pwmDuty;
pwmCount = 10;
}
//RoBoIO.rcservo_SendPWMPulses(2, pwmPeriod, pwmDuty, pwmCount);
_hardwareService.SetServo(2, pwmDuty, pwmCount);
//RoBoIO.rcservo_SendPWMPulses(3, pwmPeriod, pwmDuty, pwmCount);
_hardwareService.SetServo(3, pwmDuty, pwmCount);
//Console.WriteLine(" left = " + pwmDuty);
#endregion
}
catch (Exception ex)
{
Console.WriteLine("ERROR IN THREAD : " + ex.ToString());
}
}
}
public void SetSpeed(int left, int right)
{
currentRightSpeed = right;
currentLeftSpeed = left;
}
public void SetServoPosition(int servoPort, uint pulseWidth, uint nbPulse)
{
//RoBoIO.rcservo_SendPWMPulses(servoPort, 20000+pulseWidth,pulseWidth, nbPulse);
_hardwareService.SetServo(servoPort, pulseWidth, nbPulse);
}
public void SetServoDelta(int servoPort, int pulseWidth, uint nbPulse)
{
_hardwareService.SetServoDelta(servoPort, pulseWidth, nbPulse);
}
}
}
| 37.967532 | 123 | 0.482128 | [
"MIT"
] | flyingoverclouds/Clorofeel | ClorofeelSource/EmbedV2/QuidMind.CloRoFeel.RobotServiceModule/ServoMotorDriver.cs | 5,849 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Core.Pipeline
{
public class Target
{
[XmlAttribute]
public String Name;
[XmlAttribute]
public Single Weight;
}
}
| 16.157895 | 33 | 0.674267 | [
"MIT"
] | greymind/AnimationCustomData | importer/Target.cs | 309 | C# |
using System;
using Xunit;
namespace Fluxor.UnitTests.DisposableCallbackTests
{
public class Constructor
{
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void WhenIdIsNullOrWhitespace_ThenThrowsArgumentNullException(string id)
{
Assert.Throws<ArgumentNullException>(() => new DisposableCallback(id, () => { }));
}
[Fact]
public void WhenActionIsNull_ThenThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DisposableCallback("Test", action: null));
}
}
}
| 22.875 | 92 | 0.710383 | [
"MIT"
] | BlazorHub/Fluxor | Tests/Fluxor.UnitTests/DisposableCallbackTests/Constructor.cs | 551 | C# |
#region Comment
/*
* Project: FineUI
*
* FileName: WindowPosition.cs
* CreatedOn: 2008-06-17
* CreatedBy: 30372245@qq.com
*
*
* Description:
* ->
*
* History:
* ->
*
*
*
*
*/
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace FineUI
{
/// <summary>
/// 窗体的初始显示位置
/// </summary>
public enum WindowPosition
{
/// <summary>
/// 页面的中部
/// </summary>
Center,
/// <summary>
/// 页面的黄金分割点处(默认值)
/// </summary>
GoldenSection
}
} | 13.978261 | 34 | 0.461897 | [
"Apache-2.0"
] | JesterWang/FineUI | FineUI/Business/Enums/WindowPosition.cs | 707 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SQLServer2Dictionary
{
public class DatabaseColumn
{
public string Name { get; set; }
public Type Type { get; set; }
public int Length { get; set; }
}
}
| 19.8125 | 40 | 0.66877 | [
"Unlicense"
] | csprousers/SQLServer2CSpro | SQLServer2Dictionary/DatabaseColumn.cs | 319 | C# |
using CodeBlaze.Library.Collections.Pools;
using UnityEngine;
namespace CodeBlaze.Examples.Library {
public class ObjectPoolExample : MonoBehaviour {
private LazyObjectPool<string> _pool;
private void Start() {
_pool = new LazyObjectPool<string>(5, index => $"Hello : {index}");
Debug.Log(_pool.Claim());
}
}
} | 20.789474 | 79 | 0.6 | [
"MIT"
] | BLaZeKiLL/CodeBlazeLibrary | Assets/Examples/Scripts/Library/ObjectPoolExample.cs | 397 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DS4Windows")]
[assembly: AssemblyDescription("Sony DualShock 4 to Microsoft Xinput controller mapper")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DS4Windows")]
[assembly: AssemblyCopyright("Copyright © Scarlet.Crush Productions 2012, 2013; InhexSTER, HecticSeptic, electrobrains 2013, 2014; Jays2Kings 2013, 2014, 2015, 2016; Ryochan7 2017, 2018, 2019, 2020, 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.2.11")]
[assembly: AssemblyFileVersion("2.2.11")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: Guid("a52b5b20-d9ee-4f32-8518-307fa14aa0c6")]
| 46.137931 | 206 | 0.720105 | [
"MIT"
] | AnessZurba/DS4Windows | DS4Windows/Properties/AssemblyInfo.cs | 2,679 | C# |
/****************************************************************************
Copyright (c) 2013-2015 scutgame.com
http://www.scutgame.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using GameServer.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Service;
namespace GameServer.CsScript.Action
{
public class Action1000 : BaseStruct
{
private string UserName;
private int Score;
public Action1000(HttpGet httpGet)
: base(1000, httpGet)
{
}
public override void BuildPacket()
{
}
public override bool GetUrlElement()
{
if (httpGet.GetString("UserName", ref UserName)
&& httpGet.GetInt("Score", ref Score))
{
return true;
}
return false;
}
public override bool TakeAction()
{
var cache = new ShareCacheStruct<UserRanking>();
var ranking = cache.Find(m => m.UserName == UserName);
if (ranking == null)
{
var user = new GameUser() { UserId = (int)cache.GetNextNo(), NickName = UserName};
new PersonalCacheStruct<GameUser>().Add(user);
ranking = new UserRanking();
ranking.UserID = user.UserId;
ranking.UserName = UserName;
ranking.Score = Score;
cache.Add(ranking);
}
else
{
ranking.UserName = UserName;
ranking.Score = Score;
}
return true;
}
}
} | 33.901235 | 98 | 0.598325 | [
"Unlicense"
] | 2823896/Scut | Source/Middleware/GameWebServer/Script/CsScript/Action/Action1000.cs | 2,746 | C# |
using BoSSS.Application.XNSE_Solver;
using BoSSS.Foundation.Grid;
using BoSSS.Foundation.Grid.Classic;
using BoSSS.Platform.LinAlg;
using BoSSS.Solution.Control;
using BoSSS.Solution.LevelSetTools;
using BoSSS.Solution.NSECommon;
using BoSSS.Solution.Timestepping;
using BoSSS.Solution.XdgTimestepping;
using ilPSP.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BoSSS.Application.XNSE_Solver.PhysicalBasedTestcases {
/// <summary>
/// Collection of Simple Simulations, intended to verify XNSERefactor
/// </summary>
public static class BasicControls {
#region Basic XNSE Tests
/// <summary>
/// Simple Channelflow, Singlephase
/// </summary>
/// <param name="p"></param>
/// <param name="kelem"></param>
/// <returns></returns>
public static XNSE_Control CFSinglePhase(int p = 2, int kelem = 4) {
XNSE_Control C = new XNSE_Control();
// ============================================
#region IO
C.DbPath = null;
C.savetodb = false;
C.ProjectName = "XNSE/elementalTest";
C.ProjectDescription = "Channel flow for BC testing";
C.SuperSampling = 3;
#endregion
// ============================================
// ============================================
#region physics
#region grid
double H = 1;
double L = 5;
C.GridFunc = delegate () {
double[] Xnodes = GenericBlas.Linspace(0, L, 5 * kelem + 1);
double[] Ynodes = GenericBlas.Linspace(0, H, kelem + 1);
var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false);
grd.EdgeTagNames.Add(1, "wall_lower");
grd.EdgeTagNames.Add(2, "wall_upper");
grd.EdgeTagNames.Add(3, "velocity_inlet_left");
grd.EdgeTagNames.Add(4, "pressure_outlet_right");
grd.DefineEdgeTags(delegate (double[] X) {
byte et = 0;
if (Math.Abs(X[1]) <= 1.0e-8)
et = 1;
if (Math.Abs(X[1] - H) <= 1.0e-8)
et = 2;
if (Math.Abs(X[0]) <= 1.0e-8)
et = 3;
if (Math.Abs(X[0] - L) <= 1.0e-8)
et = 4;
return et;
});
return grd;
};
#endregion
#region initial condition
Func<double[], double> PhiFunc = (X => -1);
C.InitialValues_Evaluators.Add("Phi", PhiFunc);
Func<double[], double> UInit = X => -X[1] * (X[1] - H);
C.InitialValues_Evaluators.Add("VelocityX#A", X => 0.0);
#endregion
#region boundary condition
C.AddBoundaryValue("velocity_inlet_left", "VelocityX#A", UInit);
C.AddBoundaryValue("wall_lower");
C.AddBoundaryValue("wall_upper");
C.AddBoundaryValue("pressure_outlet_right");
#endregion
#region material
C.PhysicalParameters.rho_A = 1;
C.PhysicalParameters.rho_B = 1;
C.PhysicalParameters.mu_A = 1;
C.PhysicalParameters.mu_B = 1;
C.PhysicalParameters.Sigma = 0.0;
C.PhysicalParameters.betaS_A = 0.0;
C.PhysicalParameters.betaS_B = 0.0;
C.PhysicalParameters.IncludeConvection = true;
C.PhysicalParameters.Material = true;
#endregion
#endregion
// ============================================
// ============================================
#region numerics
#region dg degrees
C.SetDGdegree(p);
#endregion
#region level set
C.Option_LevelSetEvolution = LevelSetEvolution.None;
C.LevelSet_ConvergenceCriterion = 1e-6;
#endregion
#region solver
C.LinearSolver.NoOfMultigridLevels = 1;
C.NonLinearSolver.SolverCode = NonLinearSolverCode.Newton;
C.NonLinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.MinSolverIterations = 1;
C.LinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.ConvergenceCriterion = 1e-8;
C.LinearSolver.ConvergenceCriterion = 1e-8;
#endregion
#region timestepping
C.TimeSteppingScheme = TimeSteppingScheme.ImplicitEuler;
C.Timestepper_BDFinit = TimeStepperInit.SingleInit;
C.Timestepper_LevelSetHandling = LevelSetHandling.None;
C.TimesteppingMode = AppControl._TimesteppingMode.Transient;
double dt = 1e-1;
C.dtMax = dt;
C.dtMin = dt;
C.Endtime = 1000;
C.NoOfTimesteps = 100;
C.saveperiod = 1;
#endregion
#endregion
// ============================================
return C;
}
/// <summary>
/// Simple Channelflow, Dualphase with interface along channel direction, same velocity profile as Singlephase
/// </summary>
/// <param name="p"></param>
/// <param name="kelem"></param>
/// <returns></returns>
public static XNSE_Control CFDualPhase(int p = 2, int kelem = 4) {
XNSE_Control C = new XNSE_Control();
// ============================================
#region IO
C.DbPath = null;
C.savetodb = false;
C.ProjectName = "XNSE/elementalTest";
C.ProjectDescription = "Channel flow for BC testing";
C.SuperSampling = 3;
#endregion
// ============================================
// ============================================
#region physics
#region grid
double H = 1;
double L = 5;
C.GridFunc = delegate () {
double[] Xnodes = GenericBlas.Linspace(0, L, 5 * kelem + 1);
double[] Ynodes = GenericBlas.Linspace(0, H, kelem + 1);
var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false);
grd.EdgeTagNames.Add(1, "wall_lower");
grd.EdgeTagNames.Add(2, "wall_upper");
grd.EdgeTagNames.Add(3, "velocity_inlet_left");
grd.EdgeTagNames.Add(4, "pressure_outlet_right");
grd.DefineEdgeTags(delegate (double[] X) {
byte et = 0;
if (Math.Abs(X[1]) <= 1.0e-8)
et = 1;
if (Math.Abs(X[1] - H) <= 1.0e-8)
et = 2;
if (Math.Abs(X[0]) <= 1.0e-8)
et = 3;
if (Math.Abs(X[0] - L) <= 1.0e-8)
et = 4;
return et;
});
return grd;
};
#endregion
#region initial condition
Func<double[], double> PhiFunc = (X => X[1] - 0.5);
C.InitialValues_Evaluators.Add("Phi", PhiFunc);
Func<double[], double> UInit = X => -X[1] * (X[1] - H);
C.InitialValues_Evaluators.Add("VelocityX#A", UInit);
C.InitialValues_Evaluators.Add("VelocityX#B", UInit);
#endregion
#region boundary condition
C.AddBoundaryValue("velocity_inlet_left", "VelocityX#A", UInit);
C.AddBoundaryValue("velocity_inlet_left", "VelocityX#B", UInit);
C.AddBoundaryValue("wall_lower");
C.AddBoundaryValue("wall_upper");
C.AddBoundaryValue("pressure_outlet_right");
#endregion
#region material
C.PhysicalParameters.rho_A = 1;
C.PhysicalParameters.rho_B = 1;
C.PhysicalParameters.mu_A = 1;
C.PhysicalParameters.mu_B = 1;
C.PhysicalParameters.Sigma = 0.0;
C.PhysicalParameters.betaS_A = 0.0;
C.PhysicalParameters.betaS_B = 0.0;
C.PhysicalParameters.IncludeConvection = true;
C.PhysicalParameters.Material = true;
#endregion
#endregion
// ============================================
// ============================================
#region numerics
#region dg degrees
C.SetDGdegree(p);
#endregion
#region level set
C.Option_LevelSetEvolution = LevelSetEvolution.FastMarching;
C.LevelSet_ConvergenceCriterion = 1e-6;
#endregion
#region solver
C.CutCellQuadratureType = Foundation.XDG.XQuadFactoryHelper.MomentFittingVariants.OneStepGaussAndStokes;
C.LinearSolver.NoOfMultigridLevels = 1;
C.NonLinearSolver.SolverCode = NonLinearSolverCode.Newton;
C.NonLinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.MinSolverIterations = 1;
C.LinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.ConvergenceCriterion = 1e-8;
C.LinearSolver.ConvergenceCriterion = 1e-8;
#endregion
#region timestepping
C.TimeSteppingScheme = TimeSteppingScheme.ImplicitEuler;
C.Timestepper_BDFinit = TimeStepperInit.SingleInit;
C.Timestepper_LevelSetHandling = LevelSetHandling.Coupled_Once;
C.TimesteppingMode = AppControl._TimesteppingMode.Transient;
double dt = 1e-1;
C.dtMax = dt;
C.dtMin = dt;
C.Endtime = 1000;
C.NoOfTimesteps = 100;
C.saveperiod = 1;
#endregion
#endregion
// ============================================
return C;
}
#endregion
#region Basic XHeat Tests
/// <summary>
/// Heat conduction in a Box, Singlephase
/// </summary>
/// <param name="p"></param>
/// <param name="kelem"></param>
/// <returns></returns>
public static XNSE_Control BoxSinglePhase(int p = 2, int kelem = 4) {
XNSE_Control C = new XNSE_Control();
// ============================================
#region IO
C.DbPath = null;
C.savetodb = false;
C.ProjectName = "XNSE/elementalTest";
C.ProjectDescription = "Channel flow for BC testing";
C.SuperSampling = 3;
#endregion
// ============================================
// ============================================
#region physics
#region grid
double H = 1;
double L = 1;
C.GridFunc = delegate () {
double[] Xnodes = GenericBlas.Linspace(0, L, kelem + 1);
double[] Ynodes = GenericBlas.Linspace(0, H, kelem + 1);
var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false);
grd.EdgeTagNames.Add(1, "ZeroGradient_lower");
grd.EdgeTagNames.Add(2, "ZeroGradient_upper");
grd.EdgeTagNames.Add(3, "ConstantTemperature_left");
grd.EdgeTagNames.Add(4, "ConstantTemperature_right");
grd.DefineEdgeTags(delegate (double[] X) {
byte et = 0;
if (Math.Abs(X[1]) <= 1.0e-8)
et = 1;
if (Math.Abs(X[1] - H) <= 1.0e-8)
et = 2;
if (Math.Abs(X[0]) <= 1.0e-8)
et = 3;
if (Math.Abs(X[0] - L) <= 1.0e-8)
et = 4;
return et;
});
return grd;
};
#endregion
#region initial condition
Func<double[], double> PhiFunc = (X => -1);
C.InitialValues_Evaluators.Add("Phi", PhiFunc);
Func<double[], double> UInit = X => 1.0;
C.InitialValues_Evaluators.Add("Temperature#A", X => 0.0);
C.InitialValues_Evaluators.Add("VelocityX#A", X => Math.Sin(2 * Math.PI * X[1]));
C.InitialValues_Evaluators.Add("VelocityY#A", X => Math.Cos(2 * Math.PI * X[0]));
#endregion
#region boundary condition
C.AddBoundaryValue("ConstantTemperature_left", "Temperature#A", X => 0.0);
C.AddBoundaryValue("ZeroGradient_lower");
C.AddBoundaryValue("ZeroGradient_upper");
C.AddBoundaryValue("ConstantTemperature_right", "Temperature#A", UInit);
#endregion
#region material
C.ThermalParameters.c_A = 1.0;
C.ThermalParameters.c_B = 1.0;
C.ThermalParameters.k_A = 1.0;
C.ThermalParameters.k_B = 1.0;
C.ThermalParameters.rho_A = 1.0;
C.ThermalParameters.rho_A = 1.0;
C.ThermalParameters.IncludeConvection = true;
C.ThermalParameters.hVap = 0.0;
#endregion
#endregion
// ============================================
// ============================================
#region numerics
#region dg degrees
C.FieldOptions.Add("Temperature", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("HeatFlux*", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("PhiDG", new FieldOpts() {
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("Phi", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
#endregion
#region level set
C.Option_LevelSetEvolution = LevelSetEvolution.None;
C.LevelSet_ConvergenceCriterion = 1e-6;
#endregion
#region solver
C.LinearSolver.NoOfMultigridLevels = 1;
C.NonLinearSolver.SolverCode = NonLinearSolverCode.Newton;
C.NonLinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.MinSolverIterations = 1;
C.LinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.ConvergenceCriterion = 1e-8;
C.LinearSolver.ConvergenceCriterion = 1e-8;
C.solveCoupledHeatEquation = true;
C.conductMode = Solution.XheatCommon.ConductivityInSpeciesBulk.ConductivityMode.LDG;
#endregion
#region timestepping
C.TimeSteppingScheme = TimeSteppingScheme.ImplicitEuler;
C.Timestepper_BDFinit = TimeStepperInit.SingleInit;
C.Timestepper_LevelSetHandling = LevelSetHandling.None;
C.TimesteppingMode = AppControl._TimesteppingMode.Transient;
double dt = 1e-1;
C.dtMax = dt;
C.dtMin = dt;
C.Endtime = 1000;
C.NoOfTimesteps = 100;
C.saveperiod = 1;
#endregion
#endregion
// ============================================
return C;
}
/// <summary>
/// Heat conduction in a box, Dualphase, kink in Temperatureprofile at Interface
/// </summary>
/// <param name="p"></param>
/// <param name="kelem"></param>
/// <returns></returns>
public static XNSE_Control BoxDualPhase(int p = 2, int kelem = 4) {
XNSE_Control C = new XNSE_Control();
// ============================================
#region IO
C.DbPath = null;
C.savetodb = false;
C.ProjectName = "XNSE/elementalTest";
C.ProjectDescription = "Channel flow for BC testing";
C.SuperSampling = 3;
#endregion
// ============================================
// ============================================
#region physics
#region grid
double H = 1;
double L = 1;
C.GridFunc = delegate () {
double[] Xnodes = GenericBlas.Linspace(0, L, kelem + 1);
double[] Ynodes = GenericBlas.Linspace(0, H, kelem + 1);
var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false);
grd.EdgeTagNames.Add(1, "ZeroGradient_lower");
grd.EdgeTagNames.Add(2, "ZeroGradient_upper");
grd.EdgeTagNames.Add(3, "ConstantTemperature_left");
grd.EdgeTagNames.Add(4, "ConstantTemperature_right");
grd.DefineEdgeTags(delegate (double[] X) {
byte et = 0;
if (Math.Abs(X[1]) <= 1.0e-8)
et = 1;
if (Math.Abs(X[1] - H) <= 1.0e-8)
et = 2;
if (Math.Abs(X[0]) <= 1.0e-8)
et = 3;
if (Math.Abs(X[0] - L) <= 1.0e-8)
et = 4;
return et;
});
AffineTrafo ROT = AffineTrafo.Some2DRotation(Math.PI/6.0);
var grdT = grd.Transform(ROT);
return grdT;
};
#endregion
#region initial condition
Func<double[], double> PhiFunc = (X => X[0] - 0.6);
C.InitialValues_Evaluators.Add("Phi", PhiFunc);
Func<double[], double> UInit = X => 1.0;
C.InitialValues_Evaluators.Add("Temperature#A", X => 0.0);
//C.InitialValues_Evaluators.Add("VelocityX#A", X => Math.Sin(2 * Math.PI * X[1]));
//C.InitialValues_Evaluators.Add("VelocityY#A", X => Math.Cos(2 * Math.PI * X[0]));
C.InitialValues_Evaluators.Add("VelocityX#A", X => -0.0);
C.InitialValues_Evaluators.Add("VelocityX#B", X => -0.0);
#endregion
#region boundary condition
C.AddBoundaryValue("ConstantTemperature_left", "Temperature#A", X => 0.0);
C.AddBoundaryValue("ZeroGradient_lower");
C.AddBoundaryValue("ZeroGradient_upper");
C.AddBoundaryValue("ConstantTemperature_right", "Temperature#A", UInit);
C.AddBoundaryValue("ConstantTemperature_right", "Temperature#B", UInit);
#endregion
#region material
C.ThermalParameters.c_A = 10.0;
C.ThermalParameters.c_B = 1.0;
C.ThermalParameters.k_A = 10.0;
C.ThermalParameters.k_B = 1.0;
C.ThermalParameters.rho_A = 1.0;
C.ThermalParameters.rho_A = 1.0;
C.ThermalParameters.IncludeConvection = true;
C.ThermalParameters.hVap = 0.0;
C.ThermalParameters.T_sat = Double.MaxValue;
#endregion
#endregion
// ============================================
// ============================================
#region numerics
#region dg degrees
C.FieldOptions.Add("Temperature", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("HeatFlux*", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("PhiDG", new FieldOpts() {
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("Phi", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
#endregion
#region level set
C.Option_LevelSetEvolution = LevelSetEvolution.FastMarching;
C.LevelSet_ConvergenceCriterion = 1e-6;
#endregion
#region solver
C.conductMode = Solution.XheatCommon.ConductivityInSpeciesBulk.ConductivityMode.SIP;
C.CutCellQuadratureType = Foundation.XDG.XQuadFactoryHelper.MomentFittingVariants.OneStepGaussAndStokes;
C.LinearSolver.NoOfMultigridLevels = 1;
C.NonLinearSolver.SolverCode = NonLinearSolverCode.Newton;
C.NonLinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.MinSolverIterations = 1;
C.LinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.ConvergenceCriterion = 1e-8;
C.LinearSolver.ConvergenceCriterion = 1e-8;
C.solveCoupledHeatEquation = true;
C.conductMode = Solution.XheatCommon.ConductivityInSpeciesBulk.ConductivityMode.SIP;
#endregion
#region timestepping
C.TimeSteppingScheme = TimeSteppingScheme.ImplicitEuler;
C.Timestepper_BDFinit = TimeStepperInit.SingleInit;
C.Timestepper_LevelSetHandling = LevelSetHandling.LieSplitting;
C.TimesteppingMode = AppControl._TimesteppingMode.Transient;
double dt = 1e-1;
C.dtMax = dt;
C.dtMin = dt;
C.Endtime = 1000;
C.NoOfTimesteps = 100;
C.saveperiod = 1;
#endregion
#endregion
// ============================================
return C;
}
#endregion
#region Basic XNSFE Tests
/// <summary>
/// XNSFE with evaporation, Dualphase
/// </summary>
/// <param name="p"></param>
/// <param name="kelem"></param>
/// <returns></returns>
public static XNSE_Control BoxEvapDualPhase(int p = 3, int kelem = 1) {
XNSE_Control C = new XNSE_Control();
// ============================================
#region IO
C.DbPath = null;
C.savetodb = false;
C.ProjectName = "XNSFE/elementalTest";
C.ProjectDescription = "1D Evaporation";
C.SuperSampling = 3;
#endregion
// ============================================
// ============================================
#region physics
#region material
C.ThermalParameters.c_A = 0.0;
C.ThermalParameters.c_B = 0.0;
C.ThermalParameters.k_A = 1.0;
C.ThermalParameters.k_B = 1.0;
C.ThermalParameters.rho_A = 1.0;
C.ThermalParameters.rho_B = 0.1;
C.ThermalParameters.IncludeConvection = true;
C.ThermalParameters.hVap = 100.0;
C.ThermalParameters.T_sat = 0.0;
C.PhysicalParameters.rho_A = 1;
C.PhysicalParameters.rho_B = 0.1;
C.PhysicalParameters.mu_A = 1;
C.PhysicalParameters.mu_B = 1;
C.PhysicalParameters.Sigma = 0.0;
C.PhysicalParameters.betaS_A = 0.0;
C.PhysicalParameters.betaS_B = 0.0;
C.PhysicalParameters.IncludeConvection = true;
C.PhysicalParameters.Material = false;
#endregion
#region grid
double angle = Math.PI * 0.0 / 180.0;
AffineTrafo ROT = AffineTrafo.Some2DRotation(angle);
double H = 4;
double L = 1;
C.GridFunc = delegate () {
double[] Xnodes = GenericBlas.Linspace(0, L, kelem + 1);
double[] Ynodes = GenericBlas.Linspace(0, H, 4 * kelem + 1);
var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false);
grd.EdgeTagNames.Add(1, "freeslip_ZeroGradient_left");
grd.EdgeTagNames.Add(2, "freeslip_ZeroGradient_right");
grd.EdgeTagNames.Add(3, "wall_ConstantTemperature_lower");
grd.EdgeTagNames.Add(4, "pressure_outlet_ConstantHeatFlux_upper");
grd.DefineEdgeTags(delegate (double[] X) {
byte et = 0;
if (Math.Abs(X[1]) <= 1.0e-8)
et = 3;
if (Math.Abs(X[1] - H) <= 1.0e-8)
et = 4;
if (Math.Abs(X[0]) <= 1.0e-8)
et = 1;
if (Math.Abs(X[0] - L) <= 1.0e-8)
et = 2;
return et;
});
var grdT = grd.Transform(ROT);
return grdT;
};
#endregion
#region boundary condition
double q = 25.0;
C.AddBoundaryValue("wall_ConstantTemperature_lower", "Temperature#A", X => 0.0);
C.AddBoundaryValue("freeslip_ZeroGradient_left");
C.AddBoundaryValue("freeslip_ZeroGradient_right");
C.AddBoundaryValue("pressure_outlet_ConstantHeatFlux_upper", "HeatFluxY#B", X => Math.Cos(angle) * q);
C.AddBoundaryValue("pressure_outlet_ConstantHeatFlux_upper", "HeatFluxX#B", X => -Math.Sin(angle) * q);
#endregion
#region initial condition
double x0 = 2.5;
C.Phi0Initial = X => 1.0 / Math.Cos(angle) * (x0 + (0.1 + Math.Sin(angle)) * X);
Func<double[], double> PhiFunc = (X => Math.Cos(angle) * (X[1] - C.Phi0Initial(X[0])));
C.InitialValues_Evaluators.Add("Phi", PhiFunc);
C.InitialValues_Evaluators.Add("Temperature#B", X => (Math.Cos(angle) * X[1] - Math.Sin(angle) * X[0] - x0) * q/C.ThermalParameters.k_B);
//C.InitialValues_Evaluators.Add("VelocityX#A", X => Math.Sin(2 * Math.PI * X[1]));
//C.InitialValues_Evaluators.Add("VelocityY#A", X => Math.Cos(2 * Math.PI * X[0]));
C.InitialValues_Evaluators.Add("VelocityX#A", X => -0.0);
C.InitialValues_Evaluators.Add("VelocityX#B", X => -0.0);
#endregion
#endregion
// ============================================
// ============================================
#region numerics
#region dg degrees
C.FieldOptions.Add("VelocityX", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("VelocityY", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add(VariableNames.Pressure, new FieldOpts() {
Degree = p - 1,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("Temperature", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("HeatFlux*", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("PhiDG", new FieldOpts() {
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
C.FieldOptions.Add("Phi", new FieldOpts() {
Degree = p,
SaveToDB = FieldOpts.SaveToDBOpt.TRUE
});
#endregion
#region level set
C.Option_LevelSetEvolution = LevelSetEvolution.SplineLS;
C.LevelSet_ConvergenceCriterion = 1e-6;
#endregion
#region solver
C.AdvancedDiscretizationOptions.SST_isotropicMode = Solution.XNSECommon.SurfaceStressTensor_IsotropicMode.LaplaceBeltrami_ContactLine;
C.conductMode = Solution.XheatCommon.ConductivityInSpeciesBulk.ConductivityMode.SIP;
C.CutCellQuadratureType = Foundation.XDG.XQuadFactoryHelper.MomentFittingVariants.OneStepGaussAndStokes;
C.LinearSolver.NoOfMultigridLevels = 1;
C.NonLinearSolver.SolverCode = NonLinearSolverCode.Newton;
C.NonLinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.MinSolverIterations = 1;
C.LinearSolver.MaxSolverIterations = 50;
C.NonLinearSolver.ConvergenceCriterion = 1e-8;
C.LinearSolver.ConvergenceCriterion = 1e-8;
C.solveCoupledHeatEquation = true;
C.conductMode = Solution.XheatCommon.ConductivityInSpeciesBulk.ConductivityMode.SIP;
#endregion
#region timestepping
C.TimeSteppingScheme = TimeSteppingScheme.ImplicitEuler;
C.Timestepper_BDFinit = TimeStepperInit.SingleInit;
C.Timestepper_LevelSetHandling = LevelSetHandling.Coupled_Once;
C.TimesteppingMode = AppControl._TimesteppingMode.Transient;
double dt = 1e-1;
C.dtMax = dt;
C.dtMin = dt;
C.Endtime = 1000;
C.NoOfTimesteps = 100;
C.saveperiod = 1;
#endregion
#endregion
// ============================================
return C;
}
#endregion
}
}
| 34.889655 | 150 | 0.48758 | [
"Apache-2.0"
] | FDYdarmstadt/BoSSS | src/L4-application/XNSE_Solver/PhysicalBasedTestcases/BasicControls.cs | 29,487 | C# |
using Microsoft.Extensions.DependencyInjection;
using Midgard.Hosting;
using System;
using System.Runtime.Loader;
using System.Threading.Tasks;
namespace Midgard.Bootstrapper
{
class Program
{
static async Task Main(string[] args)
{
using var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((c, s) => {
s.AddHostedService<Core>();
})
.Build();
await host.StartAsync()
.ConfigureAwait(false);
WriteContexts();
await host.StopAsync()
.ConfigureAwait(false);
GC.Collect();
GC.WaitForPendingFinalizers();
WriteContexts();
}
private static void WriteContexts()
{
foreach (var context in AssemblyLoadContext.All)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"context: {context.Name}");
Console.ForegroundColor = ConsoleColor.Gray;
foreach (var assembly in context.Assemblies)
{
if (!assembly.FullName.StartsWith("Midgard", StringComparison.OrdinalIgnoreCase))
{
continue;
}
Console.WriteLine(" " + assembly.FullName);
}
}
}
}
}
| 27.074074 | 101 | 0.504104 | [
"MIT"
] | kaep7n/midgard | src/Midgard.Bootstrapper/Program.cs | 1,464 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class Drone3Move : EnemyMove
{
private Vector3 diff;
private float rotationZ;
private Transform myGun;
private float gunX,gunY,gunRadian,gunRotateDegree;
[SerializeField]
private Transform barSsaPos;
[SerializeField]
private int gunDamage,gunStun;
private float shotingtime;
private Transform playertransform;
private AllPoolManager allPoolManager;
[SerializeField]
private float shotDeley=2f;
private Animator animator;
void Start()
{
animator = GetComponent<Animator>();
allPoolManager = GameManager.instance.allPoolManager;
playertransform = GameManager.instance.player.transform;
myRigidbodyhi = GetComponent<Rigidbody2D>();
myGun = transform.GetChild(0);
}
protected override void Move()
{
base.Move();
if(myGun==null){
myGun = transform.GetChild(0);
}
aBarssaDeley();
}
private void aBarssaDeley(){
shotingtime+=Time.deltaTime;
if(shotingtime>shotDeley){
shotingtime=0f;
animator.SetTrigger("Shot");
}
}
public void Shoting(){
transform.DOKill();
var bullet = allPoolManager.GetPool(10).GetComponent<BulletMove>();
if(bullet==null)return;
myRigidbodyhi.AddForce(new Vector3(-gunX,-gunY,0f));
bullet.transform.position=barSsaPos.transform.position;
bullet.transform.rotation = Quaternion.Euler(0,0,90f);
bullet.bulletSet = 0;
bullet.bulletDagage = gunDamage;
bullet.stun = gunStun;
bullet.gameObject.SetActive(true);
}
}
| 28.901639 | 75 | 0.649461 | [
"MIT"
] | pqowp90/The-jet-man | Assets/netmaCode/Drone3Move.cs | 1,763 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyDescription("MSBuild Tasks for Octopus Deploy")]
[assembly: AssemblyCompany("Octopus Deploy")]
[assembly: AssemblyProduct("Octopus, an opinionated deployment solution for .NET applications")]
[assembly: AssemblyCopyright("Copyright © Octopus Deploy 2011")]
[assembly: AssemblyCulture("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: ComVisible(false)]
[assembly: CLSCompliantAttribute(false)]
| 33.470588 | 96 | 0.794376 | [
"Apache-2.0"
] | OctopusDeploy/OctoPack | source/Solution Items/SolutionInfo.cs | 572 | C# |
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace SmartBreadcrumbs.UnitTests.Features.FeatureOne
{
public class SubFeatureModel : PageModel
{
}
} | 20.25 | 56 | 0.765432 | [
"MIT"
] | Magicianred/SmartBreadcrumbs | tests/SmartBreadcrumbs.UnitTests/Features/FeatureOne/SubFeatureModel.cs | 164 | C# |
using SSDCPortal.Constants;
using SSDCPortal.Infrastructure.AuthorizationDefinitions;
using SSDCPortal.Shared.Dto.Db;
using SSDCPortal.Shared.Interfaces;
using SSDCPortal.Shared.Localizer;
using SSDCPortal.Theme.Material.Admin.Shared.Layouts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SSDCPortal.Theme.Material.Admin.Pages.Admin.Settings
{
[Authorize(Policies.IsAdmin)]
[Layout(typeof(AdminLayout))]
public abstract class SettingsBase : ComponentBase
{
protected Dictionary<SettingKey, TenantSetting> settings;
[Inject] private NavigationManager navigationManager { get; set; }
[Inject] protected IApiClient apiClient { get; set; }
[Inject] protected IViewNotifier viewNotifier { get; set; }
[Inject] protected IStringLocalizer<Global> L { get; set; }
protected async Task LoadSettings(string prefix)
{
try
{
var result = (await apiClient.GetTenantSettings()).Where(i => i.Key.ToString().StartsWith(prefix)).ToDictionary(i => i.Key, i => i);
foreach (var def in TenantSettingValues.Default.Where(i => i.Key.ToString().StartsWith(prefix)))
{
if (!result.ContainsKey(def.Key))
{
var entity = new TenantSetting() { Key = def.Key, Type = def.Value.Item2, Value = def.Value.Item1 };
result.Add(def.Key, entity);
apiClient.AddEntity(entity);
}
}
settings = result;
}
catch (Exception ex)
{
viewNotifier.Show(ex.GetBaseException().Message, ViewNotifierType.Error, L["Operation Failed"]);
}
}
protected async Task SaveChanges()
{
try
{
var reload = false;
if (settings.ContainsKey(SettingKey.MainConfiguration_Runtime) && settings[SettingKey.MainConfiguration_Runtime].EntityAspect.HasChanges())
reload = true;
await apiClient.SaveChanges();
viewNotifier.Show(L["Operation Successful"], ViewNotifierType.Success);
if (reload)
navigationManager.NavigateTo(navigationManager.Uri, true);
}
catch (Exception ex)
{
viewNotifier.Show(ex.GetBaseException().Message, ViewNotifierType.Error, L["Operation Failed"]);
}
}
}
}
| 34.493671 | 155 | 0.605505 | [
"MIT"
] | slicksys/blazorboilerplate | src/Shared/Modules/SSDCPortal.Theme.Material.Admin/Pages/Admin/Settings/SettingsBase.cs | 2,727 | C# |
using VRM;
namespace VRMViewer
{
public enum LANGUAGES
{
Japanese,
English,
Chinese,
Korean,
}
} | 11.833333 | 25 | 0.514085 | [
"MIT"
] | MoorDev/UniVRMTest | Assets/VRMViewer/Scripts/Languages.cs | 144 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BurialPlots.DAL
{
public class PartnerPlanRepository:GenericRepository<PartnerPlan>
{
}
} | 18 | 69 | 0.767677 | [
"MIT"
] | neocodejack/burial-plots | burialplots/DAL/PartnerPlanRepository.cs | 200 | C# |
/* Copyright 2021-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Bson.TestHelpers;
using MongoDB.Driver.Core.Clusters;
using MongoDB.Driver.Core.Clusters.ServerSelectors;
using MongoDB.Driver.Core.Configuration;
using MongoDB.Driver.Core.ConnectionPools;
using MongoDB.Driver.Core.Connections;
using MongoDB.Driver.Core.Helpers;
using MongoDB.Driver.Core.Servers;
using MongoDB.Driver.Core.WireProtocol.Messages;
using MongoDB.Driver.Core.WireProtocol.Messages.Encoders;
using Moq;
using Xunit;
namespace MongoDB.Driver.Core.Tests.Jira
{
public class CSharp3302Tests
{
#pragma warning disable CS0618 // Type or member is obsolete
private readonly static ClusterConnectionMode __clusterConnectionMode = ClusterConnectionMode.ReplicaSet;
private readonly static ConnectionModeSwitch __connectionModeSwitch = ConnectionModeSwitch.UseConnectionMode;
#pragma warning restore CS0618 // Type or member is obsolete
private readonly static ClusterId __clusterId = new ClusterId();
private readonly static bool? __directConnection = null;
private readonly static EndPoint __endPoint1 = new DnsEndPoint("localhost", 27017);
private readonly static EndPoint __endPoint2 = new DnsEndPoint("localhost", 27018);
private readonly static TimeSpan __heartbeatInterval = TimeSpan.FromMilliseconds(200);
private readonly static ServerId __serverId1 = new ServerId(__clusterId, __endPoint1);
private readonly static ServerId __serverId2 = new ServerId(__clusterId, __endPoint2);
[Fact]
public async Task RapidHeartbeatTimerCallback_should_ignore_reentrant_calls()
{
var clusterSettings = new ClusterSettings(
connectionMode: __clusterConnectionMode,
connectionModeSwitch: __connectionModeSwitch,
serverSelectionTimeout: TimeSpan.FromSeconds(30),
endPoints: new[] { __endPoint1 });
var allHeartbeatsReceived = new TaskCompletionSource<bool>();
const int heartbeatsExpectedMinCount = 3;
int heartbeatsCount = 0, isInHeartbeat = 0;
var calledReentrantly = false;
var serverDescription = new ServerDescription(
__serverId1,
__endPoint1,
type: ServerType.ReplicaSetPrimary,
state: ServerState.Disconnected,
replicaSetConfig: new ReplicaSetConfig(new[] { __endPoint1 }, "rs", __endPoint1, null));
var serverMock = new Mock<IClusterableServer>();
serverMock.Setup(s => s.EndPoint).Returns(__endPoint1);
serverMock.Setup(s => s.IsInitialized).Returns(true);
serverMock.Setup(s => s.Description).Returns(serverDescription);
serverMock.Setup(s => s.RequestHeartbeat()).Callback(BlockHeartbeatRequested);
var serverFactoryMock = new Mock<IClusterableServerFactory>();
serverFactoryMock
.Setup(f => f.CreateServer(It.IsAny<ClusterType>(), It.IsAny<ClusterId>(), It.IsAny<IClusterClock>(), It.IsAny<EndPoint>()))
.Returns(serverMock.Object);
using (var cluster = new MultiServerCluster(clusterSettings, serverFactoryMock.Object, new EventCapturer()))
{
cluster._minHeartbeatInterval(TimeSpan.FromMilliseconds(10));
// _minHeartbeatInterval validation might not be necessary, and can be reconsidered along with Reflector testing
cluster._minHeartbeatInterval().Should().Be(TimeSpan.FromMilliseconds(10));
ForceClusterId(cluster, __clusterId);
cluster.Initialize();
// Trigger Cluster._rapidHeartbeatTimer
var _ = cluster.SelectServerAsync(CreateWritableServerAndEndPointSelector(__endPoint1), CancellationToken.None);
// Wait for all heartbeats to complete
await Task.WhenAny(allHeartbeatsReceived.Task, Task.Delay(1000));
}
allHeartbeatsReceived.Task.Status.Should().Be(TaskStatus.RanToCompletion);
calledReentrantly.Should().Be(false);
void BlockHeartbeatRequested()
{
// Validate BlockHeartbeatRequested is not running already
calledReentrantly |= Interlocked.Exchange(ref isInHeartbeat, 1) != 0;
// Block Cluster._rapidHeartbeatTimer timer
Thread.Sleep(40);
Interlocked.Exchange(ref isInHeartbeat, 0);
if (Interlocked.Increment(ref heartbeatsCount) == heartbeatsExpectedMinCount)
{
allHeartbeatsReceived.SetResult(true);
}
}
}
[Fact(Timeout = 10000)]
public async Task Ensure_no_deadlock_after_primary_update()
{
// Force async execution, otherwise test timeout won't be respected
await Task.Yield();
var noLongerPrimaryEventStalled = new TaskCompletionSource<bool>();
var currentPrimaries = new HashSet<ServerId>() { __serverId1 };
EndPoint initialSelectedEndpoint = null;
using (var cluster = CreateAndSetupCluster(currentPrimaries))
{
ForceClusterId(cluster, __clusterId);
cluster.Initialize();
foreach (var server in cluster._servers())
{
server.DescriptionChanged += ProcessServerDescriptionChanged;
}
var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), CancellationToken.None);
initialSelectedEndpoint = selectedServer.EndPoint;
initialSelectedEndpoint.Should().Be(__endPoint1);
// Change primary
currentPrimaries.Add(__serverId2);
selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint2), CancellationToken.None);
selectedServer.EndPoint.Should().Be(__endPoint2);
// Ensure stalling happened
await noLongerPrimaryEventStalled.Task;
}
void ProcessServerDescriptionChanged(object sender, ServerDescriptionChangedEventArgs e)
{
// Stall once for first primary
if (e.NewServerDescription.ReasonChanged == "InvalidatedBecause:NoLongerPrimary" && currentPrimaries.Remove(__serverId1))
{
var server = (IServer)sender;
server.EndPoint.Should().Be(__endPoint1);
// Postpone Server.Invalidate invoke in MultiServerCluster.ProcessReplicaSetChange
Thread.Sleep(1000);
noLongerPrimaryEventStalled.SetResult(true);
}
}
}
// private methods
private IConnectionPoolFactory CreateAndSetupConnectionPoolFactory(params (ServerId ServerId, EndPoint Endpoint)[] serverInfoCollection)
{
var mockConnectionPoolFactory = new Mock<IConnectionPoolFactory>();
foreach (var serverInfo in serverInfoCollection)
{
var mockConnectionPool = new Mock<IConnectionPool>();
SetupConnectionPoolFactory(mockConnectionPoolFactory, mockConnectionPool.Object, serverInfo.ServerId, serverInfo.Endpoint);
var mockServerConnection = new Mock<IConnectionHandle>();
SetupConnection(mockServerConnection, serverInfo.ServerId);
SetupConnectionPool(mockConnectionPool, mockServerConnection.Object);
}
return mockConnectionPoolFactory.Object;
void SetupConnection(Mock<IConnectionHandle> mockConnectionHandle, ServerId serverId)
{
mockConnectionHandle.SetupGet(c => c.ConnectionId).Returns(new ConnectionId(serverId));
}
void SetupConnectionPool(Mock<IConnectionPool> mockConnectionPool, IConnectionHandle connection)
{
mockConnectionPool
.Setup(c => c.AcquireConnection(It.IsAny<CancellationToken>()))
.Returns(connection);
mockConnectionPool
.Setup(c => c.AcquireConnectionAsync(It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(connection));
}
void SetupConnectionPoolFactory(Mock<IConnectionPoolFactory> mockFactory, IConnectionPool connectionPool, ServerId serverId, EndPoint endPoint)
{
mockFactory.Setup(c => c.CreateConnectionPool(serverId, endPoint, It.IsAny<IConnectionExceptionHandler>())).Returns(connectionPool);
}
}
private IConnectionFactory CreateAndSetupServerMonitorConnectionFactory(
HashSet<ServerId> primaries,
params (ServerId ServerId, EndPoint Endpoint)[] serverInfoCollection)
{
var mockConnectionFactory = new Mock<IConnectionFactory>();
foreach (var serverInfo in serverInfoCollection)
{
var mockServerMonitorConnection = new Mock<IConnection>();
SetupServerMonitorConnection(primaries, mockServerMonitorConnection, serverInfo.ServerId);
mockConnectionFactory
.Setup(c => c.CreateConnection(serverInfo.ServerId, serverInfo.Endpoint))
.Returns(mockServerMonitorConnection.Object);
}
return mockConnectionFactory.Object;
}
private MultiServerCluster CreateAndSetupCluster(HashSet<ServerId> primaries)
{
(ServerId ServerId, EndPoint Endpoint)[] serverInfoCollection = new[]
{
(__serverId1, __endPoint1),
(__serverId2, __endPoint2),
};
var clusterSettings = new ClusterSettings(
connectionMode: __clusterConnectionMode,
connectionModeSwitch: __connectionModeSwitch,
serverSelectionTimeout: TimeSpan.FromSeconds(30),
endPoints: serverInfoCollection.Select(c => c.Endpoint).ToArray());
var serverMonitorSettings = new ServerMonitorSettings(
connectTimeout: TimeSpan.FromMilliseconds(1),
heartbeatInterval: __heartbeatInterval);
var serverSettings = new ServerSettings(serverMonitorSettings.HeartbeatInterval);
var eventCapturer = new EventCapturer();
var connectionPoolFactory = CreateAndSetupConnectionPoolFactory(serverInfoCollection);
var serverMonitorConnectionFactory = CreateAndSetupServerMonitorConnectionFactory(primaries, serverInfoCollection);
var serverMonitorFactory = new ServerMonitorFactory(serverMonitorSettings, serverMonitorConnectionFactory, eventCapturer, serverApi: null);
var serverFactory = new ServerFactory(__clusterConnectionMode, __connectionModeSwitch, __directConnection, serverSettings, connectionPoolFactory, serverMonitorFactory, eventCapturer, serverApi: null);
return new MultiServerCluster(clusterSettings, serverFactory, eventCapturer);
}
private IServerSelector CreateWritableServerAndEndPointSelector(EndPoint endPoint)
{
IServerSelector endPointServerSelector = new EndPointServerSelector(endPoint);
return new CompositeServerSelector(
new[]
{
WritableServerSelector.Instance,
endPointServerSelector
});
}
private void ForceClusterId(MultiServerCluster cluster, ClusterId clusterId)
{
Reflector.SetFieldValue(cluster, "_clusterId", clusterId);
Reflector.SetFieldValue(cluster, "_description", ClusterDescription.CreateInitial(clusterId, __clusterConnectionMode, __connectionModeSwitch, __directConnection));
}
private void SetupServerMonitorConnection(
HashSet<ServerId> primaries,
Mock<IConnection> mockConnection,
ServerId serverId)
{
var connectionId = new ConnectionId(serverId);
var serverVersion = "2.6";
var baseDocument = new BsonDocument
{
{ "ok", 1 },
{ "minWireVersion", 6 },
{ "maxWireVersion", 7 },
{ "setName", "rs" },
{ "hosts", new BsonArray(new [] { "localhost:27017", "localhost:27018" })},
{ "version", serverVersion },
{ "topologyVersion", new TopologyVersion(ObjectId.Empty, 1).ToBsonDocument(), false }
};
var primaryDocument = (BsonDocument)baseDocument.DeepClone();
primaryDocument.Add("isWritablePrimary", true);
var secondaryDocument = (BsonDocument)baseDocument.DeepClone();
secondaryDocument.Add("secondary", true);
mockConnection.SetupGet(c => c.ConnectionId).Returns(connectionId);
mockConnection.SetupGet(c => c.EndPoint).Returns(serverId.EndPoint);
mockConnection
.SetupGet(c => c.Description)
.Returns(GetConnectionDescription);
mockConnection.Setup(c => c.Open(It.IsAny<CancellationToken>())); // no action is required
mockConnection.Setup(c => c.OpenAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(true)); // no action is required
mockConnection
.Setup(c => c.ReceiveMessageAsync(It.IsAny<int>(), It.IsAny<IMessageEncoderSelector>(), It.IsAny<MessageEncoderSettings>(), It.IsAny<CancellationToken>()))
.Returns(GetHelloResponse);
Task<ResponseMessage> GetHelloResponse()
{
var helloDocument = primaries.Contains(serverId) ? primaryDocument : secondaryDocument;
ResponseMessage result = MessageHelper.BuildReply(new RawBsonDocument(helloDocument.ToBson()));
return Task.FromResult(result);
}
ConnectionDescription GetConnectionDescription()
{
var helloDocument = primaries.Contains(serverId) ? primaryDocument : secondaryDocument;
return new ConnectionDescription(
mockConnection.Object.ConnectionId,
new HelloResult(helloDocument),
new BuildInfoResult(new BsonDocument("version", serverVersion)));
}
}
}
}
| 46.329305 | 212 | 0.652299 | [
"Apache-2.0"
] | JamesKovacs/mongo-csharp-driver | tests/MongoDB.Driver.Core.Tests/Jira/CSharp3302Tests.cs | 15,337 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SageMaker.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SageMaker.Model.Internal.MarshallTransformations
{
/// <summary>
/// NotebookInstanceLifecycleHook Marshaller
/// </summary>
public class NotebookInstanceLifecycleHookMarshaller : IRequestMarshaller<NotebookInstanceLifecycleHook, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(NotebookInstanceLifecycleHook requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetContent())
{
context.Writer.WritePropertyName("Content");
context.Writer.Write(requestObject.Content);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static NotebookInstanceLifecycleHookMarshaller Instance = new NotebookInstanceLifecycleHookMarshaller();
}
} | 35.177419 | 133 | 0.677671 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/NotebookInstanceLifecycleHookMarshaller.cs | 2,181 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calculadora
{
public partial class formCalc : Form
{
public formCalc()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btAdd_Click(object sender, EventArgs e)
{
double valor1, valor2, resultado;
if((textValor1.Text == "")|| (textValor2.Text == ""))
{
MessageBox.Show("Está faltando um valor para completar a operação");
}
else
{
valor1 = Convert.ToDouble(textValor1.Text);
valor2 = Convert.ToDouble(textValor2.Text);
resultado = valor1 + valor2;
lblResultado.Text = resultado.ToString();
}
}
private void btSub_Click(object sender, EventArgs e)
{
double valor1, valor2, resultado;
if((textValor1.Text == "") || (textValor2.Text == ""))
{
MessageBox.Show("Está faltando um valor para completar a operação");
}
else
{
valor1 = Convert.ToDouble(textValor1.Text);
valor2 = Convert.ToDouble(textValor2.Text);
resultado = valor1 - valor2;
lblResultado.Text = resultado.ToString();
}
}
private void btMult_Click(object sender, EventArgs e)
{
double valor1, valor2, resultado;
if((textValor1.Text == "") || (textValor2.Text == ""))
{
MessageBox.Show("Está faltando um valor para completar a operação");
}
else
{
valor1 = Convert.ToDouble(textValor1.Text);
valor2 = Convert.ToDouble(textValor2.Text);
resultado = valor1 * valor2;
lblResultado.Text = resultado.ToString();
}
}
private void btDiv_Click(object sender, EventArgs e)
{
double valor1, valor2, resultado;
if((textValor1.Text == "") || (textValor2.Text == ""))
{
MessageBox.Show("Está faltando um valor para completar a operação");
}
else
{
valor1 = Convert.ToDouble(textValor1.Text);
valor2 = Convert.ToDouble(textValor2.Text);
resultado = valor1 / valor2;
lblResultado.Text = resultado.ToString();
}
}
private void number1_Click(object sender, EventArgs e)
{
textValor1.Text = "1";
}
private void number2_Click(object sender, EventArgs e)
{
textValor1.Text = "2";
}
private void number3_Click(object sender, EventArgs e)
{
textValor1.Text = "3";
}
private void number4_Click(object sender, EventArgs e)
{
textValor1.Text = "4";
}
private void number5_Click(object sender, EventArgs e)
{
textValor1.Text = "5";
}
private void button5_Click(object sender, EventArgs e)
{
textValor1.Text = "6";
}
private void number7_Click(object sender, EventArgs e)
{
textValor1.Text = "7";
}
private void button7_Click(object sender, EventArgs e)
{
textValor1.Text = "8";
}
private void number9_Click(object sender, EventArgs e)
{
textValor1.Text = "9";
}
private void clean_Click(object sender, EventArgs e)
{
textValor1.Text = "";
}
}
}
| 27.077419 | 85 | 0.498213 | [
"MIT"
] | hugobraganca/Calculadora-CSharp | Form1.cs | 4,211 | C# |
/*
* This file is automatically generated; any changes will be lost.
*/
#nullable enable
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Beef;
using Beef.Business;
using Beef.Entities;
using Beef.Validation;
using Beef.Demo.Common.Entities;
using Beef.Demo.Business.Validation;
using Beef.Demo.Business.DataSvc;
using RefDataNamespace = Beef.Demo.Common.Entities;
namespace Beef.Demo.Business
{
/// <summary>
/// Provides the Product business functionality.
/// </summary>
public partial class ProductManager : IProductManager
{
#region Private
#pragma warning disable CS0649 // Defaults to null by design; can be overridden in constructor.
private readonly Func<int, Task>? _getOnPreValidateAsync;
private readonly Action<MultiValidator, int>? _getOnValidate;
private readonly Func<int, Task>? _getOnBeforeAsync;
private readonly Func<Product?, int, Task>? _getOnAfterAsync;
private readonly Func<ProductArgs?, PagingArgs?, Task>? _getByArgsOnPreValidateAsync;
private readonly Action<MultiValidator, ProductArgs?, PagingArgs?>? _getByArgsOnValidate;
private readonly Func<ProductArgs?, PagingArgs?, Task>? _getByArgsOnBeforeAsync;
private readonly Func<ProductCollectionResult, ProductArgs?, PagingArgs?, Task>? _getByArgsOnAfterAsync;
#pragma warning restore CS0649
#endregion
/// <summary>
/// Gets the <see cref="Product"/> object that matches the selection criteria.
/// </summary>
/// <param name="id">The <see cref="Product"/> identifier.</param>
/// <returns>The selected <see cref="Product"/> object where found; otherwise, <c>null</c>.</returns>
public Task<Product?> GetAsync(int id)
{
return ManagerInvoker.Default.InvokeAsync(this, async () =>
{
ExecutionContext.Current.OperationType = OperationType.Read;
EntityBase.CleanUp(id);
if (_getOnPreValidateAsync != null) await _getOnPreValidateAsync(id).ConfigureAwait(false);
MultiValidator.Create()
.Add(id.Validate(nameof(id)).Mandatory())
.Additional((__mv) => _getOnValidate?.Invoke(__mv, id))
.Run().ThrowOnError();
if (_getOnBeforeAsync != null) await _getOnBeforeAsync(id).ConfigureAwait(false);
var __result = await ProductDataSvc.GetAsync(id).ConfigureAwait(false);
if (_getOnAfterAsync != null) await _getOnAfterAsync(__result, id).ConfigureAwait(false);
Cleaner.Clean(__result);
return __result;
});
}
/// <summary>
/// Gets the <see cref="Product"/> collection object that matches the selection criteria.
/// </summary>
/// <param name="args">The Args (see <see cref="ProductArgs"/>).</param>
/// <param name="paging">The <see cref="PagingArgs"/>.</param>
/// <returns>A <see cref="ProductCollectionResult"/>.</returns>
public Task<ProductCollectionResult> GetByArgsAsync(ProductArgs? args, PagingArgs? paging)
{
return ManagerInvoker.Default.InvokeAsync(this, async () =>
{
ExecutionContext.Current.OperationType = OperationType.Read;
EntityBase.CleanUp(args);
if (_getByArgsOnPreValidateAsync != null) await _getByArgsOnPreValidateAsync(args, paging).ConfigureAwait(false);
MultiValidator.Create()
.Add(args.Validate(nameof(args)).Entity(ProductArgsValidator.Default))
.Additional((__mv) => _getByArgsOnValidate?.Invoke(__mv, args, paging))
.Run().ThrowOnError();
if (_getByArgsOnBeforeAsync != null) await _getByArgsOnBeforeAsync(args, paging).ConfigureAwait(false);
var __result = await ProductDataSvc.GetByArgsAsync(args, paging).ConfigureAwait(false);
if (_getByArgsOnAfterAsync != null) await _getByArgsOnAfterAsync(__result, args, paging).ConfigureAwait(false);
Cleaner.Clean(__result);
return __result;
});
}
}
}
#nullable restore | 44.071429 | 129 | 0.644362 | [
"MIT"
] | edjo23/Beef | samples/Demo/Beef.Demo.Business/Generated/ProductManager.cs | 4,319 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(NET35 || NET20 || PORTABLE40)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters;
using System.Text;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class DynamicTests : TestFixtureBase
{
[Test]
public void SerializeDynamicObject()
{
TestDynamicObject dynamicObject = new TestDynamicObject();
dynamicObject.Explicit = true;
dynamic d = dynamicObject;
d.Int = 1;
d.Decimal = 99.9d;
d.ChildObject = new DynamicChildObject();
Dictionary<string, object> values = new Dictionary<string, object>();
IContractResolver c = DefaultContractResolver.Instance;
JsonDynamicContract dynamicContract = (JsonDynamicContract)c.ResolveContract(dynamicObject.GetType());
foreach (string memberName in dynamicObject.GetDynamicMemberNames())
{
object value;
dynamicContract.TryGetMember(dynamicObject, memberName, out value);
values.Add(memberName, value);
}
Assert.AreEqual(d.Int, values["Int"]);
Assert.AreEqual(d.Decimal, values["Decimal"]);
Assert.AreEqual(d.ChildObject, values["ChildObject"]);
string json = JsonConvert.SerializeObject(dynamicObject, Formatting.Indented);
Assert.AreEqual(@"{
""Explicit"": true,
""Decimal"": 99.9,
""Int"": 1,
""ChildObject"": {
""Text"": null,
""Integer"": 0
}
}", json);
TestDynamicObject newDynamicObject = JsonConvert.DeserializeObject<TestDynamicObject>(json);
Assert.AreEqual(true, newDynamicObject.Explicit);
d = newDynamicObject;
Assert.AreEqual(99.9, d.Decimal);
Assert.AreEqual(1, d.Int);
Assert.AreEqual(dynamicObject.ChildObject.Integer, d.ChildObject.Integer);
Assert.AreEqual(dynamicObject.ChildObject.Text, d.ChildObject.Text);
}
#if !(PORTABLE || PORTABLE40)
[Test]
public void SerializeDynamicObjectWithObjectTracking()
{
dynamic o = new ExpandoObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
o.DynamicChildObject = new DynamicChildObject
{
Integer = int.MinValue,
Text = "Child text!"
};
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
});
Console.WriteLine(json);
string dynamicChildObjectTypeName = ReflectionUtils.GetTypeName(typeof(DynamicChildObject), FormatterAssemblyStyle.Full, null);
string expandoObjectTypeName = ReflectionUtils.GetTypeName(typeof(ExpandoObject), FormatterAssemblyStyle.Full, null);
Assert.AreEqual(@"{
""$type"": """ + expandoObjectTypeName + @""",
""Text"": ""Text!"",
""Integer"": 2147483647,
""DynamicChildObject"": {
""$type"": """ + dynamicChildObjectTypeName + @""",
""Text"": ""Child text!"",
""Integer"": -2147483648
}
}", json);
dynamic n = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
});
CustomAssert.IsInstanceOfType(typeof(ExpandoObject), n);
Assert.AreEqual("Text!", n.Text);
Assert.AreEqual(int.MaxValue, n.Integer);
CustomAssert.IsInstanceOfType(typeof(DynamicChildObject), n.DynamicChildObject);
Assert.AreEqual("Child text!", n.DynamicChildObject.Text);
Assert.AreEqual(int.MinValue, n.DynamicChildObject.Integer);
}
#endif
[Test]
public void NoPublicDefaultConstructor()
{
ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Path 'contributors', line 2, position 18.",
() =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var json = @"{
""contributors"": null
}";
JsonConvert.DeserializeObject<DynamicObject>(json, settings);
});
}
public class DictionaryDynamicObject : DynamicObject
{
public IDictionary<string, object> Values { get; private set; }
protected DictionaryDynamicObject()
{
Values = new Dictionary<string, object>();
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Values[binder.Name] = value;
return true;
}
}
[Test]
public void AllowNonPublicDefaultConstructor()
{
var settings = new JsonSerializerSettings();
settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
var json = @"{
""contributors"": null,
""retweeted"": false,
""text"": ""Guys SX4 diesel is launched.what are your plans?catch us at #facebook http://bit.ly/dV3H1a #auto #car #maruti #india #delhi"",
""in_reply_to_user_id_str"": null,
""retweet_count"": 0,
""geo"": null,
""id_str"": ""40678260320768000"",
""in_reply_to_status_id"": null,
""source"": ""<a href=\""http://www.tweetdeck.com\"" rel=\""nofollow\"">TweetDeck</a>"",
""created_at"": ""Thu Feb 24 07:43:47 +0000 2011"",
""place"": null,
""coordinates"": null,
""truncated"": false,
""favorited"": false,
""user"": {
""profile_background_image_url"": ""http://a1.twimg.com/profile_background_images/206944715/twitter_bg.jpg"",
""url"": ""http://bit.ly/dcFwWC"",
""screen_name"": ""marutisuzukisx4"",
""verified"": false,
""friends_count"": 45,
""description"": ""This is the Official Maruti Suzuki SX4 Twitter ID! Men are Back - mail us on social (at) sx4bymaruti (dot) com"",
""follow_request_sent"": null,
""time_zone"": ""Chennai"",
""profile_text_color"": ""333333"",
""location"": ""India"",
""notifications"": null,
""profile_sidebar_fill_color"": ""efefef"",
""id_str"": ""196143889"",
""contributors_enabled"": false,
""lang"": ""en"",
""profile_background_tile"": false,
""created_at"": ""Tue Sep 28 12:55:15 +0000 2010"",
""followers_count"": 117,
""show_all_inline_media"": true,
""listed_count"": 1,
""geo_enabled"": true,
""profile_link_color"": ""009999"",
""profile_sidebar_border_color"": ""eeeeee"",
""protected"": false,
""name"": ""Maruti Suzuki SX4"",
""statuses_count"": 637,
""following"": null,
""profile_use_background_image"": true,
""profile_image_url"": ""http://a3.twimg.com/profile_images/1170694644/Slide1_normal.JPG"",
""id"": 196143889,
""is_translator"": false,
""utc_offset"": 19800,
""favourites_count"": 0,
""profile_background_color"": ""131516""
},
""in_reply_to_screen_name"": null,
""id"": 40678260320768000,
""in_reply_to_status_id_str"": null,
""in_reply_to_user_id"": null
}";
DictionaryDynamicObject foo = JsonConvert.DeserializeObject<DictionaryDynamicObject>(json, settings);
Assert.AreEqual(false, foo.Values["retweeted"]);
}
[Test]
public void SerializeDynamicObjectWithNullValueHandlingIgnore()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Int = int.MaxValue;
o.ChildObject = null; // Tests an explicitly defined property of a dynamic object with a null value.
o.DynamicChildObject = null; // vs. a completely dynamic defined property.
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
});
Console.WriteLine(json);
Assert.AreEqual(@"{
""Explicit"": false,
""Text"": ""Text!"",
""Int"": 2147483647
}", json);
}
[Test]
public void SerializeDynamicObjectWithNullValueHandlingInclude()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Int = int.MaxValue;
o.ChildObject = null; // Tests an explicitly defined property of a dynamic object with a null value.
o.DynamicChildObject = null; // vs. a completely dynamic defined property.
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Include,
});
Console.WriteLine(json);
Assert.AreEqual(@"{
""Explicit"": false,
""Text"": ""Text!"",
""DynamicChildObject"": null,
""Int"": 2147483647,
""ChildObject"": null
}", json);
}
[Test]
public void SerializeDynamicObjectWithDefaultValueHandlingIgnore()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Int = int.MaxValue;
o.IntDefault = 0;
o.NUllableIntDefault = default(int?);
o.ChildObject = null; // Tests an explicitly defined property of a dynamic object with a null value.
o.DynamicChildObject = null; // vs. a completely dynamic defined property.
string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore,
});
Console.WriteLine(json);
Assert.AreEqual(@"{
""Text"": ""Text!"",
""Int"": 2147483647
}", json);
}
}
public class DynamicChildObject
{
public string Text { get; set; }
public int Integer { get; set; }
}
public class TestDynamicObject : DynamicObject
{
private readonly Dictionary<string, object> _members;
public int Int;
[JsonProperty]
public bool Explicit;
public DynamicChildObject ChildObject { get; set; }
internal Dictionary<string, object> Members
{
get { return _members; }
}
public TestDynamicObject()
{
_members = new Dictionary<string, object>();
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _members.Keys.Union(new[] { "Int", "ChildObject" });
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
Type targetType = binder.Type;
if (targetType == typeof(IDictionary<string, object>) ||
targetType == typeof(IDictionary))
{
result = new Dictionary<string, object>(_members);
return true;
}
else
{
return base.TryConvert(binder, out result);
}
}
public override bool TryDeleteMember(DeleteMemberBinder binder)
{
return _members.Remove(binder.Name);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _members.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_members[binder.Name] = value;
return true;
}
}
public class ErrorSettingDynamicObject : DynamicObject
{
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return false;
}
}
}
#endif | 34.320896 | 190 | 0.619845 | [
"MIT"
] | G-P-S/JSON.net-x.y.z | Source/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs | 13,799 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d12video.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public partial struct D3D12_VIDEO_SAMPLE
{
[NativeTypeName("UINT")]
public uint Width;
[NativeTypeName("UINT")]
public uint Height;
public D3D12_VIDEO_FORMAT Format;
}
}
| 28.473684 | 145 | 0.702403 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/d3d12video/D3D12_VIDEO_SAMPLE.cs | 543 | C# |
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Es.ToolsCommon;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Es.Dpo
{
internal sealed class DpoServer
{
private readonly string _dir;
private readonly string _host;
private readonly string _key;
private readonly int _numConcurrent = 64;
private readonly Action<string> _onError;
private readonly Action<string> _onLog;
private readonly TaskCompletionSource<int> _tcs = new TaskCompletionSource<int>();
private CancellationTokenSource _cts;
private readonly ConcurrentDictionary<string, ConcurrentBag<JObject>> _metaDataIndex =
new ConcurrentDictionary<string, ConcurrentBag<JObject>>(StringComparer.OrdinalIgnoreCase);
public DpoServer(string host, string dir, string key, Action<string> onError, Action<string> onLog = null)
{
_host = host;
_dir = dir;
_key = key;
_onError = onError;
_onLog = onLog;
}
private static int CurrentPid()
{
int pid;
NativeMethods.GetWindowThreadProcessId(Process.GetCurrentProcess().MainWindowHandle, out pid);
return pid;
}
public async Task Run(CancellationToken cancellationToken)
{
_cts = new CancellationTokenSource();
CreateDirectoryRecursive(_dir);
File.WriteAllText($"{_dir}/pid", CurrentPid().ToString());
PruneEmpty(_dir);
SetupMetaData();
// ReSharper disable AccessToDisposedClosure
cancellationToken.Register(() => { _cts?.Cancel(); });
// ReSharper restore AccessToDisposedClosure
_cts.Token.Register(() => _tcs.SetResult(0));
using (var hl = new HttpListener())
{
//_tasks = new Task[_numConcurrent];
try
{
hl.Prefixes.Add($"http://{_host}/dpo/");
hl.Start();
}
catch (Exception ex)
{
_onError(ex.ToString());
}
for (var i = 0; i < _numConcurrent; ++i)
Start(hl);
await _tcs.Task;
hl.Abort();
hl.Stop();
// Because GetContextAsync doesn't take a cancellation token, or check for abort/stop
// conditions, our tasks are stuck and your only option is to orphan them. Thanks Microsoft!
}
_cts.Dispose();
_cts = null;
}
private void SetupMetaData()
{
foreach (var f in Directory.EnumerateFiles(_dir, "*.meta.json", SearchOption.AllDirectories))
{
_onLog?.Invoke($"{f}");
var pn = Path.GetFileName(Path.GetDirectoryName(f));
if (pn==null)
continue;
var zfn = f.Replace(".meta.json", ".zip");
var fn = Path.GetFileName(zfn);
if (!File.Exists(zfn))
continue;
_onLog?.Invoke($"{pn} {zfn}");
var md = JObject.Parse(File.ReadAllText(f));
md["pak"] = fn;
foreach (var tag in md.GetValue("tags", new string[] {}))
{
_metaDataIndex.GetOrAdd(tag,new ConcurrentBag<JObject>()).Add(md);
}
_metaDataIndex.GetOrAdd(pn, new ConcurrentBag<JObject>()).Add(md);
}
//if (_onLog == null)
// return;
//foreach (var bag in _metaDataIndex) { foreach (var entry in bag.Value) { _onLog($"{bag.Key} -> {entry}"); } }
}
private void Start(HttpListener hl)
{
ProcessRequest(hl)
.ContinueWith(
t =>
{
if (t.IsCompleted && !t.IsCanceled)
{
Start(hl);
}
});
}
private async Task DoRequest(HttpListenerContext httpListenerContext)
{
var resp = httpListenerContext.Response;
var req = httpListenerContext.Request;
var pathAndQuery = req.Url.PathAndQuery;
if (req.HttpMethod == "GET")
{
if (!pathAndQuery.Contains("?"))
{
var file = pathAndQuery.After("dpo/");
if (!string.IsNullOrWhiteSpace(file))
{
var tuple = await ParseFileRequest(file, resp);
if (tuple == null)
return;
var path = tuple.Item1;
var fi = new FileInfo(path + "/" + file);
if (!fi.Exists)
{
var respData = Encoding.UTF8.GetBytes("NOT FOUND");
resp.ContentType = "text/plain";
resp.StatusCode = 404;
await resp.OutputStream.WriteAsync(respData, 0, respData.Length, _cts.Token);
resp.Close();
return;
}
resp.ContentType = "application/octet-stream";
resp.Headers.Add("Content-Disposition", $"attachment; filename=\"{file}\"");
resp.Headers.Add("Content-Transfer-Encoding", "binary");
resp.ContentLength64 = fi.Length;
using (var ifs = fi.OpenRead())
{
await ifs.CopyToAsync(resp.OutputStream);
}
resp.Close();
return;
}
}
if (pathAndQuery.Contains("?q="))
{
var query = pathAndQuery.After("?q=");
if (!string.IsNullOrWhiteSpace(query))
{
resp.ContentType = "text/plain";
resp.StatusCode = 200;
var qa = new JArray();
foreach (var qq in query.Split(','))
{
ConcurrentBag<JObject> bag;
if (!_metaDataIndex.TryGetValue(qq.Trim(), out bag))
continue;
foreach (var e in bag)
{
qa.Add(e);
}
}
var respData = Encoding.UTF8.GetBytes(new JObject {["q"] = qa}.ToString(Formatting.Indented));
await resp.OutputStream.WriteAsync(respData, 0, respData.Length, _cts.Token);
resp.Close();
return;
}
}
{
var respData = Encoding.UTF8.GetBytes($"{Program._id}");
await resp.OutputStream.WriteAsync(respData, 0, respData.Length, _cts.Token);
resp.Close();
return;
}
}
if (req.HttpMethod == "PUT")
{
var file = pathAndQuery.After("dpo/").Before("?");
resp.ContentType = "text/plain";
var key = pathAndQuery.After("?key=");
var tuple = await ParseFileRequest(file, resp);
if (tuple == null)
return;
var path = tuple.Item1;
var basename = tuple.Item2;
var allowed = _key == key;
if (!allowed)
{
resp.StatusCode = 403;
var respData = Encoding.UTF8.GetBytes("403 FORBIDDEN");
await resp.OutputStream.WriteAsync(respData, 0, respData.Length, _cts.Token);
resp.Close();
return;
}
var filename = path + "/" + file;
if (File.Exists(filename))
{
resp.StatusCode = 400;
var respData = Encoding.UTF8.GetBytes(
$"EXISTS\nfile: {file}\nbasename: {basename}\npath: {path}\n");
await resp.OutputStream.WriteAsync(respData, 0, respData.Length, _cts.Token);
resp.Close();
return;
}
try
{
CreateDirectoryRecursive(path);
_onLog($"PUT {filename}");
using (var ofs = new FileStream(filename, FileMode.CreateNew))
await req.InputStream.CopyToAsync(ofs);
using (var zf = new ZipFile(filename))
{
foreach (ZipEntry ze in zf)
{
if (!ze.IsFile || !ze.Name.EndsWith(".meta.json"))
continue;
var zs = zf.GetInputStream(ze);
using (var ofs = new FileStream(path + "/" + Path.GetFileName(ze.Name),FileMode.CreateNew))
{
await zs.CopyToAsync(ofs);
}
break;
}
}
resp.StatusCode = 200;
var respData = Encoding.UTF8.GetBytes("OK");
await resp.OutputStream.WriteAsync(respData, 0, respData.Length, _cts.Token);
resp.Close();
}
catch (Exception ex)
{
_onError($"{ex}");
resp.StatusCode = 500;
var respData = Encoding.UTF8.GetBytes("SERVER ERROR");
await resp.OutputStream.WriteAsync(respData, 0, respData.Length, _cts.Token);
resp.Close();
}
}
}
private async Task<Tuple<string,string>> ParseFileRequest(string file, HttpListenerResponse resp)
{
var valid = !(file.Contains("/") || file.Contains("\\")) && file.EndsWith(".zip") && file.Contains("-v");
var path = "invalid";
var basename = "invalid";
if (!valid)
{
resp.StatusCode = 400;
var respData = Encoding.UTF8.GetBytes(
$"INVALID\nfile: {file}\nbasename: {basename}\npath: {path}\n");
await resp.OutputStream.WriteAsync(respData, 0, respData.Length, _cts.Token);
resp.Close();
return null;
}
basename = file.Before("-v");
var hash = basename.Hash().ToString("x016");
path = $"{_dir}/{hash.Substring(0, 2)}/{hash.Substring(2, 2)}/{hash.Substring(4)}/{basename}";
return Tuple.Create(path, basename);
}
private void PruneEmpty(string dir)
{
_onLog?.Invoke($"Prune: {dir}");
if (!Directory.Exists(dir))
return;
foreach (var d in Directory.GetDirectories(dir))
PruneEmpty(d);
TryDeleteDirectory(dir);
}
private void TryDeleteDirectory(string dir)
{
try
{
if (Directory.GetFileSystemEntries(dir).Length != 0)
return;
Directory.Delete(dir);
_onLog?.Invoke($"\tDeleted: {dir}");
}
catch
{
//ignored
}
}
private void CreateDirectoryRecursive(string path)
{
var parts = path.Split(Path.DirectorySeparatorChar);
var sb = new StringBuilder(path.Length);
foreach (var s in parts)
{
sb.Append(s).Append(Path.DirectorySeparatorChar);
var dir = sb.ToString();
try
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
catch (Exception)
{
_onError($"Couldn't create directory : {dir}, building path={path} failed on part {s}");
throw;
}
}
}
private async Task ProcessRequest(HttpListener hl)
{
try
{
var getContext = hl.GetContextAsync();
await getContext;
if (_cts.IsCancellationRequested || getContext.IsCanceled)
return;
var httpListenerContext = getContext.Result;
await DoRequest(httpListenerContext);
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
_onError(ex.ToString());
}
}
public void Stop()
{
using (var wc = new WebClient())
{
try
{
// ping the server to cause all the pending GetContentAsyncs to fail so the server actually shuts down
wc.DownloadStringTaskAsync(new Uri($"http://{_host}/dpo/ping/"));
}
catch
{
// ignored
}
}
}
private static class NativeMethods
{
[DllImport("user32")]
public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
}
}
} | 34.84878 | 124 | 0.449328 | [
"MIT"
] | EnokiSolutions/es-workflow | Es.Dpo/DpoServer.cs | 14,288 | C# |
namespace Wingman.Tests.ServiceFactory
{
using System;
using Moq;
using Wingman.Container;
using Wingman.ServiceFactory;
using Wingman.ServiceFactory.Strategies;
using Xunit;
public class ServiceFactoryRegistrarTests
{
private readonly Mock<IServiceRetrievalStrategy> _fromRetrieverRetrievalStrategy;
private readonly Mock<IServiceRetrievalStrategy> _perRequestRetrievalStrategy;
private readonly Mock<IDependencyRegistrar> _dependencyRegistrarMock;
private readonly Mock<IRetrievalStrategyStore> _retrievalStrategyStore;
private readonly ServiceFactoryRegistrar _serviceFactory;
public ServiceFactoryRegistrarTests()
{
_fromRetrieverRetrievalStrategy = new Mock<IServiceRetrievalStrategy>();
_perRequestRetrievalStrategy = new Mock<IServiceRetrievalStrategy>();
_dependencyRegistrarMock = new Mock<IDependencyRegistrar>();
Mock<IRetrievalStrategyFactory> retrievalStrategyFactoryMock = new Mock<IRetrievalStrategyFactory>();
retrievalStrategyFactoryMock.Setup(factory => factory.CreateFromRetriever(typeof(IService)))
.Returns(_fromRetrieverRetrievalStrategy.Object);
retrievalStrategyFactoryMock.Setup(factory => factory.CreatePerRequest(typeof(Service)))
.Returns(_perRequestRetrievalStrategy.Object);
_retrievalStrategyStore = new Mock<IRetrievalStrategyStore>();
_serviceFactory = new ServiceFactoryRegistrar(_dependencyRegistrarMock.Object,
retrievalStrategyFactoryMock.Object,
_retrievalStrategyStore.Object);
}
[Fact]
public void RegisterFromRetrieverThrowsWhenNoHandlerRegistered()
{
Action register = () => _serviceFactory.RegisterFromRetriever<IService>();
Assert.Throws<InvalidOperationException>(register);
VerifyHasHandlerCalled();
}
[Fact]
public void RegisterFromRetrieverThrowsWhenDuplicateRegistered()
{
SetupServiceIsRegistered();
SetupHasServiceHandler();
Action register = () => _serviceFactory.RegisterFromRetriever<IService>();
Assert.Throws<InvalidOperationException>(register);
VerifyIsRegisteredCalled();
}
[Fact]
public void RegisterFromRetrieverInsertsIntoStore()
{
SetupHasServiceHandler();
_serviceFactory.RegisterFromRetriever<IService>();
VerifyInsertFromRetrieverStrategyCalled();
}
[Fact]
public void RegisterPerRequestThrowsWhenDuplicateRegistered()
{
SetupServiceIsRegistered();
Action register = () => _serviceFactory.RegisterPerRequest<IService, Service>();
Assert.Throws<InvalidOperationException>(register);
VerifyIsRegisteredCalled();
}
[Fact]
public void RegisterPerRequestThrowsWhenConcreteTypeIsNotConcrete()
{
Action register = () => _serviceFactory.RegisterPerRequest<IService, IService>();
Assert.Throws<InvalidOperationException>(register);
}
[Fact]
public void RegisterPerRequestInsertsIntoStore()
{
_serviceFactory.RegisterPerRequest<IService, Service>();
VerifyInsertPerRequestStrategyCalled();
}
private void SetupHasServiceHandler()
{
_dependencyRegistrarMock.Setup(registrar => registrar.HasHandler(typeof(IService), null))
.Returns(true);
}
private void SetupServiceIsRegistered()
{
_retrievalStrategyStore.Setup(store => store.IsRegistered(typeof(IService)))
.Returns(true);
}
private void VerifyHasHandlerCalled()
{
_dependencyRegistrarMock.Verify(registrar => registrar.HasHandler(typeof(IService), null));
}
private void VerifyInsertFromRetrieverStrategyCalled()
{
_retrievalStrategyStore.Verify(store => store.Insert(typeof(IService), _fromRetrieverRetrievalStrategy.Object));
}
private void VerifyInsertPerRequestStrategyCalled()
{
_retrievalStrategyStore.Verify(store => store.Insert(typeof(IService), _perRequestRetrievalStrategy.Object));
}
private void VerifyIsRegisteredCalled()
{
_retrievalStrategyStore.Verify(store => store.IsRegistered(typeof(IService)));
}
private interface IService { }
private class Service : IService { }
}
} | 34.707143 | 124 | 0.641902 | [
"MIT"
] | Aleksbgbg/Wingman | Wingman.Tests/ServiceFactory/ServiceFactoryRegistrarTests.cs | 4,861 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace Skattergy.Core
{
public struct WorldPosition
{
public Vector2 Position { get; }
public Dictionary<Resource, int> ResourceValues { get; }
}
} | 21.181818 | 64 | 0.686695 | [
"Apache-2.0"
] | kyranet/skattergy | Skattergy/Assets/Scripts/Skattergy/Core/WorldPosition.cs | 235 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using ServiceStack.Common;
using ServiceStack.OrmLite;
using ServiceStack.Text;
namespace ServiceStack.ServiceInterface.Auth
{
public class OrmLiteAuthRepository : IUserAuthRepository, IClearable
{
//http://stackoverflow.com/questions/3588623/c-sharp-regex-for-a-username-with-a-few-restrictions
public Regex ValidUserNameRegEx = new Regex(@"^(?=.{3,15}$)([A-Za-z0-9][._-]?)*$", RegexOptions.Compiled);
private readonly IDbConnectionFactory dbFactory;
public OrmLiteAuthRepository(IDbConnectionFactory dbFactory)
{
this.dbFactory = dbFactory;
}
public void CreateMissingTables()
{
dbFactory.Exec(dbCmd => {
dbCmd.CreateTable<UserAuth>(false);
dbCmd.CreateTable<UserOAuthProvider>(false);
});
}
public void DropAndReCreateTables()
{
dbFactory.Exec(dbCmd => {
dbCmd.CreateTable<UserAuth>(true);
dbCmd.CreateTable<UserOAuthProvider>(true);
});
}
public UserAuth CreateUserAuth(UserAuth newUser, string password)
{
newUser.ThrowIfNull("newUser");
password.ThrowIfNullOrEmpty("password");
if (newUser.UserName.IsNullOrEmpty() && newUser.Email.IsNullOrEmpty())
throw new ArgumentNullException("UserName or Email is required");
if (!newUser.UserName.IsNullOrEmpty())
{
if (!ValidUserNameRegEx.IsMatch(newUser.UserName))
throw new ArgumentException("UserName contains invalid characters", "UserName");
}
return dbFactory.Exec(dbCmd => {
var effectiveUserName = newUser.UserName ?? newUser.Email;
var existingUser = GetUserAuthByUserName(dbCmd, effectiveUserName);
if (existingUser != null)
throw new ArgumentException("User {0} already exists".Fmt(effectiveUserName));
var saltedHash = new SaltedHash();
string salt;
string hash;
saltedHash.GetHashAndSaltString(password, out hash, out salt);
newUser.PasswordHash = hash;
newUser.Salt = salt;
dbCmd.Insert(newUser);
newUser = dbCmd.GetById<UserAuth>(dbCmd.GetLastInsertId());
return newUser;
});
}
public UserAuth GetUserAuthByUserName(string userNameOrEmail)
{
return dbFactory.Exec(dbCmd => GetUserAuthByUserName(dbCmd, userNameOrEmail));
}
private static UserAuth GetUserAuthByUserName(IDbCommand dbCmd, string userNameOrEmail)
{
var isEmail = userNameOrEmail.Contains("@");
var userAuth = isEmail
? dbCmd.FirstOrDefault<UserAuth>("Email = {0}", userNameOrEmail)
: dbCmd.FirstOrDefault<UserAuth>("UserName = {0}", userNameOrEmail);
return userAuth;
}
public bool TryAuthenticate(string userName, string password, out string userId)
{
userId = null;
var userAuth = GetUserAuthByUserName(userName);
if (userAuth == null) return false;
var saltedHash = new SaltedHash();
if (saltedHash.VerifyHashString(password, userAuth.PasswordHash, userAuth.Salt))
{
userId = userAuth.Id.ToString();
return true;
}
return false;
}
public void LoadUserAuth(IAuthSession session, IOAuthTokens tokens)
{
session.ThrowIfNull("session");
var userAuth = GetUserAuth(session, tokens);
LoadUserAuth(session, userAuth);
}
private void LoadUserAuth(IAuthSession session, UserAuth userAuth)
{
if (userAuth == null) return;
session.UserAuthId = userAuth.Id.ToString();
session.DisplayName = userAuth.DisplayName;
session.FirstName = userAuth.FirstName;
session.LastName = userAuth.LastName;
session.Email = userAuth.Email;
}
public UserAuth GetUserAuth(string userAuthId)
{
return dbFactory.Exec(dbCmd => dbCmd.GetByIdOrDefault<UserAuth>(userAuthId));
}
public void SaveUserAuth(IAuthSession authSession)
{
dbFactory.Exec(dbCmd => {
var userAuth = !authSession.UserAuthId.IsNullOrEmpty()
? dbCmd.GetByIdOrDefault<UserAuth>(authSession.UserAuthId)
: authSession.TranslateTo<UserAuth>();
if (userAuth.Id == default(int) && !authSession.UserAuthId.IsNullOrEmpty())
userAuth.Id = int.Parse(authSession.UserAuthId);
dbCmd.Save(userAuth);
});
}
public void SaveUserAuth(UserAuth userAuth)
{
dbFactory.Exec(dbCmd => dbCmd.Save(userAuth));
}
public List<UserOAuthProvider> GetUserOAuthProviders(string userAuthId)
{
return dbFactory.Exec(dbCmd =>
dbCmd.Select<UserOAuthProvider>("UserAuthId = {0}", userAuthId));
}
public UserAuth GetUserAuth(IAuthSession authSession, IOAuthTokens tokens)
{
if (!authSession.UserAuthId.IsNullOrEmpty())
{
var userAuth = GetUserAuth(authSession.UserAuthId);
if (userAuth != null) return userAuth;
}
if (!authSession.UserName.IsNullOrEmpty())
{
var userAuth = GetUserAuthByUserName(authSession.UserName);
if (userAuth != null) return userAuth;
}
if (tokens == null || tokens.Provider.IsNullOrEmpty() || tokens.UserId.IsNullOrEmpty())
return null;
return dbFactory.Exec(dbCmd => {
var oAuthProvider = dbCmd.FirstOrDefault<UserOAuthProvider>(
"Provider = {0} AND UserId = {1}", tokens.Provider, tokens.UserId);
if (oAuthProvider != null)
{
var userAuth = dbCmd.GetByIdOrDefault<UserAuth>(oAuthProvider.UserAuthId);
return userAuth;
}
return null;
});
}
public string CreateOrMergeAuthSession(IAuthSession authSession, IOAuthTokens tokens)
{
var userAuth = GetUserAuth(authSession, tokens) ?? new UserAuth();
return dbFactory.Exec(dbCmd => {
var oAuthProvider = dbCmd.FirstOrDefault<UserOAuthProvider>(
"Provider = {0} AND UserId = {1}", tokens.Provider, tokens.UserId);
if (oAuthProvider == null)
{
oAuthProvider = new UserOAuthProvider {
Provider = tokens.Provider,
UserId = tokens.UserId,
};
}
oAuthProvider.PopulateMissing(tokens);
userAuth.PopulateMissing(oAuthProvider);
dbCmd.Save(userAuth);
oAuthProvider.UserAuthId = userAuth.Id != default(int)
? userAuth.Id
: (int) dbCmd.GetLastInsertId();
dbCmd.Save(oAuthProvider);
return oAuthProvider.UserAuthId.ToString();
});
}
public void Clear()
{
dbFactory.Exec(dbCmd => {
dbCmd.DeleteAll<UserAuth>();
dbCmd.DeleteAll<UserOAuthProvider>();
});
}
}
} | 29.103604 | 109 | 0.684105 | [
"BSD-3-Clause"
] | xamarin/ServiceStack | src/ServiceStack.ServiceInterface/Auth/OrmLiteAuthRepository.cs | 6,463 | C# |
namespace Votify.Api.ApiModels
{
public class TokenInfo
{
public string ClientId { get; set; }
public string Scope { get; set; }
}
}
| 18.888889 | 45 | 0.564706 | [
"MIT"
] | villor/votify | Votify/Votify.Api/ApiModels/TokenInfo.cs | 172 | 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("03_MoveDownRight")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03_MoveDownRight")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("5a36b631-1b26-4699-b92d-4736df70ebb5")]
// 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.837838 | 84 | 0.749286 | [
"MIT"
] | MrPIvanov/SoftUni | 13-Algorithms/08_DYNAMIC PROGRAMMING/DynamicProgrammingPart01Lab/03_MoveDownRight/Properties/AssemblyInfo.cs | 1,403 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
public class BringUpTest
{
const int Pass = 100;
const int Fail = -1;
// This test method returns:
// 1 if x == int.MinValue
// 2 if int.MinValue < x < -1
// 3 if x == -1
// 4 if x == 0
// 5 if x == 1
// 6 if 1 < x < int.MaxValue
// 7 if x == int.MaxValue
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int JTrueLtInt1(int x)
{
int returnValue = -1;
if (x < int.MinValue)
returnValue = 0; // Never true
else if (x < (int.MinValue + 1))
returnValue = 1;
else if (x < -1)
returnValue = 2;
else if (x < 0)
returnValue = 3;
else if (x < 1)
returnValue = 4;
else if (x < (int.MaxValue - 1))
returnValue = 5;
else if (x < int.MaxValue)
returnValue = 6;
else
returnValue = 7;
return returnValue;
}
public static int Main()
{
int returnValue = Pass;
if (JTrueLtInt1(int.MinValue) != 1)
returnValue = Fail;
if (JTrueLtInt1(int.MinValue + 1) != 2)
returnValue = Fail;
if (JTrueLtInt1(-1) != 3)
returnValue = Fail;
if (JTrueLtInt1(0) != 4)
returnValue = Fail;
if (JTrueLtInt1(1) != 5)
returnValue = Fail;
if (JTrueLtInt1(int.MaxValue - 1) != 6)
returnValue = Fail;
if (JTrueLtInt1(int.MaxValue) != 7)
returnValue = Fail;
return returnValue;
}
}
| 25.285714 | 71 | 0.516949 | [
"MIT"
] | belav/runtime | src/tests/JIT/CodeGenBringUpTests/JTrueLtInt1.cs | 1,770 | C# |
/*
This source file is under MIT License (MIT)
Copyright (c) 2019 Ian Schlarman
https://opensource.org/licenses/MIT
*/
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace Epilog.Extractor.Models
{
public class Usage
{
/// <summary>
/// Paragraph Label
/// </summary>
public string Pl { get; set; }
/// <summary>
/// Paragraph Text
/// </summary>
public List<JArray> Pt { get; set; }
}
}
| 18.111111 | 44 | 0.584867 | [
"MIT"
] | kaylerich/epilexi-mwcollegiate | Epilog.MWC/Epilog.Dictionary.Extractor.MWCollegiate/Models/Usage.cs | 491 | C# |
// Copyright: ZhongShan KPP Technology Co
// Date: 2018-02-26
// Time: 16:22
// Author: Karsion
using UnityEditor;
using UnityEngine;
namespace UnrealM
{
[CustomEditor(typeof(ActionSequenceSystem))]
public class ActionSequenceSystemInspector : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
int countAll, countActive;
GUILayout.Label("ObjectPool State: Active/All", EditorStyles.boldLabel);
ActionNodeAction.GetObjectPoolInfo(out countActive, out countAll);
GUILayout.Label(string.Format("ActionNode: {0}/{1}", countActive, countAll));
ActionNodeInterval.GetObjectPoolInfo(out countActive, out countAll);
GUILayout.Label(string.Format("IntervalNode: {0}/{1}", countActive, countAll));
ActionNodeCondition.GetObjectPoolInfo(out countActive, out countAll);
GUILayout.Label(string.Format("ConditionNode: {0}/{1}", countActive, countAll));
ActionSequence.GetObjectPoolInfo(out countActive, out countAll);
GUILayout.Label(string.Format("Sequence: {0}/{1}", countActive, countAll));
//Showing ActionSequences in progress
ActionSequenceSystem actionSequenceSystem = target as ActionSequenceSystem;
GUILayout.Label(string.Format("Sequence Count: {0}", actionSequenceSystem.ListSequence.Count), EditorStyles.boldLabel);
for (int i = 0; i < actionSequenceSystem.ListSequence.Count; i++)
{
if (!actionSequenceSystem.ListSequence[i].isFinshed)
{
GUILayout.Box(string.Format("{0} id: {1}\n Loop:{2}/{3}", i, actionSequenceSystem.ListSequence[i].id,
actionSequenceSystem.ListSequence[i].cycles, actionSequenceSystem.ListSequence[i].loopTime), "TextArea");
}
}
Repaint();
}
}
} | 44.659091 | 153 | 0.636132 | [
"MIT"
] | Unreal-M/ActionSequenceSystem | Assets/Tools/ActionSequenceSystem/Editor/ActionSequenceSystemInspector.cs | 1,967 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Xunit;
namespace ComponentImporterUnitTests
{
public class ImportZipFixture : IDisposable
{
public ImportZipFixture()
{
// First, copy BlankInputModel/InputModel.xme into the test folder
File.Delete(ImportZip.mgaPath);
GME.MGA.MgaUtils.ImportXME(Common.blankInputModelPath, ImportZip.mgaPath);
Assert.True(File.Exists(ImportZip.mgaPath), "Input model not found; import may have failed.");
}
public void Dispose()
{
// Nothing to do
}
}
}
| 25.769231 | 106 | 0.646269 | [
"MIT"
] | lefevre-fraser/openmeta-mms | test/InterchangeTest/ComponentInterchangeTest/ImportTestUnits/ImportZipFixture.cs | 672 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.SimpleEmail.Model
{
/// <summary>
/// <para>An empty element. Receiving this element indicates that the request completed successfully.</para>
/// </summary>
public class DeleteIdentityResult
{
}
}
| 30.806452 | 112 | 0.718325 | [
"Apache-2.0"
] | mahanthbeeraka/dataservices-sdk-dotnet | AWSSDK/Amazon.SimpleEmail/Model/DeleteIdentityResult.cs | 955 | C# |
using System.Threading;
using Content.Shared.Actions.ActionTypes;
using Robust.Shared.Utility;
namespace Content.Server.Medical.Components
{
/// <summary>
/// Adds an innate verb when equipped to use a stethoscope.
/// </summary>
[RegisterComponent]
public sealed class StethoscopeComponent : Component
{
public bool IsActive = false;
public CancellationTokenSource? CancelToken;
[DataField("delay")]
public float Delay = 2.5f;
public EntityTargetAction Action = new()
{
Icon = new SpriteSpecifier.Texture(new ResourcePath("Clothing/Neck/Misc/stethoscope.rsi/icon.png")),
Name = "stethoscope-verb",
Priority = -1,
Event = new StethoscopeActionEvent(),
};
}
}
| 27.413793 | 112 | 0.640252 | [
"MIT"
] | EmoGarbage404/space-station-14 | Content.Server/Medical/Stethoscope/Components/StethoscopeComponent.cs | 795 | C# |
// ----------------------------------------------------------------------------
// <copyright file="PhotonAnimatorView.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2016 Exit Games GmbH
// </copyright>
// <summary>
// Component to synchronize Mecanim animations via PUN.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// This class helps you to synchronize Mecanim animations
/// Simply add the component to your GameObject and make sure that
/// the PhotonAnimatorView is added to the list of observed components
/// </summary>
/// <remarks>
/// When Using Trigger Parameters, make sure the component that sets the trigger is higher in the stack of Components on the GameObject than 'PhotonAnimatorView'
/// Triggers are raised true during one frame only.
/// </remarks>
[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(PhotonView))]
[AddComponentMenu("Photon Networking/Photon Animator View")]
public class PhotonAnimatorView : MonoBehaviour, IPunObservable
{
#region Enums
public enum ParameterType
{
Float = 1,
Int = 3,
Bool = 4,
Trigger = 9,
}
public enum SynchronizeType
{
Disabled = 0,
Discrete = 1,
Continuous = 2,
}
[System.Serializable]
public class SynchronizedParameter
{
public ParameterType Type;
public SynchronizeType SynchronizeType;
public string Name;
}
[System.Serializable]
public class SynchronizedLayer
{
public SynchronizeType SynchronizeType;
public int LayerIndex;
}
#endregion
#region Properties
#if PHOTON_DEVELOP
public PhotonAnimatorView ReceivingSender;
#endif
#endregion
#region Members
private Animator m_Animator;
private PhotonStreamQueue m_StreamQueue;
//These fields are only used in the CustomEditor for this script and would trigger a
//"this variable is never used" warning, which I am suppressing here
#pragma warning disable 0414
[HideInInspector]
[SerializeField]
private bool ShowLayerWeightsInspector = true;
[HideInInspector]
[SerializeField]
private bool ShowParameterInspector = true;
#pragma warning restore 0414
[HideInInspector]
[SerializeField]
private List<SynchronizedParameter> m_SynchronizeParameters = new List<SynchronizedParameter>();
[HideInInspector]
[SerializeField]
private List<SynchronizedLayer> m_SynchronizeLayers = new List<SynchronizedLayer>();
private Vector3 m_ReceiverPosition;
private float m_LastDeserializeTime;
private bool m_WasSynchronizeTypeChanged = true;
private PhotonView m_PhotonView;
/// <summary>
/// Cached raised triggers that are set to be synchronized in discrete mode. since a Trigger only stay up for less than a frame,
/// We need to cache it until the next discrete serialization call.
/// </summary>
List<string> m_raisedDiscreteTriggersCache = new List<string>();
#endregion
#region Unity
private void Awake()
{
this.m_PhotonView = GetComponent<PhotonView>();
this.m_StreamQueue = new PhotonStreamQueue(120);
this.m_Animator = GetComponent<Animator>();
}
private void Update()
{
if (this.m_Animator.applyRootMotion && this.m_PhotonView.isMine == false && PhotonNetwork.connected == true)
{
this.m_Animator.applyRootMotion = false;
}
if (PhotonNetwork.inRoom == false || PhotonNetwork.room.PlayerCount <= 1)
{
this.m_StreamQueue.Reset();
return;
}
if (this.m_PhotonView.isMine == true)
{
this.SerializeDataContinuously();
this.CacheDiscreteTriggers();
}
else
{
this.DeserializeDataContinuously();
}
}
#endregion
#region Setup Synchronizing Methods
/// <summary>
/// Caches the discrete triggers values for keeping track of raised triggers, and will be reseted after the sync routine got performed
/// </summary>
public void CacheDiscreteTriggers()
{
for (int i = 0; i < this.m_SynchronizeParameters.Count; ++i)
{
SynchronizedParameter parameter = this.m_SynchronizeParameters[i];
if (parameter.SynchronizeType == SynchronizeType.Discrete && parameter.Type == ParameterType.Trigger && this.m_Animator.GetBool(parameter.Name))
{
if (parameter.Type == ParameterType.Trigger)
{
this.m_raisedDiscreteTriggersCache.Add(parameter.Name);
break;
}
}
}
}
/// <summary>
/// Check if a specific layer is configured to be synchronize
/// </summary>
/// <param name="layerIndex">Index of the layer.</param>
/// <returns>True if the layer is synchronized</returns>
public bool DoesLayerSynchronizeTypeExist(int layerIndex)
{
return this.m_SynchronizeLayers.FindIndex(item => item.LayerIndex == layerIndex) != -1;
}
/// <summary>
/// Check if the specified parameter is configured to be synchronized
/// </summary>
/// <param name="name">The name of the parameter.</param>
/// <returns>True if the parameter is synchronized</returns>
public bool DoesParameterSynchronizeTypeExist(string name)
{
return this.m_SynchronizeParameters.FindIndex(item => item.Name == name) != -1;
}
/// <summary>
/// Get a list of all synchronized layers
/// </summary>
/// <returns>List of SynchronizedLayer objects</returns>
public List<SynchronizedLayer> GetSynchronizedLayers()
{
return this.m_SynchronizeLayers;
}
/// <summary>
/// Get a list of all synchronized parameters
/// </summary>
/// <returns>List of SynchronizedParameter objects</returns>
public List<SynchronizedParameter> GetSynchronizedParameters()
{
return this.m_SynchronizeParameters;
}
/// <summary>
/// Gets the type how the layer is synchronized
/// </summary>
/// <param name="layerIndex">Index of the layer.</param>
/// <returns>Disabled/Discrete/Continuous</returns>
public SynchronizeType GetLayerSynchronizeType(int layerIndex)
{
int index = this.m_SynchronizeLayers.FindIndex(item => item.LayerIndex == layerIndex);
if (index == -1)
{
return SynchronizeType.Disabled;
}
return this.m_SynchronizeLayers[index].SynchronizeType;
}
/// <summary>
/// Gets the type how the parameter is synchronized
/// </summary>
/// <param name="name">The name of the parameter.</param>
/// <returns>Disabled/Discrete/Continuous</returns>
public SynchronizeType GetParameterSynchronizeType(string name)
{
int index = this.m_SynchronizeParameters.FindIndex(item => item.Name == name);
if (index == -1)
{
return SynchronizeType.Disabled;
}
return this.m_SynchronizeParameters[index].SynchronizeType;
}
/// <summary>
/// Sets the how a layer should be synchronized
/// </summary>
/// <param name="layerIndex">Index of the layer.</param>
/// <param name="synchronizeType">Disabled/Discrete/Continuous</param>
public void SetLayerSynchronized(int layerIndex, SynchronizeType synchronizeType)
{
if (Application.isPlaying == true)
{
this.m_WasSynchronizeTypeChanged = true;
}
int index = this.m_SynchronizeLayers.FindIndex(item => item.LayerIndex == layerIndex);
if (index == -1)
{
this.m_SynchronizeLayers.Add(new SynchronizedLayer { LayerIndex = layerIndex, SynchronizeType = synchronizeType });
}
else
{
this.m_SynchronizeLayers[index].SynchronizeType = synchronizeType;
}
}
/// <summary>
/// Sets the how a parameter should be synchronized
/// </summary>
/// <param name="name">The name of the parameter.</param>
/// <param name="type">The type of the parameter.</param>
/// <param name="synchronizeType">Disabled/Discrete/Continuous</param>
public void SetParameterSynchronized(string name, ParameterType type, SynchronizeType synchronizeType)
{
if (Application.isPlaying == true)
{
this.m_WasSynchronizeTypeChanged = true;
}
int index = this.m_SynchronizeParameters.FindIndex(item => item.Name == name);
if (index == -1)
{
this.m_SynchronizeParameters.Add(new SynchronizedParameter { Name = name, Type = type, SynchronizeType = synchronizeType });
}
else
{
this.m_SynchronizeParameters[index].SynchronizeType = synchronizeType;
}
}
#endregion
#region Serialization
private void SerializeDataContinuously()
{
if (this.m_Animator == null)
{
return;
}
for (int i = 0; i < this.m_SynchronizeLayers.Count; ++i)
{
if (this.m_SynchronizeLayers[i].SynchronizeType == SynchronizeType.Continuous)
{
this.m_StreamQueue.SendNext(this.m_Animator.GetLayerWeight(this.m_SynchronizeLayers[i].LayerIndex));
}
}
for (int i = 0; i < this.m_SynchronizeParameters.Count; ++i)
{
SynchronizedParameter parameter = this.m_SynchronizeParameters[i];
if (parameter.SynchronizeType == SynchronizeType.Continuous)
{
switch (parameter.Type)
{
case ParameterType.Bool:
this.m_StreamQueue.SendNext(this.m_Animator.GetBool(parameter.Name));
break;
case ParameterType.Float:
this.m_StreamQueue.SendNext(this.m_Animator.GetFloat(parameter.Name));
break;
case ParameterType.Int:
this.m_StreamQueue.SendNext(this.m_Animator.GetInteger(parameter.Name));
break;
case ParameterType.Trigger:
this.m_StreamQueue.SendNext(this.m_Animator.GetBool(parameter.Name));
break;
}
}
}
}
private void DeserializeDataContinuously()
{
if (this.m_StreamQueue.HasQueuedObjects() == false)
{
return;
}
for (int i = 0; i < this.m_SynchronizeLayers.Count; ++i)
{
if (this.m_SynchronizeLayers[i].SynchronizeType == SynchronizeType.Continuous)
{
this.m_Animator.SetLayerWeight(this.m_SynchronizeLayers[i].LayerIndex, (float)this.m_StreamQueue.ReceiveNext());
}
}
for (int i = 0; i < this.m_SynchronizeParameters.Count; ++i)
{
SynchronizedParameter parameter = this.m_SynchronizeParameters[i];
if (parameter.SynchronizeType == SynchronizeType.Continuous)
{
switch (parameter.Type)
{
case ParameterType.Bool:
this.m_Animator.SetBool(parameter.Name, (bool)this.m_StreamQueue.ReceiveNext());
break;
case ParameterType.Float:
this.m_Animator.SetFloat(parameter.Name, (float)this.m_StreamQueue.ReceiveNext());
break;
case ParameterType.Int:
this.m_Animator.SetInteger(parameter.Name, (int)this.m_StreamQueue.ReceiveNext());
break;
case ParameterType.Trigger:
this.m_Animator.SetBool(parameter.Name, (bool)this.m_StreamQueue.ReceiveNext());
break;
}
}
}
}
private void SerializeDataDiscretly(PhotonStream stream)
{
for (int i = 0; i < this.m_SynchronizeLayers.Count; ++i)
{
if (this.m_SynchronizeLayers[i].SynchronizeType == SynchronizeType.Discrete)
{
stream.SendNext(this.m_Animator.GetLayerWeight(this.m_SynchronizeLayers[i].LayerIndex));
}
}
for (int i = 0; i < this.m_SynchronizeParameters.Count; ++i)
{
SynchronizedParameter parameter = this.m_SynchronizeParameters[i];
if (parameter.SynchronizeType == SynchronizeType.Discrete)
{
switch (parameter.Type)
{
case ParameterType.Bool:
stream.SendNext(this.m_Animator.GetBool(parameter.Name));
break;
case ParameterType.Float:
stream.SendNext(this.m_Animator.GetFloat(parameter.Name));
break;
case ParameterType.Int:
stream.SendNext(this.m_Animator.GetInteger(parameter.Name));
break;
case ParameterType.Trigger:
// here we can't rely on the current real state of the trigger, we might have missed its raise
stream.SendNext(this.m_raisedDiscreteTriggersCache.Contains(parameter.Name));
break;
}
}
}
// reset the cache, we've synchronized.
this.m_raisedDiscreteTriggersCache.Clear();
}
private void DeserializeDataDiscretly(PhotonStream stream)
{
for (int i = 0; i < this.m_SynchronizeLayers.Count; ++i)
{
if (this.m_SynchronizeLayers[i].SynchronizeType == SynchronizeType.Discrete)
{
this.m_Animator.SetLayerWeight(this.m_SynchronizeLayers[i].LayerIndex, (float)stream.ReceiveNext());
}
}
for (int i = 0; i < this.m_SynchronizeParameters.Count; ++i)
{
SynchronizedParameter parameter = this.m_SynchronizeParameters[i];
if (parameter.SynchronizeType == SynchronizeType.Discrete)
{
switch (parameter.Type)
{
case ParameterType.Bool:
if (stream.PeekNext() is bool == false)
{
return;
}
this.m_Animator.SetBool(parameter.Name, (bool)stream.ReceiveNext());
break;
case ParameterType.Float:
if (stream.PeekNext() is float == false)
{
return;
}
this.m_Animator.SetFloat(parameter.Name, (float)stream.ReceiveNext());
break;
case ParameterType.Int:
if (stream.PeekNext() is int == false)
{
return;
}
this.m_Animator.SetInteger(parameter.Name, (int)stream.ReceiveNext());
break;
case ParameterType.Trigger:
if (stream.PeekNext() is bool == false)
{
return;
}
if ((bool)stream.ReceiveNext())
{
this.m_Animator.SetTrigger(parameter.Name);
}
break;
}
}
}
}
private void SerializeSynchronizationTypeState(PhotonStream stream)
{
byte[] states = new byte[this.m_SynchronizeLayers.Count + this.m_SynchronizeParameters.Count];
for (int i = 0; i < this.m_SynchronizeLayers.Count; ++i)
{
states[i] = (byte)this.m_SynchronizeLayers[i].SynchronizeType;
}
for (int i = 0; i < this.m_SynchronizeParameters.Count; ++i)
{
states[this.m_SynchronizeLayers.Count + i] = (byte)this.m_SynchronizeParameters[i].SynchronizeType;
}
stream.SendNext(states);
}
private void DeserializeSynchronizationTypeState(PhotonStream stream)
{
byte[] state = (byte[])stream.ReceiveNext();
for (int i = 0; i < this.m_SynchronizeLayers.Count; ++i)
{
this.m_SynchronizeLayers[i].SynchronizeType = (SynchronizeType)state[i];
}
for (int i = 0; i < this.m_SynchronizeParameters.Count; ++i)
{
this.m_SynchronizeParameters[i].SynchronizeType = (SynchronizeType)state[this.m_SynchronizeLayers.Count + i];
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (this.m_Animator == null)
{
return;
}
if (stream.isWriting == true)
{
if (this.m_WasSynchronizeTypeChanged == true)
{
this.m_StreamQueue.Reset();
this.SerializeSynchronizationTypeState(stream);
this.m_WasSynchronizeTypeChanged = false;
}
this.m_StreamQueue.Serialize(stream);
this.SerializeDataDiscretly(stream);
}
else
{
#if PHOTON_DEVELOP
if( ReceivingSender != null )
{
ReceivingSender.OnPhotonSerializeView( stream, info );
}
else
#endif
{
if (stream.PeekNext() is byte[])
{
this.DeserializeSynchronizationTypeState(stream);
}
this.m_StreamQueue.Deserialize(stream);
this.DeserializeDataDiscretly(stream);
}
}
}
#endregion
} | 34.229779 | 162 | 0.558456 | [
"Unlicense"
] | FaizanHZaidi/alternate-realities | 10_photon_networking/Networking_Basics/Assets/Photon Unity Networking/Plugins/PhotonNetwork/Views/PhotonAnimatorView.cs | 18,623 | C# |
namespace ReportsService.Areas.HelpPage.ModelDescriptions
{
public class DictionaryModelDescription : KeyValuePairModelDescription
{
}
} | 24.666667 | 74 | 0.797297 | [
"MIT"
] | AlejandroIbarraC/Pandemica | API/SecondWaveAPIs/ReportsService/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs | 148 | C# |
using System;
namespace FasterQuant.PositionTracker
{
public class PositionInfo
{
public int PositionId { get; internal set; }
public double AverageEntryPrice { get; internal set; }
public long PortfolioDateTime { get; }
public double CurrentPrice { get; internal set; }
public DateTime EntryDateTime { get; }
public DateTime ExitDateTime { get; internal set; }
public int PortfolioId { get; internal set; }
public double PriceChange { get; internal set; }
public double ProfitLoss { get; internal set; }
public double Quantity { get; internal set; }
public PositionStatus Status { get; internal set; }
public int StrategyId { get; }
public string Symbol { get; }
public PositionType Type { get; }
public PositionInfo(int positionId, double averageEntryPrice, double currentPrice, DateTime entryDateTime, int portfolioId, double quantity, int strategyId, string symbol, PositionType type)
{
PositionId = positionId;
CurrentPrice = currentPrice;
AverageEntryPrice = averageEntryPrice;
EntryDateTime = entryDateTime;
Quantity = quantity;
PortfolioId = portfolioId;
StrategyId = strategyId;
Symbol = symbol;
Status = PositionStatus.Open;
Type = type;
}
public PositionInfo(int positionId, double averageEntryPrice, double currentPrice, DateTime entryDateTime, int portfolioId, double quantity, int strategyId, string symbol, PositionType type, long barStartDateTime)
{
PositionId = positionId;
CurrentPrice = currentPrice;
AverageEntryPrice = averageEntryPrice;
EntryDateTime = entryDateTime;
Quantity = quantity;
PortfolioId = portfolioId;
StrategyId = strategyId;
Symbol = symbol;
Status = PositionStatus.Open;
Type = type;
PortfolioDateTime = barStartDateTime;
}
public PositionInfo(int positionId, double averageEntryPrice, double currentPrice, DateTime entryDateTime, double priceChange, double profitLoss, int portfolioId, double quantity, int strategyId, string symbol, PositionType type, long barStartDateTime)
{
PositionId = positionId;
CurrentPrice = currentPrice;
AverageEntryPrice = averageEntryPrice;
EntryDateTime = entryDateTime;
Quantity = quantity;
PriceChange = priceChange;
ProfitLoss = profitLoss;
PortfolioId = portfolioId;
StrategyId = strategyId;
Symbol = symbol;
Status = PositionStatus.Open;
Type = type;
PortfolioDateTime = barStartDateTime;
}
public PositionInfo(int positionId, double averageEntryPrice, double currentPrice, DateTime entryDateTime, DateTime exitDateTime, double priceChange, double profitLoss, int portfolioId, double quantity, int strategyId, string symbol, PositionType type, long barStartDateTime)
{
PositionId = positionId;
CurrentPrice = currentPrice;
AverageEntryPrice = averageEntryPrice;
EntryDateTime = entryDateTime;
ExitDateTime = exitDateTime;
Quantity = quantity;
PriceChange = priceChange;
ProfitLoss = profitLoss;
PortfolioId = portfolioId;
StrategyId = strategyId;
Symbol = symbol;
Status = PositionStatus.Closed;
Type = type;
PortfolioDateTime = barStartDateTime;
}
public PositionInfo(int positionId, int portfolioId, int strategyId, string symbol, PositionType type, PositionStatus status)
{
PositionId = positionId;
PortfolioId = portfolioId;
StrategyId = strategyId;
Symbol = symbol;
Type = type;
Status = status;
}
}
}
| 42.082474 | 283 | 0.626899 | [
"MIT"
] | fasterquant/strategy-addons | source/FasterQuant.PositionTracker/PositionInfo.cs | 4,084 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Keas.Core.Domain
{
public class PersonNotification
{
public PersonNotification()
{
Pending = true;
ActionDate = DateTime.UtcNow;
}
public int Id { get; set; }
public bool Pending { get; set; }
[EmailAddress]
[StringLength(256)]
public string NotificationEmail { get; set; }
[EmailAddress]
[StringLength(256)]
public string PersonEmail { get; set; }
[StringLength(256)]
public string PersonName { get; set; }
public int PersonId { get; set; }
public DateTime ActionDate { get; set; }
[StringLength(256)]
public string ActorName { get; set; }
public string ActorId { get; set; }
[StringLength(50)]
public string Action { get; set; }
[StringLength(256)]
public string Notes { get; set; }
public Team Team { get; set; }
public int? TeamId { get; set; }
public DateTime? NotificationDate { get; set; }
//Non mapped
public bool SendEmail => !string.IsNullOrWhiteSpace(NotificationEmail);
public class Actions
{
public const string Added = "Added";
public const string Reactivated = "Reactivated";
public const string Deactivated = "Deactivated";
}
}
}
| 29.339623 | 80 | 0.560772 | [
"MIT"
] | ucdavis/Keas | Keas.Core/Domain/PersonNotification.cs | 1,555 | C# |
using Scalar.Tests.Should;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Scalar.FunctionalTests.Tools
{
public static class GitHelpers
{
private const string WindowsPathSeparator = "\\";
private const string GitPathSeparator = "/";
// A command sequence number added to the Trace2 stream to help tie the control
// and the corresponding enlistment commands together.
private static int TraceCommandSequenceId = 0;
public static string ConvertPathToGitFormat(string relativePath)
{
return relativePath.Replace(WindowsPathSeparator, GitPathSeparator);
}
public static void CheckGitCommand(string virtualRepoRoot, string command, params string[] expectedLinesInResult)
{
ProcessResult result = GitProcess.InvokeProcess(virtualRepoRoot, command);
result.Errors.ShouldBeEmpty();
foreach (string line in expectedLinesInResult)
{
result.Output.ShouldContain(line);
}
}
public static void CheckGitCommandAgainstScalarRepo(string virtualRepoRoot, string command, params string[] expectedLinesInResult)
{
ProcessResult result = InvokeGitAgainstScalarRepo(virtualRepoRoot, command);
result.Errors.ShouldBeEmpty();
foreach (string line in expectedLinesInResult)
{
result.Output.ShouldContain(line);
}
}
public static ProcessResult InvokeGitAgainstScalarRepo(
string scalarRepoRoot,
string command,
Dictionary<string, string> environmentVariables = null,
bool removeWaitingMessages = true,
bool removeUpgradeMessages = true,
string input = null)
{
ProcessResult result = GitProcess.InvokeProcess(scalarRepoRoot, command, input, environmentVariables);
string errors = result.Errors;
if (!string.IsNullOrEmpty(errors) && (removeWaitingMessages || removeUpgradeMessages))
{
IEnumerable<string> errorLines = errors.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
IEnumerable<string> filteredErrorLines = errorLines.Where(line =>
{
if (string.IsNullOrWhiteSpace(line) ||
(removeUpgradeMessages && line.StartsWith("A new version of Scalar is available.")) ||
(removeWaitingMessages && line.StartsWith("Waiting for ")))
{
return false;
}
else
{
return true;
}
});
errors = filteredErrorLines.Any() ? string.Join(Environment.NewLine, filteredErrorLines) : string.Empty;
}
return new ProcessResult(
result.Output,
errors,
result.ExitCode);
}
public static void ValidateGitCommand(
ScalarFunctionalTestEnlistment enlistment,
ControlGitRepo controlGitRepo,
string command,
params object[] args)
{
command = string.Format(command, args);
string controlRepoRoot = controlGitRepo.RootPath;
string scalarRepoRoot = enlistment.RepoRoot;
int pair_id = Interlocked.Increment(ref TraceCommandSequenceId);
Dictionary<string, string> environmentVariables = new Dictionary<string, string>();
environmentVariables["GIT_QUIET"] = "true";
environmentVariables["GIT_COMMITTER_DATE"] = "Thu Feb 16 10:07:35 2017 -0700";
environmentVariables["XXX_SEQUENCE_ID"] = pair_id.ToString();
ProcessResult expectedResult = GitProcess.InvokeProcess(controlRepoRoot, command, environmentVariables);
ProcessResult actualResult = GitHelpers.InvokeGitAgainstScalarRepo(scalarRepoRoot, command, environmentVariables);
LinesShouldMatch(command + " Errors Lines", actualResult.Errors, expectedResult.Errors);
LinesShouldMatch(command + " Output Lines", actualResult.Output, expectedResult.Output);
if (command != "status")
{
ValidateGitCommand(enlistment, controlGitRepo, "status");
}
}
public static void LinesShouldMatch(string message, string expected, string actual)
{
IEnumerable<string> actualLines = NonEmptyLines(actual);
IEnumerable<string> expectedLines = NonEmptyLines(expected);
actualLines.ShouldMatchInOrder(expectedLines, LinesAreEqual, message);
}
private static IEnumerable<string> NonEmptyLines(string data)
{
return data
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Where(s => !string.IsNullOrWhiteSpace(s));
}
private static bool LinesAreEqual(string actualLine, string expectedLine)
{
return actualLine.Equals(expectedLine);
}
}
}
| 41.03125 | 138 | 0.615765 | [
"MIT"
] | parkerbxyz/scalar | Scalar.FunctionalTests/Tools/GitHelpers.cs | 5,252 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommandTest.UserCommand.Service
{
/// <summary>
/// Interface defining a command session context.
/// </summary>
public interface IUserCommandContext
{
#region Properties
/// <summary>
/// Gets the context id.
/// </summary>
string Id
{
get;
}
/// <summary>
/// Gets the current index of the context.
/// The index references the last done command.
/// </summary>
int CurrentCommandIndex
{
get;
}
/// <summary>
/// Gets the commands executed in this context.
/// </summary>
IEnumerable<IUserCommand> Commands
{
get;
}
/// <summary>
/// Gets the flag indicating if the context can redo a command.
/// </summary>
bool CanRedo
{
get;
}
/// <summary>
/// Gets the flag indicating if the context can undo a command.
/// </summary>
bool CanUndo
{
get;
}
#endregion // Properties.
#region Events
/// <summary>
/// Event raised to notify a command execution progression.
/// </summary>
event CommandExecutionEventHandler<IUserCommandContext> CommandDoing;
/// <summary>
/// Event raised to notify a command execution successfully finished.
/// </summary>
event CommandExecutionEventHandler<IUserCommandContext> CommandDone;
/// <summary>
/// Event raised to notify a command execution or revertion failed.
/// </summary>
event CommandExecutionEventHandler<IUserCommandContext> CommandFailed;
/// <summary>
/// Event raised to notify a command revertion progression.
/// </summary>
event CommandExecutionEventHandler<IUserCommandContext> CommandUndoing;
/// <summary>
/// Event raised to notify a command revertion successfully finished.
/// </summary>
event CommandExecutionEventHandler<IUserCommandContext> CommandUndone;
#endregion // Events.
#region Methods
/// <summary>
/// Registers and execute the given command.
/// </summary>
/// <param name="pCommand">The command to execute.</param>
void Do(IUserCommand pCommand);
/// <summary>
/// Undo the current command of the context.
/// </summary>
void Undo();
/// <summary>
/// Redo the current command of the context.
/// </summary>
void Redo();
#endregion // Methods.
}
}
| 25.770642 | 79 | 0.559274 | [
"MIT"
] | mastertnt/XRay | XCommand.TestApp/UserCommand/Service/IUserCommandContext.cs | 2,811 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
namespace EfsTools.Items.Efs
{
[Serializable]
[EfsFile("/nv/item_files/ims/qipcall_1xsmsandvoice", true, 0xE1FF)]
[Attributes(9)]
public class QipCall1xSmsAndVoice
{
[ElementsCount(1)]
[ElementType("uint8")]
[Description("")]
public byte Value { get; set; }
}
} | 23.764706 | 72 | 0.626238 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Efs/QipCall1xSmsAndVoice.cs | 404 | C# |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost.Utils;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace DefaultCluster.Tests.General
{
/// <summary>
/// Summary description for ObserverTests
/// </summary>
public class ObserverTests : HostedTestClusterEnsureDefaultStarted
{
private readonly TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(10);
private int callbackCounter;
private readonly bool[] callbacksRecieved = new bool[2];
// we keep the observer objects as instance variables to prevent them from
// being garbage collected permaturely (the runtime stores them as weak references).
private SimpleGrainObserver observer1;
private SimpleGrainObserver observer2;
public ObserverTests(DefaultClusterFixture fixture) : base(fixture)
{
}
private void TestInitialize()
{
callbackCounter = 0;
callbacksRecieved[0] = false;
callbacksRecieved[1] = false;
observer1 = null;
observer2 = null;
}
private ISimpleObserverableGrain GetGrain()
{
return this.GrainFactory.GetGrain<ISimpleObserverableGrain>(GetRandomGrainId());
}
[Fact, TestCategory("BVT")]
public async Task ObserverTest_SimpleNotification()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_SimpleNotification_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(this.observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
[Fact, TestCategory("BVT")]
public async Task ObserverTest_SimpleNotification_GeneratedFactory()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_SimpleNotification_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SimpleNotification_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_SimpleNotification_Callback for {0} time with a = {1} and b = {2}", this.callbackCounter, a, b);
if (a == 3 && b == 0)
callbacksRecieved[0] = true;
else if (a == 3 && b == 2)
callbacksRecieved[1] = true;
else
throw new ArgumentOutOfRangeException("Unexpected callback with values: a=" + a + ",b=" + b);
if (callbackCounter == 1)
{
// Allow for callbacks occurring in any order
Assert.True(callbacksRecieved[0] || callbacksRecieved[1]);
}
else if (callbackCounter == 2)
{
Assert.True(callbacksRecieved[0] && callbacksRecieved[1]);
result.Done = true;
}
else
{
Assert.True(false);
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionSameReference()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_DoubleSubscriptionSameReference_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(1); // Use grain
try
{
await grain.Subscribe(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
this.Logger.Info("Received exception: {0}", baseException);
Assert.IsAssignableFrom<OrleansException>(baseException);
if (!baseException.Message.StartsWith("Cannot subscribe already subscribed observer"))
{
Assert.True(false, "Unexpected exception message: " + baseException);
}
}
await grain.SetA(2); // Use grain
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetA(2)", timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_DoubleSubscriptionSameReference_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_DoubleSubscriptionSameReference_Callback for {0} time with a={1} and b={2}", this.callbackCounter, a, b);
Assert.True(callbackCounter <= 2, "Callback has been called more times than was expected " + callbackCounter);
if (callbackCounter == 2)
{
result.Continue = true;
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscribeUnsubscribe()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_SubscribeUnsubscribe_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await grain.Unsubscribe(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SubscribeUnsubscribe_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_SubscribeUnsubscribe_Callback for {0} time with a = {1} and b = {2}", this.callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT")]
public async Task ObserverTest_Unsubscribe()
{
TestInitialize();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(null, null, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
try
{
await grain.Unsubscribe(reference);
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
if (!(baseException is OrleansException))
Assert.True(false);
}
}
[Fact, TestCategory("BVT")]
public async Task ObserverTest_DoubleSubscriptionDifferentReferences()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result, this.Logger);
ISimpleGrainObserver reference1 = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
this.observer2 = new SimpleGrainObserver(this.ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result, this.Logger);
ISimpleGrainObserver reference2 = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer2);
await grain.Subscribe(reference1);
await grain.Subscribe(reference2);
grain.SetA(6).Ignore();
Assert.True(await result.WaitForFinished(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference1);
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference2);
}
void ObserverTest_DoubleSubscriptionDifferentReferences_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_DoubleSubscriptionDifferentReferences_Callback for {0} time with a = {1} and b = {2}", this.callbackCounter, a, b);
Assert.True(callbackCounter < 3, "Callback has been called more times than was expected.");
Assert.Equal(6, a);
Assert.Equal(0, b);
if (callbackCounter == 2)
result.Done = true;
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DeleteObject()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_DeleteObject_Callback, result, this.Logger);
ISimpleGrainObserver reference = await this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await this.GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
}
void ObserverTest_DeleteObject_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
this.Logger.Info("Invoking ObserverTest_DeleteObject_Callback for {0} time with a = {1} and b = {2}", this.callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT")]
public async Task ObserverTest_SubscriberMustBeGrainReference()
{
TestInitialize();
await Assert.ThrowsAsync<NotSupportedException>(async () =>
{
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = this.GetGrain();
this.observer1 = new SimpleGrainObserver(this.ObserverTest_SimpleNotification_Callback, result, this.Logger);
ISimpleGrainObserver reference = this.observer1;
// Should be: this.GrainFactory.CreateObjectReference<ISimpleGrainObserver>(obj);
await grain.Subscribe(reference);
// Not reached
});
}
[Fact, TestCategory("BVT")]
public async Task ObserverTest_CreateObjectReference_ThrowsForInvalidArgumentTypes()
{
TestInitialize();
// Attempt to create an object reference to a Grain class.
await Assert.ThrowsAsync<ArgumentException>(() => this.Client.CreateObjectReference<ISimpleGrainObserver>(new DummyObserverGrain()));
// Attempt to create an object reference to an existing GrainReference.
var observer = new DummyObserver();
var reference = await this.Client.CreateObjectReference<ISimpleGrainObserver>(observer);
await Assert.ThrowsAsync<ArgumentException>(() => this.Client.CreateObjectReference<ISimpleGrainObserver>(reference));
}
private class DummyObserverGrain : Grain, ISimpleGrainObserver
{
public void StateChanged(int a, int b) { }
}
private class DummyObserver : ISimpleGrainObserver
{
public void StateChanged(int a, int b) { }
}
internal class SimpleGrainObserver : ISimpleGrainObserver
{
readonly Action<int, int, AsyncResultHandle> action;
readonly AsyncResultHandle result;
private readonly ILogger logger;
public SimpleGrainObserver(Action<int, int, AsyncResultHandle> action, AsyncResultHandle result, ILogger logger)
{
this.action = action;
this.result = result;
this.logger = logger;
}
public void StateChanged(int a, int b)
{
this.logger.Debug("SimpleGrainObserver.StateChanged a={0} b={1}", a, b);
action?.Invoke(a, b, result);
}
}
}
}
| 42.098551 | 167 | 0.629923 | [
"MIT"
] | Cloud33/orleans | test/DefaultCluster.Tests/ObserverTests.cs | 14,524 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace AuthorProblem
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class AuthorAttribute : Attribute
{
public AuthorAttribute(string name)
{
Name = name;
}
public string Name { get; set; }
}
}
| 22.176471 | 92 | 0.655172 | [
"MIT"
] | IvanIvTodorov/SoftUniEducation | C#OOP/Reflection/ReflectionAndAttributes-Lab/AuthorProblem/AuthorAttribute.cs | 379 | C# |
using System;
using AppKit;
using Foundation;
namespace Author.macOS
{
[Register("AppDelegate")]
public class AppDelegate : Xamarin.Forms.Platform.MacOS.FormsApplicationDelegate
{
private bool FinishedInitializing;
private Uri StartupUri;
private readonly NSWindow window;
public override NSWindow MainWindow => window;
public AppDelegate()
{
NSAppleEventManager.SharedAppleEventManager.SetEventHandler(this,
new ObjCRuntime.Selector("handleGetURLEvent:withReplyEvent:"),
AEEventClass.Internet, AEEventID.GetUrl);
var style = NSWindowStyle.Closable | NSWindowStyle.Resizable |
NSWindowStyle.Titled;
var rect = new CoreGraphics.CGRect(200, 1000, 1024, 768);
window = new NSWindow(rect, style, NSBackingStore.Buffered, false)
{
Title = "Author",
TitleVisibility = NSWindowTitleVisibility.Hidden
};
}
public override void DidFinishLaunching(NSNotification notification)
{
Xamarin.Forms.Forms.Init();
Acr.UserDialogs.UserDialogs.Instance = new CustomUserDialogs(window);
LoadApplication(new UI.Pages.App());
base.DidFinishLaunching(notification);
FinishedInitializing = true;
if (StartupUri != null)
{
HandleUri(StartupUri);
StartupUri = null;
}
}
private void HandleUri(Uri uri)
{
UI.Pages.App app = (UI.Pages.App)Xamarin.Forms.Application.Current;
app.OnUriRequestReceived(uri);
}
public override void OpenUrls(NSApplication application, NSUrl[] urls)
{
// TODO: handle all URIs in case not finished initializing
for (int i = 0; i < urls.Length; ++i)
{
NSUrl url = urls[i];
if (url.Scheme == "otpauth")
{
Uri uri = new Uri(url.AbsoluteString);
if (FinishedInitializing)
{
HandleUri(uri);
}
else
{
StartupUri = uri;
}
}
else if (url.Scheme == "file")
{
// TODO: handle file opening
}
}
}
}
}
| 31.822785 | 84 | 0.520684 | [
"Apache-2.0",
"BSD-3-Clause"
] | danielga/Author | Author.macOS/AppDelegate.cs | 2,516 | C# |
using System;
namespace Kunicardus.Touch.Helpers.UI
{
public static class Styles
{
public static readonly nfloat RegistrationFormSubHeadingTop = 100f;
// - 64f;
public static class Colors
{
public static readonly string HeaderGreen = "#8dbd3b";
public static readonly string LoginScreenBackGroundGreen = "#98cc42";
public static readonly string PlaceHolderColor = "#CDF77C";
public static readonly string Yellow = "#ffe154";
public static readonly string Gray = "#ABABAB";
public static readonly string LightGray = "#e6eced";
public static readonly string Orange = "#f28e2e";
}
public static class Fonts
{
public static readonly string BPGExtraSquare = "BPG ExtraSquare Mtavruli";
}
public static class RegistrationNextButton
{
public static readonly nfloat Width = 90;
public static readonly nfloat bottom = (Screen.IsTall ? 30 : 16);
}
}
}
| 26.5 | 77 | 0.7303 | [
"MIT"
] | nininea2/unicard_app_base | Kunicardus.Touch/Helpers/UI/Styles.cs | 903 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Element
{
public enum ElementType
{
EMPTY,
FIRE,
WATER,
ICE,
GRASS,
DARK,
HOLY
}
public static class ElementTypeToInt
{
public static int CastElementTypeToInt(ElementType elementType)
{
switch (elementType) {
case ElementType.EMPTY:
return 0;
case ElementType.FIRE:
return 1;
case ElementType.WATER:
return 2;
case ElementType.ICE:
return 3;
case ElementType.GRASS:
return 4;
case ElementType.DARK:
return 5;
case ElementType.HOLY:
return 6;
default:
return 0;
}
}
}
}
| 21.901961 | 71 | 0.402865 | [
"MIT"
] | HongCFull/Comp4971C | Assets/Scripts/Gameplay/Combat/Element/ElementType.cs | 1,117 | C# |
using NetOffice.Attributes;
using System;
using System.ComponentModel;
using NetRuntimeSystem = System;
namespace NetOffice.WordApi
{
/// <summary>
/// DispatchInterface Browser
/// SupportByVersion Word, 9,10,11,12,14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194679.aspx </remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
[EntityType(EntityType.IsDispatchInterface)]
public class Browser : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(Browser);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public Browser(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public Browser(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Browser(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Browser(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Browser(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Browser(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Browser() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Browser(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff823227.aspx </remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
public NetOffice.WordApi.Application Application
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Application>(this, "Application", NetOffice.WordApi.Application.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff839284.aspx </remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
public Int32 Creator
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "Creator");
}
}
/// <summary>
/// SupportByVersion Word 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/ff845420.aspx </remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff845753.aspx </remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
public NetOffice.WordApi.Enums.WdBrowseTarget Target
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.WordApi.Enums.WdBrowseTarget>(this, "Target");
}
set
{
Factory.ExecuteEnumPropertySet(this, "Target", value);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838558.aspx </remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
public void Next()
{
Factory.ExecuteMethod(this, "Next");
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836707.aspx </remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
public void Previous()
{
Factory.ExecuteMethod(this, "Previous");
}
#endregion
#pragma warning restore
}
}
| 35.447761 | 173 | 0.590456 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | ehsan2022002/VirastarE | Office/Word/DispatchInterfaces/Browser.cs | 7,127 | C# |
using MTT;
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Build.Framework;
using MSBuildTask = Microsoft.Build.Utilities.Task;
using System.Text.RegularExpressions;
namespace MSBuildTasks
{
public class ConvertMain : MSBuildTask
{
/// <summary>
/// The current working directory for the convert process
/// </summary>
public string WorkingDirectory { get; set; }
/// <summary>
/// The directory to save the ts models
/// </summary>
public string ConvertDirectory { get; set; }
/// <summary>
/// Comments at the top of each file that it was auto generated
/// </summary>
public bool AutoGeneratedTag { get; set; } = true; //default value if one is not provided;
protected MessageImportance LoggingImportance { get; } = MessageImportance.High; //If its not high then there are no logs
private readonly ConvertService convertService;
public ConvertMain()
{
convertService = new ConvertService(Log.LogMessage);
}
public override bool Execute()
{
Log.LogMessage(LoggingImportance, "Starting MTT");
convertService.AutoGeneratedTag = AutoGeneratedTag;
convertService.ConvertDirectory = ConvertDirectory;
convertService.WorkingDirectory = WorkingDirectory;
var result = convertService.Execute();
Log.LogMessage(LoggingImportance, "Finished MTT");
return result;
}
}
}
| 30.25 | 130 | 0.639542 | [
"MIT"
] | BlueBasher/MTT | Source/MTT/ConvertMain.cs | 1,573 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDiary
{
public class DiarySearchData
{
public DateTime BeginDate { get; set; }
public DateTime EndDate { get; set; }
public string DayOfWeek { get; set; }
public string Keyword { get; set; }
}
}
| 22 | 47 | 0.668449 | [
"MIT"
] | jkwchunjae/HelloJkwCore | HelloJkwCore/ProjectDiary/Search/DiarySearchData.cs | 376 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Naruto.WebSocket.Object.Enums
{
/// <summary>
/// 张海波
/// 2020-04-05
/// 消息的发送类型
/// </summary>
public enum MessageSendTypeEnum
{
/// <summary>
/// 指定连接
/// </summary>
Current,
/// <summary>
/// 所有人
/// </summary>
All,
/// <summary>
/// 除了连接外的所有人
/// </summary>
Other,
/// <summary>
/// 群组
/// </summary>
Group
}
/// <summary>
/// 张海波
/// 2020-04-05
/// 消息的发送方法枚举
/// </summary>
public enum MessageSendActionTypeEnum
{
/// <summary>
/// 单连接
/// </summary>
Single,
/// <summary>
/// 多连接
/// </summary>
Many
}
}
| 16.98 | 41 | 0.421673 | [
"MIT"
] | zhanghaiboshiwo/Naruto.WebSocket | src/Naruto.WebSocket/Object/Enums/MessageSendTypeEnum.cs | 943 | C# |
// Copyright (c) 2021 homuler
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
using System;
using System.Collections.Generic;
namespace Mediapipe
{
public class LandmarkListVectorPacket : Packet<List<LandmarkList>>
{
/// <summary>
/// Creates an empty <see cref="LandmarkListVectorPacket" /> instance.
/// </summary>
public LandmarkListVectorPacket() : base(true) { }
public LandmarkListVectorPacket(IntPtr ptr, bool isOwner = true) : base(ptr, isOwner) { }
public LandmarkListVectorPacket At(Timestamp timestamp)
{
return At<LandmarkListVectorPacket>(timestamp);
}
public override List<LandmarkList> Get()
{
UnsafeNativeMethods.mp_Packet__GetLandmarkListVector(mpPtr, out var serializedProtoVector).Assert();
GC.KeepAlive(this);
var landmarkLists = serializedProtoVector.Deserialize(LandmarkList.Parser);
serializedProtoVector.Dispose();
return landmarkLists;
}
public override StatusOr<List<LandmarkList>> Consume()
{
throw new NotSupportedException();
}
}
}
| 27.44186 | 106 | 0.707627 | [
"Apache-2.0"
] | SeedV/SeedAvatarStudio | Packages/com.github.homuler.mediapipe/Runtime/Scripts/Framework/Packet/LandmarkListVectorPacket.cs | 1,180 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace It.Uniba.Di.Cdg.SocialTfs.Client.Popups
{
/// <summary>
/// Interaction logic for UILoading.xaml.
/// </summary>
public partial class UILoading : UserControl
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="text">Text to show.</param>
public UILoading(string text)
{
InitializeComponent();
LoadingText.Text = text;
}
}
}
| 24.393939 | 52 | 0.662112 | [
"MIT"
] | collab-uniba/SocialCDE-proxy-server | SocialCDE_v0.23/It.Uniba.Di.Cdg.SocialTfs.Client/Popups/UILoading.xaml.cs | 807 | C# |
using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace Kore.Web
{
public static class StringExtensions
{
public static T JsonDeserialize<T>(this string json)
{
if (string.IsNullOrWhiteSpace(json))
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(json);
//return new JavaScriptSerializer().Deserialize<T>(json);
}
public static object JsonDeserialize(this string json, Type targetType)
{
return JsonConvert.DeserializeObject(json, targetType);
//return new JavaScriptSerializer().Deserialize(json, targetType);
}
public static string ToSlugUrl(this string value)
{
string stringFormKd = value.Normalize(NormalizationForm.FormKD);
var stringBuilder = new StringBuilder();
foreach (char character in stringFormKd)
{
UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(character);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(character);
}
}
// Replace some characters
stringBuilder
.Replace("!", "-")
.Replace("$", "-")
.Replace("&", "-")
.Replace("\"", "-")
.Replace("'", "-")
.Replace("(", "-")
.Replace(")", "-")
.Replace("*", "-")
.Replace("+", "-")
.Replace(",", "-")
.Replace(";", "-")
.Replace(".", "-")
.Replace("/", "-")
.Replace("\\", "-")
.Replace(":", "-")
.Replace("=", "-")
.Replace("?", "-")
.Replace("&", "-")
.Replace("_", "-")
.Replace("~", "-")
.Replace("`", "-")
.Replace("#", "-")
.Replace("%", "-")
.Replace("^", "-")
.Replace("[", "-")
.Replace("]", "-")
.Replace("{", "-")
.Replace("}", "-")
.Replace("|", "-")
.Replace("<", "-")
.Replace(">", "-");
var slug = stringBuilder.ToString().Normalize(NormalizationForm.FormKC);
//First to lower case
slug = slug.ToLowerInvariant();
if (!slug.IsRightToLeft())
{
//Remove all accents
var bytes = Encoding.GetEncoding("Cyrillic").GetBytes(slug);
slug = Encoding.ASCII.GetString(bytes);
//Remove invalid chars
slug = Regex.Replace(slug, @"[^a-z0-9\s-_]", string.Empty, RegexOptions.Compiled);
}
//Replace spaces
slug = Regex.Replace(slug, @"\s", "-", RegexOptions.Compiled);
//Trim dashes from end
slug = slug.Trim('-', '_');
//Replace double occurences of - or _
slug = Regex.Replace(slug, @"([-_]){2,}", "$1", RegexOptions.Compiled);
return slug;
}
}
} | 33.572816 | 99 | 0.433488 | [
"MIT"
] | artinite21/KoreCMS | Kore.Web/Core/StringExtensions.cs | 3,460 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
namespace Microsoft.Diagnostics.Tools.RuntimeClient
{
/// <summary>
/// Message header used to send commands to the .NET Core runtime through IPC.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MessageHeader
{
/// <summary>
/// Request type.
/// </summary>
public DiagnosticsMessageType RequestType;
/// <summary>
/// Remote process Id.
/// </summary>
public uint Pid;
}
}
| 28.076923 | 82 | 0.647945 | [
"Apache-2.0"
] | Bhekinkosi12/Benchmarks | src/BenchmarksServer/Microsoft.Diagnostics.Tools.RuntimeClient/Eventing/MessageHeader.cs | 732 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public struct NetStatInfo
{
public DateTime Timestamp;
public ulong MessageLength;
}
public static class NetStatTracker
{
public static List<NetStatInfo> MessagesReceived = new List<NetStatInfo>();
public static List<NetStatInfo> MessagesSent = new List<NetStatInfo>();
public static TimeSpan MessageLife = TimeSpan.FromSeconds(5);
public static void TrackMessageReceived(ulong messageLength)
{
MessagesReceived.Add(new NetStatInfo() { MessageLength = messageLength, Timestamp = DateTime.Now });
RemoveOldTrackedMessages(MessagesSent, DateTime.Now - MessageLife);
}
public static void TrackMessageSent(ulong messageLength)
{
MessagesSent.Add(new NetStatInfo() { MessageLength = messageLength, Timestamp = DateTime.Now });
RemoveOldTrackedMessages(MessagesSent, DateTime.Now - MessageLife);
}
public static void RemoveOldTrackedMessages(List<NetStatInfo> messages, DateTime date)
{
messages.RemoveAll(message => message.Timestamp < date);
}
public static ulong AverageBytesPerSecond(List<NetStatInfo> messageList)
{
RemoveOldTrackedMessages(messageList, DateTime.Now - MessageLife);
if (messageList.Count == 0)
return 0ul;
ulong bytesSent = 0ul;
foreach (var message in messageList)
{
bytesSent += message.MessageLength;
}
double bytesSentD = (double)bytesSent;
bytesSentD = bytesSentD / MessageLife.TotalSeconds;
bytesSent = (ulong)bytesSentD;
return bytesSent;
}
public static uint MessagesPerSecond(List<NetStatInfo> messages)
{
RemoveOldTrackedMessages(messages, DateTime.Now - MessageLife);
if (messages.Count == 0)
return 0u;
double messageCountDouble = (double)messages.Count;
messageCountDouble = messageCountDouble / MessageLife.TotalSeconds;
return (uint)(messageCountDouble);
}
public static (uint messagesSentPerSecond, ulong bytesSentPerSecond, uint messagesReceivedPerSecond, ulong bytesReceivedPerSecond) GetNetStats()
{
ulong averageBytesSent = AverageBytesPerSecond(MessagesSent);
ulong averageBytesReceived = AverageBytesPerSecond(MessagesReceived);
uint messagesSent = MessagesPerSecond(MessagesSent);
uint messagesReceived = MessagesPerSecond(MessagesReceived);
return (messagesSent, averageBytesSent, messagesReceived, averageBytesReceived);
}
}
public class NetStats : MonoBehaviour
{
public GUISkin StatsSkin;
bool mShowGUI = true;
void Start()
{
}
void OnGUI()
{
GUI.skin = StatsSkin;
if (mShowGUI)
{
var (messagesSentPerSecond, bytesSentPerSecond, messagesReceivedPerSecond, bytesReceivedPerSecond) = NetStatTracker.GetNetStats();
GUI.Box(new Rect(2, 2, 400, 300), "");
GUI.Label(new Rect(10, 30, 400, 30), $"Sent (Messages): {messagesSentPerSecond}");
GUI.Label(new Rect(10, 60, 400, 30), $"Sent (Bps): {bytesSentPerSecond}");
GUI.Label(new Rect(10, 120, 400, 30), $"Received (Messages): {messagesReceivedPerSecond}");
GUI.Label(new Rect(10, 150, 400, 30), $"Received (Bps): {bytesReceivedPerSecond}");
if (GUI.Button(new Rect(120, 250, 150, 40), "Hide Stats"))
mShowGUI = false;
}
else
{
if (GUI.Button(new Rect(120, 10, 150, 40), "Show Stats"))
mShowGUI = true;
}
}
}
| 32.22807 | 148 | 0.667392 | [
"MIT"
] | BladeBreaker/circles-and-squares | Assets/Scripts/NetStats.cs | 3,674 | C# |
namespace HealthSdkPrototype
{
internal static partial class AppSettingsExtensionsArgs
{
private enum State
{
ExpectOption,
GetClientSecret,
}
public static AppSettings FromArgs(this AppSettings result, string[] args)
{
var state = State.ExpectOption;
foreach (var arg in args)
{
switch (state)
{
case State.ExpectOption:
if (arg.Length > 2)
{
if (arg.StartsWith("-"))
{
var option = arg.TrimStart('-').ToLowerInvariant();
switch (option)
{
case "secret":
state = State.GetClientSecret;
break;
default:
break;
}
}
}
break;
case State.GetClientSecret:
result.ClientSecret = arg;
state = State.ExpectOption;
break;
default:
break;
}
}
return result;
}
}
}
| 30.14 | 83 | 0.323822 | [
"MIT"
] | jim-dale/MicrosoftBand | src/DownloadData/Utility/AppSettingsExtensions_FromArgs.cs | 1,509 | C# |
using Furiza.Base.Core.Exceptions;
using System;
using System.Runtime.Serialization;
namespace Cemig.Gecipa.CoreBusiness.Domain.Exceptions
{
[Serializable]
public class NomeNaoPodeSerNuloException : CoreException
{
public override string Key => "NomeNaoPodeSerNulo";
public override string Message => "O nome do objeto não pode estar em branco.";
public NomeNaoPodeSerNuloException() : base()
{
}
protected NomeNaoPodeSerNuloException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
} | 28.47619 | 117 | 0.69398 | [
"MIT"
] | tonihenriques/cemig-gecipa | src/Cemig.Gecipa.CoreBusiness.Domain/Exceptions/NomeNaoPodeSerNuloException.cs | 601 | C# |
using myFunctions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GContacts;
using System.Xml.Linq;
namespace Katalog
{
#region Enum Defines
[Flags]
public enum FastFlags : ushort
{
FLAG1 = 0x00000001,
FLAG2 = 0x00000002,
FLAG3 = 0x00000004,
FLAG4 = 0x00000008,
FLAG5 = 0x00000010,
FLAG6 = 0x00000020,
}
public enum ItemTypes { item = 0, book = 1, boardgame = 2 }
public enum LendStatus { Reserved = 0, Lended = 1, Returned = 2, Canceled = 3 }
#endregion
#region Structure defines
public class PInfo
{
public Guid ID { get; set; }
public string Name { get; set; }
}
public class PInfoComparer : IComparer<PInfo>
{
public int Compare(PInfo x, PInfo y)
{
if (x.Name == null || y.Name == null)
{
return 0;
}
// CompareTo() method
return x.Name.CompareTo(y.Name);
}
}
public class CInfo
{
public Guid ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string PersonalNum { get; set; }
}
public class IInfo
{
public Guid ID { get; set; }
public string Name { get; set; }
public string InventoryNumber { get; set; }
public long Barcode { get; set; }
public short Count { get; set; }
public short Available { get; set; }
public Guid ItemID { get; set; }
public string ItemType { get; set; }
public int ItemNum { get; set; }
public string Note { get; set; }
}
public class LInfo
{
public Guid ID { get; set; }
public string Name { get; set; }
public string InvNum { get; set; }
public ItemTypes ItemType { get; set; }
public string Note { get; set; }
public DateTime LendFrom { get; set; }
public DateTime LendTo { get; set; }
}
public class FInfo
{
public string Name { get; set; }
public string Group { get; set; }
public string Path { get; set; }
public string Version { get; set; }
public string Description { get; set; }
}
static class MaxInvNumbers
{
public static long Contact = Properties.Settings.Default.ContactStart - 1;
public static long Item = Properties.Settings.Default.ItemStart - 1;
public static long Book = Properties.Settings.Default.BookStart - 1;
public static long Boardgame = Properties.Settings.Default.BoardStart - 1;
}
#endregion
static class global
{
public static string RemoveDiacritics(string text)
{
var normalizedString = text.Normalize(NormalizationForm.FormD);
var stringBuilder = new StringBuilder();
foreach (var c in normalizedString)
{
var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
if (unicodeCategory != UnicodeCategory.NonSpacingMark)
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
public static string GetLendingItemName(string type, Guid id)
{
databaseEntities db = new databaseEntities();
switch (type.Trim())
{
case "item":
Items itm = db.Items.Find(id);
if (itm != null) return itm.Name.Trim();
break;
case "book":
Books book = db.Books.Find(id);
if (book != null) return book.Title.Trim();
break;
case "boardgame":
Boardgames board = db.Boardgames.Find(id);
if (board != null) return board.Name.Trim();
break;
}
return "";
}
public static List<string> DeleteDuplicates(List<string> list)
{
List<string> res = new List<string>();
for (int i = 0; i < list.Count; i++)
{
bool find = false;
for (int j = 0; j < res.Count; j++)
{
if (list[i] == res[j])
{
find = true;
break;
}
}
if (!find && list[i] != "")
res.Add(list[i]);
}
return res;
}
public static string GetInvNumList(Guid id)
{
databaseEntities db = new databaseEntities();
var list = db.Copies.Where(x => x.ItemID == id).Select(x => x.InventoryNumber).ToList();
list = DeleteDuplicates(list);
string NumList = "";
foreach (var item in list)
{
if (NumList != "") NumList += ", ";
NumList += item;
}
return NumList;
}
public static string GetLocationList(Guid id)
{
databaseEntities db = new databaseEntities();
var list = db.Copies.Where(x => x.ItemID == id).Select(x => x.Location).ToList();
list = DeleteDuplicates(list);
string NumList = "";
foreach (var item in list)
{
if (NumList != "") NumList += ", ";
NumList += item;
}
return NumList;
}
public static List<PInfo> GetParentlist(Guid RemoveGuid)
{
databaseEntities db = new databaseEntities();
List<PInfo> list = db.Objects.Where(x => (x.Active ?? true) && (x.IsParent ?? true) && (x.ID != RemoveGuid)).Select(x => new PInfo { ID = x.ID, Name = x.Name.Trim() }).ToList();
return list;
}
public static FInfo GetFInfo(string text)
{
string[] info = text.Split(new string[] { ">" }, StringSplitOptions.None);
if (info.Length == 5)
{
FInfo itm = new FInfo();
itm.Name = info[0];
itm.Path = info[1];
itm.Version = info[2];
itm.Group = info[3];
itm.Description = info[4];
return itm;
}
return null;
}
public static List<FInfo> GetFInfoList(string text)
{
List<FInfo> list = new List<FInfo>();
string[] file = text.Split(new string[] { ";" }, StringSplitOptions.None);
foreach (var item in file)
{
string[] info = item.Split(new string[] { ">" }, StringSplitOptions.None);
if (info.Length == 5)
{
FInfo itm = new FInfo();
itm.Name = info[0];
itm.Path = info[1];
itm.Version = info[2];
itm.Group = info[3];
itm.Description = info[4];
list.Add(itm);
}
}
return list;
}
public static string FInfoToText(FInfo item)
{
return item.Name + ">" + item.Path + ">" + item.Version + ">" + item.Group + ">" + item.Description;
}
public static string FInfoToText(List<FInfo> list)
{
if (list == null) return "";
string text = "";
foreach (var item in list)
{
string line = FInfoToText(item);
if (text != "") text += ";";
text += line;
}
return text;
}
public static List<Objects> GetObjectsFromText(string text)
{
List<Objects> list = new List<Objects>();
databaseEntities db = new databaseEntities(); // Database
string[] strList = text.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in strList)
{
try
{
Guid ID = Guid.Parse(item);
Objects obj = db.Objects.Find(ID);
if (obj != null)
list.Add(obj);
} catch { }
}
return list;
}
public static string GetTextFromObjects(List<Objects> list)
{
string res = "";
foreach (var item in list)
{
if (res != "") res += ";";
res += item.ID.ToString();
}
return res;
}
/// <summary>
/// Check if item available
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
public static bool IsAvailable(short? status)
{
short stat = status ?? (short)LendStatus.Returned;
if (stat == (short)LendStatus.Canceled || stat == (short)LendStatus.Returned)
return true;
else
return false;
}
/// <summary>
/// Check Duplicate Inventory number
/// </summary>
/// <param name="InventoryNumber">Ger duplicate Inventory number</param>
/// <returns>Returns true if duplicate exist</returns>
public static bool IsDuplicate(string InventoryNumber, Guid ID)
{
databaseEntities db = new databaseEntities();
var list = db.Copies.Where(x => x.ID != ID).Select(x => x.InventoryNumber).ToList();
for (int i = 0; i < list.Count; i++)
{
if (InventoryNumber.Trim() == list[i].Trim())
return true;
}
return false;
}
#region Copies
/// <summary>
/// Create new Copy item
/// </summary>
public static Copies CreateCopy(Guid ItemID, ItemTypes ItemType)
{
Copies itm = new Copies();
// ----- Init values -----
itm.ID = Guid.NewGuid(); // ID
itm.ItemID = ItemID; // Item ID
itm.ItemType = ItemType.ToString(); // Item Type - Item
itm.ItemNum = 0; // ItemNum
itm.Note = ""; // Note
itm.Status = (short)LendStatus.Returned;// Status
//itm.Price = 0; // Price
itm.AcquisitionDate = DateTime.Now; // Acqusition date
itm.Excluded = false; // Excluded
//itm.Condition = ""; // Condition
//itm.InventoryNumber = ""; // Inventory Number
//itm.Barcode = ""; // Barcode
itm.Location = ""; // Location
// ----- Return Copy -----
return itm;
}
/// <summary>
/// Create new Copy item and copy data from another structure
/// </summary>
/// <param name="input">Input</param>
public static Copies CopyCopies(Copies input)
{
// ----- Try parse ItemType -----
ItemTypes type = ItemTypes.item;
try
{
Enum.TryParse(input.ItemType, out type);
} catch { }
// ----- Create new Copy -----
Copies itm = CreateCopy(input.ItemID ?? Guid.Empty, type);
// ----- Fill Copy -----
itm.Price = input.Price; // Price
itm.AcquisitionDate = input.AcquisitionDate; // Acqusition date
itm.Excluded = input.Excluded; // Excluded
itm.Condition = input.Condition; // Condition
itm.InventoryNumber = input.InventoryNumber; // Inventory Number
itm.Barcode = input.Barcode; // Barcode
itm.Location = input.Location; // Location
itm.Note = input.Note;
// ----- Return Copy -----
return itm;
}
/// <summary>
/// Get available items
/// </summary>
/// <param name="list">Copies list</param>
/// <returns>Number of available items</returns>
public static short GetAvailableCopies(List<Copies> list)
{
short available = 0;
foreach (var item in list)
{
if (!(item.Excluded ?? false))
if (item.Status == (short)LendStatus.Canceled || item.Status == (short)LendStatus.Returned) available++;
}
return available;
}
/// <summary>
/// Get copies count
/// </summary>
/// <returns></returns>
public static short GetCopiesCount(List<Copies> list)
{
short count = 0;
foreach (var item in list)
{
if (!(item.Excluded ?? false)) count++;
}
return count;
}
/// <summary>
/// Refresh Copies status
/// </summary>
/// <param name="list">Copies list to refresf</param>
/// <param name="status">Status</param>
public static void RefreshCopiesStatus(List<Copies> list, LendStatus status)
{
RefreshCopiesStatus(list, (short)status);
}
/// <summary>
/// Refresh Copies status
/// </summary>
/// <param name="list">Copies list to refresf</param>
/// <param name="status">Status</param>
public static void RefreshCopiesStatus(List<Copies> list, short status)
{
databaseEntities db = new databaseEntities();
foreach (var itm in list)
{
var copy = db.Copies.Find(itm.ID);
copy.Status = status;
}
db.SaveChanges();
}
/// <summary>
/// Refresh Copies status
/// </summary>
/// <param name="list">Copies list to refresf</param>
/// <param name="status">Status</param>
public static void RefreshCopiesStatus(List<Lending> list)
{
databaseEntities db = new databaseEntities();
foreach (var itm in list)
{
var copy = db.Copies.Find(itm.CopyID);
if (copy != null)
copy.Status = itm.Status;
}
db.SaveChanges();
}
#endregion
#region Translate Type Names
/// <summary>
/// Get Item Type Name from ItemType
/// </summary>
/// <param name="type">Item Type</param>
/// <returns>Item Type Name</returns>
public static string GetItemTypeName(ItemTypes type)
{
string strType = type.ToString();
return GetItemTypeName(strType);
}
/// <summary>
/// Get Item Type Name from ItemType
/// </summary>
/// <param name="type">Item Type</param>
/// <returns>Item Type Name</returns>
public static ItemTypes GetItemType(string type)
{
type = type.Trim();
switch (type)
{
case "item": // Item
return ItemTypes.item;
case "book": // Book
return ItemTypes.book;
case "boardgame": // Board game
return ItemTypes.boardgame;
default: // Unknown
return ItemTypes.item;
}
}
/// <summary>
/// Get Item Type Name from ItemType
/// </summary>
/// <param name="type">Item Type</param>
/// <returns>Item Type Name</returns>
public static string GetItemTypeName(string type)
{
type = type.Trim();
switch (type)
{
case "item": // Item
return Lng.Get("Item");
case "book": // Book
return Lng.Get("Book");
case "boardgame": // Board game
return Lng.Get("Boardgame", "Board game");
default: // Unknown
return Lng.Get("Unknown");
}
}
/// <summary>
/// Get Status name from Status number
/// </summary>
/// <param name="status">Status number</param>
/// <returns>Status name</returns>
public static string GetStatusName(short status)
{
if (status == (short)LendStatus.Returned) // Returned
return Lng.Get("Returned");
else if (status == (short)LendStatus.Reserved) // Reserved
return Lng.Get("Reserved");
else if (status == (short)LendStatus.Canceled) // Canceled
return Lng.Get("Canceled");
else if(status == (short)LendStatus.Lended) // Lended
return Lng.Get("Lended");
else return Lng.Get("Unknown"); // Unknown
}
#endregion
#region Tables for PDF
/// <summary>
/// Create Lending table for PDF document
/// </summary>
/// <param name="lendList">Lending list</param>
/// <returns>PDF table</returns>
public static string[,] GetTable(List<Lending> lendList)
{
databaseEntities db = new databaseEntities();
// ----- Return if no data -----
if (lendList == null) return null;
// ----- Compute Tabsize -----
string[,] tab = new string[lendList.Count + 2, 6]; // 6 Columns
// ----- 1. ROW - columns size -----
tab[0, 0] = "1cm";
tab[0, 1] = "2cm";
tab[0, 2] = "6.5cm";
tab[0, 3] = "2cm";
tab[0, 4] = "2cm";
tab[0, 5] = "2.5cm";
// ----- 2. ROW - columns names -----
tab[1, 0] = Lng.Get("Number");
tab[1, 1] = Lng.Get("Type");
tab[1, 2] = Lng.Get("ItemName", "Name");
tab[1, 3] = Lng.Get("From", "From");
tab[1, 4] = Lng.Get("To", "To");
tab[1, 5] = Lng.Get("Status");
// ----- 3+. ROW - fill data-----
for (int i = 0; i < lendList.Count; i++)
{
var copy = db.Copies.Find(lendList[i].CopyID);
tab[i + 2, 0] = (i + 1).ToString();
tab[i + 2, 1] = global.GetItemTypeName(lendList[i].CopyType);
tab[i + 2, 2] = global.GetLendingItemName(copy.ItemType, copy.ItemID ?? Guid.Empty);
tab[i + 2, 3] = (lendList[i].From ?? DateTime.Now).ToShortDateString();
tab[i + 2, 4] = (lendList[i].To ?? DateTime.Now).ToShortDateString();
tab[i + 2, 5] = global.GetStatusName(lendList[i].Status ?? 1);
}
// ----- Return table -----
return tab;
}
/// <summary>
/// Create Borrowing table for PDF document
/// </summary>
/// <param name="borrList">Borowing list</param>
/// <returns>PDF table</returns>
public static string[,] GetTable(List<Borrowing> borrList)
{
databaseEntities db = new databaseEntities();
// ----- Return if no data -----
if (borrList == null) return null;
// ----- Compute Tabsize -----
string[,] tab = new string[borrList.Count + 2, 5]; // 5 Columns
// ----- 1. ROW - columns size -----
tab[0, 0] = "1cm";
tab[0, 1] = "8.5cm";
tab[0, 2] = "2cm";
tab[0, 3] = "2cm";
tab[0, 4] = "2.5cm";
// ----- 2. ROW - columns names -----
tab[1, 0] = Lng.Get("Number");
tab[1, 1] = Lng.Get("ItemName", "Name");
tab[1, 2] = Lng.Get("From", "From");
tab[1, 3] = Lng.Get("To", "To");
tab[1, 4] = Lng.Get("Status");
// ----- 3+. ROW - fill data-----
for (int i = 0; i < borrList.Count; i++)
{
tab[i + 2, 0] = (i + 1).ToString();
tab[i + 2, 1] = borrList[i].Item.Trim();
tab[i + 2, 2] = (borrList[i].From ?? DateTime.Now).ToShortDateString();
tab[i + 2, 3] = (borrList[i].To ?? DateTime.Now).ToShortDateString();
tab[i + 2, 4] = global.GetStatusName(borrList[i].Status ?? 1);
}
// ----- Return table -----
return tab;
}
#endregion
#region Export
/// <summary>
/// Export Image
/// </summary>
/// <param name="path">Image path</param>
/// <param name="image">Image</param>
/// <returns></returns>
public static bool ExportImage(ref string path, byte[] image)
{
// ----- Images -----
if (image != null && image.Length > 0)
{
try
{
File.WriteAllBytes(path, image);
path = Path.GetFileName(path);
}
catch
{
path = "";
return false;
}
}
else
{
path = "";
return false;
}
return true;
}
/// <summary>
/// Export Contacts to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="con">Contact list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportContactsCSV(string path, List<Contacts> con)
{
// ----- Head -----
string lines = "FialotCatalog:Contacts v1" + Environment.NewLine;
// ----- Names -----
lines += "name;surname;nick;sex;birth;phone;email;www;im;company;position;street;city;region;country;postcode;personcode;note;groups;tags;updated;googleID;active;avatar;GUID" + Environment.NewLine;
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Data -----
int imgNum = 0;
foreach (var item in con)
{
// ----- Images -----
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Avatar);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
// ----- Other data -----
lines += item.Name.Trim().Replace(";", "//") + ";" + item.Surname.Trim().Replace(";", "//") + ";" + item.Nick.Trim().Replace(";", "//") + ";" + item.Sex.Trim().Replace(";", "//") + ";" + item.Birth.ToString() + ";" + item.Phone.Trim().Replace(";", "//") + ";" + item.Email.Trim().Replace(";", "//") + ";" + item.WWW.Trim().Replace(";", "//") + ";" + item.IM.Trim().Replace(";", "//") + ";";
lines += item.Company.Trim().Replace(";", "//") + ";" + item.Position.Trim().Replace(";", "//") + ";" + item.Street.Trim().Replace(";", "//") + ";" + item.City.Trim().Replace(";", "//") + ";" + item.Region.Trim().Replace(";", "//") + ";" + item.Country.Trim().Replace(";", "//") + ";" + item.PostCode.Trim().Replace(";", "//") + ";";
lines += item.PersonCode.Trim().Replace(";", "//") + ";" + item.Note.Trim().Replace(";", "//") + ";" + item.Tags.Trim().Replace(";", "//") + ";" + item.FastTags.ToString() + ";" + item.Updated.ToString() + ";" + item.GoogleID.Trim() + ";" + (item.Active ?? true).ToString() + ";";
lines += imgFileName + ";" + item.ID + Environment.NewLine;
imgNum++;
}
return Files.SaveFile(path, lines);
}
/// <summary>
/// Export Lending to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="bor">Lending list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportLendedCSV(string path, List<Lending> bor)
{
databaseEntities db = new databaseEntities();
// ----- Head -----
string lines = "FialotCatalog:Lending v1" + Environment.NewLine;
// ----- Names -----
lines += "copyName;copyInvNum;copyType;copyID;personName;personID;from;to;status;note;fastTags;updated;GUID" + Environment.NewLine;
// ----- Data -----
foreach (var item in bor)
{
var person = db.Contacts.Find(item.PersonID); // Get person
var copy = db.Copies.Find(item.CopyID); // Get copy
lines += global.GetLendingItemName(copy.ItemType, copy.ItemID ?? Guid.Empty) + ";" + copy.InventoryNumber + ";";
lines += item.CopyType.Trim() + ";" + item.CopyID.ToString() + ";" + person.Name.Trim() + " " + person.Surname.Trim() + ";";
lines += item.PersonID.ToString() + ";" + item.From.ToString() + ";" + item.To.ToString() + ";" + item.Status.ToString() + ";";
lines += item.Note.Trim() + ";" + item.FastTags.ToString() + ";" + item.Updated.ToString() + ";" + item.ID.ToString() + Environment.NewLine;
}
// ----- Save to file ------
return Files.SaveFile(path, lines);
}
/// <summary>
/// Export Books to XML file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Books list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportLendedXML(string path, List<Lending> itm)
{
databaseEntities db = new databaseEntities();
// ----- Create XML document -----
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null)
);
var data = new XElement("Data",
new XElement("Info",
new XElement("Type", "FialotCatalog:Lending"),
new XElement("Version", "1")
)
);
var items = new XElement("Items");
int imgNum = 0;
foreach (var item in itm)
{
var objItem = new XElement("Lend");
var xmlItem = new XElement("Item");
if (item.CopyID != null)
{
var copy = db.Copies.Find(item.CopyID); // Get copy
if (copy != null)
{
xmlItem.Add(new XElement("Name", global.GetLendingItemName(copy.ItemType, copy.ItemID ?? Guid.Empty).Replace(Environment.NewLine, "\\n")));
if (copy.InventoryNumber != "" && copy.InventoryNumber != null) xmlItem.Add(new XElement("InventoryNumber", copy.InventoryNumber.Trim().Replace(Environment.NewLine, "\\n")));
}
if (item.CopyType != "" && item.CopyType != null) xmlItem.Add(new XElement("Type", item.CopyType.Trim().Replace(Environment.NewLine, "\\n")));
xmlItem.Add(new XElement("ID", item.CopyID.ToString()));
}
objItem.Add(xmlItem);
var xmlPerson = new XElement("Person");
if (item.PersonID != null)
{
var person = db.Contacts.Find(item.PersonID); // Get person
if (person != null)
xmlPerson.Add(new XElement("Person", person.Name.Trim() + " " + person.Surname.Trim()));
xmlPerson.Add(new XElement("PersonID", item.PersonID.ToString()));
}
objItem.Add(xmlPerson);
var xmlBorrowing = new XElement("Lend");
if (item.From != null) xmlBorrowing.Add(new XElement("From", item.From.ToString()));
if (item.To != null) xmlBorrowing.Add(new XElement("To", item.To.ToString()));
if (item.Note != "" && item.Note != null) xmlBorrowing.Add(new XElement("Note", item.Note.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Status != null) xmlBorrowing.Add(new XElement("Status", item.Status.ToString()));
objItem.Add(xmlBorrowing);
var xmlSystem = new XElement("System");
if (item.FastTags != null) xmlSystem.Add(new XElement("FastTags", item.FastTags.ToString()));
if (item.ID != Guid.Empty) xmlSystem.Add(new XElement("ID", item.ID));
if (item.Updated != null) xmlSystem.Add(new XElement("Updated", item.Updated.ToString()));
objItem.Add(xmlSystem);
items.Add(objItem);
imgNum++;
}
data.Add(items);
doc.Add(data);
var wr = new Utf8StringWriter();
doc.Save(wr);
return Files.SaveFile(path, wr.ToString());
}
/// <summary>
/// Export Borrowing to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="bor">Borrowing list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportBorrowingCSV(string path, List<Borrowing> bor)
{
databaseEntities db = new databaseEntities();
// ----- Head -----
string lines = "FialotCatalog:Borrowing v1" + Environment.NewLine;
// ----- Names -----
lines += "item;itemInvNum;person;personID;from;to;status;note;fastTags;updated;GUID" + Environment.NewLine;
// ----- Data -----
foreach (var item in bor)
{
var person = db.Contacts.Find(item.PersonID); // Get person
lines += item.Item + ";" + item.ItemInvNum + ";" + person.Name.Trim() + " " + person.Surname.Trim() + ";";
lines += item.PersonID.ToString() + ";" + item.From.ToString() + ";" + item.To.ToString() + ";" + item.Status.ToString() + ";";
lines += item.Note + ";" + item.FastTags.ToString() + ";" + item.Updated.ToString() + ";" + item.ID.ToString() + Environment.NewLine;
}
// ----- Save to file ------
return Files.SaveFile(path, lines);
}
/// <summary>
/// Export Books to XML file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Books list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportBorrowingXML(string path, List<Borrowing> itm)
{
databaseEntities db = new databaseEntities();
// ----- Create XML document -----
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null)
);
var data = new XElement("Data",
new XElement("Info",
new XElement("Type", "FialotCatalog:Borrowing"),
new XElement("Version", "1")
)
);
var items = new XElement("Items");
int imgNum = 0;
foreach (var item in itm)
{
var objItem = new XElement("Borrowing");
var xmlItem = new XElement("Item");
if (item.Item != "") xmlItem.Add(new XElement("Name", item.Item.Trim().Replace(Environment.NewLine, "\\n")));
if (item.ItemInvNum != "" && item.ItemInvNum != null) xmlItem.Add(new XElement("InventoryNumber", item.ItemInvNum.Trim().Replace(Environment.NewLine, "\\n")));
objItem.Add(xmlItem);
var xmlPerson = new XElement("Person");
if (item.PersonID != null)
{
var person = db.Contacts.Find(item.PersonID); // Get person
if (person != null)
xmlPerson.Add(new XElement("Person", person.Name.Trim() + " " + person.Surname.Trim()));
xmlPerson.Add(new XElement("PersonID", item.PersonID.ToString()));
}
objItem.Add(xmlPerson);
var xmlBorrowing = new XElement("Borrowing");
if (item.From != null) xmlBorrowing.Add(new XElement("From", item.From.ToString()));
if (item.To != null) xmlBorrowing.Add(new XElement("To", item.To.ToString()));
if (item.Note != "" && item.Note != null) xmlBorrowing.Add(new XElement("Note", item.Note.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Status != null) xmlBorrowing.Add(new XElement("Status", item.Status.ToString()));
objItem.Add(xmlBorrowing);
var xmlSystem = new XElement("System");
if (item.FastTags != null) xmlSystem.Add(new XElement("FastTags", item.FastTags.ToString()));
if (item.ID != Guid.Empty) xmlSystem.Add(new XElement("ID", item.ID));
if (item.Updated != null) xmlSystem.Add(new XElement("Updated", item.Updated.ToString()));
objItem.Add(xmlSystem);
items.Add(objItem);
imgNum++;
}
data.Add(items);
doc.Add(data);
var wr = new Utf8StringWriter();
doc.Save(wr);
return Files.SaveFile(path, wr.ToString());
}
/// <summary>
/// Export Copies to CSV file
/// </summary>
/// <param name="path"></param>
/// <param name="itm"></param>
public static void ExportCopiesCSV(string path, List<Copies> itm)
{
// ----- Head -----
string lines = "FialotCatalog:Copies v1" + Environment.NewLine;
// ----- Names -----
lines += "itemName;itemType;itemID;itemNum;invNumber;condition;location;note;acqDate;price;excluded;status;GUID" + Environment.NewLine;
// ----- Data -----
foreach (var item in itm)
{
// ----- Other data -----
lines += global.GetLendingItemName(item.ItemType, item.ItemID ?? Guid.Empty) + ";" + item.ItemType.Trim() + ";" + item.ItemID.ToString() + ";" + item.ItemNum.ToString() + ";";
lines += item.InventoryNumber.Trim() + ";" + item.Condition.Trim() + ";" + item.Location.Trim() + ";" + item.Note.Trim() + ";";
lines += item.AcquisitionDate.ToString() + ";" + item.Price.ToString() + ";" + item.Excluded.ToString() + ";" + item.Status + ";";
lines += item.ID + Environment.NewLine;
}
// ----- Save to file ------
Files.SaveFile(path, lines);
}
/// <summary>
/// Export XML Copies
/// </summary>
/// <param name="copies">Copies list</param>
/// <returns>Copies elements</returns>
public static XElement ExportCopiesXML(List<Copies> copies)
{
var xmlCopies = new XElement("Copies");
foreach (var copy in copies)
{
var xmlCopy = new XElement("Copy");
xmlCopy.Add(new XElement("ItemName", global.GetLendingItemName(copy.ItemType, copy.ItemID ?? Guid.Empty)));
if (copy.ItemID != null) xmlCopy.Add(new XElement("ItemID", copy.ItemID.ToString()));
if (copy.ItemType != "") xmlCopy.Add(new XElement("ItemType", copy.ItemType.Trim()));
if (copy.ItemNum != null) xmlCopy.Add(new XElement("ItemNum", copy.ItemNum.ToString()));
if (copy.InventoryNumber != "") xmlCopy.Add(new XElement("InventoryNumber", copy.InventoryNumber.Trim()));
if (copy.Barcode != null) xmlCopy.Add(new XElement("Barcode", copy.Barcode.ToString()));
if (copy.Condition != "") xmlCopy.Add(new XElement("Condition", copy.Condition.Trim().Replace(Environment.NewLine, "\\n")));
if (copy.Location != "") xmlCopy.Add(new XElement("Location", copy.Location.Trim().Replace(Environment.NewLine, "\\n")));
if (copy.Note != "") xmlCopy.Add(new XElement("Note", copy.Note.Trim().Replace(Environment.NewLine, "\\n")));
if (copy.AcquisitionDate != null) xmlCopy.Add(new XElement("AcquisitionDate", copy.AcquisitionDate.ToString()));
if (copy.Price != null) xmlCopy.Add(new XElement("Price", copy.Price.ToString()));
if (copy.Excluded != null) xmlCopy.Add(new XElement("Excluded", copy.Excluded.ToString()));
//if (copy.Status != null) xmlCopy.Add(new XElement("Status", copy.Status.ToString()));
xmlCopy.Add(new XElement("ID", copy.ID.ToString()));
xmlCopies.Add(xmlCopy);
}
return xmlCopies;
}
/// <summary>
/// Export Items to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Item list</param>
public static void ExportItemsCSV(string path, List<Items> itm)
{
databaseEntities db = new databaseEntities();
// ----- Head -----
string lines = "FialotCatalog:Items v1" + Environment.NewLine;
// ----- Names -----
lines += "name;category;subcategory;subcategory2;keywords;manufacturer;note;excluded;count;fasttags;image;updated;GUID" + Environment.NewLine;
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Copies -----
var copies = db.Copies.Where(x => (x.ItemType.Trim() == ItemTypes.item.ToString())).ToList();
string copiesPath = filePath + Path.DirectorySeparatorChar + "copies.csv";
ExportCopiesCSV(copiesPath, copies);
// ----- Data -----
int imgNum = 0;
foreach (var item in itm)
{
// ----- Images -----
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Image);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
// ----- Other data -----
lines += item.Name.Trim() + ";" + item.Category.Trim() + ";" + item.Subcategory.Trim() + ";" + item.Subcategory2 + ";" + item.Keywords.Trim().Replace(";", ",") + ";";
lines += item.Manufacturer + ";" + item.Note.Trim().Replace(Environment.NewLine, "\\n") + ";" + item.Excluded.ToString() + ";" + item.Count.ToString() + ";" ;
lines += item.FastTags.ToString() + ";" + imgFileName + ";" + item.Updated.ToString() + ";" + item.ID + Environment.NewLine;
imgNum++;
}
// ----- Save to file ------
Files.SaveFile(path, lines);
}
/// <summary>
/// Export Books to XML file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Books list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportItemsXML(string path, List<Items> itm)
{
databaseEntities db = new databaseEntities();
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Create XML document -----
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null)
);
var data = new XElement("Data",
new XElement("Info",
new XElement("Type", "FialotCatalog:Items"),
new XElement("Version", "1")
)
);
var items = new XElement("Items");
int imgNum = 0;
foreach (var item in itm)
{
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Image);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
var objItem = new XElement("Item");
var xmlGeneral = new XElement("General");
if (item.Name != "") xmlGeneral.Add(new XElement("Name", item.Name.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Manufacturer != "") xmlGeneral.Add(new XElement("Manufacturer", item.Manufacturer.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Note != "") xmlGeneral.Add(new XElement("Note", item.Note.Trim().Replace(Environment.NewLine, "\\n")));
objItem.Add(xmlGeneral);
var xmlClassification = new XElement("Classification");
if (item.Category != "") xmlClassification.Add(new XElement("Category", item.Category.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Subcategory != "") xmlClassification.Add(new XElement("Subcategory", item.Subcategory.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Subcategory2 != "") xmlClassification.Add(new XElement("Subcategory2", item.Subcategory2.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Keywords != "") xmlClassification.Add(new XElement("Keywords", item.Keywords.Trim()));
if (item.FastTags != null) xmlClassification.Add(new XElement("FastTags", item.FastTags.ToString()));
objItem.Add(xmlClassification);
/*var xmlRating = new XElement("Rating");
if (item.Rating != null) xmlRating.Add(new XElement("Rating", item.Rating.ToString()));
if (item.MyRating != null) xmlRating.Add(new XElement("MyRating", item.MyRating.ToString()));
objItem.Add(xmlRating);*/
var xmlSystem = new XElement("System");
if (item.ID != Guid.Empty) xmlSystem.Add(new XElement("ID", item.ID));
if (item.Updated != null) xmlSystem.Add(new XElement("Updated", item.Updated.ToString()));
if (item.Excluded != null) xmlSystem.Add(new XElement("Excluded", Conv.ToString(item.Excluded ?? false)));
if (imgFileName != "") xmlSystem.Add(new XElement("Image", imgFileName));
objItem.Add(xmlSystem);
items.Add(objItem);
imgNum++;
}
// ----- Copies -----
var copies = db.Copies.Where(x => (x.ItemType.Trim() == ItemTypes.item.ToString())).ToList();
var xmlCopies = ExportCopiesXML(copies);
data.Add(items);
data.Add(xmlCopies);
doc.Add(data);
var wr = new Utf8StringWriter();
doc.Save(wr);
return Files.SaveFile(path, wr.ToString());
}
/// <summary>
/// Export Books to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Book list</param>
public static void ExportBooksCSV(string path, List<Books> book)
{
databaseEntities db = new databaseEntities();
// ----- Head -----
string lines = "FialotCatalog:Books v1" + Environment.NewLine;
// ----- Names -----
lines += "Title;AuthorName;AuthorSurname;ISBN;Illustrator;Translator;Language;Publisher;Edition;Year;Pages;MainCharacter;URL;Note;Note1;Note2;Content;OrigName;OrigLanguage;OrigYear;Genre;SubGenre;Series;SeriesNum;Keywords;Rating;MyRating;Readed;Type;Bookbinding;EbookPath;EbookType;Publication;Excluded;Cover;Updated;FastTags;GUID" + Environment.NewLine;
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Copies -----
var copies = db.Copies.Where(x => (x.ItemType.Trim() == ItemTypes.book.ToString())).ToList();
string copiesPath = filePath + Path.DirectorySeparatorChar + "copies.csv";
ExportCopiesCSV(copiesPath, copies);
// ----- Data -----
int imgNum = 0;
foreach (var item in book)
{
// ----- Cover -----
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Cover);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
// ----- Other data -----
lines += item.Title.Trim() + ";" + item.AuthorName.Trim() + ";" + item.AuthorSurname.Trim() + ";" + item.ISBN + ";" + item.Illustrator + ";" + item.Translator + ";";
lines += item.Language + ";" + item.Publisher + ";" + item.Edition + ";" + item.Year + ";" + item.Pages + ";" + item.MainCharacter + ";";
lines += item.URL + ";" + item.Note.Replace(Environment.NewLine, "\\n") + ";" + item.Note1.Replace(Environment.NewLine, "\\n") + ";" + item.Note2.Replace(Environment.NewLine, "\\n") + ";" + item.Content.Replace(Environment.NewLine, "\\n") + ";";
lines += item.OrigName + ";" + item.OrigLanguage + ";" + item.OrigYear + ";" + item.Genre + ";" + item.SubGenre + ";" + item.Series + ";" + item.SeriesNum + ";";
lines += item.Keywords.Replace(";", ",") + ";" + item.Rating + ";" + item.MyRating + ";" + item.Readed + ";" + item.Type + ";" + item.Bookbinding + ";";
lines += item.EbookPath + ";" + item.EbookType + ";" + item.Publication + ";" + item.Excluded + ";" + imgFileName + ";" + item.Updated + ";";
lines += item.FastTags.ToString() + ";" + item.ID + Environment.NewLine;
imgNum++;
}
// ----- Save to file ------
Files.SaveFile(path, lines);
}
/// <summary>
/// Export Books to XML file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Books list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportBooksXML(string path, List<Books> itm)
{
databaseEntities db = new databaseEntities();
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Create XML document -----
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null)
);
var data = new XElement("Data",
new XElement("Info",
new XElement("Type", "FialotCatalog:Books"),
new XElement("Version", "1")
)
);
var items = new XElement("Items");
int imgNum = 0;
foreach (var item in itm)
{
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Cover);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
var objItem = new XElement("Book");
var xmlGeneral = new XElement("General");
if (item.Title != "") xmlGeneral.Add(new XElement("Title", item.Title.Trim().Replace(Environment.NewLine, "\\n")));
if (item.AuthorName != "") xmlGeneral.Add(new XElement("AuthorName", item.AuthorName.Trim().Replace(Environment.NewLine, "\\n")));
if (item.AuthorSurname != "") xmlGeneral.Add(new XElement("AuthorSurname", item.AuthorSurname.ToString()));
if (item.Note != "") xmlGeneral.Add(new XElement("Note", item.Note.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Note1 != "") xmlGeneral.Add(new XElement("Note1", item.Note1.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Note2 != "") xmlGeneral.Add(new XElement("Note2", item.Note2.Trim().Replace(Environment.NewLine, "\\n")));
if (item.ISBN != "") xmlGeneral.Add(new XElement("ISBN", item.ISBN.ToString()));
if (item.Illustrator != "") xmlGeneral.Add(new XElement("Illustrator", item.Illustrator.ToString().Replace(Environment.NewLine, "\\n")));
if (item.Translator != "") xmlGeneral.Add(new XElement("Translator", item.Translator.ToString().Replace(Environment.NewLine, "\\n")));
if (item.Language != "") xmlGeneral.Add(new XElement("Language", item.Language.Replace(Environment.NewLine, "\\n")));
if (item.Publisher != "") xmlGeneral.Add(new XElement("Publisher", item.Publisher.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Edition != "") xmlGeneral.Add(new XElement("Edition", item.Edition.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Year != null) xmlGeneral.Add(new XElement("Year", item.Year.ToString()));
if (item.Pages != null) xmlGeneral.Add(new XElement("Pages", item.Pages.ToString()));
if (item.URL != "") xmlGeneral.Add(new XElement("URL", item.URL.ToString()));
if (item.MainCharacter != "") xmlGeneral.Add(new XElement("MainCharacter", item.MainCharacter.ToString().Replace(Environment.NewLine, "\\n")));
if (item.Content != "") xmlGeneral.Add(new XElement("Content", item.Content.Trim().Replace(Environment.NewLine, "\\n")));
if (item.OrigName != "") xmlGeneral.Add(new XElement("OrigName", item.OrigName.Trim().Replace(Environment.NewLine, "\\n")));
if (item.OrigLanguage != "") xmlGeneral.Add(new XElement("OrigLanguage", item.OrigLanguage.Trim().Replace(Environment.NewLine, "\\n")));
if (item.OrigYear != null) xmlGeneral.Add(new XElement("OrigYear", item.OrigYear.ToString()));
if (item.Series != "") xmlGeneral.Add(new XElement("Series", item.Series.Trim().Replace(Environment.NewLine, "\\n")));
if (item.SeriesNum != null) xmlGeneral.Add(new XElement("SeriesNum", item.SeriesNum.ToString()));
if (item.Type != "") xmlGeneral.Add(new XElement("Type", item.Type.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Bookbinding != "") xmlGeneral.Add(new XElement("Bookbinding", item.Bookbinding.Trim().Replace(Environment.NewLine, "\\n")));
if (item.EbookType != "") xmlGeneral.Add(new XElement("EbookType", item.EbookType.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Publication != null) xmlGeneral.Add(new XElement("Publication", item.Publication.ToString()));
objItem.Add(xmlGeneral);
var xmlClassification = new XElement("Classification");
if (item.Genre != "") xmlClassification.Add(new XElement("Genre", item.Genre.Trim().Replace(Environment.NewLine, "\\n")));
if (item.SubGenre != "") xmlClassification.Add(new XElement("SubGenre", item.SubGenre.Trim().Replace(Environment.NewLine, "\\n")));
if (item.Keywords != "") xmlClassification.Add(new XElement("Keywords", item.Keywords.Trim()));
if (item.FastTags != null) xmlClassification.Add(new XElement("FastTags", item.FastTags.ToString()));
objItem.Add(xmlClassification);
var xmlRating = new XElement("Rating");
if (item.Rating != null) xmlRating.Add(new XElement("Rating", item.Rating.ToString()));
if (item.MyRating != null) xmlRating.Add(new XElement("MyRating", item.MyRating.ToString()));
objItem.Add(xmlRating);
var xmlSystem = new XElement("System");
if (item.ID != Guid.Empty) xmlSystem.Add(new XElement("ID", item.ID));
if (item.Updated != null) xmlSystem.Add(new XElement("Updated", item.Updated.ToString()));
if (item.Excluded != null) xmlSystem.Add(new XElement("Excluded", Conv.ToString(item.Excluded ?? false)));
if (imgFileName != "") xmlSystem.Add(new XElement("Cover", imgFileName));
if (item.Readed != null) xmlSystem.Add(new XElement("Readed", Conv.ToString(item.Readed ?? false)));
objItem.Add(xmlSystem);
items.Add(objItem);
imgNum++;
}
// ----- Copies -----
var copies = db.Copies.Where(x => (x.ItemType.Trim() == ItemTypes.book.ToString())).ToList();
var xmlCopies = ExportCopiesXML(copies);
data.Add(items);
data.Add(xmlCopies);
doc.Add(data);
var wr = new Utf8StringWriter();
doc.Save(wr);
return Files.SaveFile(path, wr.ToString());
}
/// <summary>
/// Export Boardgames to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Item list</param>
public static void ExportBoardCSV(string path, List<Boardgames> itm)
{
databaseEntities db = new databaseEntities();
// ----- Head -----
string lines = "FialotCatalog:Boardgames v1" + Environment.NewLine;
// ----- Names -----
lines += "Name;Category;MinPlayers;MaxPlayers;MinAge;GameTime;GameWorld;Language;Publisher;Author;Year;Description;Keywords;Note;Family;Extension;ExtensionNumber;Rules;Cover;Img1;Img2;Img3;MaterialPath;Rating;MyRating;URL;Excluded;FastTags;Updated;GUID" + Environment.NewLine;
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Copies -----
var copies = db.Copies.Where(x => (x.ItemType.Trim() == ItemTypes.boardgame.ToString())).ToList();
string copiesPath = filePath + Path.DirectorySeparatorChar + "copies.csv";
ExportCopiesCSV(copiesPath, copies);
// ----- Data -----
int imgNum = 0;
foreach (var item in itm)
{
// ----- Images -----
string imgCover = filePath + Path.DirectorySeparatorChar + "imgC" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgCover, item.Cover);
imgCover = Path.GetFileName(imgCover);
string img1 = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + "A.jpg";
ExportImage(ref img1, item.Img1);
img1 = Path.GetFileName(img1);
string img2 = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + "B.jpg";
ExportImage(ref img2, item.Img2);
img2 = Path.GetFileName(img2);
string img3 = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + "C.jpg";
ExportImage(ref img3, item.Img3);
img3 = Path.GetFileName(img3);
// ----- Other data -----
lines += item.Name + ";" + item.Category + ";" + item.MinPlayers + ";" + item.MaxPlayers + ";" + item.MinAge + ";" + item.GameTime + ";" + item.GameWorld + ";";
lines += item.Language + ";" + item.Publisher + ";" + item.Author + ";" + item.Year + ";" + item.Description.Replace(Environment.NewLine, "\\n") + ";" + item.Keywords.Trim().Replace(";", ",") + ";";
lines += item.Note.Replace(Environment.NewLine, "\\n") + ";" + item.Family + ";" + item.Extension + ";" + item.ExtensionNumber + ";" + item.Rules.Replace(Environment.NewLine, "\\n") + ";";
lines += imgCover + ";" + img1 + ";" + img2 + ";" + img3 + ";" + item.MaterialPath + ";" + item.Rating + ";" + item.MyRating + ";" + item.URL + ";";
lines += item.Excluded + ";" + item.FastTags + ";" + item.Updated + ";" + item.ID + Environment.NewLine;
imgNum++;
}
// ----- Save to file ------
Files.SaveFile(path, lines);
}
/// <summary>
/// Export Board games to XML file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Recipes list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportBoardXML(string path, List<Boardgames> itm)
{
databaseEntities db = new databaseEntities();
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Create XML document -----
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null)
);
var data = new XElement("Data",
new XElement("Info",
new XElement("Type", "FialotCatalog:Boardgames"),
new XElement("Version", "1")
)
);
var items = new XElement("Items");
int imgNum = 0;
foreach (var item in itm)
{
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
string imgFileNameA = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + "A.jpg";
string imgFileNameB = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + "B.jpg";
string imgFileNameC = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + "C.jpg";
ExportImage(ref imgFileName, item.Cover);
ExportImage(ref imgFileNameA, item.Img1);
ExportImage(ref imgFileNameB, item.Img2);
ExportImage(ref imgFileNameC, item.Img3);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
try
{
imgFileNameA = Path.GetFileName(imgFileNameA);
}
catch { }
try
{
imgFileNameB = Path.GetFileName(imgFileNameB);
}
catch { }
try
{
imgFileNameC = Path.GetFileName(imgFileNameC);
}
catch { }
var objItem = new XElement("BoardGame");
objItem.Add(new XElement("General",
new XElement("Name", item.Name.Trim()),
new XElement("Description", item.Description.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Note", item.Note.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("MinAge", item.MinAge.ToString()),
new XElement("MinPlayers", item.MinPlayers.ToString()),
new XElement("MaxPlayers", item.MaxPlayers.ToString()),
new XElement("GameTime", item.GameTime.ToString()),
new XElement("GameWorld", item.GameWorld.Replace(Environment.NewLine, "\\n")),
new XElement("Language", item.Language.Trim()),
new XElement("Publisher", item.Publisher.Trim()),
new XElement("Author", item.Author.Trim()),
new XElement("Year", item.Year.ToString()),
new XElement("Extension", item.Extension.ToString()),
new XElement("ExtensionNumber", item.ExtensionNumber.ToString()),
new XElement("Rules", item.Rules.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("MaterialPath", item.MaterialPath.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Family", item.Family.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("URL", item.URL.Trim())
));
objItem.Add(new XElement("Classification",
new XElement("Category", item.Category.Trim()),
//new XElement("Subcategory", item.Subcategory.Trim()),
new XElement("Keywords", item.Keywords.Trim()),
new XElement("FastTags", item.FastTags.ToString())
));
objItem.Add(new XElement("Rating",
new XElement("Rating", item.Rating.ToString()),
new XElement("MyRating", item.MyRating.ToString())
));
objItem.Add(new XElement("System",
new XElement("ID", item.ID),
new XElement("Updated", item.Updated.ToString()),
new XElement("Excluded", (item.Excluded ?? false).ToString()),
new XElement("Cover", imgFileName),
new XElement("Img1", imgFileNameA),
new XElement("Img2", imgFileNameB),
new XElement("Img3", imgFileNameC)
));
items.Add(objItem);
imgNum++;
}
// ----- Copies -----
var copies = db.Copies.Where(x => (x.ItemType.Trim() == ItemTypes.boardgame.ToString())).ToList();
var xmlCopies = ExportCopiesXML(copies);
data.Add(items);
data.Add(xmlCopies);
doc.Add(data);
var wr = new Utf8StringWriter();
doc.Save(wr);
return Files.SaveFile(path, wr.ToString());
}
/// <summary>
/// Export Games to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Contact list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportGamesCSV(string path, List<Games> itm)
{
// ----- Head -----
string lines = "FialotCatalog:Games v1" + Environment.NewLine;
// ----- Names -----
lines += "name;category;subcategory;keywords;note;description;image;playerage;minplayers;maxplayers;duration;durationpreparation;things;url;rules;preparation;enviroment;files;rating;myrating;fasttags;updated;excluded;GUID" + Environment.NewLine;
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Data -----
int imgNum = 0;
foreach (var item in itm)
{
// ----- Images -----
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Image);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
// ----- Other data -----
lines += item.Name.Trim().Replace(";", "//") + ";" + item.Category.Trim().Replace(";", "//") + ";" + item.Subcategory.Trim().Replace(";", "//") + ";" +
item.Keywords.Trim().Replace(";", "//") + ";" + item.Note.Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" + item.Description.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" +
imgFileName + ";" + item.PlayerAge.Trim().Replace(";", "//") + ";" + item.MinPlayers.ToString() + ";" + item.MaxPlayers.ToString() + ";" + item.Duration.ToString() + ";" +
item.DurationPreparation.ToString() + ";" + item.Things.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" + item.URL.Trim().Replace(";", "//") + ";" + item.Rules.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" +
item.Preparation.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" + item.Environment.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" + item.Files.Trim().Replace(";", "//") + ";" +
item.Rating.ToString() + ";" + item.MyRating.ToString() + ";" + item.FastTags.ToString() + ";" + item.Updated.ToString() + ";" +
(item.Excluded ?? false).ToString() + ";" + item.ID + Environment.NewLine;
imgNum++;
}
return Files.SaveFile(path, lines);
}
/// <summary>
/// Export Games to XML file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Recipes list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportGamesXML(string path, List<Games> itm)
{
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Create XML document -----
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null)
);
var data = new XElement("Data",
new XElement("Info",
new XElement("Type", "FialotCatalog:Games"),
new XElement("Version", "1")
)
);
var items = new XElement("Items");
int imgNum = 0;
foreach (var item in itm)
{
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Image);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
var objItem = new XElement("Game");
objItem.Add(new XElement("General",
new XElement("Name", item.Name.Trim()),
new XElement("Description", item.Description.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Note", item.Note.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("PlayerAge", item.PlayerAge.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("MinPlayers", item.MinPlayers.ToString()),
new XElement("MaxPlayers", item.MaxPlayers.ToString()),
new XElement("Duration", item.Duration.ToString()),
new XElement("DurationPreparation", item.DurationPreparation.ToString()),
new XElement("Things", item.Things.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Rules", item.Rules.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Preparation", item.Preparation.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Environment", item.Environment.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Files", item.Files.Trim()),
new XElement("URL", item.URL.Trim())
));
objItem.Add(new XElement("Classification",
new XElement("Category", item.Category.Trim()),
new XElement("Subcategory", item.Subcategory.Trim()),
new XElement("Keywords", item.Keywords.Trim()),
new XElement("FastTags", item.FastTags.ToString())
));
objItem.Add(new XElement("Rating",
new XElement("Rating", item.Rating.ToString()),
new XElement("MyRating", item.MyRating.ToString())
));
objItem.Add(new XElement("System",
new XElement("ID", item.ID),
new XElement("Updated", item.Updated.ToString()),
new XElement("Excluded", (item.Excluded ?? false).ToString()),
new XElement("Image", imgFileName)
));
items.Add(objItem);
imgNum++;
}
data.Add(items);
doc.Add(data);
var wr = new Utf8StringWriter();
doc.Save(wr);
return Files.SaveFile(path, wr.ToString());
}
/// <summary>
/// Export Recipes to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Contact list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportRecipesCSV(string path, List<Recipes> itm)
{
// ----- Head -----
string lines = "FialotCatalog:Recipes v1" + Environment.NewLine;
// ----- Names -----
lines += "name;category;subcategory;keywords;note;description;image;procedure;resources;rating;myrating;fasttags;updated;excluded;GUID" + Environment.NewLine;
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Data -----
int imgNum = 0;
foreach (var item in itm)
{
// ----- Images -----
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Image);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
// ----- Other data -----
lines += item.Name.Trim().Replace(";", "//") + ";" + item.Category.Trim().Replace(";", "//") + ";" + item.Subcategory.Trim().Replace(";", "//") + ";" +
item.Keywords.Trim().Replace(";", "//") + ";" + item.Note.Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" + item.Description.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" +
imgFileName + ";" + item.Procedure.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" + item.Resources.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" +
item.Rating.ToString() + ";" + item.MyRating.ToString() + ";" + item.FastTags.ToString() + ";" + item.Updated.ToString() + ";" +
(item.Excluded ?? false).ToString() + ";" + item.ID + Environment.NewLine;
imgNum++;
}
return Files.SaveFile(path, lines);
}
/// <summary>
/// Export Recipes to XML file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Recipes list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportRecipesXML(string path, List<Recipes> itm)
{
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Create XML document -----
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null)
);
var data = new XElement("Data",
new XElement("Info",
new XElement("Type", "FialotCatalog:Recipes"),
new XElement("Version", "1")
)
);
var items = new XElement("Items");
int imgNum = 0;
foreach (var item in itm)
{
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Image);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
var objItem = new XElement("Recipe");
objItem.Add(new XElement("General",
new XElement("Name", item.Name.Trim()),
new XElement("Description", item.Description.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Note", item.Note.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Procedure", item.Procedure.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Resources", item.Resources.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("URL", item.URL.Trim())
));
objItem.Add(new XElement("Classification",
new XElement("Category", item.Category.Trim()),
new XElement("Subcategory", item.Subcategory.Trim()),
new XElement("Keywords", item.Keywords.Trim()),
new XElement("FastTags", item.FastTags.ToString())
));
objItem.Add(new XElement("Rating",
new XElement("Rating", item.Rating.ToString()),
new XElement("MyRating", item.MyRating.ToString())
));
objItem.Add(new XElement("System",
new XElement("ID", item.ID),
new XElement("Updated", item.Updated.ToString()),
new XElement("Excluded", (item.Excluded ?? false).ToString()),
new XElement("Image", imgFileName)
));
items.Add(objItem);
imgNum++;
}
data.Add(items);
doc.Add(data);
var wr = new Utf8StringWriter();
doc.Save(wr);
return Files.SaveFile(path, wr.ToString());
}
/// <summary>
/// Export Objects to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Contact list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportObjectCSV(string path, List<Objects> itm)
{
// ----- Head -----
string lines = "FialotCatalog:Objects v1" + Environment.NewLine;
// ----- Names -----
lines += "name;category;subcategory;keywords;note;description;URL;image;rating;myrating;fasttags;updated;active;version;files;folder;type;objectnum;language;parent;customer;development;isparent;usedobject;GUID" + Environment.NewLine;
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Data -----
int imgNum = 0;
foreach (var item in itm)
{
// ----- Images -----
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Image);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
// ----- Other data -----
lines += item.Name.Trim().Replace(";", "//") + ";" + item.Category.Trim().Replace(";", "//") + ";" + item.Subcategory.Trim().Replace(";", "//") + ";" +
item.Keywords.Trim().Replace(";", "//") + ";" + item.Note.Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" + item.Description.Trim().Replace(";", "//").Replace(Environment.NewLine, "\\n") + ";" +
item.URL.Trim() + ";" +
imgFileName + ";" + item.Rating.ToString() + ";" + item.MyRating.ToString() + ";" + item.FastTags.ToString() + ";" + item.Updated.ToString() + ";" +
(item.Active ?? true).ToString() + ";" + item.Version.Trim().Replace(";", "//") + ";" + item.Files.Trim().Replace(";", "//") + ";" + item.Folder.Trim().Replace(";", "//") + ";" +
item.Type.Trim().Replace(";", "//") + ";" + item.ObjectNum.Trim().Replace(";", "//") + ";" + item.Language.Trim().Replace(";", "//") + ";" + item.Parent.ToString() + ";" +
item.Customer.Trim().Replace(";", "//") + ";" + item.Development.Trim().Replace(";", "//") + ";" + (item.IsParent ?? true).ToString() + ";" +
item.UsedObjects.Trim().Replace(";", "//") + ";" + item.ID + Environment.NewLine;
imgNum++;
}
return Files.SaveFile(path, lines);
}
/// <summary>
/// Export Objects to CSV file
/// </summary>
/// <param name="path">File path</param>
/// <param name="itm">Contact list</param>
/// <returns>Return True if saved succesfully</returns>
public static bool ExportObjectXML(string path, List<Objects> itm)
{
// ----- Create files path -----
string filePath = "";
try
{
filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
Directory.CreateDirectory(filePath);
}
catch { }
// ----- Create XML document -----
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null)
);
var data = new XElement("Data",
new XElement("Info",
new XElement("Type", "FialotCatalog:Objects"),
new XElement("Version", "1")
)
);
var items = new XElement("Items");
int imgNum = 0;
foreach (var item in itm)
{
string imgFileName = filePath + Path.DirectorySeparatorChar + "img" + imgNum.ToString("D4") + ".jpg";
ExportImage(ref imgFileName, item.Image);
try
{
imgFileName = Path.GetFileName(imgFileName);
}
catch { }
var objItem = new XElement("Object");
objItem.Add(new XElement("General",
new XElement("Name", item.Name.Trim()),
new XElement("ObjectNumber", item.ObjectNum.Trim()),
new XElement("Description", item.Description.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Note", item.Note.Trim().Replace(Environment.NewLine, "\\n")),
new XElement("Version", item.Version.Trim()),
new XElement("Files", item.Files.Trim()),
new XElement("Folder", item.Folder.Trim()),
new XElement("URL", item.URL.Trim()),
new XElement("Customer", item.Customer.Trim()),
new XElement("Development", item.Development.Trim()),
new XElement("Language", item.Language.Trim())
));
objItem.Add(new XElement("Classification",
new XElement("Type", item.Type.Trim()),
new XElement("Category", item.Category.Trim()),
new XElement("Subcategory", item.Subcategory.Trim()),
new XElement("Keywords", item.Keywords.Trim()),
new XElement("FastTags", item.FastTags.ToString())
));
objItem.Add(new XElement("Rating",
new XElement("Rating", item.Rating.ToString()),
new XElement("MyRating", item.MyRating.ToString())
));
objItem.Add(new XElement("System",
new XElement("ID", item.ID),
new XElement("Updated", item.Updated.ToString()),
new XElement("Active", (item.Active ?? true).ToString()),
new XElement("Parent", item.Parent.ToString()),
new XElement("IsParent", (item.IsParent ?? true).ToString()),
new XElement("UsedObjects", item.UsedObjects.Trim()),
new XElement("Image", imgFileName)
));
items.Add(objItem);
imgNum++;
}
data.Add(items);
doc.Add(data);
var wr = new Utf8StringWriter();
doc.Save(wr);
return Files.SaveFile(path, wr.ToString());
}
#endregion
#region Import
/// <summary>
/// Import Contacts from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Contact list</returns>
public static List<Contacts> ImportContactsCSV(string path)
{
List<Contacts> con = new List<Contacts>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Contacts"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 25)
return null;
// ----- Parse data -----
foreach (var item in file.data)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + item[23];
Contacts contact = new Contacts();
contact.Name = item[0].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Surname = item[1].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Nick = item[2].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Sex = item[3].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Birth = Conv.ToDateTimeNull(item[4]);
contact.Phone = item[5].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Email = item[6].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.WWW = item[7].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.IM = item[8].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Company = item[9].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Position = item[10].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Street = item[11].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.City = item[12].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Region = item[13].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Country = item[14].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.PostCode = item[15].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.PersonCode = item[16].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Note = item[17].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Tags = item[18].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.FastTags = Conv.ToShortDef(item[19], 0);
contact.Updated = Conv.ToDateTimeNull(item[20]);
contact.GoogleID = item[21].Replace("//", ";").Replace("\\n", Environment.NewLine);
contact.Active = Conv.ToBoolDef(item[22], true);
if (item[23] != "")
contact.Avatar = Files.LoadBinFile(imgPath);
contact.ID = Conv.ToGuid(item[24]);
con.Add(contact);
}
return con;
}
private static string CValueToString(List<cValue> val)
{
string res = "";
if (val != null)
{
foreach(var item in val)
{
if (res != "") res += ";";
res += item.Value + "," + item.Desc;
}
}
return res;
}
private static List<cValue> StringToCValue(string text)
{
List<cValue> list = new List<cValue>();
if (text == "") return null;
string[] items = text.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < items.Length; i++)
{
cValue val = new cValue() { Desc = "", Value = "", Primary = false};
string[] split = items[i].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
val.Primary = true;
if (split.Length > 0)
val.Value = split[0];
if (split.Length > 1)
val.Desc = split[1];
list.Add(val);
}
return list;
}
private static string GetCompany(List<cCompany> val)
{
string res = "";
if (val != null)
{
foreach (var item in val)
{
if (res != "") res += ";";
res += item.Name;
}
}
return res;
}
private static string GetPosition(List<cCompany> val)
{
string res = "";
if (val != null)
{
foreach (var item in val)
{
if (res != "") res += ";";
res += item.Position;
}
}
return res;
}
private static string GetStreet(List<cAddress> val)
{
if (val != null && val.Count > 0)
{
foreach (var item in val)
{
if (item.Primary)
{
return item.Street;
}
}
return val[0].Street;
}
return "";
}
private static string GetCity(List<cAddress> val)
{
if (val != null && val.Count > 0)
{
foreach (var item in val)
{
if (item.Primary)
{
return item.City;
}
}
return val[0].City;
}
return "";
}
private static string GetRegion(List<cAddress> val)
{
if (val != null && val.Count > 0)
{
foreach (var item in val)
{
if (item.Primary)
{
return item.Region;
}
}
return val[0].Region;
}
return "";
}
private static string GetCountry(List<cAddress> val)
{
if (val != null && val.Count > 0)
{
foreach (var item in val)
{
if (item.Primary)
{
return item.Country;
}
}
return val[0].Country;
}
return "";
}
private static string GetPostCode(List<cAddress> val)
{
if (val != null && val.Count > 0)
{
foreach (var item in val)
{
if (item.Primary)
{
return item.ZipCode;
}
}
return val[0].ZipCode;
}
return "";
}
private static Contacts ConvertToContacts(contacts item)
{
Contacts contact = new Contacts();
contact.Name = item.Name.Firstname;
if (item.Name.AdditionalName != null && item.Name.AdditionalName != "")
contact.Name += " " + item.Name.AdditionalName;
contact.Surname = item.Name.Surname;
contact.Nick = item.Name.Nick;
contact.Sex = item.Genre;
if (item.BirthDate != DateTime.MinValue)
contact.Birth = item.BirthDate;
contact.Phone = CValueToString(item.Phone);
contact.Email = CValueToString(item.Email);
contact.WWW = CValueToString(item.Web);
contact.IM = CValueToString(item.IM);
contact.Company = GetCompany(item.Company);
contact.Position = GetPosition(item.Company);
contact.Street = GetStreet(item.Address);
contact.City = GetCity(item.Address);
contact.Region = GetRegion(item.Address);
contact.Country = GetCountry(item.Address);
contact.PostCode = GetPostCode(item.Address);
contact.PersonCode = "";
contact.Note = item.Note;
contact.Tags = item.Group;
contact.FastTags = 0;
contact.Updated = DateTime.Now;
contact.GoogleID = item.gID;
contact.Active = true;
CheckNullContacts(ref contact);
return contact;
}
private static void FillContacts(ref contacts item, Contacts contact)
{
item.Name.Firstname = "";
item.Name.AdditionalName = "";
string[] split = contact.Name.Split(new string[] { " ", "\t" }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length > 0)
item.Name.Firstname = split[0];
for (int i = 1; i < split.Length; i++)
{
if (item.Name.AdditionalName != "") item.Name.AdditionalName += " ";
item.Name.AdditionalName += split[i];
}
item.Name.Surname = contact.Surname;
item.Name.Nick = contact.Nick;
item.Name.FullName = item.Name.Firstname;
if (item.Name.AdditionalName != "") item.Name.FullName += " " + item.Name.AdditionalName;
if (item.Name.Surname != "") item.Name.FullName += " " + item.Name.Surname;
item.Genre = contact.Sex.Trim();
if (contact.Birth != null)
item.BirthDate = contact.Birth ?? DateTime.MinValue;
item.Phone = StringToCValue(contact.Phone);
item.Email = StringToCValue(contact.Email);
item.Web = StringToCValue(contact.WWW);
item.IM = StringToCValue(contact.IM);
item.Company = new List<cCompany>();
item.Company.Add(new cCompany()
{
Name = contact.Company,
Position = contact.Position
});
/*
contact.Street = GetStreet(item.Address);
contact.City = GetCity(item.Address);
contact.Region = GetRegion(item.Address);
contact.Country = GetCountry(item.Address);
contact.PostCode = GetPostCode(item.Address);*/
//contact.PersonCode = "";
item.Note = contact.Note;
item.Group = contact.Tags;
//contact.FastTags = 0;
//contact.Updated = DateTime.Now;
//contact.GoogleID = item.gID;
//contact.Active = true;
}
/// <summary>
/// Import Contacts from Google
/// </summary>
/// <returns>Contact list</returns>
public static List<Contacts> ImportContactsGoogle()
{
List<Contacts> con = new List<Contacts>();
GoogleContacts GC = new GoogleContacts();
string user = Properties.Settings.Default.LastGUserCred;
if (GC.Login(ref user))
{
GC.ImportGmail();
}
else
return null;
Properties.Settings.Default.LastGUserCred = user;
Properties.Settings.Default.Save();
// ----- Parse data -----
foreach (var item in GC.Contact)
{
//string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_images" + Path.DirectorySeparatorChar + item[23];
Contacts contact = ConvertToContacts(item);
contact.Avatar = Conv.StreamToByteArray(GC.GetAvatar(item.AvatarUri));
con.Add(contact);
}
return con;
}
public static Contacts ImportContactGoogle(string GoogleID)
{
Contacts con = new Contacts();
GoogleContacts GC = new GoogleContacts();
string user = Properties.Settings.Default.LastGUserCred;
if (GC.Login(ref user))
{
contacts item = GC.GetContact(GoogleID);
con = ConvertToContacts(item);
con.Avatar = Conv.StreamToByteArray(GC.GetAvatar(item.AvatarUri));
}
else
return null;
Properties.Settings.Default.LastGUserCred = user;
Properties.Settings.Default.Save();
return con;
}
public static bool ExportContactGoogle(Contacts contacts)
{
GoogleContacts GC = new GoogleContacts();
string user = Properties.Settings.Default.LastGUserCred;
if (GC.Login(ref user))
{
contacts item = GC.GetContact(contacts.GoogleID);
FillContacts(ref item, contacts);
GC.UpdateContact(item);
//GC.UpdateContactPhoto(item.AvatarUri, con.Avatar)
// = Conv.StreamToByteArray(GC.GetAvatar(item.AvatarUri));
}
else
return false;
Properties.Settings.Default.LastGUserCred = user;
Properties.Settings.Default.Save();
return true;
}
public static void CheckNullContacts(ref Contacts contact)
{
if (contact.Name == null) contact.Name = "";
if (contact.Surname == null) contact.Surname = "";
if (contact.Nick == null) contact.Nick = "";
if (contact.Sex == null) contact.Sex = "";
if (contact.Phone == null) contact.Phone = "";
if (contact.Email == null) contact.Email = "";
if (contact.WWW == null) contact.WWW = "";
if (contact.IM == null) contact.IM = "";
if (contact.Company == null) contact.Company = "";
if (contact.Position == null) contact.Position = "";
if (contact.Street == null) contact.Street = "";
if (contact.City == null) contact.City = "";
if (contact.Region == null) contact.Region = "";
if (contact.Country == null) contact.Country = "";
if (contact.PostCode == null) contact.PostCode = "";
if (contact.PersonCode == null) contact.PersonCode = "";
if (contact.Note == null) contact.Note = "";
if (contact.Tags == null) contact.Tags = "";
if (contact.GoogleID == null) contact.GoogleID = "";
}
/// <summary>
/// Import Lended from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Lending list</returns>
public static List<Lending> ImportLendedCSV(string path)
{
List<Lending> con = new List<Lending>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Lending"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 13)
return null;
// ----- Parse data -----
foreach (var item in file.data)
{
Lending itm = new Lending();
//itm.CopyName = item[0];
//itm.CopyInvNum = item[1];
itm.CopyType = item[2];
itm.CopyID = Conv.ToGuid(item[3]);
//itm.PersonName = Conv.ToGuid(item[4]);
itm.PersonID = Conv.ToGuid(item[5]);
itm.From = Conv.ToDateTimeNull(item[6]);
itm.To = Conv.ToDateTimeNull(item[7]);
itm.Status = Conv.ToShortNull(item[8]);
itm.Note = item[9].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.FastTags = Conv.ToShortNull(item[10]);
itm.Updated = Conv.ToDateTimeNull(item[11]);
itm.ID = Conv.ToGuid(item[12]);
con.Add(itm);
}
return con;
}
/// <summary>
/// Import Lending from XML
/// </summary>
/// <param name="path">File path</param>
/// <returns>Recipes list</returns>
public static List<Lending> ImportLendedXML(string path)
{
List<Lending> objList = new List<Lending>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Parse XML to Structure -----
var xml = XDocument.Parse(text);
var xmlType = xml.Elements().Elements("Info").Elements("Type");
// ----- Check File Head -----
if (xmlType.First().Value != "FialotCatalog:Lending")
return null;
var xmlItems = xml.Elements().Elements("Items").Elements("Lend");
// ----- Parse data -----
foreach (var item in xmlItems)
{
Lending obj = new Lending();
var xmlItem = item.Element("Item");
if (xmlItem.Element("ID") != null)
obj.CopyID = Conv.ToGuidNull(xmlItem.Element("ID").Value);
if (xmlItem.Element("Type") != null)
obj.CopyType = xmlItem.Element("Type").Value;
else obj.CopyType = "";
/*if (xmlItem.Element("Name") != null)
obj.Item = xmlItem.Element("Name").Value.Replace("\\n", Environment.NewLine);
else obj.Item = "";*/
/*if (xmlItem.Element("InventoryNumber") != null)
obj.ItemInvNum = xmlItem.Element("InventoryNumber").Value.Replace("\\n", Environment.NewLine);
else obj.ItemInvNum = "";*/
var xmlPerson = item.Element("Person");
if (xmlPerson.Element("PersonID") != null)
obj.PersonID = Conv.ToGuidNull(xmlPerson.Element("PersonID").Value);
else obj.PersonID = null;
/*if (xmlPerson.Element("Person") != null)
obj.Person = xmlPerson.Element("Person").Value;
else obj.Person = "";*/
var xmlLending = item.Element("Lend");
if (xmlLending.Element("From") != null)
obj.From = Conv.ToDateTimeNull(xmlLending.Element("From").Value);
if (xmlLending.Element("To") != null)
obj.To = Conv.ToDateTimeNull(xmlLending.Element("To").Value);
if (xmlLending.Element("Note") != null)
obj.Note = xmlLending.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
if (xmlLending.Element("Status") != null)
obj.Status = Conv.ToShortNull(xmlLending.Element("Status").Value);
else obj.Status = 2;
var xmlSystem = item.Element("System");
if (xmlSystem.Element("ID") != null)
obj.ID = Conv.ToGuid(xmlSystem.Element("ID").Value);
if (xmlSystem.Element("Updated") != null)
obj.Updated = Conv.ToDateTimeNull(xmlSystem.Element("Updated").Value);
if (xmlSystem.Element("FastTags") != null)
obj.FastTags = Conv.ToShortDef(xmlSystem.Element("FastTags").Value, 0);
else obj.FastTags = 0;
objList.Add(obj);
}
return objList;
}
/// <summary>
/// Import Borrowing from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Borrowing list</returns>
public static List<Borrowing> ImportBorowingCSV(string path)
{
List<Borrowing> con = new List<Borrowing>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Borrowing"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 11)
return null;
// ----- Parse data -----
foreach (var item in file.data)
{
Borrowing itm = new Borrowing();
itm.Item = item[0];
itm.ItemInvNum = item[1];
// PersonName = item[2];
itm.PersonID = Conv.ToGuid(item[3]);
itm.From = Conv.ToDateTimeNull(item[4]);
itm.To = Conv.ToDateTimeNull(item[5]);
itm.Status = Conv.ToShortNull(item[6]);
itm.Note = item[7].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.FastTags = Conv.ToShortNull(item[8]);
itm.Updated = Conv.ToDateTimeNull(item[9]);
itm.ID = Conv.ToGuid(item[10]);
con.Add(itm);
}
return con;
}
/// <summary>
/// Import Items from XML
/// </summary>
/// <param name="path">File path</param>
/// <returns>Recipes list</returns>
public static List<Borrowing> ImportBorrowingXML(string path)
{
List<Borrowing> objList = new List<Borrowing>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Parse XML to Structure -----
var xml = XDocument.Parse(text);
var xmlType = xml.Elements().Elements("Info").Elements("Type");
// ----- Check File Head -----
if (xmlType.First().Value != "FialotCatalog:Borrowing")
return null;
var xmlItems = xml.Elements().Elements("Items").Elements("Borrowing");
// ----- Parse data -----
foreach (var item in xmlItems)
{
Borrowing obj = new Borrowing();
var xmlItem = item.Element("Item");
if (xmlItem.Element("Name") != null)
obj.Item = xmlItem.Element("Name").Value.Replace("\\n", Environment.NewLine);
else obj.Item = "";
if (xmlItem.Element("InventoryNumber") != null)
obj.ItemInvNum = xmlItem.Element("InventoryNumber").Value.Replace("\\n", Environment.NewLine);
else obj.ItemInvNum = "";
var xmlPerson = item.Element("Person");
if (xmlPerson.Element("PersonID") != null)
obj.PersonID = Conv.ToGuidNull(xmlPerson.Element("PersonID").Value);
else obj.PersonID = null;
/*if (xmlPerson.Element("Person") != null)
obj.Person = xmlPerson.Element("Person").Value;
else obj.Person = "";*/
var xmlBorrowing = item.Element("Borrowing");
if (xmlBorrowing.Element("From") != null)
obj.From = Conv.ToDateTimeNull(xmlBorrowing.Element("From").Value);
if (xmlBorrowing.Element("To") != null)
obj.To = Conv.ToDateTimeNull(xmlBorrowing.Element("To").Value);
if (xmlBorrowing.Element("Note") != null)
obj.Note = xmlBorrowing.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
if (xmlBorrowing.Element("Status") != null)
obj.Status = Conv.ToShortNull(xmlBorrowing.Element("Status").Value);
else obj.Status = 2;
var xmlSystem = item.Element("System");
if (xmlSystem.Element("ID") != null)
obj.ID = Conv.ToGuid(xmlSystem.Element("ID").Value);
if (xmlSystem.Element("Updated") != null)
obj.Updated = Conv.ToDateTimeNull(xmlSystem.Element("Updated").Value);
if (xmlSystem.Element("FastTags") != null)
obj.FastTags = Conv.ToShortDef(xmlSystem.Element("FastTags").Value, 0);
else obj.FastTags = 0;
objList.Add(obj);
}
return objList;
}
/// <summary>
/// Import Copies from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Item list</returns>
public static List<Copies> ImportCopiesCSV(string path)
{
List<Copies> con = new List<Copies>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Copies"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 13)
return null;
foreach (var item in file.data)
{
Copies itm = new Copies();
//itm.ItemName = item[0];
itm.ItemType = item[1].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.ItemID = Conv.ToGuid(item[2]);
itm.ItemNum = Conv.ToShortNull(item[3]);
itm.InventoryNumber = item[4].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Condition = item[5].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Location = item[6].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Note = item[7].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.AcquisitionDate = Conv.ToDateTimeNull(item[8]);
itm.Price = Conv.ToFloatDef(item[9], 0);
itm.Excluded = Conv.ToBoolNull(item[11]);
itm.Status = Conv.ToShortNull(item[11]);
itm.ID = Conv.ToGuid(item[12]);
con.Add(itm);
}
return con;
}
/// <summary>
/// Import Copies from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Item list</returns>
public static List<Copies> ImportCopiesXML(IEnumerable<XElement> xmlCopies)
{
List<Copies> copies = new List<Copies>();
foreach (var item in xmlCopies)
{
Copies obj = new Copies();
/*if (item.Element("ItemName") != null)
obj.ItemName = item.Element("ItemName").Value;
else obj.ItemName = "";*/
if (item.Element("ItemType") != null)
obj.ItemType = item.Element("ItemType").Value.Replace("\\n", Environment.NewLine);
else obj.ItemType = "";
if (item.Element("ItemID") != null)
obj.ItemID = Conv.ToGuidNull(item.Element("ItemID").Value);
if (item.Element("ItemNum") != null)
obj.ItemNum = Conv.ToShortNull(item.Element("ItemNum").Value);
if (item.Element("InventoryNumber") != null)
obj.InventoryNumber = item.Element("InventoryNumber").Value.Replace("\\n", Environment.NewLine);
else obj.InventoryNumber = "";
if (item.Element("Barcode") != null)
obj.Barcode = Conv.ToLongNull(item.Element("Barcode").Value);
if (item.Element("Condition") != null)
obj.Condition = item.Element("Condition").Value.Replace("\\n", Environment.NewLine);
else obj.Condition = "";
if (item.Element("Location") != null)
obj.Location = item.Element("Location").Value.Replace("\\n", Environment.NewLine);
else obj.Location = "";
if (item.Element("Note") != null)
obj.Note = item.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
if (item.Element("AcquisitionDate") != null)
obj.AcquisitionDate = Conv.ToDateTimeNull(item.Element("AcquisitionDate").Value);
if (item.Element("Price") != null)
obj.Price = Conv.ToDoubleNull(item.Element("Price").Value);
if (item.Element("Excluded") != null)
obj.Excluded = Conv.ToBoolDef(item.Element("Excluded").Value, false);
else obj.Excluded = false;
if (item.Element("Status") != null)
obj.Status = Conv.ToShortNull(item.Element("Status").Value);
else obj.Status = 2;
if (item.Element("ID") != null)
obj.ID = Conv.ToGuid(item.Element("ID").Value);
copies.Add(obj);
}
return copies;
}
/// <summary>
/// Import Items from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Item list</returns>
public static List<Items> ImportItemsCSV(string path, out List<Copies> copies)
{
List<Items> con = new List<Items>();
copies = null;
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Items"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 13)
return null;
// ----- Import Copies -----
string filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
copies = ImportCopiesCSV(filePath + Path.DirectorySeparatorChar + "copies.csv");
foreach (var item in file.data)
{
string imgPath = filePath + Path.DirectorySeparatorChar + item[10];
Items itm = new Items();
itm.Name = item[0].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Category = item[1].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Subcategory = item[2].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Subcategory2 = item[3].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Keywords = item[4].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Manufacturer = item[5].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Note = item[6].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Excluded = Conv.ToBoolNull(item[7]);
itm.Count = Conv.ToShortNull(item[8]);
itm.FastTags = Conv.ToShortDef(item[9], 0);
if (item[10] != "")
itm.Image = Files.LoadBinFile(imgPath);
itm.Updated = Conv.ToDateTimeNull(item[11]);
itm.ID = Conv.ToGuid(item[12]);
con.Add(itm);
}
return con;
}
/// <summary>
/// Import Items from XML
/// </summary>
/// <param name="path">File path</param>
/// <returns>Recipes list</returns>
public static List<Items> ImportItemsXML(string path, out List<Copies> copies)
{
List<Items> objList = new List<Items>();
copies = null;
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Parse XML to Structure -----
var xml = XDocument.Parse(text);
var xmlType = xml.Elements().Elements("Info").Elements("Type");
// ----- Check File Head -----
if (xmlType.First().Value != "FialotCatalog:Items")
return null;
var xmlItems = xml.Elements().Elements("Items").Elements("Item");
var objItem = new XElement("Item");
// ----- Parse data -----
foreach (var item in xmlItems)
{
Items obj = new Items();
var xmlGeneral = item.Element("General");
if (xmlGeneral.Element("Name") != null)
obj.Name = xmlGeneral.Element("Name").Value.Replace("\\n", Environment.NewLine);
else obj.Name = "";
if (xmlGeneral.Element("Manufacturer") != null)
obj.Manufacturer = xmlGeneral.Element("Manufacturer").Value.Replace("\\n", Environment.NewLine);
else obj.Manufacturer = "";
if (xmlGeneral.Element("Note") != null)
obj.Note = xmlGeneral.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
var xmlClass = item.Element("Classification");
if (xmlClass.Element("Category") != null)
obj.Category = xmlClass.Element("Category").Value;
else obj.Category = "";
if (xmlClass.Element("Subcategory") != null)
obj.Subcategory = xmlClass.Element("Subcategory").Value;
else obj.Subcategory = "";
if (xmlClass.Element("Subcategory2") != null)
obj.Subcategory2 = xmlClass.Element("Subcategory2").Value;
else obj.Subcategory2 = "";
if (xmlClass.Element("Keywords") != null)
obj.Keywords = xmlClass.Element("Keywords").Value;
else obj.Keywords = "";
if (xmlClass.Element("FastTags") != null)
obj.FastTags = Conv.ToShortDef(xmlClass.Element("FastTags").Value, 0);
else obj.FastTags = 0;
/*var xmlRating = item.Element("Rating");
if (xmlRating.Element("Rating") != null)
obj.Rating = Conv.ToShortNull(xmlRating.Element("Rating").Value);
if (xmlRating.Element("MyRating") != null)
obj.MyRating = Conv.ToShortNull(xmlRating.Element("MyRating").Value);*/
var xmlSystem = item.Element("System");
if (xmlSystem.Element("ID") != null)
obj.ID = Conv.ToGuid(xmlSystem.Element("ID").Value);
if (xmlSystem.Element("Updated") != null)
obj.Updated = Conv.ToDateTimeNull(xmlSystem.Element("Updated").Value);
if (xmlSystem.Element("Excluded") != null)
obj.Excluded = Conv.ToBoolDef(xmlSystem.Element("Excluded").Value, false);
else obj.Excluded = false;
if (xmlSystem.Element("Image") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Image").Value;
obj.Image = Files.LoadBinFile(imgPath);
}
objList.Add(obj);
}
// ----- Parse copies -----
IEnumerable<XElement> xmlCopies = xml.Elements().Elements("Copies").Elements("Copy");
copies = ImportCopiesXML(xmlCopies);
return objList;
}
/// <summary>
/// Import Books from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Book list</returns>
public static List<Books> ImportBooksCSV(string path, out List<Copies> copies)
{
List<Books> con = new List<Books>();
copies = null;
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Books"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 38)
return null;
// ----- Import Copies -----
string filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
copies = ImportCopiesCSV(filePath + Path.DirectorySeparatorChar + "copies.csv");
foreach (var item in file.data)
{
string imgPath = filePath + Path.DirectorySeparatorChar + item[34];
Books itm = new Books();
itm.Title = item[0].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.AuthorName = item[1].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.AuthorSurname = item[2].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.ISBN = item[3].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Illustrator = item[4].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Translator = item[5].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Language = item[6].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Publisher = item[7].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Edition = item[8].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Year = Conv.ToShortNull(item[9]);
itm.Pages = Conv.ToShortNull(item[10]);
itm.MainCharacter = item[11].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.URL = item[12].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Note = item[13].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Note1 = item[14].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Note2 = item[15].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Content = item[16].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.OrigName = item[17].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.OrigLanguage = item[18].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.OrigYear = Conv.ToShortNull(item[19]);
itm.Genre = item[20].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.SubGenre = item[21].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Series = item[22].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.SeriesNum = Conv.ToShortNull(item[23]);
itm.Keywords = item[24].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Rating = Conv.ToShortNull(item[25]);
itm.MyRating = Conv.ToShortNull(item[26]);
itm.Readed = Conv.ToBoolNull(item[27]);
itm.Type = item[28].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Bookbinding = item[29].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.EbookPath = item[30].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.EbookType = item[31].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Publication = Conv.ToShortNull(item[32]);
itm.Excluded = Conv.ToBoolNull(item[33]);
if (item[34] != "")
itm.Cover = Files.LoadBinFile(imgPath);
itm.Updated = Conv.ToDateTimeNull(item[35]);
itm.FastTags = Conv.ToShortNull(item[36]);
itm.ID = Conv.ToGuid(item[37]);
con.Add(itm);
}
return con;
}
/// <summary>
/// Import Books from XML
/// </summary>
/// <param name="path">File path</param>
/// <returns>Recipes list</returns>
public static List<Books> ImportBooksXML(string path, out List<Copies> copies)
{
List<Books> objList = new List<Books>();
copies = null;
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Parse XML to Structure -----
var xml = XDocument.Parse(text);
var xmlType = xml.Elements().Elements("Info").Elements("Type");
// ----- Check File Head -----
if (xmlType.First().Value != "FialotCatalog:Books")
return null;
var xmlItems = xml.Elements().Elements("Items").Elements("Book");
// ----- Parse data -----
foreach (var item in xmlItems)
{
Books obj = new Books();
var xmlGeneral = item.Element("General");
if (xmlGeneral.Element("Title") != null)
obj.Title = xmlGeneral.Element("Title").Value.Replace("\\n", Environment.NewLine);
else obj.Title = "";
if (xmlGeneral.Element("AuthorName") != null)
obj.AuthorName = xmlGeneral.Element("AuthorName").Value.Replace("\\n", Environment.NewLine);
else obj.AuthorName = "";
if (xmlGeneral.Element("AuthorSurname") != null)
obj.AuthorSurname = xmlGeneral.Element("AuthorSurname").Value.Replace("\\n", Environment.NewLine);
else obj.AuthorSurname = "";
if (xmlGeneral.Element("Note") != null)
obj.Note = xmlGeneral.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
if (xmlGeneral.Element("Note1") != null)
obj.Note1 = xmlGeneral.Element("Note1").Value.Replace("\\n", Environment.NewLine);
else obj.Note1 = "";
if (xmlGeneral.Element("Note2") != null)
obj.Note2 = xmlGeneral.Element("Note2").Value.Replace("\\n", Environment.NewLine);
else obj.Note2 = "";
if (xmlGeneral.Element("ISBN") != null)
obj.ISBN = xmlGeneral.Element("ISBN").Value.Replace("\\n", Environment.NewLine);
else obj.ISBN = "";
if (xmlGeneral.Element("Illustrator") != null)
obj.Illustrator = xmlGeneral.Element("Illustrator").Value.Replace("\\n", Environment.NewLine);
else obj.Illustrator = "";
if (xmlGeneral.Element("Translator") != null)
obj.Translator = xmlGeneral.Element("Translator").Value.Replace("\\n", Environment.NewLine);
else obj.Translator = "";
if (xmlGeneral.Element("Language") != null)
obj.Language = xmlGeneral.Element("Language").Value.Replace("\\n", Environment.NewLine);
else obj.Language = "";
if (xmlGeneral.Element("Publisher") != null)
obj.Publisher = xmlGeneral.Element("Publisher").Value.Replace("\\n", Environment.NewLine);
else obj.Publisher = "";
if (xmlGeneral.Element("Edition") != null)
obj.Edition = xmlGeneral.Element("Edition").Value.Replace("\\n", Environment.NewLine);
else obj.Edition = "";
if (xmlGeneral.Element("Year") != null)
obj.Year = Conv.ToShortNull(xmlGeneral.Element("Year").Value);
if (xmlGeneral.Element("Pages") != null)
obj.Pages = Conv.ToShortNull(xmlGeneral.Element("Pages").Value);
if (xmlGeneral.Element("URL") != null)
obj.URL = xmlGeneral.Element("URL").Value.Replace("\\n", Environment.NewLine);
else obj.URL = "";
if (xmlGeneral.Element("MainCharacter") != null)
obj.MainCharacter = xmlGeneral.Element("MainCharacter").Value.Replace("\\n", Environment.NewLine);
else obj.MainCharacter = "";
if (xmlGeneral.Element("Content") != null)
obj.Content = xmlGeneral.Element("Content").Value.Replace("\\n", Environment.NewLine);
else obj.Content = "";
if (xmlGeneral.Element("OrigName") != null)
obj.OrigName = xmlGeneral.Element("OrigName").Value.Replace("\\n", Environment.NewLine);
else obj.OrigName = "";
if (xmlGeneral.Element("OrigLanguage") != null)
obj.OrigLanguage = xmlGeneral.Element("OrigLanguage").Value.Replace("\\n", Environment.NewLine);
else obj.OrigLanguage = "";
if (xmlGeneral.Element("OrigYear") != null)
obj.OrigYear = Conv.ToShortNull(xmlGeneral.Element("OrigYear").Value);
if (xmlGeneral.Element("Series") != null)
obj.Series = xmlGeneral.Element("Series").Value.Replace("\\n", Environment.NewLine);
else obj.Series = "";
if (xmlGeneral.Element("SeriesNum") != null)
obj.SeriesNum = Conv.ToLongNull(xmlGeneral.Element("SeriesNum").Value);
if (xmlGeneral.Element("Type") != null)
obj.Type = xmlGeneral.Element("Type").Value.Replace("\\n", Environment.NewLine);
else obj.Type = "";
if (xmlGeneral.Element("Bookbinding") != null)
obj.Bookbinding = xmlGeneral.Element("Bookbinding").Value.Replace("\\n", Environment.NewLine);
else obj.Bookbinding = "";
if (xmlGeneral.Element("EbookPath") != null)
obj.EbookPath = xmlGeneral.Element("EbookPath").Value.Replace("\\n", Environment.NewLine);
else obj.EbookPath = "";
if (xmlGeneral.Element("EbookType") != null)
obj.EbookType = xmlGeneral.Element("EbookType").Value.Replace("\\n", Environment.NewLine);
else obj.EbookType = "";
if (xmlGeneral.Element("Publication") != null)
obj.Publication = Conv.ToShortNull(xmlGeneral.Element("Publication").Value);
var xmlClass = item.Element("Classification");
if (xmlClass.Element("Genre") != null)
obj.Genre = xmlClass.Element("Genre").Value;
else obj.Genre = "";
if (xmlClass.Element("SubGenre") != null)
obj.SubGenre = xmlClass.Element("SubGenre").Value;
else obj.SubGenre = "";
if (xmlClass.Element("Keywords") != null)
obj.Keywords = xmlClass.Element("Keywords").Value;
else obj.Keywords = "";
if (xmlClass.Element("FastTags") != null)
obj.FastTags = Conv.ToShortDef(xmlClass.Element("FastTags").Value, 0);
else obj.FastTags = 0;
var xmlRating = item.Element("Rating");
if (xmlRating.Element("Rating") != null)
obj.Rating = Conv.ToShortNull(xmlRating.Element("Rating").Value);
if (xmlRating.Element("MyRating") != null)
obj.MyRating = Conv.ToShortNull(xmlRating.Element("MyRating").Value);
var xmlSystem = item.Element("System");
if (xmlSystem.Element("ID") != null)
obj.ID = Conv.ToGuid(xmlSystem.Element("ID").Value);
if (xmlSystem.Element("Updated") != null)
obj.Updated = Conv.ToDateTimeNull(xmlSystem.Element("Updated").Value);
if (xmlSystem.Element("Excluded") != null)
obj.Excluded = Conv.ToBoolDef(xmlSystem.Element("Excluded").Value, false);
else obj.Excluded = false;
if (xmlSystem.Element("Readed") != null)
obj.Readed = Conv.ToBoolDef(xmlSystem.Element("Readed").Value, false);
else obj.Readed = false;
if (xmlSystem.Element("Cover") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Cover").Value;
obj.Cover = Files.LoadBinFile(imgPath);
}
objList.Add(obj);
}
// ----- Parse copies -----
IEnumerable<XElement> xmlCopies = xml.Elements().Elements("Copies").Elements("Copy");
copies = ImportCopiesXML(xmlCopies);
return objList;
}
/// <summary>
/// Import Boardgames from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Boardgame list</returns>
public static List<Boardgames> ImportBoardgamesCSV(string path, out List<Copies> copies)
{
List<Boardgames> con = new List<Boardgames>();
copies = null;
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Boardgames"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 30)
return null;
// ----- Import Copies -----
string filePath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files";
copies = ImportCopiesCSV(filePath + Path.DirectorySeparatorChar + "copies.csv");
foreach (var item in file.data)
{
//MaterialPath;Rating;MyRating;URL;Excluded;FastTags;Updated;GUID" + Environment.NewLine;
string CoverPath = filePath + Path.DirectorySeparatorChar + item[18];
string Img1Path = filePath + Path.DirectorySeparatorChar + item[19];
string Img2Path = filePath + Path.DirectorySeparatorChar + item[20];
string Img3Path = filePath + Path.DirectorySeparatorChar + item[21];
Boardgames itm = new Boardgames();
itm.Name = item[0].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Category = item[1].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.MinPlayers = Conv.ToShortNull(item[2]);
itm.MaxPlayers = Conv.ToShortNull(item[3]);
itm.MinAge = Conv.ToShortNull(item[4]);
itm.GameTime = Conv.ToShortNull(item[5]);
itm.GameWorld = item[6].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Language = item[7].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Publisher = item[8].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Author = item[9].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Year = Conv.ToShortNull(item[10]);
itm.Description = item[11].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Keywords = item[12].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Note = item[13].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Family = item[14].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Extension = Conv.ToBoolNull(item[15]);
itm.ExtensionNumber = Conv.ToShortNull(item[16]);
itm.Rules = item[17].Replace("//", ";").Replace("\\n", Environment.NewLine);
if (item[18] != "")
itm.Cover = Files.LoadBinFile(CoverPath);
if (item[19] != "")
itm.Img1 = Files.LoadBinFile(Img1Path);
if (item[20] != "")
itm.Img2 = Files.LoadBinFile(Img2Path);
if (item[21] != "")
itm.Img3 = Files.LoadBinFile(Img3Path);
itm.MaterialPath = item[22].Replace("//", ";").Replace("\\n", Environment.NewLine);
itm.Rating = Conv.ToShortNull(item[23]);
itm.MyRating = Conv.ToShortNull(item[24]);
itm.URL = item[25];
itm.Excluded = Conv.ToBoolNull(item[26]);
itm.FastTags = Conv.ToShortNull(item[27]);
itm.Updated = Conv.ToDateTimeNull(item[28]);
itm.ID = Conv.ToGuid(item[29]);
con.Add(itm);
}
return con;
}
/// <summary>
/// Import Board games from XML
/// </summary>
/// <param name="path">File path</param>
/// <returns>Recipes list</returns>
public static List<Boardgames> ImportBoardgamesXML(string path, out List<Copies> copies)
{
List<Boardgames> objList = new List<Boardgames>();
copies = null;
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Parse XML to Structure -----
var xml = XDocument.Parse(text);
var xmlType = xml.Elements().Elements("Info").Elements("Type");
// ----- Check File Head -----
if (xmlType.First().Value != "FialotCatalog:Boardgames")
return null;
var xmlItems = xml.Elements().Elements("Items").Elements("BoardGame");
// ----- Parse data -----
foreach (var item in xmlItems)
{
Boardgames obj = new Boardgames();
var xmlGeneral = item.Element("General");
if (xmlGeneral.Element("Name") != null)
obj.Name = xmlGeneral.Element("Name").Value;
else obj.Name = "";
if (xmlGeneral.Element("Description") != null)
obj.Description = xmlGeneral.Element("Description").Value.Replace("\\n", Environment.NewLine);
else obj.Description = "";
if (xmlGeneral.Element("Note") != null)
obj.Note = xmlGeneral.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
if (xmlGeneral.Element("MinAge") != null)
obj.MinAge = Conv.ToShortNull(xmlGeneral.Element("MinAge").Value);
if (xmlGeneral.Element("MinPlayers") != null)
obj.MinPlayers = Conv.ToShortNull(xmlGeneral.Element("MinPlayers").Value);
if (xmlGeneral.Element("MaxPlayers") != null)
obj.MaxPlayers = Conv.ToShortNull(xmlGeneral.Element("MaxPlayers").Value);
if (xmlGeneral.Element("GameTime") != null)
obj.GameTime = Conv.ToShortNull(xmlGeneral.Element("GameTime").Value);
if (xmlGeneral.Element("GameWorld") != null)
obj.GameWorld = xmlGeneral.Element("GameWorld").Value.Replace("\\n", Environment.NewLine);
else obj.GameWorld = "";
if (xmlGeneral.Element("Language") != null)
obj.Language = xmlGeneral.Element("Language").Value.Replace("\\n", Environment.NewLine);
else obj.Language = "";
if (xmlGeneral.Element("Publisher") != null)
obj.Publisher = xmlGeneral.Element("Publisher").Value.Replace("\\n", Environment.NewLine);
else obj.Publisher = "";
if (xmlGeneral.Element("Author") != null)
obj.Author = xmlGeneral.Element("Author").Value.Replace("\\n", Environment.NewLine);
else obj.Author = "";
if (xmlGeneral.Element("Year") != null)
obj.Year = Conv.ToShortNull(xmlGeneral.Element("Year").Value);
if (xmlGeneral.Element("Extension") != null)
obj.Extension = Conv.ToBoolNull(xmlGeneral.Element("Extension").Value);
if (xmlGeneral.Element("ExtensionNumber") != null)
obj.ExtensionNumber = Conv.ToShortNull(xmlGeneral.Element("ExtensionNumber").Value);
if (xmlGeneral.Element("Rules") != null)
obj.Rules = xmlGeneral.Element("Rules").Value.Replace("\\n", Environment.NewLine);
else obj.Rules = "";
if (xmlGeneral.Element("MaterialPath") != null)
obj.MaterialPath = xmlGeneral.Element("MaterialPath").Value.Replace("\\n", Environment.NewLine);
else obj.MaterialPath = "";
if (xmlGeneral.Element("Family") != null)
obj.Family = xmlGeneral.Element("Family").Value.Replace("\\n", Environment.NewLine);
else obj.Family = "";
if (xmlGeneral.Element("URL") != null)
obj.URL = xmlGeneral.Element("URL").Value;
else obj.URL = "";
var xmlClass = item.Element("Classification");
if (xmlClass.Element("Category") != null)
obj.Category = xmlClass.Element("Category").Value;
else obj.Category = "";
/*if (xmlClass.Element("Subcategory") != null)
obj.Subcategory = xmlClass.Element("Subcategory").Value;
else obj.Subcategory = "";*/
if (xmlClass.Element("Keywords") != null)
obj.Keywords = xmlClass.Element("Keywords").Value;
else obj.Keywords = "";
if (xmlClass.Element("FastTags") != null)
obj.FastTags = Conv.ToShortDef(xmlClass.Element("FastTags").Value, 0);
else obj.FastTags = 0;
var xmlRating = item.Element("Rating");
if (xmlRating.Element("Rating") != null)
obj.Rating = Conv.ToShortNull(xmlRating.Element("Rating").Value);
if (xmlRating.Element("MyRating") != null)
obj.MyRating = Conv.ToShortNull(xmlRating.Element("MyRating").Value);
var xmlSystem = item.Element("System");
if (xmlSystem.Element("ID") != null)
obj.ID = Conv.ToGuid(xmlSystem.Element("ID").Value);
if (xmlSystem.Element("Updated") != null)
obj.Updated = Conv.ToDateTimeNull(xmlSystem.Element("Updated").Value);
if (xmlSystem.Element("Excluded") != null)
obj.Excluded = Conv.ToBoolDef(xmlSystem.Element("Excluded").Value, false);
else obj.Excluded = false;
if (xmlSystem.Element("Cover") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Cover").Value;
obj.Cover = Files.LoadBinFile(imgPath);
}
if (xmlSystem.Element("Img1") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Img1").Value;
obj.Img1 = Files.LoadBinFile(imgPath);
}
if (xmlSystem.Element("Img2") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Img2").Value;
obj.Img2 = Files.LoadBinFile(imgPath);
}
if (xmlSystem.Element("Img3") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Img3").Value;
obj.Img3 = Files.LoadBinFile(imgPath);
}
objList.Add(obj);
}
// ----- Parse copies -----
IEnumerable<XElement> xmlCopies = xml.Elements().Elements("Copies").Elements("Copy");
copies = ImportCopiesXML(xmlCopies);
return objList;
}
/// <summary>
/// Import Games from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Contact list</returns>
public static List<Games> ImportGamesCSV(string path)
{
List<Games> objList = new List<Games>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Games"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 24)
return null;
// ----- Parse data -----
foreach (var item in file.data)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + item[6];
Games obj = new Games();
obj.Name = item[0].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Category = item[1].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Subcategory = item[2].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Keywords = item[3].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Note = item[4].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Description = item[5].Replace("//", ";").Replace("\\n", Environment.NewLine);
if (item[6] != "")
obj.Image = Files.LoadBinFile(imgPath);
obj.PlayerAge = item[7].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.MinPlayers = Conv.ToShortNull(item[8]);
obj.MaxPlayers = Conv.ToShortNull(item[9]);
obj.Duration = Conv.ToShortNull(item[10]);
obj.DurationPreparation = Conv.ToShortNull(item[11]);
obj.Things = item[12].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.URL = item[13].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Rules = item[14].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Preparation = item[15].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Environment = item[16].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Files = item[17].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Rating = Conv.ToShortNull(item[18]);
obj.MyRating = Conv.ToShortNull(item[19]);
obj.FastTags = Conv.ToShortDef(item[20], 0);
obj.Updated = Conv.ToDateTimeNull(item[21]);
obj.Excluded = Conv.ToBoolDef(item[22], true);
obj.ID = Conv.ToGuid(item[23]);
objList.Add(obj);
}
return objList;
}
/// <summary>
/// Import Games from XML
/// </summary>
/// <param name="path">File path</param>
/// <returns>Recipes list</returns>
public static List<Games> ImportGamesXML(string path)
{
List<Games> objList = new List<Games>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Parse XML to Structure -----
var xml = XDocument.Parse(text);
var xmlType = xml.Elements().Elements("Info").Elements("Type");
// ----- Check File Head -----
if (xmlType.First().Value != "FialotCatalog:Games")
return null;
var xmlItems = xml.Elements().Elements("Items").Elements("Game");
// ----- Parse data -----
foreach (var item in xmlItems)
{
Games obj = new Games();
var xmlGeneral = item.Element("General");
if (xmlGeneral.Element("Name") != null)
obj.Name = xmlGeneral.Element("Name").Value;
else obj.Name = "";
if (xmlGeneral.Element("Description") != null)
obj.Description = xmlGeneral.Element("Description").Value.Replace("\\n", Environment.NewLine);
else obj.Description = "";
if (xmlGeneral.Element("Note") != null)
obj.Note = xmlGeneral.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
if (xmlGeneral.Element("PlayerAge") != null)
obj.PlayerAge = xmlGeneral.Element("PlayerAge").Value.Replace("\\n", Environment.NewLine);
else obj.PlayerAge = "";
if (xmlGeneral.Element("MinPlayers") != null)
obj.MinPlayers = Conv.ToShortNull(xmlGeneral.Element("MinPlayers").Value);
if (xmlGeneral.Element("MaxPlayers") != null)
obj.MaxPlayers = Conv.ToShortNull(xmlGeneral.Element("MaxPlayers").Value);
if (xmlGeneral.Element("Duration") != null)
obj.Duration = Conv.ToShortNull(xmlGeneral.Element("Duration").Value);
if (xmlGeneral.Element("DurationPreparation") != null)
obj.DurationPreparation = Conv.ToShortNull(xmlGeneral.Element("DurationPreparation").Value);
if (xmlGeneral.Element("Things") != null)
obj.Things = xmlGeneral.Element("Things").Value.Replace("\\n", Environment.NewLine);
else obj.Things = "";
if (xmlGeneral.Element("Rules") != null)
obj.Rules = xmlGeneral.Element("Rules").Value.Replace("\\n", Environment.NewLine);
else obj.Rules = "";
if (xmlGeneral.Element("Preparation") != null)
obj.Preparation = xmlGeneral.Element("Preparation").Value.Replace("\\n", Environment.NewLine);
else obj.Preparation = "";
if (xmlGeneral.Element("Environment") != null)
obj.Environment = xmlGeneral.Element("Environment").Value.Replace("\\n", Environment.NewLine);
else obj.Environment = "";
if (xmlGeneral.Element("Files") != null)
obj.Files = xmlGeneral.Element("Files").Value.Replace("\\n", Environment.NewLine);
else obj.Files = "";
if (xmlGeneral.Element("URL") != null)
obj.URL = xmlGeneral.Element("URL").Value;
else obj.URL = "";
var xmlClass = item.Element("Classification");
if (xmlClass.Element("Category") != null)
obj.Category = xmlClass.Element("Category").Value;
else obj.Category = "";
if (xmlClass.Element("Subcategory") != null)
obj.Subcategory = xmlClass.Element("Subcategory").Value;
else obj.Subcategory = "";
if (xmlClass.Element("Keywords") != null)
obj.Keywords = xmlClass.Element("Keywords").Value;
else obj.Keywords = "";
if (xmlClass.Element("FastTags") != null)
obj.FastTags = Conv.ToShortDef(xmlClass.Element("FastTags").Value, 0);
else obj.FastTags = 0;
var xmlRating = item.Element("Rating");
if (xmlRating.Element("Rating") != null)
obj.Rating = Conv.ToShortNull(xmlRating.Element("Rating").Value);
if (xmlRating.Element("MyRating") != null)
obj.MyRating = Conv.ToShortNull(xmlRating.Element("MyRating").Value);
var xmlSystem = item.Element("System");
if (xmlSystem.Element("ID") != null)
obj.ID = Conv.ToGuid(xmlSystem.Element("ID").Value);
if (xmlSystem.Element("Updated") != null)
obj.Updated = Conv.ToDateTimeNull(xmlSystem.Element("Updated").Value);
if (xmlSystem.Element("Excluded") != null)
obj.Excluded = Conv.ToBoolDef(xmlSystem.Element("Excluded").Value, false);
else obj.Excluded = false;
if (xmlSystem.Element("Image") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Image").Value;
obj.Image = Files.LoadBinFile(imgPath);
}
objList.Add(obj);
}
return objList;
}
/// <summary>
/// Import Recipes from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Contact list</returns>
public static List<Recipes> ImportRecipesCSV(string path)
{
List<Recipes> objList = new List<Recipes>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Recipes"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 15)
return null;
// ----- Parse data -----
foreach (var item in file.data)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + item[6];
Recipes obj = new Recipes();
obj.Name = item[0].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Category = item[1].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Subcategory = item[2].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Keywords = item[3].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Note = item[4].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Description = item[5].Replace("//", ";").Replace("\\n", Environment.NewLine);
if (item[6] != "")
obj.Image = Files.LoadBinFile(imgPath);
obj.Procedure = item[7].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Resources = item[8].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Rating = Conv.ToShortNull(item[9]);
obj.MyRating = Conv.ToShortNull(item[10]);
obj.FastTags = Conv.ToShortDef(item[11], 0);
obj.Updated = Conv.ToDateTimeNull(item[12]);
obj.Excluded = Conv.ToBoolDef(item[13], true);
obj.ID = Conv.ToGuid(item[14]);
objList.Add(obj);
}
return objList;
}
/// <summary>
/// Import Recipes from XML
/// </summary>
/// <param name="path">File path</param>
/// <returns>Recipes list</returns>
public static List<Recipes> ImportRecipesXML(string path)
{
List<Recipes> objList = new List<Recipes>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Parse XML to Structure -----
var xml = XDocument.Parse(text);
var xmlType = xml.Elements().Elements("Info").Elements("Type");
// ----- Check File Head -----
if (xmlType.First().Value != "FialotCatalog:Recipes")
return null;
var xmlItems = xml.Elements().Elements("Items").Elements("Recipe");
// ----- Parse data -----
foreach (var item in xmlItems)
{
Recipes obj = new Recipes();
var xmlGeneral = item.Element("General");
if (xmlGeneral.Element("Name") != null)
obj.Name = xmlGeneral.Element("Name").Value;
else obj.Name = "";
if (xmlGeneral.Element("Description") != null)
obj.Description = xmlGeneral.Element("Description").Value.Replace("\\n", Environment.NewLine);
else obj.Description = "";
if (xmlGeneral.Element("Note") != null)
obj.Note = xmlGeneral.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
if (xmlGeneral.Element("Procedure") != null)
obj.Procedure = xmlGeneral.Element("Procedure").Value.Replace("\\n", Environment.NewLine);
else obj.Procedure = "";
if (xmlGeneral.Element("Resources") != null)
obj.Resources = xmlGeneral.Element("Resources").Value.Replace("\\n", Environment.NewLine);
else obj.Resources = "";
if (xmlGeneral.Element("URL") != null)
obj.URL = xmlGeneral.Element("URL").Value;
else obj.URL = "";
var xmlClass = item.Element("Classification");
if (xmlClass.Element("Category") != null)
obj.Category = xmlClass.Element("Category").Value;
else obj.Category = "";
if (xmlClass.Element("Subcategory") != null)
obj.Subcategory = xmlClass.Element("Subcategory").Value;
else obj.Subcategory = "";
if (xmlClass.Element("Keywords") != null)
obj.Keywords = xmlClass.Element("Keywords").Value;
else obj.Keywords = "";
if (xmlClass.Element("FastTags") != null)
obj.FastTags = Conv.ToShortDef(xmlClass.Element("FastTags").Value, 0);
else obj.FastTags = 0;
var xmlRating = item.Element("Rating");
if (xmlRating.Element("Rating") != null)
obj.Rating = Conv.ToShortNull(xmlRating.Element("Rating").Value);
if (xmlRating.Element("MyRating") != null)
obj.MyRating = Conv.ToShortNull(xmlRating.Element("MyRating").Value);
var xmlSystem = item.Element("System");
if (xmlSystem.Element("ID") != null)
obj.ID = Conv.ToGuid(xmlSystem.Element("ID").Value);
if (xmlSystem.Element("Updated") != null)
obj.Updated = Conv.ToDateTimeNull(xmlSystem.Element("Updated").Value);
if (xmlSystem.Element("Excluded") != null)
obj.Excluded = Conv.ToBoolDef(xmlSystem.Element("Excluded").Value, false);
else obj.Excluded = false;
if (xmlSystem.Element("Image") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Image").Value;
obj.Image = Files.LoadBinFile(imgPath);
}
objList.Add(obj);
}
return objList;
}
/// <summary>
/// Import Objects from CSV
/// </summary>
/// <param name="path">File path</param>
/// <returns>Contact list</returns>
public static List<Objects> ImportObjectsCSV(string path)
{
List<Objects> objList = new List<Objects>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Check File Head -----
if (!Str.GetFirstLine(ref text, true).Contains("FialotCatalog:Objects"))
return null;
// ----- Parse CSV File -----
CSVfile file = Files.ParseCSV(text);
// ----- Check table size -----
if (file.head.Length != 25)
return null;
// ----- Parse data -----
foreach (var item in file.data)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + item[7];
Objects obj = new Objects();
obj.Name = item[0].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Category = item[1].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Subcategory = item[2].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Keywords = item[3].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Note = item[4].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Description = item[5].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.URL = item[6].Replace("//", ";");
if (item[7] != "")
obj.Image = Files.LoadBinFile(imgPath);
obj.Rating = Conv.ToShortNull(item[8]);
obj.MyRating = Conv.ToShortNull(item[9]);
obj.FastTags = Conv.ToShortDef(item[10], 0);
obj.Updated = Conv.ToDateTimeNull(item[11]);
obj.Active = Conv.ToBoolDef(item[12], true);
obj.Version = item[13].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Files = item[14].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Folder = item[15].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Type = item[16].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.ObjectNum = item[17].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Language = item[18].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Parent = Conv.ToGuidNull(item[19]);
obj.Customer = item[20].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.Development = item[21].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.IsParent = Conv.ToBoolDef(item[22], true);
obj.UsedObjects = item[23].Replace("//", ";").Replace("\\n", Environment.NewLine);
obj.ID = Conv.ToGuid(item[24]);
objList.Add(obj);
}
return objList;
}
/// <summary>
/// Import Objects from XML
/// </summary>
/// <param name="path">File path</param>
/// <returns>Contact list</returns>
public static List<Objects> ImportObjectsXML(string path)
{
List<Objects> objList = new List<Objects>();
// ----- Load file -----
string text = Files.LoadFile(path);
// ----- Parse XML to Structure -----
var xml = XDocument.Parse(text);
var xmlType = xml.Elements().Elements("Info").Elements("Type");
// ----- Check File Head -----
if (xmlType.First().Value != "FialotCatalog:Objects")
return null;
var xmlItems = xml.Elements().Elements("Items").Elements("Object");
// ----- Parse data -----
foreach (var item in xmlItems)
{
Objects obj = new Objects();
var xmlGeneral = item.Element("General");
if (xmlGeneral.Element("Name") != null)
obj.Name = xmlGeneral.Element("Name").Value;
else obj.Name = "";
if (xmlGeneral.Element("ObjectNumber") != null)
obj.ObjectNum = xmlGeneral.Element("ObjectNumber").Value;
else obj.ObjectNum = "";
if (xmlGeneral.Element("Description") != null)
obj.Description = xmlGeneral.Element("Description").Value.Replace("\\n", Environment.NewLine);
else obj.Description = "";
if (xmlGeneral.Element("Note") != null)
obj.Note = xmlGeneral.Element("Note").Value.Replace("\\n", Environment.NewLine);
else obj.Note = "";
if (xmlGeneral.Element("Version") != null)
obj.Version = xmlGeneral.Element("Version").Value;
else obj.Version = "";
if (xmlGeneral.Element("Files") != null)
obj.Files = xmlGeneral.Element("Files").Value;
else obj.Files = "";
if (xmlGeneral.Element("Folder") != null)
obj.Folder = xmlGeneral.Element("Folder").Value;
else obj.Folder = "";
if (xmlGeneral.Element("URL") != null)
obj.URL = xmlGeneral.Element("URL").Value;
else obj.URL = "";
if (xmlGeneral.Element("Customer") != null)
obj.Customer = xmlGeneral.Element("Customer").Value;
else obj.Customer = "";
if (xmlGeneral.Element("Development") != null)
obj.Development = xmlGeneral.Element("Development").Value;
else obj.Development = "";
if (xmlGeneral.Element("Language") != null)
obj.Language = xmlGeneral.Element("Language").Value;
else obj.Language = "";
var xmlClass = item.Element("Classification");
if (xmlClass.Element("Type") != null)
obj.Type = xmlClass.Element("Type").Value;
else obj.Type = "";
if (xmlClass.Element("Category") != null)
obj.Category = xmlClass.Element("Category").Value;
else obj.Category = "";
if (xmlClass.Element("Subcategory") != null)
obj.Subcategory = xmlClass.Element("Subcategory").Value;
else obj.Subcategory = "";
if (xmlClass.Element("Keywords") != null)
obj.Keywords = xmlClass.Element("Keywords").Value;
else obj.Keywords = "";
if (xmlClass.Element("FastTags") != null)
obj.FastTags = Conv.ToShortDef(xmlClass.Element("FastTags").Value, 0);
else obj.FastTags = 0;
var xmlRating = item.Element("Rating");
if (xmlRating.Element("Rating") != null)
obj.Rating = Conv.ToShortNull(xmlRating.Element("Rating").Value);
if (xmlRating.Element("MyRating") != null)
obj.MyRating = Conv.ToShortNull(xmlRating.Element("MyRating").Value);
var xmlSystem = item.Element("System");
if (xmlSystem.Element("ID") != null)
obj.ID = Conv.ToGuid(xmlSystem.Element("ID").Value);
if (xmlSystem.Element("Updated") != null)
obj.Updated = Conv.ToDateTimeNull(xmlSystem.Element("Updated").Value);
if (xmlSystem.Element("Active") != null)
obj.Active = Conv.ToBoolDef(xmlSystem.Element("Active").Value, true);
else obj.Active = true;
if (xmlSystem.Element("Parent") != null)
obj.Parent = Conv.ToGuidNull(xmlSystem.Element("Parent").Value);
if (xmlSystem.Element("IsParent") != null)
obj.IsParent = Conv.ToBoolDef(xmlSystem.Element("IsParent").Value, true);
else obj.IsParent = true;
if (xmlSystem.Element("UsedObjects") != null)
obj.UsedObjects = xmlSystem.Element("UsedObjects").Value;
else obj.UsedObjects = "";
if (xmlSystem.Element("Image") != null)
{
string imgPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(path) + "_files" + Path.DirectorySeparatorChar + xmlSystem.Element("Image").Value;
obj.Image = Files.LoadBinFile(imgPath);
}
objList.Add(obj);
}
return objList;
}
#endregion
}
}
| 41.512582 | 406 | 0.502222 | [
"MIT"
] | fialot/Catalog | global.cs | 169,913 | C# |
using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls;
using SharpVectors.Renderers.Wpf;
using SharpVectors.Converters;
namespace WpfTestSvgSample
{
/// <summary>
/// Interaction logic for DrawingPage.xaml
/// </summary>
public partial class DrawingPage : Page, IDrawingPage
{
#region Private Fields
private bool _saveXaml;
private string _drawingDir;
private DirectoryInfo _directoryInfo;
private FileSvgReader _fileReader;
private WpfDrawingSettings _wpfSettings;
private DirectoryInfo _workingDir;
/// <summary>
/// Specifies the current state of the mouse handling logic.
/// </summary>
private MouseHandlingMode mouseHandlingMode;
/// <summary>
/// The point that was clicked relative to the ZoomAndPanControl.
/// </summary>
private Point origZoomAndPanControlMouseDownPoint;
/// <summary>
/// The point that was clicked relative to the content that is contained within the ZoomAndPanControl.
/// </summary>
private Point origContentMouseDownPoint;
/// <summary>
/// Records which mouse button clicked during mouse dragging.
/// </summary>
private MouseButton mouseButtonDown;
#endregion
#region Constructors and Destructor
public DrawingPage()
{
InitializeComponent();
_saveXaml = true;
_wpfSettings = new WpfDrawingSettings();
_wpfSettings.CultureInfo = _wpfSettings.NeutralCultureInfo;
_fileReader = new FileSvgReader(_wpfSettings);
_fileReader.SaveXaml = _saveXaml;
_fileReader.SaveZaml = false;
mouseHandlingMode = MouseHandlingMode.None;
string workDir = Path.Combine(Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location), "XamlDrawings");
_workingDir = new DirectoryInfo(workDir);
this.Loaded += new RoutedEventHandler(OnPageLoaded);
}
#endregion
#region Public Properties
public string XamlDrawingDir
{
get
{
return _drawingDir;
}
set
{
_drawingDir = value;
if (!string.IsNullOrWhiteSpace(_drawingDir))
{
_directoryInfo = new DirectoryInfo(_drawingDir);
if (_fileReader != null)
{
_fileReader.SaveXaml = Directory.Exists(_drawingDir);
}
}
}
}
public bool SaveXaml
{
get
{
return _saveXaml;
}
set
{
_saveXaml = value;
}
}
#endregion
#region Public Methods
public bool LoadDocument(string svgFilePath)
{
if (string.IsNullOrWhiteSpace(svgFilePath) || !File.Exists(svgFilePath))
{
return false;
}
DirectoryInfo workingDir = _workingDir;
if (_directoryInfo != null)
{
workingDir = _directoryInfo;
}
//double currentZoom = zoomSlider.Value;
svgViewer.UnloadDiagrams();
//zoomSlider.Value = 1.0;
string fileExt = Path.GetExtension(svgFilePath);
if (string.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase) ||
string.Equals(fileExt, ".svg", StringComparison.OrdinalIgnoreCase))
{
if (_fileReader != null)
{
_fileReader.SaveXaml = _saveXaml;
_fileReader.SaveZaml = false;
DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir);
if (drawing != null)
{
svgViewer.RenderDiagrams(drawing);
//zoomSlider.Value = currentZoom;
Rect bounds = svgViewer.Bounds;
//Rect rect = new Rect(0, 0,
// mainFrame.RenderSize.Width, mainFrame.RenderSize.Height);
//Rect rect = new Rect(0, 0,
// bounds.Width, bounds.Height);
if (bounds.IsEmpty)
{
bounds = new Rect(0, 0,
canvasScroller.ActualWidth, canvasScroller.ActualHeight);
}
zoomPanControl.AnimatedZoomTo(bounds);
return true;
}
}
}
else if (string.Equals(fileExt, ".xaml", StringComparison.OrdinalIgnoreCase) ||
string.Equals(fileExt, ".zaml", StringComparison.OrdinalIgnoreCase))
{
svgViewer.LoadDiagrams(svgFilePath);
//zoomSlider.Value = currentZoom;
svgViewer.InvalidateMeasure();
return true;
}
return false;
}
public void UnloadDocument()
{
if (svgViewer != null)
{
svgViewer.UnloadDiagrams();
}
}
public bool SaveDocument(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
{
return false;
}
if (_fileReader == null || _fileReader.Drawing == null)
{
return false;
}
return _fileReader.Save(fileName, true, false);
}
public void PageSelected(bool isSelected)
{
}
#endregion
#region Protected Methods
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
}
#endregion
#region Private Event Handlers
private void OnPageLoaded(object sender, RoutedEventArgs e)
{
zoomSlider.Value = 100;
if (zoomPanControl != null)
{
zoomPanControl.IsMouseWheelScrollingEnabled = true;
}
}
private void OnZoomSliderValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (zoomPanControl != null)
{
zoomPanControl.AnimatedZoomTo(zoomSlider.Value / 100.0);
}
}
private void OnZoomInClick(object sender, RoutedEventArgs e)
{
this.ZoomIn();
}
private void OnZoomOutClick(object sender, RoutedEventArgs e)
{
this.ZoomOut();
}
private void OnResetZoom(object sender, RoutedEventArgs e)
{
if (zoomPanControl == null)
{
return;
}
zoomPanControl.ContentScale = 1.0;
}
/// <summary>
/// The 'ZoomIn' command (bound to the plus key) was executed.
/// </summary>
private void OnZoomFitClick(object sender, RoutedEventArgs e)
{
if (svgViewer == null || zoomPanControl == null)
{
return;
}
Rect bounds = svgViewer.Bounds;
//Rect rect = new Rect(0, 0,
// mainFrame.RenderSize.Width, mainFrame.RenderSize.Height);
//Rect rect = new Rect(0, 0,
// bounds.Width, bounds.Height);
if (bounds.IsEmpty)
{
bounds = new Rect(0, 0,
canvasScroller.ActualWidth, canvasScroller.ActualHeight);
}
zoomPanControl.AnimatedZoomTo(bounds);
}
private void OnPanClick(object sender, RoutedEventArgs e)
{
//if (drawScrollView == null)
//{
// return;
//}
//drawScrollView.ZoomableCanvas.IsPanning =
// (tbbPanning.IsChecked != null && tbbPanning.IsChecked.Value);
}
#region Private Zoom Panel Handlers
/// <summary>
/// Event raised on mouse down in the ZoomAndPanControl.
/// </summary>
private void OnZoomPanMouseDown(object sender, MouseButtonEventArgs e)
{
svgViewer.Focus();
Keyboard.Focus(svgViewer);
mouseButtonDown = e.ChangedButton;
origZoomAndPanControlMouseDownPoint = e.GetPosition(zoomPanControl);
origContentMouseDownPoint = e.GetPosition(svgViewer);
if ((Keyboard.Modifiers & ModifierKeys.Shift) != 0 &&
(e.ChangedButton == MouseButton.Left ||
e.ChangedButton == MouseButton.Right))
{
// Shift + left- or right-down initiates zooming mode.
mouseHandlingMode = MouseHandlingMode.Zooming;
}
else if (mouseButtonDown == MouseButton.Left)
{
// Just a plain old left-down initiates panning mode.
mouseHandlingMode = MouseHandlingMode.Panning;
}
if (mouseHandlingMode != MouseHandlingMode.None)
{
// Capture the mouse so that we eventually receive the mouse up event.
zoomPanControl.CaptureMouse();
e.Handled = true;
}
}
/// <summary>
/// Event raised on mouse up in the ZoomAndPanControl.
/// </summary>
private void OnZoomPanMouseUp(object sender, MouseButtonEventArgs e)
{
if (mouseHandlingMode != MouseHandlingMode.None)
{
if (mouseHandlingMode == MouseHandlingMode.Zooming)
{
if (mouseButtonDown == MouseButton.Left)
{
// Shift + left-click zooms in on the content.
ZoomIn();
}
else if (mouseButtonDown == MouseButton.Right)
{
// Shift + left-click zooms out from the content.
ZoomOut();
}
}
zoomPanControl.ReleaseMouseCapture();
mouseHandlingMode = MouseHandlingMode.None;
e.Handled = true;
}
}
/// <summary>
/// Event raised on mouse move in the ZoomAndPanControl.
/// </summary>
private void OnZoomPanMouseMove(object sender, MouseEventArgs e)
{
if (mouseHandlingMode == MouseHandlingMode.Panning)
{
//
// The user is left-dragging the mouse.
// Pan the viewport by the appropriate amount.
//
Point curContentMousePoint = e.GetPosition(svgViewer);
Vector dragOffset = curContentMousePoint - origContentMouseDownPoint;
zoomPanControl.ContentOffsetX -= dragOffset.X;
zoomPanControl.ContentOffsetY -= dragOffset.Y;
e.Handled = true;
}
}
/// <summary>
/// Event raised by rotating the mouse wheel
/// </summary>
private void OnZoomPanMouseWheel(object sender, MouseWheelEventArgs e)
{
e.Handled = true;
if (e.Delta > 0)
{
ZoomIn();
}
else if (e.Delta < 0)
{
ZoomOut();
}
}
/// <summary>
/// The 'ZoomIn' command (bound to the plus key) was executed.
/// </summary>
private void OnZoomFit(object sender, RoutedEventArgs e)
{
if (svgViewer == null || zoomPanControl == null)
{
return;
}
Rect bounds = svgViewer.Bounds;
//Rect rect = new Rect(0, 0,
// mainFrame.RenderSize.Width, mainFrame.RenderSize.Height);
//Rect rect = new Rect(0, 0,
// bounds.Width, bounds.Height);
if (bounds.IsEmpty)
{
bounds = new Rect(0, 0,
canvasScroller.ActualWidth, canvasScroller.ActualHeight);
}
zoomPanControl.AnimatedZoomTo(bounds);
}
/// <summary>
/// The 'ZoomIn' command (bound to the plus key) was executed.
/// </summary>
private void OnZoomIn(object sender, RoutedEventArgs e)
{
ZoomIn();
}
/// <summary>
/// The 'ZoomOut' command (bound to the minus key) was executed.
/// </summary>
private void OnZoomOut(object sender, RoutedEventArgs e)
{
ZoomOut();
}
/// <summary>
/// Zoom the viewport out by a small increment.
/// </summary>
private void ZoomOut()
{
if (zoomPanControl == null)
{
return;
}
zoomPanControl.ContentScale -= 0.1;
}
/// <summary>
/// Zoom the viewport in by a small increment.
/// </summary>
private void ZoomIn()
{
if (zoomPanControl == null)
{
return;
}
zoomPanControl.ContentScale += 0.1;
}
#endregion
#endregion
}
}
| 30.135881 | 111 | 0.487389 | [
"BSD-3-Clause"
] | johncao158/SharpVectors | Samples/WpfTestSvgSample/DrawingPage.xaml.cs | 14,196 | C# |
using System;
using System.Collections.Generic;
namespace Codestellation.Statsd.Builder
{
internal static class UriParseExtensions
{
public const string Background = "background";
public const string IgnoreExceptions = "ignore_exceptions";
public const string Prefix = "prefix";
public const string DnsUpdatePeriod = "dns_update_period";
public static Dictionary<string, string> GetQueryValues(this Uri self)
{
if (self == null)
{
throw new ArgumentNullException(nameof(self));
}
var queryValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(self.Query))
{
string query = self.Query.Replace("?", string.Empty);
string[] kvp = query.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string pair in kvp)
{
var tokens = pair.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
var key = tokens[0];
//we may not have value for background and ignore_exception options.
var value = tokens.Length > 1 ? tokens[1] : string.Empty;
queryValues.Add(key, value);
}
}
return queryValues;
}
public static bool ParseOrDefault(this IDictionary<string, string> self, string key, bool onDefault = false)
{
string candidate;
bool result;
if (self.TryGetValue(key, out candidate) && !string.IsNullOrWhiteSpace(candidate) && bool.TryParse(candidate, out result))
{
return result;
}
return onDefault;
}
public static string ParseOrDefault(this IDictionary<string, string> self, string key, string onDefault = null)
{
string candidate;
if (self.TryGetValue(key, out candidate) && !string.IsNullOrWhiteSpace(candidate))
{
return candidate;
}
return onDefault;
}
public static int ParseOrDefault(this IDictionary<string, string> self, string key, int onDefault = 0)
{
string candidate;
if (self.TryGetValue(key, out candidate) && !string.IsNullOrWhiteSpace(candidate) && int.TryParse(candidate, out int result))
{
return result;
}
return onDefault;
}
}
} | 37.142857 | 137 | 0.565385 | [
"MIT"
] | Codestellation/statsd | src/Statsd/Builder/UriParseExtensions.cs | 2,602 | C# |
using DGP.Genshin.DataModel.Promotion;
namespace DGP.Genshin.Service.Abstraction
{
public interface IMaterialListService
{
MaterialList Load();
void Save(MaterialList? materialList);
}
}
| 19.727273 | 46 | 0.705069 | [
"MIT"
] | CzHUV/Snap.Genshin | DGP.Genshin/Service/Abstraction/IMaterialListService.cs | 219 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace SharpCircuit {
public class SwitchSPDT : SwitchSPST {
public Circuit.Lead leadC { get { return lead1; } }
public SwitchSPDT() : base() {
posCount = 3;
}
public override int getLeadCount() {
return posCount;
}
public override void calculateCurrent() {
if(position == 2)
current = 0;
}
public override void stamp(Circuit sim) {
if(position == 2) return; // in center?
sim.stampVoltageSource(lead_node[0], lead_node[position + 1], voltSource, 0);
}
public override int getVoltageSourceCount() {
return (position == 2) ? 0 : 1;
}
/*public override void getInfo(String[] arr) {
arr[0] = "switch (SPDT)";
arr[1] = "I = " + CircuitElement.getCurrentDText(getCurrent());
}*/
public override bool leadsAreConnected(int leadX, int leadY) {
if(position == 2) return false;
return comparePair(leadX, leadY, 0, 1 + position);
}
}
}
| 22.272727 | 80 | 0.663265 | [
"MIT"
] | 741645596/Lab | Assets/Scripts/CircuitCom/Engine/elements/SwitchSPDT.cs | 982 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace DogsIRL.Models
{
public class DeviceInstallation
{
[JsonProperty("installationId")]
public string InstallationId { get; set; }
[JsonProperty("platform")]
public string Platform { get; set; }
[JsonProperty("pushChannel")]
public string PushChannel { get; set; }
[JsonProperty("tags")]
public List<string> Tags { get; set; } = new List<string>();
}
}
| 23.043478 | 68 | 0.633962 | [
"MIT"
] | 401FinalProjectOrg/DogsIRL | DogsIRL/DogsIRL/Models/DeviceInstallation.cs | 532 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.