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 Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace HealthChecks.CosmosDb
{
public class CosmosDbHealthCheck
: IHealthCheck
{
private static readonly ConcurrentDictionary<string, CosmosClient> _connections = new ConcurrentDictionary<string, CosmosClient>();
private readonly string _connectionString;
public CosmosDbHealthCheck(string connectionString)
{
_connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
CosmosClient cosmosDbClient;
if (!_connections.TryGetValue(_connectionString, out cosmosDbClient))
{
cosmosDbClient = new CosmosClient(_connectionString);
if (!_connections.TryAdd(_connectionString, cosmosDbClient))
{
cosmosDbClient.Dispose();
cosmosDbClient = _connections[_connectionString];
}
}
await cosmosDbClient.GetAccountSettingsAsync();
return HealthCheckResult.Healthy();
}
catch (Exception ex)
{
return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
}
}
}
}
| 37.577778
| 140
| 0.61029
|
[
"Apache-2.0"
] |
FurstLevy/AspNetCore.Diagnostics.HealthChecks
|
src/HealthChecks.CosmosDb/CosmosDbHealthCheck.cs
| 1,693
|
C#
|
#nullable enable
namespace Microsoft.Maui.Handlers
{
public partial class GraphicsViewHandler
{
public static IPropertyMapper<IGraphicsView, GraphicsViewHandler> GraphicsViewMapper = new PropertyMapper<IGraphicsView, GraphicsViewHandler>(ViewHandler.ViewMapper)
{
[nameof(IGraphicsView.Drawable)] = MapDrawable,
[nameof(IView.FlowDirection)] = MapFlowDirection
};
public static CommandMapper<IGraphicsView, GraphicsViewHandler> GraphicsViewCommandMapper = new(ViewCommandMapper)
{
[nameof(IGraphicsView.Invalidate)] = MapInvalidate
};
public GraphicsViewHandler() : base(GraphicsViewMapper, GraphicsViewCommandMapper)
{
}
public GraphicsViewHandler(IPropertyMapper? mapper = null, CommandMapper? commandMapper = null)
: base(mapper ?? GraphicsViewMapper, commandMapper ?? GraphicsViewCommandMapper)
{
}
}
}
| 30.392857
| 167
| 0.784959
|
[
"MIT"
] |
APopatanasov/maui
|
src/Core/src/Handlers/GraphicsView/GraphicsViewHandler.cs
| 853
|
C#
|
using System;
namespace Escrevendo_Nome
{
class Program
{
static void Main(string[] args)
{
for(int c = 11; c>0; c++){
Console.WriteLine("R");
c--;
}
}
}
}
| 15.4375
| 39
| 0.408907
|
[
"MIT"
] |
Christian-M-Silva/Exercicios-Aprendiz-De-programacao
|
C#/Escrevendo-Nome/Program.cs
| 249
|
C#
|
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Packages.V1Alpha1
{
public class PackageSpecControllerDeploymentSpecTemplateSpecContainersReadinessProbeHttpGetPortArgs : Pulumi.ResourceArgs
{
public PackageSpecControllerDeploymentSpecTemplateSpecContainersReadinessProbeHttpGetPortArgs()
{
}
}
}
| 30.55
| 125
| 0.774141
|
[
"Apache-2.0"
] |
pulumi/pulumi-kubernetes-crds
|
operators/crossplane/dotnet/Kubernetes/Crds/Operators/Crossplane/Packages/V1Alpha1/Inputs/PackageSpecControllerDeploymentSpecTemplateSpecContainersReadinessProbeHttpGetPortArgs.cs
| 611
|
C#
|
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2018. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace Leap.Unity.GraphicalRenderer {
[CustomPropertyDrawer(typeof(LeapDynamicRenderer))]
public class LeapDynamicRendererDrawer : LeapMesherBaseDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
base.OnGUI(position, property, label);
//Nothing to do yet!
}
}
}
| 41.185185
| 95
| 0.517086
|
[
"MIT"
] |
crookookoo/handUI
|
Assets/Vendor/LeapMotion/Modules/GraphicRenderer/Scripts/RenderingMethods/Editor/LeapDynamicRendererDrawer.cs
| 1,112
|
C#
|
using DbUp.Builder;
namespace EventSourcing.Extensions.DatabaseMigrations.Persistence.PostgreSql.DbUp.Extensions
{
/// <summary>
/// Extensions for <see cref="UpgradeEngineBuilder"/>
/// </summary>
public static class UpgradeEngineBuilderExtensions
{
/// <summary>
/// Adds database migration DbUp scripts provider for PostgreSQL implementation of EventSourcing.Persistence.Abstraction package to the builder.
/// </summary>
/// <param name="builder">
/// The <see cref="UpgradeEngineBuilder"/>.
/// </param>
/// <returns>
/// The <see cref="UpgradeEngineBuilder"/>.
/// </returns>
public static UpgradeEngineBuilder WithPostgreSqlScriptsForEventSourcing(
this UpgradeEngineBuilder builder) =>
builder.WithScripts(new PostgreSqlDatabaseMigrationDbUpScriptsProvider());
}
}
| 39.217391
| 152
| 0.666297
|
[
"MIT"
] |
TheName/EventSourcing
|
EventSourcing.Persistence/PostgreSql/Extensions.DatabaseMigrations.Persistence.PostgreSql.DbUp/Extensions/UpgradeEngineBuilderExtensions.cs
| 904
|
C#
|
using System;
using System.Collections.Generic;
using Microsoft.ML.Data;
namespace Microsoft.ML.Samples.Dynamic
{
/// <summary>
/// Sample class showing how to use Skip.
/// </summary>
public static class SkipRows
{
public static void Example()
{
// Create a new context for ML.NET operations. It can be used for exception tracking and logging,
// as a catalog of available operations and as the source of randomness.
var mlContext = new MLContext();
// Get a small dataset as an IEnumerable.
var enumerableOfData = SamplesUtils.DatasetUtils.GetSampleTemperatureData(10);
var data = mlContext.Data.LoadFromEnumerable(enumerableOfData);
// Before we apply a filter, examine all the records in the dataset.
Console.WriteLine($"Date\tTemperature");
foreach (var row in enumerableOfData)
{
Console.WriteLine($"{row.Date.ToString("d")}\t{row.Temperature}");
}
Console.WriteLine();
// Expected output:
// Date Temperature
// 1/2/2012 36
// 1/3/2012 36
// 1/4/2012 34
// 1/5/2012 35
// 1/6/2012 35
// 1/7/2012 39
// 1/8/2012 40
// 1/9/2012 35
// 1/10/2012 30
// 1/11/2012 29
// Skip the first 5 rows in the dataset
var filteredData = mlContext.Data.SkipRows(data, 5);
// Look at the filtered data and observe that the first 5 rows have been dropped
var enumerable = mlContext.Data.CreateEnumerable<SamplesUtils.DatasetUtils.SampleTemperatureData>(filteredData, reuseRowObject: true);
Console.WriteLine($"Date\tTemperature");
foreach (var row in enumerable)
{
Console.WriteLine($"{row.Date.ToString("d")}\t{row.Temperature}");
}
// Expected output:
// Date Temperature
// 1/7/2012 39
// 1/8/2012 40
// 1/9/2012 35
// 1/10/2012 30
// 1/11/2012 29
}
}
}
| 37.467742
| 146
| 0.521309
|
[
"MIT"
] |
IndigoShock/machinelearning
|
docs/samples/Microsoft.ML.Samples/Dynamic/DataOperations/SkipRows.cs
| 2,325
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ow.Utils;
namespace Ow.Net.netty.commands
{
class MessageWildcardReplacementModule
{
public const short ID = 1059;
public ClientUITooltipTextFormatModule var_1507;
public String wildcard;
public String replacement;
public MessageWildcardReplacementModule(String param1, String param2, ClientUITooltipTextFormatModule param3)
{
this.wildcard = param1;
this.replacement = param2;
this.var_1507 = param3;
}
public byte[] write()
{
var param1 = new ByteArray(ID);
param1.writeUTF(this.replacement);
param1.write(var_1507.write());
param1.writeShort(28496);
param1.writeUTF(this.wildcard);
return param1.Message.ToArray();
}
}
}
| 26.416667
| 117
| 0.631966
|
[
"MIT"
] |
yusufsahinhamza/darkorbit-emulators
|
DarkOrbit 10.0/Net/netty/commands/MessageWildcardReplacementModule.cs
| 953
|
C#
|
public class Rebel : IBuyer
{
public Rebel(string name, int age, string group)
{
this.Group = group;
this.Name = name;
this.ID = "n/a";
this.BirthDate = "n/a";
this.Age = age;
this.Food = 0;
}
public string Group { get; private set; }
public string Name { get; private set; }
public string ID { get; private set; }
public string BirthDate { get; private set; }
public int Age { get; private set; }
public int Food { get; private set; }
public void BuyFood()
{
this.Food += 5;
}
}
| 24.416667
| 52
| 0.554608
|
[
"MIT"
] |
Koceto/SoftUni
|
C# Fundamentals/C# OOP Advanced/Interfaces and Abstraction/Food Shortage/Entities/Rebel.cs
| 588
|
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization.Formatters;
using Exceptionless.Json.Serialization;
using System.Runtime.Serialization;
namespace Exceptionless.Json
{
/// <summary>
/// Specifies the settings on a <see cref="JsonSerializer"/> object.
/// </summary>
public class JsonSerializerSettings
{
internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error;
internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore;
internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include;
internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include;
internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto;
internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None;
internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default;
internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None;
internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default;
internal const FormatterAssemblyStyle DefaultTypeNameAssemblyFormat = FormatterAssemblyStyle.Simple;
internal static readonly StreamingContext DefaultContext;
internal const Formatting DefaultFormatting = Formatting.None;
internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat;
internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime;
internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double;
internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String;
internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default;
internal const FormatterAssemblyStyle DefaultFormatterAssemblyStyle = FormatterAssemblyStyle.Simple;
internal static readonly CultureInfo DefaultCulture;
internal const bool DefaultCheckAdditionalContent = false;
internal const string DefaultDateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
internal Formatting? _formatting;
internal DateFormatHandling? _dateFormatHandling;
internal DateTimeZoneHandling? _dateTimeZoneHandling;
internal DateParseHandling? _dateParseHandling;
internal FloatFormatHandling? _floatFormatHandling;
internal FloatParseHandling? _floatParseHandling;
internal StringEscapeHandling? _stringEscapeHandling;
internal CultureInfo _culture;
internal bool? _checkAdditionalContent;
internal int? _maxDepth;
internal bool _maxDepthSet;
internal string _dateFormatString;
internal bool _dateFormatStringSet;
internal FormatterAssemblyStyle? _typeNameAssemblyFormat;
internal DefaultValueHandling? _defaultValueHandling;
internal PreserveReferencesHandling? _preserveReferencesHandling;
internal NullValueHandling? _nullValueHandling;
internal ObjectCreationHandling? _objectCreationHandling;
internal MissingMemberHandling? _missingMemberHandling;
internal ReferenceLoopHandling? _referenceLoopHandling;
internal StreamingContext? _context;
internal ConstructorHandling? _constructorHandling;
internal TypeNameHandling? _typeNameHandling;
internal MetadataPropertyHandling? _metadataPropertyHandling;
/// <summary>
/// Gets or sets how reference loops (e.g. a class referencing itself) is handled.
/// </summary>
/// <value>Reference loop handling.</value>
public ReferenceLoopHandling ReferenceLoopHandling
{
get { return _referenceLoopHandling ?? DefaultReferenceLoopHandling; }
set { _referenceLoopHandling = value; }
}
/// <summary>
/// Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// </summary>
/// <value>Missing member handling.</value>
public MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling ?? DefaultMissingMemberHandling; }
set { _missingMemberHandling = value; }
}
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling ObjectCreationHandling
{
get { return _objectCreationHandling ?? DefaultObjectCreationHandling; }
set { _objectCreationHandling = value; }
}
/// <summary>
/// Gets or sets how null values are handled during serialization and deserialization.
/// </summary>
/// <value>Null value handling.</value>
public NullValueHandling NullValueHandling
{
get { return _nullValueHandling ?? DefaultNullValueHandling; }
set { _nullValueHandling = value; }
}
/// <summary>
/// Gets or sets how null default are handled during serialization and deserialization.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling DefaultValueHandling
{
get { return _defaultValueHandling ?? DefaultDefaultValueHandling; }
set { _defaultValueHandling = value; }
}
/// <summary>
/// Gets or sets a collection <see cref="JsonConverter"/> that will be used during serialization.
/// </summary>
/// <value>The converters.</value>
public IList<JsonConverter> Converters { get; set; }
/// <summary>
/// Gets or sets how object references are preserved by the serializer.
/// </summary>
/// <value>The preserve references handling.</value>
public PreserveReferencesHandling PreserveReferencesHandling
{
get { return _preserveReferencesHandling ?? DefaultPreserveReferencesHandling; }
set { _preserveReferencesHandling = value; }
}
/// <summary>
/// Gets or sets how type name writing and reading is handled by the serializer.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling TypeNameHandling
{
get { return _typeNameHandling ?? DefaultTypeNameHandling; }
set { _typeNameHandling = value; }
}
/// <summary>
/// Gets or sets how metadata properties are used during deserialization.
/// </summary>
/// <value>The metadata properties handling.</value>
public MetadataPropertyHandling MetadataPropertyHandling
{
get { return _metadataPropertyHandling ?? DefaultMetadataPropertyHandling; }
set { _metadataPropertyHandling = value; }
}
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// </summary>
/// <value>The type name assembly format.</value>
public FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _typeNameAssemblyFormat ?? DefaultFormatterAssemblyStyle; }
set { _typeNameAssemblyFormat = value; }
}
/// <summary>
/// Gets or sets how constructors are used during deserialization.
/// </summary>
/// <value>The constructor handling.</value>
public ConstructorHandling ConstructorHandling
{
get { return _constructorHandling ?? DefaultConstructorHandling; }
set { _constructorHandling = value; }
}
/// <summary>
/// Gets or sets the contract resolver used by the serializer when
/// serializing .NET objects to JSON and vice versa.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver { get; set; }
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
/// <value>The reference resolver.</value>
public IReferenceResolver ReferenceResolver { get; set; }
/// <summary>
/// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages.
/// </summary>
/// <value>The trace writer.</value>
public ITraceWriter TraceWriter { get; set; }
/// <summary>
/// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
/// <value>The binder.</value>
public SerializationBinder Binder { get; set; }
/// <summary>
/// Gets or sets the error handler called during serialization and deserialization.
/// </summary>
/// <value>The error handler called during serialization and deserialization.</value>
public EventHandler<ErrorEventArgs> Error { get; set; }
/// <summary>
/// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
/// </summary>
/// <value>The context.</value>
public StreamingContext Context
{
get { return _context ?? DefaultContext; }
set { _context = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString ?? DefaultDateFormatString; }
set
{
_dateFormatString = value;
_dateFormatStringSet = true;
}
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get { return _maxDepth; }
set
{
if (value <= 0)
throw new ArgumentException("Value must be positive.", "value");
_maxDepth = value;
_maxDepthSet = true;
}
}
/// <summary>
/// Indicates how JSON text output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting ?? DefaultFormatting; }
set { _formatting = value; }
}
/// <summary>
/// Get or set how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling ?? DefaultDateFormatHandling; }
set { _dateFormatHandling = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling during serialization and deserialization.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling ?? DefaultDateTimeZoneHandling; }
set { _dateTimeZoneHandling = value; }
}
/// <summary>
/// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get { return _dateParseHandling ?? DefaultDateParseHandling; }
set { _dateParseHandling = value; }
}
/// <summary>
/// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>,
/// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>,
/// are written as JSON.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get { return _floatFormatHandling ?? DefaultFloatFormatHandling; }
set { _floatFormatHandling = value; }
}
/// <summary>
/// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get { return _floatParseHandling ?? DefaultFloatParseHandling; }
set { _floatParseHandling = value; }
}
/// <summary>
/// Get or set how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get { return _stringEscapeHandling ?? DefaultStringEscapeHandling; }
set { _stringEscapeHandling = value; }
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? DefaultCulture; }
set { _culture = value; }
}
/// <summary>
/// Gets a value indicating whether there will be a check for additional content after deserializing an object.
/// </summary>
/// <value>
/// <c>true</c> if there will be a check for additional content after deserializing an object; otherwise, <c>false</c>.
/// </value>
public bool CheckAdditionalContent
{
get { return _checkAdditionalContent ?? DefaultCheckAdditionalContent; }
set { _checkAdditionalContent = value; }
}
static JsonSerializerSettings()
{
DefaultContext = new StreamingContext();
DefaultCulture = CultureInfo.InvariantCulture;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializerSettings"/> class.
/// </summary>
public JsonSerializerSettings()
{
Converters = new List<JsonConverter>();
}
}
}
| 43.065574
| 146
| 0.651313
|
[
"Apache-2.0"
] |
mahizsas/Exceptionless
|
Source/Clients/Shared/Newtonsoft.Json/JsonSerializerSettings.cs
| 15,762
|
C#
|
// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Threading.Tasks;
using SmugMug.v2.Authentication;
namespace SmugMug.v2.Types
{
public partial class ImageDownloadEntity : SmugMugEntity
{
public ImageDownloadEntity()
{
//Empty constructor to enable deserialization
}
public ImageDownloadEntity(OAuthToken oauthToken)
: base(oauthToken)
{
_oauthToken = oauthToken;
}
}
}
| 25.041667
| 101
| 0.667221
|
[
"MIT"
] |
AlexGhiondea/SmugMug.NET
|
src/SmugMug.NET/Types/Images/ImageDownload/ImageDownload.methods.cs
| 601
|
C#
|
using CommandLine;
using System;
namespace Lime.Cli
{
public class Options : IOptions
{
[Option(HelpText = "The identity for connection")]
public string Identity { get; set; }
[Option]
public string Password { get; set; }
[Option]
public string AccessKey { get; set; }
[Option(HelpText = "The session instance name")]
public string Instance { get; set; }
[Option(HelpText = "The address of the server to connect to", Required = true)]
public Uri Uri { get; set; }
[Option("presence.status")]
public string PresenceStatus { get; set; }
[Option("presence.routingrule")]
public string PresenceRoutingRule { get; set; }
[Option("receipt.events")]
public string ReceiptEvents { get; set; }
[Option(HelpText = "The timeout for channel operations, in seconds", Default = 30)]
public int Timeout { get; set; }
[Option(HelpText = "The action to be executed in the non-interactive mode")]
public string Action { get; set; }
}
}
| 27.55
| 91
| 0.604356
|
[
"Apache-2.0"
] |
fsnader/lime-csharp
|
src/Lime.Cli/Options.cs
| 1,104
|
C#
|
using System.Web;
using System.Web.Optimization;
namespace HelloAngular
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| 38.84375
| 113
| 0.574417
|
[
"Apache-2.0"
] |
Kiandr/Angular
|
Practice/VisualStudioMVC5/MVC/Windows/HelloAngular/App_Start/BundleConfig.cs
| 1,245
|
C#
|
/*
Copyright (c) 2012 <a href="http://www.gutgames.com">James Craig</a>
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.*/
#region Usings
using Utilities.IO.ExtensionMethods;
using Xunit;
#endregion
namespace UnitTests.IO.ExtensionMethods
{
public class String
{
[Fact]
public void RemoveIllegalDirectoryNameCharacters()
{
Assert.Equal(@"C:\TestDirectory_Stuff__Hope_ThisWorks", @"C:\TestDirectory""Stuff<>Hope|ThisWorks".RemoveIllegalDirectoryNameCharacters());
}
[Fact]
public void RemoveIllegalFileNameCharacters()
{
Assert.Equal(@"TestDirectory_Stuff__Hope_ThisWorks.txt", @"TestDirectory""Stuff<>Hope|ThisWorks.txt".RemoveIllegalFileNameCharacters());
}
}
}
| 38.891304
| 152
| 0.734489
|
[
"MIT"
] |
JoySky/Craig-s-Utility-Library
|
UnitTests/IO/ExtensionMethods/String.cs
| 1,791
|
C#
|
using System.Collections.Generic;
using DemoApiProject.Model;
using Newtonsoft.Json;
namespace DemoApiProject.Data.Seed
{
public static class ClientSeed
{
public static List<Client> Clients =>
JsonConvert.DeserializeObject<List<Client>>(@"[{
""Name"": ""Frederick"",
""LastName"": ""Archer"",
""Email"": ""farcher0@wsj.com""
}, {
""Name"": ""Meara"",
""LastName"": ""Horley"",
""Email"": ""mhorley1@ebay.co.uk""
}, {
""Name"": ""Addia"",
""LastName"": ""Gambles"",
""Email"": ""agambles2@wikispaces.com""
}, {
""Name"": ""Hart"",
""LastName"": ""MacDermot"",
""Email"": ""hmacdermot3@pen.io""
}, {
""Name"": ""Ki"",
""LastName"": ""Lavallin"",
""Email"": ""klavallin4@guardian.co.uk""
}, {
""Name"": ""Jacklin"",
""LastName"": ""Danford"",
""Email"": ""jdanford5@amazon.co.uk""
}, {
""Name"": ""Rod"",
""LastName"": ""Cuxon"",
""Email"": ""rcuxon6@google.pl""
}, {
""Name"": ""Care"",
""LastName"": ""Rogge"",
""Email"": ""crogge7@utexas.edu""
}, {
""Name"": ""Shaina"",
""LastName"": ""Weitzel"",
""Email"": ""sweitzel8@a8.net""
}, {
""Name"": ""Noel"",
""LastName"": ""Cowerd"",
""Email"": ""ncowerd9@chicagotribune.com""
}]");
}
}
| 39.490566
| 66
| 0.315815
|
[
"MIT"
] |
ArmandJ77/VueJsDemoAppApi
|
DemoApiProject/Data/Seed/ClientSeed.cs
| 2,095
|
C#
|
using System.Collections.Generic;
using UnityEngine;
public class PotionsManager : MonoBehaviour
{
[SerializeField]
private List<GameObject> potionsGOList;
[SerializeField]
private GameObject badPotionGO;
private static List<GameObject> potionsList;
public static GameObject badPotion;
private void Awake()
{
potionsList = new List<GameObject>();
badPotion = badPotionGO;
foreach (GameObject potion in potionsGOList)
{
potionsList.Add(potion.gameObject);
}
}
public static GameObject GetPotion(string potionName)
{
foreach (GameObject potion in potionsList)
{
if (string.Equals(potion.GetComponent<Potion>().GetName(), potionName))
return potion;
}
return null;
}
public static GameObject GetBadPotion()
{
return badPotion;
}
}
| 23.410256
| 83
| 0.638554
|
[
"MIT"
] |
JoanOrtiga/BrackeysJam2021.2
|
BrackeysJam2021.2/Assets/Scripts/Delivery Logic/PotionsManager.cs
| 913
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Analytics.Synapse.Artifacts.Models;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.Analytics.Synapse.Artifacts
{
/// <summary> The SparkJobDefinition service client. </summary>
public partial class SparkJobDefinitionClient
{
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
internal SparkJobDefinitionRestClient RestClient { get; }
/// <summary> Initializes a new instance of SparkJobDefinitionClient for mocking. </summary>
protected SparkJobDefinitionClient()
{
}
/// <summary> Initializes a new instance of SparkJobDefinitionClient. </summary>
/// <param name="endpoint"> The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net. </param>
/// <param name="credential"> A credential used to authenticate to an Azure Service. </param>
/// <param name="options"> The options for configuring the client. </param>
public SparkJobDefinitionClient(Uri endpoint, TokenCredential credential, ArtifactsClientOptions options = null)
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (credential == null)
{
throw new ArgumentNullException(nameof(credential));
}
options ??= new ArtifactsClientOptions();
_clientDiagnostics = new ClientDiagnostics(options);
string[] scopes = { "https://dev.azuresynapse.net/.default" };
_pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, scopes));
RestClient = new SparkJobDefinitionRestClient(_clientDiagnostics, _pipeline, endpoint);
}
/// <summary> Initializes a new instance of SparkJobDefinitionClient. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="endpoint"> The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net. </param>
internal SparkJobDefinitionClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri endpoint)
{
RestClient = new SparkJobDefinitionRestClient(clientDiagnostics, pipeline, endpoint);
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
/// <summary> Gets a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="ifNoneMatch"> ETag of the Spark Job Definition entity. Should only be specified for get. If the ETag matches the existing entity tag, or if * was provided, then no content will be returned. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual async Task<Response<SparkJobDefinitionResource>> GetSparkJobDefinitionAsync(string sparkJobDefinitionName, string ifNoneMatch = null, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.GetSparkJobDefinition");
scope.Start();
try
{
return await RestClient.GetSparkJobDefinitionAsync(sparkJobDefinitionName, ifNoneMatch, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="ifNoneMatch"> ETag of the Spark Job Definition entity. Should only be specified for get. If the ETag matches the existing entity tag, or if * was provided, then no content will be returned. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Response<SparkJobDefinitionResource> GetSparkJobDefinition(string sparkJobDefinitionName, string ifNoneMatch = null, CancellationToken cancellationToken = default)
{
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.GetSparkJobDefinition");
scope.Start();
try
{
return RestClient.GetSparkJobDefinition(sparkJobDefinitionName, ifNoneMatch, cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Lists spark job definitions. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual AsyncPageable<SparkJobDefinitionResource> GetSparkJobDefinitionsByWorkspaceAsync(CancellationToken cancellationToken = default)
{
async Task<Page<SparkJobDefinitionResource>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.GetSparkJobDefinitionsByWorkspace");
scope.Start();
try
{
var response = await RestClient.GetSparkJobDefinitionsByWorkspaceAsync(cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SparkJobDefinitionResource>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.GetSparkJobDefinitionsByWorkspace");
scope.Start();
try
{
var response = await RestClient.GetSparkJobDefinitionsByWorkspaceNextPageAsync(nextLink, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Lists spark job definitions. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public virtual Pageable<SparkJobDefinitionResource> GetSparkJobDefinitionsByWorkspace(CancellationToken cancellationToken = default)
{
Page<SparkJobDefinitionResource> FirstPageFunc(int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.GetSparkJobDefinitionsByWorkspace");
scope.Start();
try
{
var response = RestClient.GetSparkJobDefinitionsByWorkspace(cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SparkJobDefinitionResource> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.GetSparkJobDefinitionsByWorkspace");
scope.Start();
try
{
var response = RestClient.GetSparkJobDefinitionsByWorkspaceNextPage(nextLink, cancellationToken);
return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Creates or updates a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="sparkJobDefinition"> Spark Job Definition resource definition. </param>
/// <param name="ifMatch"> ETag of the Spark Job Definition entity. Should only be specified for update, for which it should match existing entity or can be * for unconditional update. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> or <paramref name="sparkJobDefinition"/> is null. </exception>
public virtual async Task<SparkJobDefinitionCreateOrUpdateSparkJobDefinitionOperation> StartCreateOrUpdateSparkJobDefinitionAsync(string sparkJobDefinitionName, SparkJobDefinitionResource sparkJobDefinition, string ifMatch = null, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
if (sparkJobDefinition == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinition));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartCreateOrUpdateSparkJobDefinition");
scope.Start();
try
{
var originalResponse = await RestClient.CreateOrUpdateSparkJobDefinitionAsync(sparkJobDefinitionName, sparkJobDefinition, ifMatch, cancellationToken).ConfigureAwait(false);
return new SparkJobDefinitionCreateOrUpdateSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateSparkJobDefinitionRequest(sparkJobDefinitionName, sparkJobDefinition, ifMatch).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates or updates a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="sparkJobDefinition"> Spark Job Definition resource definition. </param>
/// <param name="ifMatch"> ETag of the Spark Job Definition entity. Should only be specified for update, for which it should match existing entity or can be * for unconditional update. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> or <paramref name="sparkJobDefinition"/> is null. </exception>
public virtual SparkJobDefinitionCreateOrUpdateSparkJobDefinitionOperation StartCreateOrUpdateSparkJobDefinition(string sparkJobDefinitionName, SparkJobDefinitionResource sparkJobDefinition, string ifMatch = null, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
if (sparkJobDefinition == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinition));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartCreateOrUpdateSparkJobDefinition");
scope.Start();
try
{
var originalResponse = RestClient.CreateOrUpdateSparkJobDefinition(sparkJobDefinitionName, sparkJobDefinition, ifMatch, cancellationToken);
return new SparkJobDefinitionCreateOrUpdateSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateCreateOrUpdateSparkJobDefinitionRequest(sparkJobDefinitionName, sparkJobDefinition, ifMatch).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public virtual async Task<SparkJobDefinitionDeleteSparkJobDefinitionOperation> StartDeleteSparkJobDefinitionAsync(string sparkJobDefinitionName, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartDeleteSparkJobDefinition");
scope.Start();
try
{
var originalResponse = await RestClient.DeleteSparkJobDefinitionAsync(sparkJobDefinitionName, cancellationToken).ConfigureAwait(false);
return new SparkJobDefinitionDeleteSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteSparkJobDefinitionRequest(sparkJobDefinitionName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Deletes a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public virtual SparkJobDefinitionDeleteSparkJobDefinitionOperation StartDeleteSparkJobDefinition(string sparkJobDefinitionName, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartDeleteSparkJobDefinition");
scope.Start();
try
{
var originalResponse = RestClient.DeleteSparkJobDefinition(sparkJobDefinitionName, cancellationToken);
return new SparkJobDefinitionDeleteSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateDeleteSparkJobDefinitionRequest(sparkJobDefinitionName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Executes the spark job definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public virtual async Task<SparkJobDefinitionExecuteSparkJobDefinitionOperation> StartExecuteSparkJobDefinitionAsync(string sparkJobDefinitionName, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartExecuteSparkJobDefinition");
scope.Start();
try
{
var originalResponse = await RestClient.ExecuteSparkJobDefinitionAsync(sparkJobDefinitionName, cancellationToken).ConfigureAwait(false);
return new SparkJobDefinitionExecuteSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateExecuteSparkJobDefinitionRequest(sparkJobDefinitionName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Executes the spark job definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public virtual SparkJobDefinitionExecuteSparkJobDefinitionOperation StartExecuteSparkJobDefinition(string sparkJobDefinitionName, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartExecuteSparkJobDefinition");
scope.Start();
try
{
var originalResponse = RestClient.ExecuteSparkJobDefinition(sparkJobDefinitionName, cancellationToken);
return new SparkJobDefinitionExecuteSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateExecuteSparkJobDefinitionRequest(sparkJobDefinitionName).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Renames a sparkJobDefinition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="request"> proposed new name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> or <paramref name="request"/> is null. </exception>
public virtual async Task<SparkJobDefinitionRenameSparkJobDefinitionOperation> StartRenameSparkJobDefinitionAsync(string sparkJobDefinitionName, ArtifactRenameRequest request, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartRenameSparkJobDefinition");
scope.Start();
try
{
var originalResponse = await RestClient.RenameSparkJobDefinitionAsync(sparkJobDefinitionName, request, cancellationToken).ConfigureAwait(false);
return new SparkJobDefinitionRenameSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateRenameSparkJobDefinitionRequest(sparkJobDefinitionName, request).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Renames a sparkJobDefinition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="request"> proposed new name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> or <paramref name="request"/> is null. </exception>
public virtual SparkJobDefinitionRenameSparkJobDefinitionOperation StartRenameSparkJobDefinition(string sparkJobDefinitionName, ArtifactRenameRequest request, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartRenameSparkJobDefinition");
scope.Start();
try
{
var originalResponse = RestClient.RenameSparkJobDefinition(sparkJobDefinitionName, request, cancellationToken);
return new SparkJobDefinitionRenameSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateRenameSparkJobDefinitionRequest(sparkJobDefinitionName, request).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Debug the spark job definition. </summary>
/// <param name="sparkJobDefinitionAzureResource"> Spark Job Definition resource definition. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionAzureResource"/> is null. </exception>
public virtual async Task<SparkJobDefinitionDebugSparkJobDefinitionOperation> StartDebugSparkJobDefinitionAsync(SparkJobDefinitionResource sparkJobDefinitionAzureResource, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionAzureResource == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionAzureResource));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartDebugSparkJobDefinition");
scope.Start();
try
{
var originalResponse = await RestClient.DebugSparkJobDefinitionAsync(sparkJobDefinitionAzureResource, cancellationToken).ConfigureAwait(false);
return new SparkJobDefinitionDebugSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateDebugSparkJobDefinitionRequest(sparkJobDefinitionAzureResource).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Debug the spark job definition. </summary>
/// <param name="sparkJobDefinitionAzureResource"> Spark Job Definition resource definition. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionAzureResource"/> is null. </exception>
public virtual SparkJobDefinitionDebugSparkJobDefinitionOperation StartDebugSparkJobDefinition(SparkJobDefinitionResource sparkJobDefinitionAzureResource, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionAzureResource == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionAzureResource));
}
using var scope = _clientDiagnostics.CreateScope("SparkJobDefinitionClient.StartDebugSparkJobDefinition");
scope.Start();
try
{
var originalResponse = RestClient.DebugSparkJobDefinition(sparkJobDefinitionAzureResource, cancellationToken);
return new SparkJobDefinitionDebugSparkJobDefinitionOperation(_clientDiagnostics, _pipeline, RestClient.CreateDebugSparkJobDefinitionRequest(sparkJobDefinitionAzureResource).Request, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 54.888393
| 285
| 0.657666
|
[
"MIT"
] |
93mishra/azure-sdk-for-net
|
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/SparkJobDefinitionClient.cs
| 24,590
|
C#
|
/***********************************************************************************************\
* (C) KAL ATM Software GmbH, 2021
* KAL ATM Software GmbH licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
*
* This file was created automatically as part of the XFS4IoT CardReader interface.
* EMVClessQueryApplications_g.cs uses automatically generated parts.
\***********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using XFS4IoT.Commands;
namespace XFS4IoT.CardReader.Commands
{
//Original name = EMVClessQueryApplications
[DataContract]
[Command(Name = "CardReader.EMVClessQueryApplications")]
public sealed class EMVClessQueryApplicationsCommand : Command<EMVClessQueryApplicationsCommand.PayloadData>
{
public EMVClessQueryApplicationsCommand(int RequestId, EMVClessQueryApplicationsCommand.PayloadData Payload)
: base(RequestId, Payload)
{ }
[DataContract]
public sealed class PayloadData : MessagePayload
{
public PayloadData(int Timeout)
: base(Timeout)
{
}
}
}
}
| 34.421053
| 116
| 0.603976
|
[
"MIT"
] |
KAL-ATM-Software/KAL_XFS4IoT_SP-Dev
|
Framework/Core/CardReader/Commands/EMVClessQueryApplications_g.cs
| 1,308
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoidsManagerSystem : MonoBehaviour {
public bool showfishdebug;
private BoidsManagerSystem bms;
public GameObject Fish;
public float frameToSkip = 1;//7
private int frameSkipped;
public float tankSize;//200
public int fishCount;//100
[HideInInspector]
public FishAgentComponent[] fishAgentsCmp;
public Vector3 goalPosition;
public int fishOnGoal;
[HideInInspector]
public float tankOffset;
private void Start() {
bms = this;
fishAgentsCmp = new FishAgentComponent[fishCount];
GenerateComponent();
RandomizeGoalPosition();
}
void GenerateComponent() {
for(int i = 0; i < fishCount; i++) {
Vector3 RandomPosition = transform.position + new Vector3(Random.Range(-tankSize, tankSize), Random.Range(-tankSize, tankSize), Random.Range(-tankSize, tankSize));
fishAgentsCmp[i] = new FishAgentComponent(i, tankSize, tankOffset, transform.position);
fishAgentsCmp[i].abstrat_transform.Set(Instantiate(Fish).transform);
fishAgentsCmp[i].abstrat_transform.Position = RandomPosition;
fishAgentsCmp[i].abstrat_transform.Parent = transform;
}
for(int i = 0; i < fishCount; i++)
fishAgentsCmp[i].SetFishList(fishAgentsCmp);
}
void Update() {
CheckFishesOnGoal();
if(fishOnGoal >= fishCount / 7) {
RandomizeGoalPosition();
fishOnGoal = 0;
}
UpdateFishes();
}
void LateUpdate() {
int rndevnt = Random.Range(1, 350);
for(int i = 0; i < fishCount; i++) {
if(rndevnt == 2) {
fishAgentsCmp[i].BrakeCohesion();
fishAgentsCmp[i].GoalPosUpdated(GetRandomPosition());
}
fishAgentsCmp[i].SyncVars();
}
}
void UpdateFishes() {
if(frameSkipped >= frameToSkip) {
for(int i = 0; i < fishCount; i++) {
fishAgentsCmp[i].ApplayRule();
}
frameSkipped = 0;
}
else
frameSkipped++;
MoveTransforms();
}
void MoveTransforms() {
float deltatime = Time.deltaTime;
for(int i = 0; i < fishCount; i++) {
fishAgentsCmp[i].abstrat_transform.Rotation = Quaternion.Slerp(fishAgentsCmp[i].abstrat_transform.Rotation, Quaternion.LookRotation(fishAgentsCmp[i].Velocity), deltatime * fishAgentsCmp[i].avgRotationSpeed);
fishAgentsCmp[i].abstrat_transform.Position = fishAgentsCmp[i].lastPosition + (fishAgentsCmp[i].Velocity * deltatime * fishAgentsCmp[i].avgSpeed);
}
}
void RandomizeGoalPosition() {
goalPosition = GetRandomPosition();
for(int i = 0; i < fishCount; i++) {
fishAgentsCmp[i].GoalPosUpdated(goalPosition);
}
}
Vector3 GetRandomPosition() {
return new Vector3(Random.Range(-tankSize + tankOffset, tankSize - tankOffset), Random.Range(-tankSize + tankOffset, tankSize - tankOffset), Random.Range(-tankSize + tankOffset, tankSize - tankOffset)) + transform.position;
}
public void CheckFishesOnGoal() {
for(int i = 0; i < fishCount; i++) {
if(fishAgentsCmp[i].GoalReached) {
if(fishAgentsCmp[i].useCohesion) {
GoalReached();
fishAgentsCmp[i].GoalReached = false;
}
else {
fishAgentsCmp[i].GoalPosUpdated(GetRandomPosition());
fishAgentsCmp[i].GoalReached = false;
}
}
}
}
public void GoalReached() {
fishOnGoal++;
}
void OnDrawGizmos() {
if(!showfishdebug) return;
Gizmos.color = new Color(1, 1, 1, 0.2f);
Gizmos.DrawCube(transform.position, Vector3.one * (tankSize * 2));
Gizmos.color = new Color(0, 0, 0, 1);
Gizmos.DrawSphere(goalPosition, 0.3f);
if(Application.isPlaying) {
for(int i = 0; i < fishCount; i++) {
showCohesionDebug(fishAgentsCmp[i]);
showAlignmentDebug(fishAgentsCmp[i]);
showSeparationDebug(fishAgentsCmp[i]);
}
}
}
public void showAlignmentDebug(FishAgentComponent f) {
Debug.DrawRay(f.lastPosition, f.Alignment.normalized * 10, Color.blue);
}
public void showCohesionDebug(FishAgentComponent f) {
Debug.DrawRay(f.lastPosition, f.Cohesion.normalized * 10, Color.green);
}
public void showSeparationDebug(FishAgentComponent f) {
Debug.DrawRay(f.lastPosition, f.Separation.normalized * 10, Color.red);
}
}
| 29.565517
| 227
| 0.670166
|
[
"MIT"
] |
fabriziospadaro/Unity-Boids-Flocking
|
BoidsManagerSystem.cs
| 4,289
|
C#
|
using Sandbox.Game.EntityComponents;
using Sandbox.ModAPI.Ingame;
using Sandbox.ModAPI.Interfaces;
using SpaceEngineers.Game.ModAPI.Ingame;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System;
using VRage.Collections;
using VRage.Game.Components;
using VRage.Game.GUI.TextPanel;
using VRage.Game.ModAPI.Ingame.Utilities;
using VRage.Game.ModAPI.Ingame;
using VRage.Game.ObjectBuilders.Definitions;
using VRage.Game;
using VRage;
using VRageMath;
namespace IngameScript {
partial class Program {
//Internal (Don't touch!)
Dictionary<String, List<CommandParameter>> propertyWords = NewDictionary<string, List<CommandParameter>>();
string[] separateTokensFirstPass = new[] { "(", ")", "[", "]", ",", "*", "/", "!", "^", "..", "%", ">=", "<=", "==", "&&", "||", "@", "$", "->", "++", "+=", "--", "-=" };
string[] separateTokensSecondPass = new[] { "<", ">", "=", "&", "|", ".", "-", "+", "?", ":" };
Dictionary<UniOperand, String> uniOperandToString = NewDictionary<UniOperand, String>();
Dictionary<BiOperand, String> biOperandToString = NewDictionary<BiOperand, String>();
Dictionary<Return, String> returnToString = NewDictionary(
KeyValuePair(Return.BOOLEAN, "boolean"),
KeyValuePair(Return.NUMERIC, "number"),
KeyValuePair(Return.STRING, "string"),
KeyValuePair(Return.VECTOR, "vector"),
KeyValuePair(Return.COLOR, "color"),
KeyValuePair(Return.LIST, "list")
);
static Dictionary<string, Converter> castMap = NewDictionary(
CastFunction("bool", p => CastBoolean(p)),
CastFunction("string", CastString),
CastFunction("number", p => CastNumber(p)),
CastFunction("vector", p => CastVector(p)),
CastFunction("color", p => CastColor(p)),
CastFunction("list", CastList)
);
static Dictionary<string, Color> colors = NewDictionary(
KeyValuePair("red", Color.Red),
KeyValuePair("blue", Color.Blue),
KeyValuePair("green", Color.Green),
KeyValuePair("orange", Color.Orange),
KeyValuePair("yellow", Color.Yellow),
KeyValuePair("white", Color.White),
KeyValuePair("black", Color.Black)
);
public void InitializeParsers() {
//Ignored words that have no command parameters
AddWords(Words("the", "than", "turned", "block", "panel", "chamber", "drive", "to", "from", "then", "of", "either", "for", "in", "do", "does", "second", "seconds", "be", "being"), new IgnoreCommandParameter());
//Selector Related Words
AddWords(Words("blocks", "group", "panels", "chambers", "drives"), new GroupCommandParameter());
AddWords(Words("my", "self", "this"), new SelfCommandParameter());
AddWords(Words("$"), new VariableSelectorCommandParameter());
//Direction Words
AddWords(Words("up", "upward", "upwards", "upper"), new DirectionCommandParameter(Direction.UP));
AddWords(Words("down", "downward", "downwards", "lower"), new DirectionCommandParameter(Direction.DOWN));
AddWords(Words("left", "lefthand"), new DirectionCommandParameter(Direction.LEFT));
AddWords(Words("right", "righthand"), new DirectionCommandParameter(Direction.RIGHT));
AddWords(Words("forward", "forwards", "front"), new DirectionCommandParameter(Direction.FORWARD));
AddWords(Words("backward", "backwards", "back"), new DirectionCommandParameter(Direction.BACKWARD));
AddWords(Words("clockwise", "clock"), new DirectionCommandParameter(Direction.CLOCKWISE));
AddWords(Words("counter", "counterclock", "counterclockwise"), new DirectionCommandParameter(Direction.COUNTERCLOCKWISE));
//Action Words
AddWords(Words("bind", "tie", "link"), new AssignmentCommandParameter(true));
AddWords(Words("move", "go", "tell", "turn", "rotate", "set", "assign", "allocate", "designate", "apply"), new AssignmentCommandParameter());
AddWords(Words("reverse", "reversed"), new ReverseCommandParameter());
AddWords(Words("raise", "extend"), new AssignmentCommandParameter(), new DirectionCommandParameter(Direction.UP));
AddWords(Words("retract"), new AssignmentCommandParameter(), new DirectionCommandParameter(Direction.DOWN));
AddWords(Words("increase", "increment", "add", "by", "++", "+="), new IncrementCommandParameter());
AddWords(Words("decrease", "decrement", "reduce", "subtract", "--", "-="), new IncrementCommandParameter(false));
AddWords(Words("global"), new GlobalCommandParameter());
//Value Words
AddWords(Words("on", "begin", "true", "start", "started", "resume", "resumed"), new BooleanCommandParameter(true));
AddWords(Words("off", "terminate", "cancel", "end", "false", "stopped", "halt", "halted"), new BooleanCommandParameter(false));
//Property Words
AddPropertyWords(AllWords(PluralWords("height", "length", "level", "size", "period", "scale"), Words("weight", "mass")), Property.LEVEL);
AddPropertyWords(PluralWords("angle"), Property.ANGLE);
AddPropertyWords(AllWords(PluralWords("speed", "rate", "pace"), Words("velocity", "velocities")), Property.VELOCITY);
AddPropertyWords(Words("connect", "attach", "connected", "attached", "dock", "docked", "docking"), Property.CONNECTED);
AddPropertyWords(Words("disconnect", "detach", "disconnected", "detached", "undock", "undocked"), Property.CONNECTED, false);
AddPropertyWords(Words("lock", "locked", "freeze", "frozen", "brake", "braking", "handbrake", "permanent"), Property.LOCKED);
AddPropertyWords(Words("unlock", "unlocked", "unfreeze"), Property.LOCKED, false);
AddPropertyWords(Words("run", "running", "execute", "executing", "script"), Property.RUN);
AddPropertyWords(Words("use", "used", "occupy", "occupied", "control", "controlled"), Property.USE);
AddPropertyWords(Words("unused", "unoccupied", "vacant", "available"), Property.USE, false);
AddPropertyWords(Words("done", "ready", "complete", "finished", "built", "finish", "pressurized", "depressurized"), Property.COMPLETE);
AddPropertyWords(Words("open", "opened"), Property.OPEN);
AddPropertyWords(Words("close", "closed", "shut"), Property.OPEN, false);
AddPropertyWords(PluralWords("font"), Property.FONT);
AddPropertyWords(PluralWords("text", "message", "argument"), Property.TEXT);
AddPropertyWords(AllWords(Words("colors"), PluralWords("foreground")), Property.COLOR);
AddAmbiguousWords(Words("color"), new PropertyCommandParameter(Property.COLOR));
AddPropertyWords(PluralWords("background"), Property.BACKGROUND);
AddPropertyWords(Words("power", "powered"), Property.POWER);
AddPropertyWords(Words("enable", "enabled", "arm", "armed"), Property.ENABLE);
AddPropertyWords(Words("disable", "disabled", "disarm", "disarmed"), Property.ENABLE, false);
AddPropertyWords(Words("music", "sound", "song", "track", "image", "play", "playing", "unsilence"), Property.MEDIA);
AddPropertyWords(Words("silence", "silent", "quiet"), Property.MEDIA, false);
AddPropertyWords(Words("sounds", "songs", "images", "tracks"), Property.MEDIA_LIST);
AddPropertyWords(AllWords(PluralWords("volume", "output"), Words("intensity", "intensities")), Property.VOLUME);
AddPropertyWords(AllWords(PluralWords("range", "distance", "limit", "delay"), Words("radius", "radii", "capacity", "capacities")), Property.RANGE);
AddPropertyWords(PluralWords("interval"), Property.INTERVAL);
AddPropertyWords(PluralWords("offset", "padding"), Property.OFFSET);
AddPropertyWords(PluralWords("falloff"), Property.FALLOFF);
AddPropertyWords(Words("trigger", "triggered", "detect", "detected", "trip", "tripped", "deploy", "deployed", "shoot", "shooting", "shot", "detonate"), Property.TRIGGER);
AddPropertyWords(Words("pressure", "pressurize", "pressurizing", "supply", "supplying", "generate", "generating", "discharge", "discharging", "broadcast", "broadcasting", "assemble", "assembling"), Property.SUPPLY);
AddPropertyWords(Words("stockpile", "stockpiling", "depressurize", "depressurizing", "gather", "gathering", "intake", "recharge", "recharging", "consume", "consuming", "collect", "collecting", "disassemble", "disassembling"), Property.SUPPLY, false);
AddPropertyWords(AllWords(PluralWords("ratio", "percentage", "percent", "completion"), Words("progress", "progresses")), Property.RATIO);
AddPropertyWords(PluralWords("input", "pilot", "user"), Property.INPUT);
AddPropertyWords(PluralWords("roll", "rollInput", "rotation"), Property.ROLL_INPUT);
AddPropertyWords(Words("auto", "autopilot", "refill", "drain", "draining", "cooperate", "cooperating"), Property.AUTO);
AddPropertyWords(AllWords(PluralWords("override", "dampener"), Words("overridden")), Property.OVERRIDE);
AddPropertyWords(PluralWords("direction"), Property.DIRECTION);
AddPropertyWords(PluralWords("position", "location", "alignment"), Property.POSITION);
AddPropertyWords(Words("target", "destination", "waypoint", "coords", "coordinates"), Property.TARGET);
AddPropertyWords(Words("waypoints", "destinations"), Property.WAYPOINTS);
AddPropertyWords(Words("targetvelocity"), Property.TARGET_VELOCITY);
AddPropertyWords(AllWords(PluralWords("strength", "force", "torque"), Words("gravity", "gravities")), Property.STRENGTH);
AddPropertyWords(PluralWords("countdown"), Property.COUNTDOWN);
AddPropertyWords(Words("name", "label"), Property.NAME);
AddPropertyWords(Words("names", "labels"), Property.NAMES);
AddPropertyWords(Words("show", "showing"), Property.SHOW);
AddPropertyWords(Words("hide", "hiding"), Property.SHOW, false);
AddPropertyWords(Words("properties", "attributes"), Property.PROPERTIES);
AddPropertyWords(Words("actions"), Property.ACTIONS);
//ValueProperty Words
AddWords(PluralWords("amount"), new ValuePropertyCommandParameter(ValueProperty.AMOUNT));
AddWords(Words("property", "attribute"), new ValuePropertyCommandParameter(ValueProperty.PROPERTY));
AddWords(Words("action"), new ValuePropertyCommandParameter(ValueProperty.ACTION));
AddWords(Words("produce", "producing", "create", "creating", "build", "building", "make", "making"), new ValuePropertyCommandParameter(ValueProperty.CREATE));
AddWords(Words("destroy", "destroying", "recycle", "recycling"), new ValuePropertyCommandParameter(ValueProperty.DESTROY));
//Special Command Words
AddWords(Words("times", "iterations"), new RepeatCommandParameter());
AddWords(Words("wait", "hold"), new WaitCommandParameter());
AddWords(Words("call", "gosub"), new FunctionCommandParameter(false));
AddWords(Words("goto"), new FunctionCommandParameter(true));
AddWords(Words("listen", "channel"), new ListenCommandParameter());
AddWords(Words("send"), new SendCommandParameter());
AddWords(Words("print", "log", "echo", "write"), new PrintCommandParameter());
AddWords(Words("queue", "schedule"), new QueueCommandParameter(false));
AddWords(Words("async", "parallel"), new QueueCommandParameter(true));
AddWords(Words("transfer", "give"), new TransferCommandParameter(true));
AddWords(Words("take"), new TransferCommandParameter(false));
AddWords(Words("->"), new KeyedVariableCommandParameter());
AddWords(Words("?"), new TernaryConditionIndicatorParameter());
AddWords(Words(":"), new TernaryConditionSeparatorParameter());
AddWords(Words("each", "every"), new IteratorCommandParameter());
//Conditional Words
AddWords(Words("if"), new IfCommandParameter(false, false, false));
AddWords(Words("unless"), new IfCommandParameter(true, false, false));
AddWords(Words("while"), new IfCommandParameter(false, true, false));
AddWords(Words("until"), new IfCommandParameter(true, true, false));
AddWords(Words("when"), new IfCommandParameter(true, true, true));
AddWords(Words("else", "otherwise"), new ElseCommandParameter());
AddWords(Words("that", "which", "whose"), new ThatCommandParameter());
//Comparison Words
AddWords(Words("less", "<", "below"), new ComparisonCommandParameter((a, b) => a.Compare(b) < 0));
AddWords(Words("<="), new ComparisonCommandParameter((a, b) => a.Compare(b) <= 0));
AddWords(Words("is", "are", "equal", "equals", "=", "=="), new ComparisonCommandParameter((a, b) => a.Compare(b) == 0));
AddWords(Words(">="), new ComparisonCommandParameter((a, b) => a.Compare(b) >= 0));
AddWords(Words("greater", ">", "above", "more"), new ComparisonCommandParameter((a, b) => a.Compare(b) > 0));
AddWords(Words("contain", "contains"), new ComparisonCommandParameter((a, b) => CastBoolean(PROGRAM.PerformOperation(BiOperand.CONTAINS, a, b))));
//Aggregation Words
AddWords(Words("any"), new AggregationModeCommandParameter(AggregationMode.ANY));
AddWords(Words("all"), new AggregationModeCommandParameter(AggregationMode.ALL));
AddWords(Words("none"), new AggregationModeCommandParameter(AggregationMode.NONE));
AddWords(Words("average", "avg"), new PropertyAggregationCommandParameter((blocks, primitiveSupplier) => SumAggregator(blocks, primitiveSupplier).Divide(ResolvePrimitive(Math.Max(1, blocks.Count())))));
AddWords(Words("minimum", "min"), new PropertyAggregationCommandParameter((blocks, primitiveSupplier) => blocks.Select(b => primitiveSupplier(b)).DefaultIfEmpty(ResolvePrimitive(0)).Aggregate((a, b) => (a.Compare(b) < 0 ? a : b))));
AddWords(Words("maximum", "max"), new PropertyAggregationCommandParameter((blocks, primitiveSupplier) => blocks.Select(b => primitiveSupplier(b)).DefaultIfEmpty(ResolvePrimitive(0)).Aggregate((a, b) => (a.Compare(b) > 0 ? a : b))));
AddWords(Words("count"), new PropertyAggregationCommandParameter((blocks, primitiveSupplier) => ResolvePrimitive(blocks.Count())));
AddAmbiguousWords(Words("number"), new PropertyAggregationCommandParameter((blocks, primitiveSupplier) => ResolvePrimitive(blocks.Count())));
AddWords(Words("sum", "total"), new PropertyAggregationCommandParameter(SumAggregator));
AddWords(Words("collection"), new PropertyAggregationCommandParameter((blocks, primitiveSupplier) => ResolvePrimitive(NewKeyedList(blocks.Select(b => new StaticVariable(primitiveSupplier(b)))))));
AddAmbiguousWords(Words("list"), new PropertyAggregationCommandParameter((blocks, primitiveSupplier) => ResolvePrimitive(NewKeyedList(blocks.Select(b => new StaticVariable(primitiveSupplier(b)))))));
//Operations Words
AddWords(Words("("), new OpenParenthesisCommandParameter());
AddWords(Words(")"), new CloseParenthesisCommandParameter());
AddWords(Words("and", "&", "&&", "but", "yet"), new AndCommandParameter());
AddWords(Words("or", "|", "||"), new OrCommandParameter());
AddWords(Words("not", "!", "stop"), new NotCommandParameter());
AddWords(Words("@"), new IndexCommandParameter());
AddRightUniOperationWords(Words("absolute", "abs"), UniOperand.ABS);
AddRightUniOperationWords(Words("sqrt"), UniOperand.SQRT);
AddRightUniOperationWords(Words("sin"), UniOperand.SIN);
AddRightUniOperationWords(Words("cosine", "cos"), UniOperand.COS);
AddRightUniOperationWords(Words("tangent", "tan"), UniOperand.TAN);
AddRightUniOperationWords(Words("arcsin", "asin"), UniOperand.ASIN);
AddRightUniOperationWords(Words("arccos", "acos"), UniOperand.ACOS);
AddRightUniOperationWords(Words("arctan", "atan"), UniOperand.ATAN);
AddRightUniOperationWords(Words("round", "rnd"), UniOperand.ROUND);
AddRightUniOperationWords(Words("sort", "sorted"), UniOperand.SORT);
AddRightUniOperationWords(Words("ln"), UniOperand.LN);
AddRightUniOperationWords(Words("rand", "random", "randomize"), UniOperand.RANDOM);
AddRightUniOperationWords(Words("shuffle", "shuffled"), UniOperand.SHUFFLE);
AddLeftUniOperationWords(Words("tick", "ticks"), UniOperand.TICKS);
AddLeftUniOperationWords(Words("keys", "indexes"), UniOperand.KEYS);
AddLeftUniOperationWords(Words("values"), UniOperand.VALUES);
AddWords(Words("dot", "."), new BiOperandTier0Operand(BiOperand.DOT));
AddTier1OperationWords(Words("multiply", "*"), BiOperand.MULTIPLY);
AddTier1OperationWords(Words("divide", "/"), BiOperand.DIVIDE);
AddTier1OperationWords(Words("mod", "%"), BiOperand.MOD);
AddTier1OperationWords(Words("pow", "^", "xor"), BiOperand.EXPONENT);
AddTier1OperationWords(Words("split", "separate", "separated"), BiOperand.SPLIT);
AddTier1OperationWords(Words("join", "joined"), BiOperand.JOIN);
AddTier2OperationWords(Words("plus", "+"), BiOperand.ADD);
AddTier2OperationWords(Words("minus"), BiOperand.SUBTRACT);
AddTier3OperationWords(Words("as", "cast"), BiOperand.CAST);
AddTier3OperationWords(Words(".."), BiOperand.RANGE);
AddWords(Words("-"), new MinusCommandParameter());
//List Words
AddWords(Words("["), new OpenBracketCommandParameter());
AddWords(Words("]"), new CloseBracketCommandParameter());
AddWords(Words(","), new ListSeparatorCommandParameter());
//Control Types
AddControlWords(Words("restart", "reset", "reboot"), thread => {
PROGRAM.ClearAllState();
throw new InterruptException(ProgramState.RUNNING);
});
AddControlWords(Words("repeat", "loop", "rerun", "replay"), thread => {
thread.Command = thread.Command.Clone();
return false;
});
AddControlWords(Words("exit"), thread => {
PROGRAM.ClearAllState();
throw new InterruptException(ProgramState.STOPPED);
});
AddControlWords(Words("pause"), thread => {
if (PROGRAM.state != ProgramState.PAUSED) throw new InterruptException(ProgramState.PAUSED);
return true;
});
AddControlWords(Words("break"), thread => {
GetInterrupableCommand("break").Break();
return false;
});
AddControlWords(Words("continue"), thread => {
GetInterrupableCommand("continue").Continue();
return false;
});
AddControlWords(Words("return"), thread => {
FunctionCommand currentFunction = thread.GetCurrentCommand<FunctionCommand>(command => true);
if (currentFunction == null) throw new Exception("Invalid use of return command");
currentFunction.function = new NullCommand();
return false;
});
//Blocks
AddBlockWords(Words("piston"), Block.PISTON);
AddBlockWords(Words("light", "spotlight"), Block.LIGHT);
AddBlockWords(Words("rotor"), Block.ROTOR);
AddBlockWords(Words("hinge"), Block.HINGE);
AddBlockWords(Words("program", "programmable"), Block.PROGRAM);
AddBlockWords(Words("timer"), Block.TIMER);
AddBlockWords(Words("projector"), Block.PROJECTOR);
AddBlockWords(Words("merge"), Words(), Block.MERGE);
AddBlockWords(Words("connector"), Block.CONNECTOR);
AddBlockWords(Words("welder"), Block.WELDER);
AddBlockWords(Words("grinder"), Block.GRINDER);
AddBlockWords(Words("door", "hangar", "bay", "gate"), Block.DOOR);
AddBlockWords(PluralWords("display", "screen", "lcd"), Words(), Block.DISPLAY);
AddBlockWords(Words("speaker", "alarm", "siren"), Block.SOUND);
AddBlockWords(Words("camera"), Block.CAMERA);
AddBlockWords(Words("sensor"), Block.SENSOR);
AddBlockWords(Words("beacon"), Block.BEACON);
AddBlockWords(Words("antenna"), Block.ANTENNA);
AddBlockWords(Words("ship", "rover", "cockpit", "seat", "station"), Block.COCKPIT);
AddBlockWords(Words("cryo"), Block.CRYO_CHAMBER);
AddBlockWords(Words("drone", "remote", "robot"), Block.REMOTE);
AddBlockWords(Words("thruster"), Block.THRUSTER);
AddBlockWords(Words("airvent", "vent"), Block.AIRVENT);
AddBlockWords(Words("gun", "rocket", "missile", "launcher"), Block.GUN);
AddBlockWords(Words("turret"), Block.TURRET);
AddBlockWords(Words("generator"), Block.GENERATOR);
AddBlockWords(Words("tank"), Block.TANK);
AddBlockWords(Words("magnet", "gear"), Block.MAGNET);
AddBlockWords(Words("battery"), Words("batteries"), Block.BATTERY);
AddBlockWords(Words("chute", "parachute"), Block.PARACHUTE);
AddBlockWords(Words("wheel"), Words("wheels", "suspension"), Block.SUSPENSION);
AddBlockWords(Words("detector"), Block.DETECTOR);
AddBlockWords(Words("drill"), Block.DRILL);
AddBlockWords(Words("engine"), Block.ENGINE);
AddBlockWords(Words("turbine"), Block.TURBINE);
AddBlockWords(Words("reactor"), Block.REACTOR);
AddBlockWords(Words("solar"), Block.SOLAR_PANEL);
AddBlockWords(Words("sorter"), Block.SORTER);
AddBlockWords(Words("gyro", "gyroscope"), Block.GYROSCOPE);
AddBlockWords(Words("gravitygenerator"), Block.GRAVITY_GENERATOR);
AddBlockWords(Words("gravitysphere"), Block.GRAVITY_SPHERE);
AddBlockWords(Words("cargo", "container", "inventory", "inventories"), Words("cargos", "containers"), Block.CARGO);
AddBlockWords(Words("warhead", "bomb"), Block.WARHEAD);
AddBlockWords(Words("assembler"), Block.ASSEMBLER);
AddBlockWords(Words("collector"), Block.COLLECTOR);
AddBlockWords(Words("ejector"), Block.EJECTOR);
AddBlockWords(Words("decoy"), Block.DECOY);
AddBlockWords(Words("jump", "jumpdrive"), Block.JUMPDRIVE);
AddBlockWords(Words("laser", "laserantenna"), Block.LASER_ANTENNA);
AddBlockWords(Words("terminal"), Block.TERMINAL);
AddBlockWords(Words("refinery"), Words("refineries"), Block.REFINERY);
//Register Special CommandParameter Output Values
RegisterToString<GroupCommandParameter>(p => "group");
RegisterToString<AmbiguousCommandParameter>(p => "[Ambiguous]");
RegisterToString<AmbiguousStringCommandParameter>(p => "\"" + p.value + "\"");
RegisterToString<StringCommandParameter>(p => "'" + p.value + "'");
RegisterToString<VariableAssignmentCommandParameter>(p => "Assign[name=" + p.variableName + ",global=" + p.isGlobal + ",ref=" + p.useReference + "]");
RegisterToString<VariableCommandParameter>(p => "[Variable]");
RegisterToString<VariableSelectorCommandParameter>(p => "[VariableSelector]");
RegisterToString<IndexSelectorCommandParameter>(p => "[IndexSelector]");
RegisterToString<FunctionDefinitionCommandParameter>(p => "Function[switch=" + p.switchExecution + ",name=" + p.functionDefinition.functionName + "]");
RegisterToString<ConditionCommandParameter>(p => "[Condition]");
RegisterToString<BlockConditionCommandParameter>(p => "[BlockCondition]");
RegisterToString<CommandReferenceParameter>(p => "[Command]");
RegisterToString<RepetitionCommandParameter>(p => "[Repeat]");
RegisterToString<SelectorCommandParameter>(p => "[Selector]");
RegisterToString<ThatCommandParameter>(p => "That");
RegisterToString<AssignmentCommandParameter>(p => "[Action]");
RegisterToString<PropertyCommandParameter>(p => "Property[id=" + p.value.propertyType + "]");
}
Dictionary<Type, Func<CommandParameter, object>> commandParameterStrings = NewDictionary<Type, Func<CommandParameter, object>>();
void RegisterToString<T>(Func<T, object> toString) where T : CommandParameter {
commandParameterStrings[typeof(T)] = (p) => toString((T)p);
}
string CommandParameterToString(CommandParameter parameter) {
Func<CommandParameter, object> func;
if (!commandParameterStrings.TryGetValue(parameter.GetType(), out func)) {
func = (p) => p.Token;
}
return func(parameter).ToString();
}
String[] Words(params String[] words) => words;
String[] AllWords(params String[][] words) => words.Aggregate((a, b) => a.Concat(b).ToArray());
String[] PluralWords(params String[] words) => words.Concat(words.Select(w => w + "s")).ToArray();
void AddControlWords(String[] words, ControlFunction function) {
AddWords(words, new CommandReferenceParameter(new ControlCommand { controlFunction = function }));
}
void AddPropertyWords(String[] words, Property property, bool nonNegative = true) {
if (!nonNegative) AddWords(words, new PropertyCommandParameter(property), new BooleanCommandParameter(false));
else AddWords(words, new PropertyCommandParameter(property));
}
void AddRightUniOperationWords(String[] words, UniOperand operand) {
AddWords(words, new UniOperationCommandParameter(operand));
uniOperandToString[operand] = words[0];
}
void AddLeftUniOperationWords(String[] words, UniOperand operand) {
AddWords(words, new LeftUniOperationCommandParameter(operand));
uniOperandToString[operand] = words[0];
}
void AddTier1OperationWords(String[] words, BiOperand operand) {
AddWords(words, new BiOperandTier1Operand(operand));
biOperandToString[operand] = words[0];
}
void AddTier2OperationWords(String[] words, BiOperand operand) {
AddWords(words, new BiOperandTier2Operand(operand));
biOperandToString[operand] = words[0];
}
void AddTier3OperationWords(String[] words, BiOperand operand) {
AddWords(words, new BiOperandTier3Operand(operand));
biOperandToString[operand] = words[0];
}
//Assume group words are just blockWords with "s" added to the end
void AddBlockWords(String[] blockWords, Block blockType) => AddBlockWords(blockWords, blockWords.Select(b => b + "s").ToArray(), blockType);
void AddBlockWords(String[] blockWords, String[] groupWords, Block blockType) {
AddWords(blockWords, new BlockTypeCommandParameter(blockType));
AddWords(groupWords, new BlockTypeCommandParameter(blockType), new GroupCommandParameter());
}
void AddAmbiguousWords(String[] words, params CommandParameter[] commandParameters) {
foreach (String word in words)
AddWords(Words(word), new AmbiguousStringCommandParameter(word, false, new AmbiguousCommandParameter(commandParameters)));
}
void AddWords(String[] words, params CommandParameter[] commandParameters) {
foreach (String word in words) propertyWords.Add(word, commandParameters.ToList());
}
List<CommandParameter> ParseCommandParameters(List<Token> tokens) {
var parameters = NewList<CommandParameter>();
foreach (var token in tokens) {
var newParameters = ParseCommandParameters(token);
newParameters.ForEach(p => p.Token = token.original);
parameters.AddRange(newParameters);
}
return parameters;
}
List<CommandParameter> ParseCommandParameters(Token token) {
var commandParameters = NewList<CommandParameter>();
String t = token.token;
if (token.isExplicitString) {
commandParameters.Add(new StringCommandParameter(token.original, true));
} else if (token.isString) {
List<Token> subTokens = ParseTokens(t);
List<CommandParameter> subtokenParams = ParseCommandParameters(subTokens);
commandParameters.Add(new AmbiguousStringCommandParameter(token.original, false, subtokenParams.ToArray()));
} else if (propertyWords.ContainsKey(t)) {
commandParameters.AddList(propertyWords[t]);
} else { //If no property matches, must be a string
commandParameters.Add(new AmbiguousStringCommandParameter(token.original, true));
}
return commandParameters;
}
public List<Token> ParseTokens(String commandString) => (String.IsNullOrWhiteSpace(commandString) || commandString.Trim().StartsWith("#")) ? NewList<Token>() :
ParseSurrounded(commandString, "`\'\"",
u => u.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.SelectMany(ParseSeparateTokens)
.Select(v => new Token(v, false, false))
.ToArray())
.ToList();
Token[] ParseSurrounded(String token, string characters, Func<String, Token[]> parseSubTokens) =>
characters.Length == 0 ? parseSubTokens(token) :
token.Trim().Split(characters[0])
.SelectMany((element, index) => index % 2 == 0 // If even index
? ParseSurrounded(element, characters.Remove(0,1), parseSubTokens) // Split the item
: new Token[] { new Token(element, true, characters.Length > 1) }) // Keep the entire item
.ToArray();
String[] ParseSeparateTokens(String command) {
var newCommand = command;
foreach (var token in separateTokensFirstPass) newCommand = newCommand.Replace(token, " " + token + " ");
newCommand = string.Join(" ", newCommand.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).SelectMany(token => {
Primitive ignored;
if (separateTokensFirstPass.Contains(token) || ParsePrimitive(token, out ignored)) return new[] { token };
foreach (var s in separateTokensSecondPass) token = token.Replace(s, " " + s + " ");
return token.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}));
List<char> commandArray = newCommand.ToCharArray().ToList();
return new string(commandArray.ToArray()).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
public static bool ParsePrimitive(String token, out Primitive primitive) {
primitive = null;
var vector = GetVector(token);
Double numeric;
var color = GetColor(token);
if (Double.TryParse(token, out numeric)) primitive = ResolvePrimitive((float)numeric);
if (vector.HasValue) primitive = ResolvePrimitive(vector.Value);
if (color.HasValue) primitive = ResolvePrimitive(color.Value);
return primitive != null;
}
public class Token {
public String token;
public String original;
public bool isString;
public bool isExplicitString;
public Token(string tokenParameter, bool isStringParameter, bool isExplicit) {
isString = isStringParameter;
isExplicitString = isExplicit;
token = tokenParameter.ToLower();
original = tokenParameter;
}
public override string ToString() => token;
}
}
}
| 64.423529
| 262
| 0.633735
|
[
"MIT"
] |
MerlinofMines/EasyCommands
|
EasyCommands/CommandParsers/ParameterParsers.cs
| 32,858
|
C#
|
using System.Collections.Generic;
using SexyColor.BusinessComponents;
namespace SexyColor.CommonComponents
{
public class UserService : IUserService
{
public IUserRepository userRepository { get; set; }
/// <summary>
/// 根据帐号邮箱获取用户
/// </summary>
/// <param name="accountEmail">帐号邮箱</param>
public User FindUserByEmail(string accountEmail)
{
long userId = userRepository.GetUserIdByEmail(accountEmail);
return GetUser(userId);
}
/// <summary>
/// 根据手机号获取用户
/// </summary>
/// <param name="accountMobile">手机号</param>
public User FindUserByMobile(string accountMobile)
{
long userId = userRepository.GetUserIdByMobile(accountMobile);
return GetUser(userId);
}
/// <summary>
/// 获取用户根据用户Id
/// </summary>
/// <param name="userId">用户Id</param>
public User GetUser(long userId)
{
if (userId <= 0)
return null;
return userRepository.GetUser(userId);
}
/// <summary>
/// 获取用户根据用户名
/// </summary>
/// <param name="userName">用户名</param>
public User GetUser(string userName)
{
long userId = userRepository.GetUserIdByUserName(userName);
return GetUser(userId);
}
/// <summary>
/// 根据昵称获取昵称
/// </summary>
/// <param name="nickName">昵称</param>
public User GetUserByNickName(string nickName)
{
long userId = userRepository.GetUserIdByNickName(nickName);
return GetUser(userId);
}
/// <summary>
/// 根据用户Id集合获取用户对象集合
/// </summary>
/// <param name="userIds">用户Id集合</param>
/// <returns>用户对象集合</returns>
public IEnumerable<User> GetUsers(IEnumerable<long> userIds)
{
if (userIds == null)
return new List<User>();
return userRepository.GetModelByIds<long>(w => w.UserId, userIds);
}
/// <summary>
/// 根用户Id集合删除用户
/// </summary>
/// <param name="userIds">用户Id集合</param>
public void DeleteUsers(IEnumerable<long> userIds)
{
List<User> users = new List<User>();
foreach (var userId in userIds)
{
User user = userRepository.GetUser(userId);
if (user == null)
continue;
var result = userRepository.DeleteCache(user);
if (result) {
UserIdToUserNameDictionary.RemoveUserId(userId);
UserIdToUserNameDictionary.RemoveUserName(user.UserName);
}
}
}
/// <summary>
/// 删除用户
/// </summary>
/// <param name="userId">用户Id</param>
public void DeleteUser(long userId)
{
User user = userRepository.GetUser(userId);
var result = userRepository.DeleteCache(user);
if (result)
{
UserIdToUserNameDictionary.RemoveUserId(userId);
UserIdToUserNameDictionary.RemoveUserName(user.UserName);
}
}
/// <summary>
/// 编辑用户
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool EditUser(User entity)
{
return userRepository.UpdateCache(entity);
}
}
}
| 30.603448
| 78
| 0.523099
|
[
"Apache-2.0"
] |
lxkbest/SexyColor.Net
|
SexyColor.CommonComponents/Users/UserService.cs
| 3,762
|
C#
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AgencyPI.Models.Dto
{
public class CustomerDto
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string WorkingArea { get; set; }
public int Grade { get; set; }
public string PhoneNumber { get; set; }
public virtual Agent Agent { get; set; }
public virtual List<Order> Orders { get; set; }
}
}
| 30.117647
| 55
| 0.623047
|
[
"MIT"
] |
ddenizakpinar/AgencyPI
|
Models/Dto/CustomerDto.cs
| 512
|
C#
|
using System;
using System.Collections.Generic;
using ZeldaOracle.Common.Audio;
using ZeldaOracle.Common.Geometry;
using ZeldaOracle.Common.Graphics;
using ZeldaOracle.Game.Items;
using ZeldaOracle.Game.Main;
namespace ZeldaOracle.Game.Control.Menus {
public class MenuWeapons : InventoryMenu {
private int ammoSlot;
private Point2I ammoMenuSize;
private SlotGroup ammoSlotGroup;
private ItemWeapon[] oldEquippedWeapons;
//-----------------------------------------------------------------------------
// Constructors
//-----------------------------------------------------------------------------
public MenuWeapons(GameManager gameManager)
: base(gameManager)
{
background = GameData.SPR_BACKGROUND_MENU_WEAPONS;
ammoSlot = 0;
ammoMenuSize = new Point2I(16, 8);
ammoSlotGroup = null;
oldEquippedWeapons = new ItemWeapon[2];
SlotGroup group = new SlotGroup();
currentSlotGroup = group;
slotGroups.Add(group);
Slot[,] slots = new Slot[4, 4];
Point2I gridSize = new Point2I(4, 4);
// Create the slot grid
for (int y = 0; y < gridSize.Y; y++) {
for (int x = 0; x < gridSize.X; x++) {
slots[x, y] = group.AddSlot(
new Point2I(24 + 32 * x, 8 + 24 * y), 24);
}
}
// Setep the slot connections
for (int y = 0; y < gridSize.Y; y++) {
for (int x = 0; x < gridSize.X; x++) {
// Horizontal connections will wrap to the next/previous rows
if (x == 0)
slots[x, y].SetConnection(Direction.Left,
slots[gridSize.X - 1, (y + gridSize.Y - 1) % gridSize.Y]);
else
slots[x, y].SetConnection(Direction.Left, slots[x - 1, y]);
if (x == gridSize.X - 1)
slots[x, y].SetConnection(Direction.Right,
slots[0, (y + 1) % gridSize.Y]);
else
slots[x, y].SetConnection(Direction.Right, slots[x + 1, y]);
// Vertical connections wrap around
slots[x, y].SetConnection(Direction.Up,
slots[x, (y + gridSize.Y - 1) % gridSize.Y]);
slots[x, y].SetConnection(Direction.Down,
slots[x, (y + 1) % gridSize.Y]);
}
}
}
//-----------------------------------------------------------------------------
// Item Management
//-----------------------------------------------------------------------------
public bool AddToInventory(ItemWeapon weapon) {
if (weapon.IsTwoHanded &&
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_A] == null &&
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_A] == null)
{
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_A] = weapon;
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_B] = weapon;
weapon.Equip(Inventory.SLOT_A);
return true;
}
else if (!weapon.IsTwoHanded &&
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_A] == null)
{
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_A] = weapon;
weapon.Equip(Inventory.SLOT_A);
return true;
}
else if (!weapon.IsTwoHanded &&
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_B] == null)
{
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_B] = weapon;
weapon.Equip(Inventory.SLOT_B);
return true;
}
else {
// Find an empty slot in the inventory grid
Slot emptySlot = NextAvailableSlot;
if (emptySlot != null) {
emptySlot.SlotItem = weapon;
return true;
}
else {
// No room for the item
return false;
}
}
}
public void RemoveFromInventory(ItemWeapon weapon) {
// Clear all slots containing the weapon
if (GameControl.Inventory.EquippedWeapons[Inventory.SLOT_A] == weapon)
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_A] = null;
if (GameControl.Inventory.EquippedWeapons[Inventory.SLOT_B] == weapon)
GameControl.Inventory.EquippedWeapons[Inventory.SLOT_B] = null;
SlotGroup slots = slotGroups[0];
for (int i = 0; i < slots.NumSlots; i++) {
if (slots[i].SlotItem == weapon)
slots[i].SlotItem = null;
}
weapon.Unequip();
}
//-----------------------------------------------------------------------------
// Weapon Equipping
//-----------------------------------------------------------------------------
/// <summary>Equip the given weapon for the desired equip slot (A or B). This
/// will first find the item in the inventory, then swap it with the item
/// currently equipped in the slot.</summary>
public bool EquipWeapon(ItemWeapon equippedWeapon, int equipSlot) {
// Do nothing if this weapon type is already equipped in the correct slot
if (GameControl.Inventory.EquippedWeapons[equipSlot] == equippedWeapon)
return true;
// If the weapon is equipped but in the wrong slot, then simply swap the
// slots of the two equipped weapons
if (GameControl.Inventory.EquippedWeapons[1 - equipSlot] ==
equippedWeapon)
{
SwapEquippedWeaponSlots();
return true;
}
// Find the inventory slot which contains this weapon
Slot inventorySlot = null;
SlotGroup slotGroup = slotGroups[0];
for (int i = 0; i < slotGroup.NumSlots; i++) {
if (slotGroup[i].SlotItem == equippedWeapon)
inventorySlot = slotGroup[i];
}
if (inventorySlot == null)
return false;
// Equip the weapon from the slot
return EquipWeaponFromSlot(inventorySlot, equipSlot);
}
/// <summary>Equip the weapon in an inventory slot for the desired equip slot
/// (A or B). This will swap it with the item currently equipped in the slot.
/// </summary>
private bool EquipWeaponFromSlot(Slot swapSlot, int equipSlot) {
int otherEquipSlot = 1 - equipSlot;
ItemWeapon weaponToEquip = swapSlot.SlotItem as ItemWeapon;
ItemWeapon[] equippedWeapons = GameControl.Inventory.EquippedWeapons;
// Get a list of currently equipped weapons that we'll need to unequip
List<ItemWeapon> weaponsToUnequip = new List<ItemWeapon>();
if (equippedWeapons[equipSlot] != null)
weaponsToUnequip.Add(equippedWeapons[equipSlot]);
if (weaponToEquip != null && weaponToEquip.IsTwoHanded &&
equippedWeapons[otherEquipSlot] != null &&
!equippedWeapons[otherEquipSlot].IsTwoHanded)
weaponsToUnequip.Add(equippedWeapons[otherEquipSlot]);
// If we need to unequip two weapons, then find an empty slot to put the
// second weapon in. If there are none, then cancel the equip action.
// Note that if the inventory is completely full, then two-handed weapons
// can never be equipped.
if (weaponsToUnequip.Count == 2) {
Slot emptySlot = NextAvailableSlot;
if (emptySlot != null) {
emptySlot.SlotItem = weaponsToUnequip[1];
equippedWeapons[otherEquipSlot] = null;
}
else {
swapSlot.SlotItem = weaponToEquip;
return false;
}
}
// Unequip the first weapon
if (weaponsToUnequip.Count >= 1) {
swapSlot.SlotItem = weaponsToUnequip[0];
if (weaponsToUnequip[0].IsTwoHanded)
equippedWeapons[otherEquipSlot] = null;
}
else
swapSlot.SlotItem = null;
// Equip the weapon from the slot
equippedWeapons[equipSlot] = weaponToEquip;
if (weaponToEquip != null && weaponToEquip.IsTwoHanded)
equippedWeapons[otherEquipSlot] = weaponToEquip;
// Invoke the ItemEquipment callbacks
for (int i = 0; i < weaponsToUnequip.Count; i++)
weaponsToUnequip[i].Unequip();
weaponToEquip?.Equip(equipSlot);
return true;
}
/// <summary>Swap equip slots of the two equipped weapons.</summary>
private void SwapEquippedWeaponSlots() {
ItemWeapon placeHolder = GameControl.Inventory.EquippedWeapons[0];
GameControl.Inventory.EquippedWeapons[0] =
GameControl.Inventory.EquippedWeapons[1];
GameControl.Inventory.EquippedWeapons[1] = placeHolder;
GameControl.Inventory.EquippedWeapons[0].CurrentEquipSlot = 0;
GameControl.Inventory.EquippedWeapons[1].CurrentEquipSlot = 1;
}
/// <summary>Equip the weapon in the currently selected inventory slot.
/// </summary>
private bool EquipWeaponFromCursor(int equipSlot) {
bool success = EquipWeaponFromSlot(
slotGroups[0].CurrentSlot, equipSlot);
ResetDescription();
return success;
}
//-----------------------------------------------------------------------------
// Overridden methods
//-----------------------------------------------------------------------------
public override void OnOpen() {
// Remember the equipped items from before opening the menu.
for (int i = 0; i < Inventory.NumEquipSlots; i++)
oldEquippedWeapons[i] = GameControl.Inventory.EquippedWeapons[i];
}
public override void OnClose() {
// Unequp old weapons.
for (int i = 0; i < Inventory.NumEquipSlots; i++) {
ItemWeapon weapon = oldEquippedWeapons[i];
if (weapon != null && !GameControl.Inventory.IsWeaponEquipped(weapon)) {
weapon.Unequip();
if (weapon.IsTwoHanded)
break;
}
}
// Equip new weapons.
for (int i = 0; i < Inventory.NumEquipSlots; i++) {
ItemWeapon weapon = GameControl.Inventory.EquippedWeapons[i];
if (weapon != null) {
weapon.Equip(i);
if (weapon.IsTwoHanded)
break;
}
}
}
public override void Update() {
base.Update();
if (!inSubMenu) {
// Equip weapons.
if (Controls.A.IsPressed() || Controls.B.IsPressed()) {
int slot = (Controls.A.IsPressed() ? 0 : 1);
ItemWeapon selectedItem = slotGroups[0].CurrentSlot.SlotItem as ItemWeapon;
if (selectedItem != null && selectedItem.AmmoCount > 1) {
ammoMenuSize = new Point2I(16, 8);
ammoSlot = slot;
inSubMenu = true;
currentSlotGroup = null;
ammoSlotGroup = new SlotGroup();
List<Ammo> ammo = new List<Ammo>();
int currentAmmoIndex = 0;
for (int i = 0; i < selectedItem.AmmoCount; i++) {
if (selectedItem.GetAmmoAt(i).IsObtained) {
if (selectedItem.AmmoIndex == i)
currentAmmoIndex = ammo.Count;
ammo.Add(selectedItem.GetAmmoAt(i));
}
}
int start = (160 - (ammo.Count * 24 + 8)) / 2 + 8;
int y = (DrawAmmoMenuAtTop ? 20 : 60);
for (int i = 0; i < ammo.Count; i++) {
ammoSlotGroup.AddSlot(new Point2I(start + 24 * i, y), 16);
ammoSlotGroup.GetSlotAt(i).SlotItem = ammo[i];
}
for (int i = 0; i < ammo.Count; i++) {
ammoSlotGroup.GetSlotAt(i).SetConnection(Direction.Left, ammoSlotGroup.GetSlotAt((i + ammo.Count - 1) % ammo.Count));
ammoSlotGroup.GetSlotAt(i).SetConnection(Direction.Right, ammoSlotGroup.GetSlotAt((i + 1) % ammo.Count));
}
ammoSlotGroup.SetCurrentSlot(ammoSlotGroup.GetSlotAt(currentAmmoIndex));
}
else {
AudioSystem.PlaySound(GameData.SOUND_MENU_SELECT);
EquipWeaponFromCursor(slot);
ResetDescription();
}
}
}
else {
Point2I maxSize = new Point2I(ammoSlotGroup.NumSlots * 24 + 8, 32);
if (ammoMenuSize.X < maxSize.X) {
ammoMenuSize.X += 8;
}
else if (ammoMenuSize.Y < maxSize.Y) {
ammoMenuSize.Y += 4;
if (ammoMenuSize.Y == maxSize.Y) {
currentSlotGroup = ammoSlotGroup;
ResetDescription();
}
}
else if (Controls.A.IsPressed() || Controls.B.IsPressed() || Controls.Start.IsPressed()) {
Ammo selectedAmmo = ammoSlotGroup.CurrentSlot.SlotItem as Ammo;
ItemWeapon weapon = slotGroups[0].CurrentSlot.SlotItem as ItemWeapon;
for (int i = 0; i < weapon.AmmoCount; i++) {
if (weapon.GetAmmoAt(i) == selectedAmmo)
weapon.AmmoIndex = i;
}
AudioSystem.PlaySound(GameData.SOUND_MENU_SELECT);
EquipWeaponFromCursor(ammoSlot);
ResetDescription();
inSubMenu = false;
ammoSlotGroup = null;
currentSlotGroup = slotGroups[0];
}
}
}
protected override void DrawMenu(Graphics2D g) {
base.DrawMenu(g);
if (inSubMenu) {
Point2I maxSize = new Point2I(ammoSlotGroup.NumSlots * 24 + 8, 32);
Point2I menuPos = new Point2I((160 - (ammoSlotGroup.NumSlots * 24 + 8)) / 2 + (maxSize.X - ammoMenuSize.X) / 2, DrawAmmoMenuAtTop ? 16 : 56);
//ISprite ammoMenuSprite = GameData.SHEET_MENU_SMALL_LIGHT.GetSprite(1, 4);
g.DrawSprite(GameData.SPR_HUD_AMMO_SELECT_BACKGROUND, new Rectangle2I(menuPos, ammoMenuSize));
if (IsAmmoMenuFullyOpen) {
ammoSlotGroup.Draw(g);
}
if (currentSlotGroup != null) {
DrawSlotCursor(g, currentSlotGroup.CurrentSlot);
}
}
}
public override void DrawSlotCursor(Graphics2D g, Slot slot) {
if (!inSubMenu) {
base.DrawSlotCursor(g, slot);
}
else if (IsAmmoMenuFullyOpen) {
//ISprite arrowSprite = GameData.SHEET_MENU_SMALL_LIGHT.GetSprite(5, 5);
g.DrawSprite(GameData.SPR_HUD_AMMO_SELECT_ARROW, slot.Position + new Point2I(4, 20));
}
}
//-----------------------------------------------------------------------------
// Properties
//-----------------------------------------------------------------------------
private Slot NextAvailableSlot {
get {
for (int i = 0; i < slotGroups[0].NumSlots; i++) {
if (slotGroups[0].GetSlotAt(i).SlotItem == null)
return slotGroups[0].GetSlotAt(i);
}
return null;
}
}
private bool IsAmmoMenuFullyOpen {
get {
return (ammoMenuSize.X == (ammoSlotGroup.NumSlots * 24 + 8) &&
ammoMenuSize.Y == 32);
}
}
private bool DrawAmmoMenuAtTop {
get { return (slotGroups[0].CurrentSlotIndex >= 8); }
}
}
}
| 33.368421
| 145
| 0.628436
|
[
"MIT"
] |
trigger-death/ZeldaOracle
|
ZeldaOracle/Game/Game/Control/Menus/MenuWeapons.cs
| 13,316
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Owlvey.Falcon.Core.Entities
{
public partial class MemberEntity: BaseEntity
{
public virtual SquadEntity Squad { get; set; }
public int SquadId { get; set; }
public virtual UserEntity User { get; set; }
public int UserId { get; set; }
}
}
| 26.4375
| 54
| 0.659574
|
[
"Apache-2.0"
] |
owlvey/owlvey_falcon
|
src/Owlvey.Falcon.Core/Entities/MemberEntity.cs
| 425
|
C#
|
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CC.Blazor.Dx;
public partial class CcToast
{
[Inject] CcToastService ToastSrv { get; set; }
protected override void OnInitialized()
{
ToastSrv.CcToastRef = this;
base.OnInitialized();
}
readonly ConcurrentDictionary<CcToastConfig, CancellationTokenSource> _messages = new ConcurrentDictionary<CcToastConfig, CancellationTokenSource>();
protected override void OnAfterRender(bool firstRender)
{
foreach (var kvp in _messages)
RemoveMessageAsync(kvp.Key, kvp.Value.Token);
}
async void RemoveMessageAsync(CcToastConfig config, CancellationToken ct)
{
await Task.Yield();
try
{
await Task.Delay(config.Duration ?? ToastSrv.Duration, ct);
await InvokeAsync(() =>
{
if (_messages.TryRemove(config, out var cts))
{
cts.Dispose();
StateHasChanged();
}
});
}
catch (Exception) { }
}
CancellationTokenSource AddValueFactory(CcToastConfig key)
{
InvokeAsync(StateHasChanged);
return new CancellationTokenSource();
}
CancellationTokenSource UpdateValueFactory(CcToastConfig config, CancellationTokenSource cts)
{
using (cts)
cts.Cancel();
cts = new CancellationTokenSource();
RemoveMessageAsync(config, cts.Token);
return cts;
}
public void OnNext(CcToastConfig msg)
{
_messages.AddOrUpdate(msg, AddValueFactory, UpdateValueFactory);
}
internal void OnClose(CcToastConfig msg)
{
if (_messages.TryRemove(msg, out var cts))
{
cts.Dispose();
StateHasChanged();
}
}
internal void OnRefresh()
{
InvokeAsync(StateHasChanged);
}
}
public class CcToastService
{
public int Duration { get; set; } = 5000;
internal CcToast CcToastRef { get; set; }
/// <summary>
/// 显示提示
/// </summary>
/// <param name="config"></param>
public void Show(CcToastConfig config)
{
CcToastRef.OnNext(config);
}
public void Refresh()
{
CcToastRef.OnRefresh();
}
/// <summary>
/// 关闭提示
/// </summary>
/// <param name="msgConfig"></param>
public void Close(CcToastConfig msgConfig)
{
CcToastRef.OnClose(msgConfig);
}
public void Info(string message)
{
CcToastRef.OnNext(new CcToastConfig()
{
Title = "提示",
Message = message,
});
}
public void Success(string message)
{
CcToastRef.OnNext(new CcToastConfig()
{
Title = "成功",
Message = message,
IconCssClass = "fas fa-check",
ToastType = CcToastType.Success,
});
}
public void Error(string message)
{
CcToastRef.OnNext(new CcToastConfig()
{
Title = "错误",
Message = message,
IconCssClass = "fas fa-times",
ToastType = CcToastType.Error,
});
}
public void Warning(string message)
{
CcToastRef.OnNext(new CcToastConfig()
{
Title = "警告",
Message = message,
IconCssClass = "fas fa-exclamation-triangle",
ToastType = CcToastType.Warning,
});
}
}
public class CcToastConfig
{
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
public string Subtitle { get; set; }
public string Message { get; set; }
public CcToastType ToastType { get; set; } = CcToastType.Info;
internal string ToastTypeCss => ToastType switch
{
CcToastType.Info => "",
CcToastType.Error => "border-danger",
CcToastType.Warning => "border-warning",
CcToastType.Success => "border-success",
_ => "",
};
internal long ShowSort { get; set; } = DateTime.Now.Ticks;
/// <summary>
/// 图标
/// </summary>
public string IconCssClass { get; set; } = "far fa-comment-alt";
/// <summary>
/// 延迟时间
/// </summary>
public int? Duration { get; set; }
/// <summary>
/// 关闭按钮
/// </summary>
public bool ShowCloseButton { get; set; } = true;
}
public enum CcToastType
{
Success,
Error,
Warning,
Info,
}
| 22.349515
| 153
| 0.572328
|
[
"MIT"
] |
TimChen44/CC.Blazor
|
CC.Blazor.Dx/Components/CcToast.razor.cs
| 4,662
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using IB.WatchServer.Abstract.Entity;
using IB.WatchServer.Service.Entity;
using IB.WatchServer.Service.Entity.Settings;
using IB.WatchServer.Abstract.Entity.WatchFace;
using IB.WatchServer.Service.Migrations;
using IB.WatchServer.Service.Service;
using IB.WatchServer.Service.Service.HttpClients;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Moq.Contrib.HttpClient;
using Xunit;
using Xunit.Abstractions;
namespace IB.WatchServer.XUnitTest.IntegrationTests
{
public class YafControllerGetNoDatabaseTest : IClassFixture<ServiceAppTestFixture>, IDisposable
{
private readonly ServiceAppTestFixture _factory;
private readonly HttpClient _client;
private readonly decimal _lat;
private readonly decimal _lon;
private readonly Mock<HttpMessageHandler> _handler;
public void Dispose() => _factory.Output = null;
public YafControllerGetNoDatabaseTest(ServiceAppTestFixture factory, ITestOutputHelper output)
{
factory.Output = output;
_factory = factory;
// Mock database
//
var dataProviderMock = new Mock<PostgresDataProvider>(null, null, null, null);
// Mock kafka
//
var kafkaProviderMock = new Mock<KafkaProvider>(TestHelper.GetKafkaSettings(), TestHelper.GetLoggerMock<KafkaProvider>().Object);
// Mock web requests
//
var faceSettings = _factory.Services.GetRequiredService<FaceSettings>();
var openWeatherResponse =
"{\"coord\":{\"lon\":-94.8,\"lat\":38.88},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"}],\"base\":\"stations\",\"main\":{\"temp\":4.28,\"feels_like\":0.13,\"temp_min\":3,\"temp_max\":5.56,\"pressure\":1034,\"humidity\":51},\"visibility\":16093,\"wind\":{\"speed\":2.21,\"deg\":169},\"clouds\":{\"all\":1},\"dt\":1584811457,\"sys\":{\"type\":1,\"id\":5188,\"country\":\"US\",\"sunrise\":1584793213,\"sunset\":1584837126},\"timezone\":-18000,\"id\":4276614,\"name\":\"Olathe\",\"cod\":200}";
var darkSkyResponse =
"{\"currently\":{\"time\":1584864023,\"summary\":\"Possible Drizzle\",\"icon\":\"rain\",\"precipIntensity\":0.2386,\"precipProbability\":0.4,\"precipType\":\"rain\",\"temperature\":9.39,\"apparentTemperature\":8.3,\"dewPoint\":9.39,\"humidity\":1,\"pressure\":1010.8,\"windSpeed\":2.22,\"windGust\":3.63,\"windBearing\":71,\"cloudCover\":0.52,\"uvIndex\":1,\"visibility\":16.093,\"ozone\":391.9},\"offset\":1}";
var locationResponse =
"{\"resourceSets\": [{\"resources\": [{\"name\": \"Olathe, KS\", \"address\": { \"adminDistrict\": \"KS\",\"adminDistrict2\": \"Johnson Co.\",\"countryRegion\": \"United States\",\"formattedAddress\": \"Olathe, KS\",\"locality\": \"Olathe\"}}]}]}";
var ccResponse = "{\"USD_DKK\": 1.1}";
_lat = (decimal) 38.855652;
_lon = (decimal)-94.799712;
_handler = new Mock<HttpMessageHandler>();
_handler.SetupRequest(HttpMethod.Get, faceSettings.BuildOpenWeatherUrl(_lat, _lon))
.ReturnsResponse(openWeatherResponse, "application/json");
_handler.SetupRequest(HttpMethod.Get, faceSettings.BuildDarkSkyUrl(_lat, _lon, "fake-key"))
.ReturnsResponse(darkSkyResponse, "application/json");
_handler.SetupRequest(HttpMethod.Get, faceSettings.BuildDarkSkyUrl(_lat, _lon, "wrong-key"))
.ReturnsResponse(HttpStatusCode.Unauthorized);
_handler.SetupRequest(HttpMethod.Get, faceSettings.BuildLocationUrl(_lat, _lon))
.ReturnsResponse(locationResponse, "application/json");
_handler.SetupRequest(HttpMethod.Get, faceSettings.BuildOpenWeatherUrl(0, 0))
.ReturnsResponse(HttpStatusCode.BadRequest);
_handler.SetupRequest(HttpMethod.Get, faceSettings.BuildCurrencyConverterUrl("USD", "DKK"))
.ReturnsResponse(ccResponse, "application/json");
var httpFactory = _handler.CreateClientFactory();
// Set Mock services on DI
//
_client = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddSingleton(_ => httpFactory);
services.AddScoped(_ => dataProviderMock.Object);
services.AddSingleton(kafkaProviderMock.Object);
});
})
.CreateClient();
}
[Fact]
public async Task NextRequestWithTheSameDeviceWithin5SecShouldReturn429()
{
// Arrange
//
var expected = new ErrorResponse
{
StatusCode = 429,
Description = "Too many requests, retry after 5"
};
var expectedJson = JsonSerializer.Serialize(expected);
// Act
//
var faceSetting = _factory.Services.GetRequiredService<FaceSettings>();
var url = $"/api/v2/YAFace?apiToken={faceSetting.AuthSettings.Token}&did=test-device10";
await _client.GetAsync(url);
var response = await _client.GetAsync(url);
// Assert
//
Assert.Equal(HttpStatusCode.TooManyRequests, response.StatusCode); // Status Code 429
Assert.Equal(expectedJson, await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task WrongTokenShouldReturnAuthError()
{
// Act
//
var url = $"/api/v2/YAFace?apiToken=wrong-token&did=test-device11";
await _client.GetAsync(url);
var responseWrong = await _client.GetAsync(url);
// Assert
//
Assert.Equal(HttpStatusCode.Forbidden, responseWrong.StatusCode); // Status Code 403
}
[Fact]
public async Task WrongApiVersionShouldReturnError()
{
// Act
//
var response = await _client.GetAsync($"/api/v1/YAFace");
// Assert
//
Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode);
var error = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync(), typeof(ErrorResponse));
Assert.IsType<ErrorResponse>(error);
}
[Fact]
public async Task NullRequestShouldReturnEmptyResponse()
{
// Arrange
//
var expected = new WatchResponse();
var expectedJson = JsonSerializer.Serialize(expected);
// Act
//
var faceSetting = _factory.Services.GetRequiredService<FaceSettings>();
var response = await _client.GetAsync($"/api/v2/YAFace?apiToken={faceSetting.AuthSettings.Token}");
// Assert
//
response.EnsureSuccessStatusCode(); // Status Code 2xx
Assert.Equal(expectedJson, await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task CorrectExchangeRequestShouldReturnCurrency()
{
// Arrange
//
var expected = new WatchResponse
{
ExchangeRateInfo = new ExchangeRateInfo
{
RequestStatus = new RequestStatus(RequestStatusCode.Ok),
ExchangeRate = (decimal) 1.1
}
};
// Act
//
var faceSetting = _factory.Services.GetRequiredService<FaceSettings>();
var url = $"/api/v2/YAFace?apiToken={faceSetting.AuthSettings.Token}&did=test-device12&bc=USD&tc=DKK";
var response = await _client.GetAsync(url);
// Assert
//
response.EnsureSuccessStatusCode();
var actual = JsonSerializer.Deserialize<WatchResponse>(await response.Content.ReadAsStringAsync());
Assert.Equal(expected.ExchangeRateInfo.ExchangeRate, actual.ExchangeRateInfo.ExchangeRate);
Assert.Equal(RequestStatusCode.Ok, actual.ExchangeRateInfo.RequestStatus.StatusCode);
}
[Fact]
public async Task OnExceptionShouldReturnBadRequest()
{
// Arrange
//
var expected = new ErrorResponse
{
StatusCode = 400,
Description = "Bad request"
};
var expectedJson = JsonSerializer.Serialize(expected);
var faceSettings = _factory.Services.GetRequiredService<FaceSettings>();
//_handler.SetupAnyRequest().Throws(new Exception());
var url = $"/api/v2/YAFace?apiToken={faceSettings.AuthSettings.Token}&did=test-device14&bc=DKK&tc=CHF";
// Act
//
var response = await _client.GetAsync(url);
// Assert
//
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); // Status Code 400
Assert.Equal(expectedJson, await response.Content.ReadAsStringAsync());
}
}
}
| 41.823789
| 551
| 0.597535
|
[
"MIT"
] |
Laverlin/WatchServer
|
IB.WatchServer.XUnitTest/IntegrationTests/YafControllerGetNoDatabaseTest.cs
| 9,496
|
C#
|
// This is part of Favalon project - https://github.com/kekyo/Favalon
// Copyright (c) 2019 Kouji Matsui
//
// 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 System.Runtime.CompilerServices
{
#if NET40 || NET45 || NETSTANDARD1_0
public static class FormattableStringFactory
{
private sealed class ConcreteFormattableString : FormattableString
{
private readonly object[] arguments;
public ConcreteFormattableString(string format, object[] arguments)
{
this.Format = format;
this.arguments = arguments;
}
public override string Format { get; }
public override int ArgumentCount => arguments.Length;
public override object GetArgument(int index) => arguments[index];
public override object[] GetArguments() => arguments;
public override string ToString(IFormatProvider formatProvider) =>
string.Format(formatProvider, this.Format, arguments);
}
public static FormattableString Create(string format, params object[] arguments) =>
new ConcreteFormattableString(format, arguments);
}
#endif
}
| 35.9375
| 91
| 0.678261
|
[
"Apache-2.0"
] |
kekyo/Favalon.PoC
|
Favalon.5/Favalon.Core/Compat/FormattableStringFactory.cs
| 1,727
|
C#
|
using component.logger;
using iot.solution.model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using EF = iot.solution.model.Models;
using Entity = iot.solution.entity;
namespace iot.solution.model
{
public class UnitOfWork : IUnitOfWork
{
public UnitOfWork(DbContext dbContext, ILogger logManager)
{
if (dbContext == null)
throw new ArgumentNullException("DBContext cannot be null.");
if (logManager == null)
throw new ArgumentNullException("LogManager cannot be null");
DbContext = (EF.devairqualityContext) dbContext;
_logger = logManager;
}
private bool _disposed;
private readonly ILogger _logger;
private IDbContextTransaction _transaction { get; set; }
public bool InTransaction { get; private set; }
public EF.devairqualityContext DbContext { get; }
public virtual void BeginTransaction()
{
_logger.Information(Constants.ACTION_ENTRY, "UnitOfWork.BeginTransaction");
try
{
InTransaction = true;
_transaction = DbContext.Database.BeginTransaction();
_logger.Information(Constants.ACTION_EXIT, "UnitOfWork.BeginTransaction");
}
catch (Exception ex)
{
_logger.Error(Constants.ACTION_EXCEPTION + ":UnitofWork.BeginTransaction", ex);
throw;
}
}
public virtual Entity.ActionStatus EndTransaction()
{
_logger.Information(Constants.ACTION_ENTRY, "UnitOfWork.EndTransaction");
var status = new Entity.ActionStatus();
try
{
if (_disposed) throw new ObjectDisposedException(GetType().FullName);
DbContext.SaveChanges();
_transaction.Commit();
InTransaction = false;
status.Success = true;
}
//catch (DbEntityValidationException dbEx)
//{
// _logger.Error(Constants.ACTION_EXCEPTION + ":UnitofWork.EndTransaction", dbEx);
// status.Message = dbEx.Message;
// status.Success = false;
// _inTransaction = false;
//}
catch (Exception ex)
{
_logger.Error(Constants.ACTION_EXCEPTION + ":UnitofWork.SaveAndContinue", ex);
status.Message = ex.Message;
status.Success = false;
}
_logger.Information(Constants.ACTION_EXIT, "UnitOfWork.EndTransaction");
return status;
}
public virtual void RollBack()
{
_logger.Information(Constants.ACTION_ENTRY, "UnitOfWork.RollBack");
try
{
_transaction.Rollback();
_transaction.Dispose();
InTransaction = false;
}
catch (Exception ex)
{
_logger.Error(Constants.ACTION_EXCEPTION + ":UnitofWork.BeginTransaction", ex);
throw;
}
_logger.Information(Constants.ACTION_EXIT, "UnitOfWork.RollBack");
}
public virtual Entity.ActionStatus SaveAndContinue()
{
_logger.Information(Constants.ACTION_ENTRY, "UnitOfWork.SaveAndContinue");
var status = new Entity.ActionStatus();
try
{
DbContext.SaveChanges();
status.Success = true;
}
//catch (DbEntityValidationException dbEx)
//{
// _logger.Error(Constants.ACTION_EXCEPTION + ":UnitofWork.SaveAndContinue", dbEx);
// var errorMessages = dbEx.EntityValidationErrors
// .SelectMany(x => x.ValidationErrors)
// .Select(x => x.ErrorMessage);
// status.Message = string.Join("; ", errorMessages);
// status.Success = false;
//}
catch (Exception ex)
{
_logger.Error(Constants.ACTION_EXCEPTION + ":UnitofWork.SaveAndContinue", ex);
status.Message = ex.Message;
status.Success = false;
}
_logger.Information(Constants.ACTION_EXIT, "UnitOfWork.SaveAndContinue");
return status;
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing && DbContext != null && InTransaction) _transaction.Dispose();
if (disposing && DbContext != null) DbContext.Dispose();
_disposed = true;
}
public void Dispose()
{
_logger.Information(Constants.ACTION_ENTRY, "UnitOfWork.Dispose");
Dispose(true);
GC.SuppressFinalize(this);
_logger.Information(Constants.ACTION_EXIT, "UnitOfWork.Dispose");
}
}
}
| 36.89781
| 98
| 0.558259
|
[
"MIT"
] |
iotconnect-apps/AppConnect-AirQualityMonitoring
|
iot.solution.model/UnitOfWork/Implementation/UnitOfWork.cs
| 5,057
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GeotrackerShapefileMaker.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.774194
| 152
| 0.570784
|
[
"MIT"
] |
Zedalve/GeoTracker_Shapefile_Creator
|
Properties/Settings.Designer.cs
| 1,111
|
C#
|
// Copyright © 2012 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InterfaceFactory;
using VirtualRadar.Interface.Listener;
using VirtualRadar.Interface.Network;
namespace VirtualRadar.Interface.Network
{
/// <summary>
/// The interface for a singleton object that can configure and control a collection of <see cref="IRebroadcastServer"/>s.
/// </summary>
[Singleton]
public interface IRebroadcastServerManager : IBackgroundThreadExceptionCatcher, IDisposable
{
/// <summary>
/// Gets the collection of rebroadcast servers that are being controlled by the manager.
/// </summary>
List<IRebroadcastServer> RebroadcastServers { get; }
/// <summary>
/// Gets or sets a flag indicating that the server is online.
/// </summary>
/// <remarks>
/// Setting this to false does not disconnect the clients attached to the <see cref="RebroadcastServers"/>,
/// it just stops sending bytes to them. To disconnect the clients you need to dispose of the provider
/// and create a new one after you go offline.
/// </remarks>
bool Online { get; set; }
/// <summary>
/// Raised when <see cref="Online"/> changes.
/// </summary>
event EventHandler OnlineChanged;
/// <summary>
/// Raised when a client connects to one of the servers.
/// </summary>
event EventHandler<ConnectionEventArgs> ClientConnected;
/// <summary>
/// Raised when a client disconnects from one of the servers.
/// </summary>
event EventHandler<ConnectionEventArgs> ClientDisconnected;
/// <summary>
/// Creates the initial collection of rebroadcast servers from the configuration settings.
/// </summary>
void Initialise();
/// <summary>
/// Returns a list of objects describing all of the connections to the rebroadcast servers.
/// </summary>
List<RebroadcastServerConnection> GetConnections();
}
}
| 54.073529
| 750
| 0.697308
|
[
"BSD-3-Clause"
] |
AlexAX135/vrs
|
VirtualRadar.Interface/Network/IRebroadcastServerManager.cs
| 3,680
|
C#
|
namespace BuddyApiClient.Variables.Models.Request
{
using System.Text.Json.Serialization;
using BuddyApiClient.Actions.Models;
public sealed record Action : IScope
{
[JsonPropertyName("id")]
public ActionId Id { get; set; }
}
}
| 24.090909
| 50
| 0.675472
|
[
"MIT"
] |
logikfabrik/BuddyApiClient
|
src/BuddyApiClient/Variables/Models/Request/Action.cs
| 267
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Microsoft.DotNet.XHarness.CLI.CommandArguments.Android;
internal class AndroidAdbCommandArguments : XHarnessCommandArguments
{
public TimeoutArgument Timeout { get; set; } = new(TimeSpan.FromMinutes(1));
protected override IEnumerable<Argument> GetArguments() => new[]
{
Timeout,
};
}
| 30.263158
| 80
| 0.751304
|
[
"MIT"
] |
jkoritzinsky/xharness
|
src/Microsoft.DotNet.XHarness.CLI/CommandArguments/Android/AndroidAdbCommandArguments.cs
| 577
|
C#
|
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatch), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatch")]
public interface IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatch
{
/// <summary>all_query_arguments block.</summary>
[JsiiProperty(name: "allQueryArguments", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchAllQueryArguments\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchAllQueryArguments[]? AllQueryArguments
{
get
{
return null;
}
}
/// <summary>body block.</summary>
[JsiiProperty(name: "body", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchBody\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchBody[]? Body
{
get
{
return null;
}
}
/// <summary>method block.</summary>
[JsiiProperty(name: "method", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchMethod\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchMethod[]? Method
{
get
{
return null;
}
}
/// <summary>query_string block.</summary>
[JsiiProperty(name: "queryString", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryString\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryString[]? QueryString
{
get
{
return null;
}
}
/// <summary>single_header block.</summary>
[JsiiProperty(name: "singleHeader", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleHeader\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleHeader[]? SingleHeader
{
get
{
return null;
}
}
/// <summary>single_query_argument block.</summary>
[JsiiProperty(name: "singleQueryArgument", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleQueryArgument\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleQueryArgument[]? SingleQueryArgument
{
get
{
return null;
}
}
/// <summary>uri_path block.</summary>
[JsiiProperty(name: "uriPath", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchUriPath\"},\"kind\":\"array\"}}", isOptional: true)]
[Amazon.JSII.Runtime.Deputy.JsiiOptional]
aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchUriPath[]? UriPath
{
get
{
return null;
}
}
[JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatch), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatch")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatch
{
private _Proxy(ByRefValue reference): base(reference)
{
}
/// <summary>all_query_arguments block.</summary>
[JsiiOptional]
[JsiiProperty(name: "allQueryArguments", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchAllQueryArguments\"},\"kind\":\"array\"}}", isOptional: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchAllQueryArguments[]? AllQueryArguments
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchAllQueryArguments[]?>();
}
/// <summary>body block.</summary>
[JsiiOptional]
[JsiiProperty(name: "body", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchBody\"},\"kind\":\"array\"}}", isOptional: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchBody[]? Body
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchBody[]?>();
}
/// <summary>method block.</summary>
[JsiiOptional]
[JsiiProperty(name: "method", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchMethod\"},\"kind\":\"array\"}}", isOptional: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchMethod[]? Method
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchMethod[]?>();
}
/// <summary>query_string block.</summary>
[JsiiOptional]
[JsiiProperty(name: "queryString", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryString\"},\"kind\":\"array\"}}", isOptional: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryString[]? QueryString
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryString[]?>();
}
/// <summary>single_header block.</summary>
[JsiiOptional]
[JsiiProperty(name: "singleHeader", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleHeader\"},\"kind\":\"array\"}}", isOptional: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleHeader[]? SingleHeader
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleHeader[]?>();
}
/// <summary>single_query_argument block.</summary>
[JsiiOptional]
[JsiiProperty(name: "singleQueryArgument", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleQueryArgument\"},\"kind\":\"array\"}}", isOptional: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleQueryArgument[]? SingleQueryArgument
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchSingleQueryArgument[]?>();
}
/// <summary>uri_path block.</summary>
[JsiiOptional]
[JsiiProperty(name: "uriPath", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchUriPath\"},\"kind\":\"array\"}}", isOptional: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchUriPath[]? UriPath
{
get => GetInstanceProperty<aws.IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatchUriPath[]?>();
}
}
}
}
| 60.401316
| 257
| 0.693933
|
[
"MIT"
] |
scottenriquez/cdktf-alpha-csharp-testing
|
resources/.gen/aws/aws/IWafv2WebAclRuleStatementOrStatementStatementSizeConstraintStatementFieldToMatch.cs
| 9,181
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Romontinka.Server.Core;
using Romontinka.Server.Core.Security;
using Romontinka.Server.WebSite.Common;
namespace Romontinka.Server.WebSite.Controllers
{
/// <summary>
/// Комбобокс с документами.
/// </summary>
[Authorize]
public class AjaxCustomReportComboBoxController: AjaxComboBoxBaseController<Guid>
{
/// <summary>
/// Переопределяется для получения переопределенного списка с пунктами.
/// </summary>
/// <param name="token">Токен безопасности. </param>
/// <param name="list">Список который необходимо инициализировать.</param>
/// <param name="selectedId"> Выбранный пункт.</param>
/// <param name="parentValue">Значение родительского контрола.</param>
public override void GetInitializedItems(SecurityToken token,List<JSelectListItem<Guid>> list, Guid? selectedId, string parentValue)
{
foreach (var customReportItem in RemontinkaServer.Instance.EntitiesFacade.GetCustomReportItems(token))
{
list.Add(new JSelectListItem<Guid>
{
Text = customReportItem.Title,
Value = customReportItem.CustomReportID,
Selected = selectedId == customReportItem.CustomReportID
});
}
}
}
}
| 39.763158
| 140
| 0.622105
|
[
"MIT"
] |
alexs0ff/remboard
|
Server/Romontinka.Server.WebSite/Controllers/AjaxCustomReportComboBoxController.cs
| 1,693
|
C#
|
using System.Collections.Generic;
namespace CSETWebCore.Model.Aggregation
{
public class BestToWorstCategory
{
public string Category { get; set; }
public List<GetComparisonBestToWorst> Assessments { get; set; }
}
}
| 24.5
| 71
| 0.702041
|
[
"MIT"
] |
Project-CSET-RM-Module/cset
|
CSETWebApi/CSETWeb_Api/CSETWebCore.Model/Aggregation/BestToWorstCategory.cs
| 247
|
C#
|
using System.Collections.Generic;
using System;
namespace windows
{
public class ListTest
{
public static void test()
{
var names = new List<string> { "<name>", "Ana", "Felipe" };
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
names.Add("Maria");
names.Add("Bill");
names.Remove("Ana");
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
Console.WriteLine($"The list has {names.Count} people in it");
var index = names.IndexOf("Felipe");
if (index == -1)
{
Console.WriteLine($"When an item is not found, IndexOf returns {index}");
}
else
{
Console.WriteLine($"The name {names[index]} is at index {index}");
}
names.Sort();
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
}
}
}
| 30.184211
| 89
| 0.4551
|
[
"Unlicense"
] |
jufeng98/b2c-master
|
windows/ListTest.cs
| 1,147
|
C#
|
using OrchardCore.ContentManagement;
namespace OrchardCore.Forms.Models
{
public class FormPart : ContentPart
{
public string Action { get; set; }
public string Method { get; set; }
public string WorkflowTypeId { get; set; }
public string EncType { get; set; }
public bool EnableAntiForgeryToken { get; set; } = true;
}
}
| 26.785714
| 64
| 0.642667
|
[
"BSD-3-Clause"
] |
1051324354/OrchardCore
|
src/OrchardCore.Modules/OrchardCore.Forms/Models/FormPart.cs
| 375
|
C#
|
/*
The MIT License (MIT)
Copyright (c) 2007 - 2021 Microting A/S
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.
*/
namespace Microting.EformBackendConfigurationBase.Infrastructure.Data.Entities
{
public class ProperyAreaFolder: PnBase
{
public int ProperyAreaAsignmentId { get; set; }
public int FolderId { get; set; }
public virtual AreaProperty AreaProperty { get; set; }
}
}
| 37.972973
| 78
| 0.769395
|
[
"MIT"
] |
microting/eform-backendconfiguration-base
|
Microting.EformBackendConfigurationBase/Infrastructure/Data/Entities/ProperyAreaFolder.cs
| 1,407
|
C#
|
using System;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Core.Response
{
/// <summary>
/// ZolozAuthenticationCustomerFacemanageCreateResponse.
/// </summary>
public class ZolozAuthenticationCustomerFacemanageCreateResponse : AopResponse
{
/// <summary>
/// 业务结果
/// </summary>
[XmlElement("result")]
public string Result { get; set; }
/// <summary>
/// 返回码
/// </summary>
[XmlElement("retcode")]
public string Retcode { get; set; }
/// <summary>
/// 返回详细码
/// </summary>
[XmlElement("retcodesub")]
public string Retcodesub { get; set; }
/// <summary>
/// 返回信息
/// </summary>
[XmlElement("retmessage")]
public string Retmessage { get; set; }
/// <summary>
/// 返回详细信息
/// </summary>
[XmlElement("retmessagesub")]
public string Retmessagesub { get; set; }
}
}
| 23.809524
| 82
| 0.533
|
[
"MIT"
] |
KenyonLi/Alipay.AopSdk.Core
|
Alipay.AopSdk.Core/Response/ZolozAuthenticationCustomerFacemanageCreateResponse.cs
| 1,044
|
C#
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using FluentAssertions;
using IdentityModel.Jwk;
namespace IdentityModel.HttpSigning.Tests.Confirmation
{
public class JwkTests
{
[Fact]
public void invalid_key_type_should_throw()
{
var jwk = new JsonWebKey
{
Kty = "foo",
K = "1234",
E = "1234",
N = "abc"
};
Assert.Throws<InvalidOperationException>(() => jwk.ToPublicKey());
}
[Fact]
public void symmetric_key_type_should_create_correct_public_key_object()
{
var jwk = new JsonWebKey
{
Kty = "oct",
Alg = "HS256",
K = "1234"
};
var key = jwk.ToPublicKey();
key.Should().BeOfType<SymmetricKey>();
}
[Fact]
public void asymmetric_key_type_should_create_correct_public_key_object()
{
var jwk = new JsonWebKey
{
Kty = "RSA",
Alg = "RS256",
E = "1234",
N = "abc"
};
var key = jwk.ToPublicKey();
key.Should().BeOfType<RSAPublicKey>();
}
}
}
| 25.048387
| 107
| 0.519639
|
[
"Apache-2.0"
] |
cuteant/IdentityModel
|
test/IdentityModel.HttpSigning.Tests/Confirmation/JwkTests.cs
| 1,555
|
C#
|
using Umbraco.Core.Models;
namespace Endzone.uSplit.Models
{
public interface IPublishedContentVariation
{
/// <summary>
/// Might be null for server-side variation
/// </summary>
IPublishedContent Content { get; set; }
/// <summary>
/// The 0-based index of chosen variation
/// </summary>
int GoogleVariationId { get; set; }
string GoogleExperimentId { get; set; }
}
}
| 25.388889
| 51
| 0.588621
|
[
"Unlicense"
] |
EndzoneSoftware/uSplit
|
src/Endzone.uSplit/Models/IPublishedContentVariation.cs
| 459
|
C#
|
using System;
using System.Linq;
using DocsBr.Utils;
namespace DocsBr.Validation.IE
{
/// <summary>
/// Validação da IE de Maranhão
/// </summary>
/// <remarks>
/// ROTEIRO DE CRÍTICA DA INSCRIÇÃO ESTADUAL:
/// http://www.sintegra.gov.br/Cad_Estados/cad_MA.html
/// </remarks>
public class IEMaranhaoValidator : IIEValidator
{
private string inscEstadual;
public IEMaranhaoValidator(string inscEstadual)
{
this.inscEstadual = new OnlyNumbers(inscEstadual).ToString();
}
public bool IsValid()
{
if (!IsSizeValid()) return false;
if (!BeginsCorrectly()) return false;
return HasValidCheckDigits();
}
private bool IsSizeValid()
{
return this.inscEstadual.Length == 9;
}
private bool BeginsCorrectly()
{
return this.inscEstadual.Substring(0, 2) == "12";
}
private bool HasValidCheckDigits()
{
string number = this.inscEstadual.Substring(0, this.inscEstadual.Length - 1);
DigitoVerificador digitoVerificador = new DigitoVerificador(number)
.ComMultiplicadoresDeAte(2, 9)
.Substituindo("0", 0, 1);
return digitoVerificador.CalculaDigito() == this.inscEstadual.Substring(this.inscEstadual.Length - 1, 1);
}
}
}
| 30.04
| 117
| 0.557923
|
[
"MIT"
] |
WalissonPires/docsbr.net
|
DocsBr/Validation/IE/IEMaranhaoValidator.cs
| 1,510
|
C#
|
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace SrkToolkit.WildServiceRef.Clients {
partial class BaseHttpClient {
#region Assisted HTTP query
protected string GetStringResponse(string action, params string[] keyValues) {
Dictionary<string, string> postParams = null;
return GetStringResponse(action, HttpTools.GetDictionaryFromKeyValues(keyValues), postParams);
}
#endregion
#region HTTP query
/// <summary>
/// Execute a HTTP request with optional POST parameters. Returns HTTP response body as a string.
/// </summary>
/// <param name="action"></param>
/// <param name="queryParams"></param>
/// <param name="postParams"></param>
/// <returns></returns>
protected virtual string GetStringResponse(string action, Dictionary<string, string> queryParams, Dictionary<string, string> postParams) {
string url = string.Format(UrlFormat, BaseUrl, action, HttpTools.GetParamsAsQueryString(queryParams));
if (postParams == null)
return http.GetString(url);
else
return http.GetString(url, postParams);
}
/// <summary>
/// Execute a HTTP request with optional POST stream. Returns HTTP response body as a string.
/// </summary>
/// <param name="action"></param>
/// <param name="queryParams"></param>
/// <param name="postStream"></param>
/// <returns></returns>
protected virtual string GetStringResponse(string action, Dictionary<string, string> queryParams, Stream postStream) {
string url = string.Format(UrlFormat, BaseUrl, action, HttpTools.GetParamsAsQueryString(queryParams));
if (postStream == null)
return http.GetString(url);
else
return http.GetString(url, postStream);
}
/// <summary>
/// Execute a HTTP request with optional POST parameters. Returns HTTP response body as a stream.
/// </summary>
/// <param name="action"></param>
/// <param name="queryParams"></param>
/// <param name="postParams"></param>
/// <returns></returns>
protected virtual Stream GetStreamResponse(string action, Dictionary<string, string> queryParams, Dictionary<string, string> postParams) {
string url = string.Format(UrlFormat, BaseUrl, action, HttpTools.GetParamsAsQueryString(queryParams));
if (postParams == null)
return http.GetStream(url);
else
return http.GetStream(url, postParams);
}
/// <summary>
/// Execute a HTTP request with optional POST stream. Returns HTTP response body as a stream.
/// </summary>
/// <param name="action"></param>
/// <param name="queryParams"></param>
/// <param name="postStream"></param>
/// <returns></returns>
protected virtual Stream GetStreamResponse(string action, Dictionary<string, string> queryParams, Stream postStream) {
string url = string.Format(UrlFormat, BaseUrl, action, HttpTools.GetParamsAsQueryString(queryParams));
if (postStream == null)
return http.GetStream(url);
else
return http.GetStream(url, postStream);
}
/// <summary>
/// Execute a HTTP request with optional POST parameters. Returns a full HTTP response.
/// </summary>
/// <param name="action"></param>
/// <param name="queryParams"></param>
/// <param name="postParams"></param>
/// <returns></returns>
protected virtual HttpWebResponse GetFullResponse(string action, Dictionary<string, string> queryParams, Dictionary<string, string> postParams) {
string url = string.Format(UrlFormat, BaseUrl, action, HttpTools.GetParamsAsQueryString(queryParams));
if (postParams == null)
return http.GetResponse(url);
else
return http.GetResponse(url, postParams);
}
/// <summary>
/// Execute a HTTP request with optional POST stream. Returns a full HTTP response.
/// </summary>
/// <param name="action"></param>
/// <param name="queryParams"></param>
/// <param name="postStream"></param>
/// <returns></returns>
protected virtual HttpWebResponse GetFullResponse(string action, Dictionary<string, string> queryParams, Stream postStream) {
string url = string.Format(UrlFormat, BaseUrl, action, HttpTools.GetParamsAsQueryString(queryParams));
if (postStream == null)
return http.GetResponse(url);
else
return http.GetResponse(url, postStream);
}
#endregion
}
}
| 42.208333
| 154
| 0.592695
|
[
"Apache-2.0"
] |
sandrock/SrkToolkit
|
Sources/SrkToolkit.WildServiceRef/Clients/BaseHttpClient.cs
| 5,067
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a recurring charge.
/// </summary>
public partial class RecurringCharge
{
private double? _amount;
private RecurringChargeFrequency _frequency;
/// <summary>
/// Gets and sets the property Amount.
/// <para>
/// The amount of the recurring charge.
/// </para>
/// </summary>
public double Amount
{
get { return this._amount.GetValueOrDefault(); }
set { this._amount = value; }
}
// Check to see if Amount property is set
internal bool IsSetAmount()
{
return this._amount.HasValue;
}
/// <summary>
/// Gets and sets the property Frequency.
/// <para>
/// The frequency of the recurring charge.
/// </para>
/// </summary>
public RecurringChargeFrequency Frequency
{
get { return this._frequency; }
set { this._frequency = value; }
}
// Check to see if Frequency property is set
internal bool IsSetFrequency()
{
return this._frequency != null;
}
}
}
| 28
| 101
| 0.612857
|
[
"Apache-2.0"
] |
jasoncwik/aws-sdk-net
|
sdk/src/Services/EC2/Generated/Model/RecurringCharge.cs
| 2,100
|
C#
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace GuestBook.Data.Migrations
{
public partial class Initial_1 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 18.555556
| 71
| 0.667665
|
[
"MIT"
] |
olkerr/YMS8518
|
GuestBook/GuestBook.Data/Migrations/20191208122316_Initial_1.cs
| 336
|
C#
|
using System;
using System.Globalization;
namespace Qowaiv.TestTools
{
/// <summary>Represents the unit test format provider.</summary>
public class UnitTestFormatProvider : IFormatProvider, ICustomFormatter
{
/// <summary>Returns an object that provides formatting services for the specified type.</summary>
/// <param name="formatType">
/// The type of format object to return.
/// </param>
/// <remarks>
/// Supports ICustomFormatter.
/// </remarks>
public object GetFormat(Type formatType)
{
return (typeof(ICustomFormatter).IsAssignableFrom(formatType)) ? this : null;
}
/// <summary>Formats the object as String.</summary>
/// <param name="format">
/// The format to use.
/// </param>
/// <param name="arg">
/// The object to format.
/// </param>
/// <param name="formatProvider">
/// The specified formatProvider.
/// </param>
public string Format(string format, object arg, IFormatProvider formatProvider)
{
return string.Format(CultureInfo.InvariantCulture, "Unit Test Formatter, value: '{0}', format: '{1}'", arg?.ToString(), format);
}
}
}
| 34.540541
| 140
| 0.593114
|
[
"MIT"
] |
LauraXiulan/Qowaiv
|
src/Qowaiv.TestTools/UnitTestFormatProvider.cs
| 1,280
|
C#
|
using System.Xml.Serialization;
// Generated from cobertura XML schema
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace MergeCoberturaXml.CoberturaModel
{
[XmlRoot(ElementName = "class")]
public class Class
{
[XmlElement(ElementName = "methods")]
public Methods Methods { get; set; }
[XmlElement(ElementName = "lines")]
public Lines Lines { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "filename")]
public string Filename { get; set; }
[XmlAttribute(AttributeName = "line-rate")]
public float LineRate { get; set; }
[XmlAttribute(AttributeName = "branch-rate")]
public float BranchRate { get; set; }
[XmlAttribute(AttributeName = "complexity")]
public float Complexity { get; set; }
}
}
| 29.46875
| 89
| 0.640509
|
[
"MIT"
] |
marcelion/MergeCoberturaXml
|
src/MergeCoberturaXml/CoberturaModel/Class.cs
| 945
|
C#
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using CsvHelper;
using CsvHelper.Configuration;
using GeoUtility.GeoSystem;
using NmeaParser.Nmea.Gps;
using SteuerSoft.KoordinatenSammeln.Commands;
using SteuerSoft.KoordinatenSammeln.Model;
using SteuerSoft.KoordinatenSammeln.ViewModel.Base;
using SteuerSoft.Maps.Core.Material;
namespace SteuerSoft.KoordinatenSammeln.ViewModel
{
class MainViewModel : ViewModelBase
{
public ActionCommand CloseCommand { get; }
public ActionCommand SavePlaceCommand { get; }
public ConnectionViewModel ConnectionViewModel { get; } = new ConnectionViewModel();
public GpsData GpsData { get; set; } = new GpsData();
public Place CurrentPlace { get; set; } = new Place();
public MapPointLatLon MapLocation { get; set; }
private bool _trackOnMap = true;
public bool TrackMeOnMap
{
get { return _trackOnMap;}
set
{
_trackOnMap = value;
CanMoveMap = !value;
}
}
public bool CanMoveMap { get; set; } = false;
public bool SaveTrack { get; set; } = true;
public string LatStr { get; set; }
public string LonStr { get; set; }
public string DateStr { get; set; }
public string SpeedString { get; set; }
public string FixString { get; set; }
public string UtmrefString { get; set; }
public MainViewModel()
{
CloseCommand = new ActionCommand(CloseCommandAction);
SavePlaceCommand = new ActionCommand(SavePlace);
ConnectionViewModel.Received += ConnectionViewModel_Received;
}
private void ConnectionViewModel_Received(object sender, NmeaParser.NmeaMessageReceivedEventArgs e)
{
switch (e.Message)
{
case Gprmc rmc:
GpsData.FixInfo = FixString = rmc.Active ? "Fix" : "No Fix";
if (rmc.Active)
{
GpsData.Lat = rmc.Latitude;
LatStr = $"{rmc.Latitude:0.0000}";
GpsData.Lon = rmc.Longitude;
LonStr = $"{rmc.Longitude:0.0000}";
var dto = new DateTime(rmc.FixTime.Ticks, DateTimeKind.Utc);
GpsData.Time = dto.ToLocalTime();
DateStr = $"{GpsData.Time:dd.MM.yyyy HH:mm:ss}";
GpsData.Speed = rmc.Speed * 1.852;
SpeedString = $"{GpsData.Speed:0.0} km/h";
var latlon = new Geographic(rmc.Longitude, rmc.Latitude);
GpsData.UtmRef = UtmrefString = ((MGRS)latlon).ToString();
if (TrackMeOnMap)
{
MapLocation = new MapPointLatLon(rmc.Latitude, rmc.Longitude);
}
if (SaveTrack)
{
try
{
using (var fs = File.AppendText("track.csv"))
using (var csv = new CsvWriter(fs, new Configuration() { Delimiter = ";" }))
{
csv.WriteRecord(GpsData);
csv.NextRecord();
}
}
catch (Exception exception)
{
SaveTrack = false;
ConnectionViewModel.StatusText = $"Failed to write track. {exception.Message}";
}
}
}
break;
}
}
private void CloseCommandAction()
{
Environment.Exit(0);
}
private void SavePlace()
{
CurrentPlace.Lat = GpsData.Lat;
CurrentPlace.Lon = GpsData.Lon;
CurrentPlace.UtmRef = GpsData.UtmRef;
CurrentPlace.Time = DateTime.Now;
try
{
using (var fs = File.AppendText("places.csv"))
using (var csv = new CsvWriter(fs, new Configuration() { Delimiter = ";" }))
{
csv.WriteRecord(CurrentPlace);
csv.NextRecord();
}
CurrentPlace = new Place();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
}
| 31.73913
| 111
| 0.486693
|
[
"MIT"
] |
2steuer/steuersoft-maps
|
SteuerSoft.KoordinatenSammeln/ViewModel/MainViewModel.cs
| 5,112
|
C#
|
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using BuzzBot.Discord.Services;
namespace BuzzBot.Epgp
{
public class RaidRepository : IRaidRepository
{
private readonly ConcurrentDictionary<ulong, RaidData> _raids = new ConcurrentDictionary<ulong, RaidData>();
public IReadOnlyCollection<RaidData> GetRaids()
{
return _raids.Values.ToList().AsReadOnly();
}
public void AddOrUpdateRaid(RaidData raidData)
{
_raids.AddOrUpdate(raidData.Id, id => raidData, (id, data) => raidData);
}
public void RemoveRaid(ulong id)
{
_raids.TryRemove(id, out _);
}
public RaidData GetRaid(ulong id = 0)
{
if (id == 0) return _raids.Values.LastOrDefault();
return Contains(id) ? _raids[id] : null;
}
public bool Contains(ulong raidId)
{
return _raids.ContainsKey(raidId);
}
public int Count => _raids.Count;
}
}
| 27.230769
| 116
| 0.606403
|
[
"MIT"
] |
mfuqua3/BuzzBot
|
BuzzBot/BuzzBot/Epgp/RaidRepository.cs
| 1,064
|
C#
|
using System;
using System.Linq;
using System.Numerics;
using System.Reflection;
using Dalamud.Game.ClientState.Objects.Enums;
using Dalamud.Game.ClientState.Objects.SubKinds;
using Dalamud.Game.ClientState.Objects.Types;
using Dalamud.Interface;
using Dalamud.Logging;
using Glamourer.Customization;
using Glamourer.Designs;
using Glamourer.FileSystem;
using ImGuiNET;
using Penumbra.GameData.Structs;
using Penumbra.PlayerWatch;
namespace Glamourer.Gui
{
internal partial class Interface
{
private readonly CharacterSave _currentSave = new();
private string _newDesignName = string.Empty;
private bool _keyboardFocus;
private const string DesignNamePopupLabel = "Save Design As...";
private const uint RedHeaderColor = 0xFF1818C0;
private const uint GreenHeaderColor = 0xFF18C018;
private void DrawPlayerHeader()
{
var color = _player == null ? RedHeaderColor : GreenHeaderColor;
var buttonColor = ImGui.GetColorU32(ImGuiCol.FrameBg);
using var raii = new ImGuiRaii()
.PushColor(ImGuiCol.Text, color)
.PushColor(ImGuiCol.Button, buttonColor)
.PushColor(ImGuiCol.ButtonHovered, buttonColor)
.PushColor(ImGuiCol.ButtonActive, buttonColor)
.PushStyle(ImGuiStyleVar.ItemSpacing, Vector2.Zero)
.PushStyle(ImGuiStyleVar.FrameRounding, 0);
ImGui.Button($"{_currentLabel}##playerHeader", -Vector2.UnitX * 0.0001f);
}
private static void DrawCopyClipboardButton(CharacterSave save)
{
ImGui.PushFont(UiBuilder.IconFont);
if (ImGui.Button(FontAwesomeIcon.Clipboard.ToIconString()))
ImGui.SetClipboardText(save.ToBase64());
ImGui.PopFont();
ImGuiCustom.HoverTooltip("Copy customization code to clipboard.");
}
private static void ConditionalApply(CharacterSave save, Character player)
{
if (ImGui.GetIO().KeyShift)
save.ApplyOnlyCustomizations(player);
else if (ImGui.GetIO().KeyCtrl)
save.ApplyOnlyEquipment(player);
else
save.Apply(player);
}
private CharacterSave ConditionalCopy(CharacterSave save)
{
var copy = save.Copy();
if (ImGui.GetIO().KeyShift)
{
copy.Load(new CharacterEquipment());
copy.SetHatState = false;
copy.SetVisorState = false;
copy.SetWeaponState = false;
copy.WriteEquipment = CharacterEquipMask.None;
}
else if (ImGui.GetIO().KeyCtrl)
{
copy.Load(CharacterCustomization.Default);
copy.SetHatState = false;
copy.SetVisorState = false;
copy.SetWeaponState = false;
copy.WriteCustomizations = false;
}
return save.Copy();
}
private bool DrawApplyClipboardButton()
{
ImGui.PushFont(UiBuilder.IconFont);
var applyButton = ImGui.Button(FontAwesomeIcon.Paste.ToIconString()) && _player != null;
ImGui.PopFont();
ImGuiCustom.HoverTooltip("Apply customization code from clipboard.\nHold Shift to apply only customizations.\nHold Control to apply only equipment.");
if (!applyButton)
return false;
try
{
var text = ImGui.GetClipboardText();
if (!text.Any())
return false;
var save = CharacterSave.FromString(text);
ConditionalApply(save, _player!);
}
catch (Exception e)
{
PluginLog.Information($"{e}");
return false;
}
return true;
}
private void DrawSaveDesignButton()
{
ImGui.PushFont(UiBuilder.IconFont);
if (ImGui.Button(FontAwesomeIcon.Save.ToIconString()))
OpenDesignNamePopup(DesignNameUse.SaveCurrent);
ImGui.PopFont();
ImGuiCustom.HoverTooltip("Save the current design.\nHold Shift to save only customizations.\nHold Control to save only equipment.");
DrawDesignNamePopup(DesignNameUse.SaveCurrent);
}
private void DrawTargetPlayerButton()
{
if (ImGui.Button("Target Player"))
Dalamud.Targets.SetTarget(_player);
}
private void DrawApplyToPlayerButton(CharacterSave save)
{
if (!ImGui.Button("Apply to Self"))
return;
var player = _inGPose
? (Character?) Dalamud.Objects[GPoseObjectId]
: Dalamud.ClientState.LocalPlayer;
var fallback = _inGPose ? Dalamud.ClientState.LocalPlayer : null;
if (player == null)
return;
ConditionalApply(save, player);
if (_inGPose)
ConditionalApply(save, fallback!);
Glamourer.Penumbra.UpdateCharacters(player, fallback);
}
private static Character? TransformToCustomizable(Character? actor)
{
if (actor == null)
return null;
if (actor.ModelType() == 0)
return actor;
actor.SetModelType(0);
CharacterCustomization.Default.Write(actor.Address);
return actor;
}
private void DrawApplyToTargetButton(CharacterSave save)
{
if (!ImGui.Button("Apply to Target"))
return;
var player = TransformToCustomizable(CharacterFactory.Convert(Dalamud.Targets.Target));
if (player == null)
return;
var fallBackCharacter = _gPoseActors.TryGetValue(player.Name.ToString(), out var f) ? f : null;
ConditionalApply(save, player);
if (fallBackCharacter != null)
ConditionalApply(save, fallBackCharacter!);
Glamourer.Penumbra.UpdateCharacters(player, fallBackCharacter);
}
private void DrawRevertButton()
{
if (!DrawDisableButton("Revert", _player == null))
return;
Glamourer.RevertableDesigns.Revert(_player!);
var fallBackCharacter = _gPoseActors.TryGetValue(_player!.Name.ToString(), out var f) ? f : null;
if (fallBackCharacter != null)
Glamourer.RevertableDesigns.Revert(fallBackCharacter);
Glamourer.Penumbra.UpdateCharacters(_player, fallBackCharacter);
}
private void SaveNewDesign(CharacterSave save)
{
try
{
var (folder, name) = _designs.FileSystem.CreateAllFolders(_newDesignName);
if (!name.Any())
return;
var newDesign = new Design(folder, name) { Data = save };
folder.AddChild(newDesign);
_designs.Designs[newDesign.FullName()] = save;
_designs.SaveToFile();
}
catch (Exception e)
{
PluginLog.Error($"Could not save new design {_newDesignName}:\n{e}");
}
}
private void DrawMonsterPanel()
{
if (DrawApplyClipboardButton())
Glamourer.Penumbra.UpdateCharacters(_player!);
ImGui.SameLine();
if (ImGui.Button("Convert to Character"))
{
TransformToCustomizable(_player);
_currentLabel = _currentLabel.Replace("(Monster)", "(NPC)");
Glamourer.Penumbra.UpdateCharacters(_player!);
}
if (!_inGPose)
{
ImGui.SameLine();
DrawTargetPlayerButton();
}
var currentModel = _player!.ModelType();
using var raii = new ImGuiRaii();
if (!raii.Begin(() => ImGui.BeginCombo("Model Id", currentModel.ToString()), ImGui.EndCombo))
return;
foreach (var (id, _) in _models.Skip(1))
{
if (!ImGui.Selectable($"{id:D6}##models", id == currentModel) || id == currentModel)
continue;
_player!.SetModelType((int) id);
Glamourer.Penumbra.UpdateCharacters(_player!);
}
}
private void DrawPlayerPanel()
{
DrawCopyClipboardButton(_currentSave);
ImGui.SameLine();
var changes = !_currentSave.WriteProtected && DrawApplyClipboardButton();
ImGui.SameLine();
DrawSaveDesignButton();
ImGui.SameLine();
DrawApplyToPlayerButton(_currentSave);
if (!_inGPose)
{
ImGui.SameLine();
DrawApplyToTargetButton(_currentSave);
if (_player != null && !_currentSave.WriteProtected)
{
ImGui.SameLine();
DrawTargetPlayerButton();
}
}
var data = _currentSave;
if (!_currentSave.WriteProtected)
{
ImGui.SameLine();
DrawRevertButton();
}
else
{
ImGui.PushStyleVar(ImGuiStyleVar.Alpha, 0.8f);
data = data.Copy();
}
if (DrawCustomization(ref data.Customizations) && _player != null)
{
Glamourer.RevertableDesigns.Add(_player);
_currentSave.Customizations.Write(_player.Address);
changes = true;
}
changes |= DrawEquip(data.Equipment);
changes |= DrawMiscellaneous(data, _player);
if (_player != null && changes)
Glamourer.Penumbra.UpdateCharacters(_player);
if (_currentSave.WriteProtected)
ImGui.PopStyleVar();
}
private void DrawActorPanel()
{
using var raii = ImGuiRaii.NewGroup();
DrawPlayerHeader();
if (!ImGui.BeginChild("##playerData", -Vector2.One, true))
{
ImGui.EndChild();
return;
}
if (_player == null || _player.ModelType() == 0)
DrawPlayerPanel();
else
DrawMonsterPanel();
ImGui.EndChild();
}
}
}
| 35.944984
| 163
| 0.526515
|
[
"Apache-2.0"
] |
4679/Glamourer
|
Glamourer/Gui/InterfaceActorPanel.cs
| 11,109
|
C#
|
using System;
using System.Collections.Generic;
namespace Seq.App.EventTimeout.Classes
{
/// <summary>
/// Property matching methods
/// </summary>
public static class PropertyMatch
{
/// <summary>
/// Return a property matching rule given a property number, property name, and text to match
/// </summary>
/// <param name="property"></param>
/// <param name="propertyName"></param>
/// <param name="propertyMatch"></param>
/// <returns></returns>
public static KeyValuePair<string, string> GetProperty(int property, string propertyName, string propertyMatch)
{
var key = string.Empty;
var value = string.Empty;
if (string.IsNullOrEmpty(propertyName) && property == 1)
key = "@Message";
else if (!string.IsNullOrEmpty(propertyName)) key = propertyName.Trim();
if (!string.IsNullOrEmpty(key))
value = string.IsNullOrWhiteSpace(propertyMatch) ? string.Empty : propertyMatch.Trim();
return new KeyValuePair<string, string>(key, value);
}
/// <summary>
/// Return a human readable match expression, given a list of match rules
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
public static string MatchConditions(Dictionary<string, string> properties)
{
var count = 0;
var condition = string.Empty;
foreach (var property in properties)
{
count++;
var propValue = "'" + property.Value + "'";
if (string.IsNullOrEmpty(property.Value)) propValue = "ANY value";
if (count == 1)
condition = property.Key + " contains " + propValue;
else if (!string.IsNullOrEmpty(property.Key))
condition = condition + " AND " + property.Key + " contains " + propValue;
}
return condition;
}
/// <summary>
/// Validate whether a case-insensitive match can be obtained
/// </summary>
/// <param name="text"></param>
/// <param name="matchText"></param>
/// <returns></returns>
public static bool Matches(string text, string matchText)
{
if (string.IsNullOrEmpty(matchText))
return true;
return text.IndexOf(matchText, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}
| 36.671429
| 119
| 0.552785
|
[
"Apache-2.0"
] |
MattMofDoom/Seq.App.EventTimeout
|
Seq.App.EventTimeout/Classes/PropertyMatch.cs
| 2,569
|
C#
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Resources;
using System.Reflection;
using System.Globalization;
namespace Microsoft.Build.Shared
{
/// <summary>
/// This class provides access to the assembly's resources.
/// </summary>
internal static class AssemblyResources
{
/// <summary>
/// Loads the specified resource string, either from the assembly's primary resources, or its shared resources.
/// </summary>
/// <remarks>This method is thread-safe.</remarks>
/// <returns>The resource string, or null if not found.</returns>
internal static string GetString(string name)
{
// NOTE: the ResourceManager.GetString() method is thread-safe
string resource = PrimaryResources.GetString(name, CultureInfo.CurrentUICulture) ?? SharedResources.GetString(name, CultureInfo.CurrentUICulture);
ErrorUtilities.VerifyThrow(resource != null, "Missing resource '{0}'", name);
return resource;
}
/// <summary>
/// Gets the assembly's primary resources i.e. the resources exclusively owned by this assembly.
/// </summary>
/// <remarks>This property is thread-safe.</remarks>
/// <value>ResourceManager for primary resources.</value>
internal static ResourceManager PrimaryResources { get; } = new ResourceManager("Microsoft.Build.Tasks.Core.Strings", typeof(AssemblyResources).GetTypeInfo().Assembly);
/// <summary>
/// Gets the assembly's shared resources i.e. the resources this assembly shares with other assemblies.
/// </summary>
/// <remarks>This property is thread-safe.</remarks>
/// <value>ResourceManager for shared resources.</value>
internal static ResourceManager SharedResources { get; } = new ResourceManager("Microsoft.Build.Tasks.Core.Strings.shared", typeof(AssemblyResources).GetTypeInfo().Assembly);
// assembly resources
// shared resources
}
}
| 44.4375
| 182
| 0.674637
|
[
"MIT"
] |
0xced/msbuild
|
src/Tasks/AssemblyResources.cs
| 2,135
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace M
{
public interface IReplyEx<TReturn> : IReply<TReturn>
{
bool HasException { get; }
Exception Exception { get; }
/// <summary>
/// Does nothing when HasException is false.
/// When true, throws exactly the same exception from Exception property.
/// </summary>
void ThrowCaughtException();
}
}
| 23.368421
| 81
| 0.626126
|
[
"MIT"
] |
LeandroMBarreto/MlIB.Reply
|
source/MlIB.Reply/Interfaces/IReplyEx.cs
| 446
|
C#
|
using System;
using System.ComponentModel.DataAnnotations;
namespace UserPerformanceApp.Models
{
public class SaveUserActivityModel
{
[Required]
public DateTime day { get; set; }
[Required]
public long activityId { get; set; }
public decimal? count { get; set; }
public string hours { get; set; }
}
}
| 24.133333
| 44
| 0.629834
|
[
"MIT"
] |
vyatkin0/UserPerformance
|
UserPerformance/Models/SaveUserActivitiesModel.cs
| 364
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Discount.Grpc.Extensions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Discount.Grpc
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
host.MigrateDatabase<Program>();
host.Run();
}
// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 30.967742
| 136
| 0.645833
|
[
"MIT"
] |
Pradeep-Kumar-3325/AspnetMicroservices
|
src/Services/Discount/Discount.Grpc/Program.cs
| 960
|
C#
|
using Basket.API.Entities;
using System.Threading.Tasks;
namespace Basket.API.Repositories
{
public interface IBasketRepository
{
Task<ShoppingCart> GetBasket(string UserName);
Task<ShoppingCart> UpdateBasket(ShoppingCart Basket);
Task DeleteBasket(string UserName);
}
}
| 18.933333
| 55
| 0.788732
|
[
"MIT"
] |
Amin-Shiravand/AspnetMicroservices
|
src/Services/Basket/Basket.API/Repositories/IBasketRepository.cs
| 286
|
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.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using CleanArchitecture.Razor.Application.Common.Interfaces;
using CleanArchitecture.Razor.Application.Common.Interfaces.Caching;
using CleanArchitecture.Razor.Application.Common.Models;
using CleanArchitecture.Razor.Application.Constants;
using CleanArchitecture.Razor.Application.Customers.Caching;
using CleanArchitecture.Razor.Application.Customers.Commands.AddEdit;
using CleanArchitecture.Razor.Application.Customers.DTOs;
using CleanArchitecture.Razor.Domain.Entities;
using CleanArchitecture.Razor.Domain.Enums;
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace CleanArchitecture.Razor.Application.Customers.Commands.Import
{
public class ImportCustomersCommand : IRequest<Result>, ICacheInvalidator
{
public string FileName { get; set; }
public byte[] Data { get; set; }
public string CacheKey => Cache.GetAllCustomersCacheKey;
public CancellationTokenSource ResetCacheToken => CustomerCacheTokenSource.ResetCacheToken;
}
public class CreateCustomerTemplateCommand : IRequest<byte[]>
{
public IEnumerable<string> Fields { get; set; }
public string SheetName { get;set; }
}
public class ImportCustomersCommandHandler :
IRequestHandler<CreateCustomerTemplateCommand, byte[]>,
IRequestHandler<ImportCustomersCommand, Result>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
private readonly IExcelService _excelService;
private readonly IStringLocalizer<ImportCustomersCommandHandler> _localizer;
private readonly IValidator<AddEditCustomerCommand> _addValidator;
public ImportCustomersCommandHandler(
IApplicationDbContext context,
IMapper mapper,
IExcelService excelService,
IStringLocalizer<ImportCustomersCommandHandler> localizer,
IValidator<AddEditCustomerCommand> addValidator
)
{
_context = context;
_mapper = mapper;
_excelService = excelService;
_localizer = localizer;
_addValidator = addValidator;
}
public async Task<Result> Handle(ImportCustomersCommand request, CancellationToken cancellationToken)
{
var result = await _excelService.ImportAsync(request.Data, mappers: new Dictionary<string, Func<DataRow, CustomerDto, object>>
{
{ _localizer["Name"], (row,item) => item.Name = row[_localizer["Name"]]?.ToString() },
{ _localizer["Name Of English"], (row,item) => item.NameOfEnglish = row[_localizer["Name Of English"]]?.ToString() },
{ _localizer["Group Name"], (row,item) => item.GroupName = row[_localizer["Group Name"]]?.ToString() },
{ _localizer["Partner Type"], (row,item) => item.PartnerType = row[_localizer["Partner Type"]].ToString()},
{ _localizer["Region"], (row,item) => item.Region = row[_localizer["Region"]]?.ToString() },
{ _localizer["Sales"], (row,item) => item.Sales = row[_localizer["Sales"]]?.ToString() },
{ _localizer["Region Sales Director"], (row,item) => item.RegionSalesDirector = row[_localizer["Region Sales Director"]]?.ToString() },
{ _localizer["Address"], (row,item) => item.Address = row[_localizer["Address"]].ToString() },
{ _localizer["Address Of English"], (row,item) => item.AddressOfEnglish = row[_localizer["Address Of English"]]?.ToString() },
{ _localizer["Contact"], (row,item) => item.Contact = row[_localizer["Contact"]]?.ToString() },
{ _localizer["Email"], (row,item) => item.Email = row[_localizer["Email"]]?.ToString() },
{ _localizer["Phone Number"], (row,item) => item.PhoneNumber = row[_localizer["Phone Number"]]?.ToString() },
{ _localizer["Fax"], (row,item) => item.Fax = row[_localizer["Fax"]]?.ToString() },
{ _localizer["Comments"], (row,item) => item.Comments = row[_localizer["Comments"]]?.ToString() }
}, _localizer["Customers"]);
if (result.Succeeded)
{
var importItems = result.Data;
var errors = new List<string>();
var errorsOccurred = false;
foreach (var item in importItems)
{
var validationResult = await _addValidator.ValidateAsync(_mapper.Map<AddEditCustomerCommand>(item), cancellationToken);
if (validationResult.IsValid)
{
var exist = await _context.Customers.AnyAsync(x => x.Name==item.Name,cancellationToken);
if (!exist)
{
await _context.Customers.AddAsync(_mapper.Map<Customer>(item), cancellationToken);
}
}
else
{
errorsOccurred = true;
errors.AddRange(validationResult.Errors.Select(e => $"{(!string.IsNullOrWhiteSpace(item.Name) ? $"{item.Name} - " : string.Empty)}{e.ErrorMessage}"));
}
}
if (errorsOccurred)
{
return await Result.FailureAsync(errors);
}
await _context.SaveChangesAsync(cancellationToken);
return await Result.SuccessAsync();
}
else
{
return await Result.FailureAsync(result.Errors);
}
}
public async Task<byte[]> Handle(CreateCustomerTemplateCommand request, CancellationToken cancellationToken)
{
var fields = new string[] {
_localizer["Name"],
_localizer["Name Of English"],
_localizer["Group Name"],
_localizer["Partner Type"],
_localizer["Region"],
_localizer["Sales"],
_localizer["Region Sales Director"],
_localizer["Address"],
_localizer["Address Of English"],
_localizer["Contact"],
_localizer["Email"],
_localizer["Phone Number"],
_localizer["Fax"],
_localizer["Comments"],
};
var result = await _excelService.CreateTemplateAsync(fields, _localizer["Customers"]);
return result;
}
}
}
| 48.069444
| 174
| 0.607194
|
[
"MIT"
] |
urmatgit/RazorPageCleanArchitecture
|
src/Application/Customers/Commands/Import/ImportCustomersCommand.cs
| 6,922
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cocos2D;
namespace tests
{
public class FadeOutUpTilesDemo : CCFadeOutUpTiles
{
public static CCActionInterval actionWithDuration(float t)
{
CCFadeOutUpTiles fadeout = new CCFadeOutUpTiles(t, new CCGridSize(16, 12));
CCFiniteTimeAction back = fadeout.Reverse();
CCDelayTime delay = new CCDelayTime (0.5f);
return (CCActionInterval)(new CCSequence(fadeout, delay, back));
}
}
}
| 26.428571
| 87
| 0.672072
|
[
"MIT"
] |
Karunp/cocos2d-xna
|
tests/tests/classes/tests/EffectsTest/FadeOutUpTilesDemo.cs
| 555
|
C#
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace SkiaSharp.Extended.UI.Extensions
{
public static partial class SKImageSourceExtensions
{
private static Task<SKImage?> PlatformToSKImageAsync(ImageSource imageSource, CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
}
}
| 26.214286
| 129
| 0.811989
|
[
"MIT"
] |
8529447889/SkiaSharp.Extended
|
source/SkiaSharp.Extended.UI/Extensions/SKImageSourceExtensions.ref.cs
| 369
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
namespace Azure.Management.Network.Models
{
/// <summary> Response for DisconnectActiveSessions. </summary>
public partial class BastionSessionDeleteResult
{
/// <summary> Initializes a new instance of BastionSessionDeleteResult. </summary>
internal BastionSessionDeleteResult()
{
Value = new ChangeTrackingList<BastionSessionState>();
}
/// <summary> Initializes a new instance of BastionSessionDeleteResult. </summary>
/// <param name="value"> List of sessions with their corresponding state. </param>
/// <param name="nextLink"> The URL to get the next set of results. </param>
internal BastionSessionDeleteResult(IReadOnlyList<BastionSessionState> value, string nextLink)
{
Value = value;
NextLink = nextLink;
}
/// <summary> List of sessions with their corresponding state. </summary>
public IReadOnlyList<BastionSessionState> Value { get; }
/// <summary> The URL to get the next set of results. </summary>
public string NextLink { get; }
}
}
| 35.27027
| 102
| 0.669732
|
[
"MIT"
] |
AbelHu/azure-sdk-for-net
|
sdk/testcommon/Azure.Management.Network.2020_04/src/Generated/Models/BastionSessionDeleteResult.cs
| 1,305
|
C#
|
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.MSHTMLApi
{
///<summary>
/// DispatchInterface IHTCAttachBehavior
/// SupportByVersion MSHTML, 4
///</summary>
[SupportByVersionAttribute("MSHTML", 4)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class IHTCAttachBehavior : IHTCAttachBehavior2
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IHTCAttachBehavior);
return _type;
}
}
#endregion
#region Construction
///<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 IHTCAttachBehavior(Core factory, COMObject 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 IHTCAttachBehavior(COMObject 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 IHTCAttachBehavior(Core factory, COMObject 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 IHTCAttachBehavior(COMObject 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 IHTCAttachBehavior(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTCAttachBehavior() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTCAttachBehavior(string progId) : base(progId)
{
}
#endregion
#region Properties
#endregion
#region Methods
/// <summary>
/// SupportByVersion MSHTML 4
///
/// </summary>
/// <param name="evt">object evt</param>
[SupportByVersionAttribute("MSHTML", 4)]
public void FireEvent(object evt)
{
object[] paramsArray = Invoker.ValidateParamsArray(evt);
Invoker.Method(this, "FireEvent", paramsArray);
}
/// <summary>
/// SupportByVersion MSHTML 4
///
/// </summary>
[SupportByVersionAttribute("MSHTML", 4)]
public void detachEvent()
{
object[] paramsArray = null;
Invoker.Method(this, "detachEvent", paramsArray);
}
#endregion
#pragma warning restore
}
}
| 32.282258
| 173
| 0.676992
|
[
"MIT"
] |
NetOffice/NetOffice
|
Source/MSHTML/DispatchInterfaces/IHTCAttachBehavior.cs
| 4,003
|
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Razor.Language.Intermediate;
namespace Microsoft.AspNetCore.Razor.Language
{
internal class DefaultDocumentClassifierPassFeature : RazorEngineFeatureBase
{
public IList<
Action<RazorCodeDocument, ClassDeclarationIntermediateNode>
> ConfigureClass { get; } =
new List<Action<RazorCodeDocument, ClassDeclarationIntermediateNode>>();
public IList<
Action<RazorCodeDocument, NamespaceDeclarationIntermediateNode>
> ConfigureNamespace { get; } =
new List<Action<RazorCodeDocument, NamespaceDeclarationIntermediateNode>>();
public IList<
Action<RazorCodeDocument, MethodDeclarationIntermediateNode>
> ConfigureMethod { get; } =
new List<Action<RazorCodeDocument, MethodDeclarationIntermediateNode>>();
}
}
| 38.535714
| 111
| 0.721965
|
[
"Apache-2.0"
] |
belav/aspnetcore
|
src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDocumentClassifierPassFeature.cs
| 1,081
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TTY.GMP.Entity.View
{
/// <summary>
/// 地区门店采购统计
/// </summary>
public class DbStatisticsPurchaseShopView
{
/// <summary>
/// 门店ID
/// </summary>
public long ShopId { get; set; }
/// <summary>
/// 门店名称
/// </summary>
public string ShopName { get; set; }
/// <summary>
/// 地区ID
/// </summary>
public long AreaId { get; set; }
/// <summary>
/// 总重量
/// </summary>
public decimal TotalWeight { get; set; }
/// <summary>
/// 重量折百比
/// </summary>
public decimal TotalContentsWeight { get; set; }
/// <summary>
/// 类别ID
/// </summary>
public long GoodsCategoryId { get; set; }
/// <summary>
/// 类别名称
/// </summary>
public string GoodsCategoryName { get; set; }
}
}
| 20.666667
| 56
| 0.474798
|
[
"MIT"
] |
chenjian8541/gmp
|
src/TTY.GMP.Entity/View/DbStatisticsPurchaseShopView.cs
| 1,054
|
C#
|
using Microsoft.EntityFrameworkCore;
using Volo.Abp;
namespace PasswordlessAuthentication.EntityFrameworkCore
{
public static class PasswordlessAuthenticationDbContextModelCreatingExtensions
{
public static void ConfigurePasswordlessAuthentication(this ModelBuilder builder)
{
Check.NotNull(builder, nameof(builder));
/* Configure your own tables/entities inside here */
//builder.Entity<YourEntity>(b =>
//{
// b.ToTable(PasswordlessAuthenticationConsts.DbTablePrefix + "YourEntities", PasswordlessAuthenticationConsts.DbSchema);
// b.ConfigureByConvention(); //auto configure for the base class props
// //...
//});
}
}
}
| 35.863636
| 137
| 0.638783
|
[
"MIT"
] |
271943794/abp-samples
|
PasswordlessAuthentication/src/PasswordlessAuthentication.EntityFrameworkCore/EntityFrameworkCore/PasswordlessAuthenticationDbContextModelCreatingExtensions.cs
| 791
|
C#
|
#pragma warning disable 0649
using System.Collections.Generic;
using UnityEngine;
namespace MonsterRPG
{
public class Summoner : Combatant
{
[SerializeField]
private AttributeSet attributeSet;
[SerializeField]
private MonsterRuntimeSet monsterRuntimeSet;
protected readonly List<Monster> monsters = new List<Monster>();
protected Monster selectedMonster;
protected Monster activeMonster;
protected AbilitySpec activeAbility;
protected override void Initialise()
{
CreateStartupAttributes();
CreateStartupAbilities();
CreateStartupMonsterSet();
}
private void CreateStartupAttributes()
{
var health = new Attribute(AttributeType.Health, attributeSet.Health);
abilitySystemComponent.AddAttributeToSet(health);
var attack = new Attribute(AttributeType.Attack, attributeSet.Attack);
abilitySystemComponent.AddAttributeToSet(attack);
var defence = new Attribute(AttributeType.Defence, attributeSet.Defence);
abilitySystemComponent.AddAttributeToSet(defence);
var speed = new Attribute(AttributeType.Speed, attributeSet.Speed);
abilitySystemComponent.AddAttributeToSet(speed);
}
private void CreateStartupAbilities()
{
var abilities = attributeSet.Abilities;
for (int i = 0; i < abilities.Length; i++)
{
var spec = abilities[i].CreateAbilitySpec(abilitySystemComponent);
abilitySystemComponent.AddAbilityToSet(spec);
}
activeAbility = abilitySystemComponent.GetAbilityByType<Summon>();
}
private void CreateStartupMonsterSet()
{
int count = monsterRuntimeSet.Count();
for (int i = 0; i < count; i++)
{
var asset = monsterRuntimeSet.GetItem(i);
var monster = asset.CreateMonsterFromAsset(this);
AddMonsterToSet(monster);
}
}
public virtual void Summon(Monster monster)
{
activeMonster = monster;
}
public virtual void Recall(Monster monster)
{
activeMonster = null;
}
public virtual void Select(int index)
{
selectedMonster = monsters[index];
}
public virtual void Deselect()
{
selectedMonster = null;
}
public virtual void AddMonsterToSet(Monster monster)
{
if (!monsters.Contains(monster))
{
monsters.Add(monster);
}
}
public virtual void RemoveMonsterFromSet(Monster monster)
{
if (monsters.Contains(monster))
{
monsters.Remove(monster);
}
}
public void SetActiveAbility(AbilitySpec spec)
{
if (abilitySystemComponent.ContainsAbility(spec))
{
activeAbility = spec;
}
}
public bool TryGetActiveMonster(out Monster monster)
{
monster = null;
if (activeMonster != null)
{
monster = activeMonster;
return true;
}
return false;
}
public bool TryGetSelectedMonster(out Monster monster)
{
monster = null;
if (selectedMonster != null)
{
monster = selectedMonster;
return true;
}
return false;
}
public bool TryGetActiveAbility(out AbilitySpec ability)
{
ability = null;
if (activeAbility != null)
{
ability = activeAbility;
return true;
}
return false;
}
public bool HasAtLeastOneMonsterAlive()
{
for (int i = 0; i < monsters.Count; i++)
{
if (monsters[i].IsAlive)
{
return true;
}
}
return false;
}
public bool HasSummonedAtLeastOneMonster()
{
return activeMonster != null;
}
}
}
| 25.686047
| 85
| 0.530557
|
[
"Apache-2.0"
] |
RippinPepperoni/MonsterRPG
|
Assets/Scripts/Combat/Combatants/Summoner.cs
| 4,420
|
C#
|
using BulletSharp;
using DemoFramework;
using SharpDX;
namespace CcdPhysicsDemo
{
class Physics : PhysicsContext
{
bool ccdMode = true;
public bool CcdMode
{
get { return ccdMode; }
}
float CubeHalfExtents = 0.5f;
float ExtraHeight = 1.0f;
public void ToggleCcdMode()
{
ccdMode = !ccdMode;
ClientResetScene();
}
void CreateStack(CollisionShape boxShape, int size, float zPos)
{
Matrix trans;
float mass = 1.0f;
for (int i = 0; i < size; i++)
{
// This constructs a row, from left to right
int rowSize = size - i;
for (int j = 0; j < rowSize; j++)
{
trans = Matrix.Translation(
-rowSize * CubeHalfExtents + CubeHalfExtents + j * 2.0f * CubeHalfExtents,
CubeHalfExtents + i * CubeHalfExtents * 2.0f,
zPos);
RigidBody body = LocalCreateRigidBody(mass, trans, boxShape);
body.ActivationState = ActivationState.IslandSleeping;
}
}
}
public override void InitPhysics()
{
int i;
shootBoxInitialSpeed = 4000;
// collision configuration contains default setup for memory, collision setup
CollisionConf = new DefaultCollisionConfiguration();
Dispatcher = new CollisionDispatcher(CollisionConf);
Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.BoxShape, BroadphaseNativeType.BoxShape,
CollisionConf.GetCollisionAlgorithmCreateFunc(BroadphaseNativeType.ConvexShape, BroadphaseNativeType.ConvexShape));
Broadphase = new DbvtBroadphase();
// the default constraint solver.
Solver = new SequentialImpulseConstraintSolver();
World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf);
World.SolverInfo.SplitImpulse = 1;
World.SolverInfo.NumIterations = 20;
World.DispatchInfo.UseContinuous = ccdMode;
World.Gravity = new Vector3(0, -10, 0);
BoxShape ground = new BoxShape(200, 1, 200);
ground.InitializePolyhedralFeatures();
CollisionShapes.Add(ground);
RigidBody body = LocalCreateRigidBody(0, Matrix.Identity, ground);
body.UserObject = "Ground";
CollisionShape shape = new CylinderShape(CubeHalfExtents, CubeHalfExtents, CubeHalfExtents);
CollisionShapes.Add(shape);
int numObjects = 120;
for (i = 0; i < numObjects; i++)
{
//stack them
int colsize = 10;
int row = (int)((i * CubeHalfExtents * 2) / (colsize * 2 * CubeHalfExtents));
int row2 = row;
int col = (i) % (colsize) - colsize / 2;
if (col > 3)
{
col = 11;
row2 |= 1;
}
Matrix trans = Matrix.Translation(col * 2 * CubeHalfExtents + (row2 % 2) * CubeHalfExtents,
row * 2 * CubeHalfExtents + CubeHalfExtents + ExtraHeight, 0);
body = LocalCreateRigidBody(1, trans, shape);
if (ccdMode)
{
body.CcdMotionThreshold = 1e-7f;
body.CcdSweptSphereRadius = 0.9f * CubeHalfExtents;
}
}
}
public override void ShootBox(Vector3 camPos, Vector3 destination)
{
if (World != null)
{
float mass = 1.0f;
if (shootBoxShape == null)
{
shootBoxShape = new BoxShape(1.0f);
shootBoxShape.InitializePolyhedralFeatures();
}
RigidBody body = LocalCreateRigidBody(mass, Matrix.Translation(camPos), shootBoxShape);
body.LinearFactor = new Vector3(1, 1, 1);
//body->setRestitution(1);
Vector3 linVel = destination - camPos;
linVel.Normalize();
body.LinearVelocity = linVel * shootBoxInitialSpeed;
body.AngularVelocity = Vector3.Zero;
body.ContactProcessingThreshold = 1e30f;
///when using m_ccdMode, disable regular CCD
if (ccdMode)
{
body.CcdMotionThreshold = 0.0001f;
body.CcdSweptSphereRadius = 0.4f;
}
}
}
}
}
| 34.013889
| 132
| 0.507554
|
[
"MIT"
] |
AndresTraks/BulletSharp
|
demos/SharpDX/CcdPhysicsDemo/Physics.cs
| 4,900
|
C#
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using AspxCommerce.Core;
using SageFrame.Common;
using SageFrame.NewsLetter;
using SageFrame.Web;
using SageFrame.Web.Utilities;
using System.Threading.Tasks;
using System.Web.SessionState;
using System.Threading;
using System.Data;
namespace AspxCommerce.Core
{
public class AspxCoreController
{
public static Thread catalogThread;
#region General Functions
//--------------------Roles Lists------------------------
public List<PortalRole> GetAllRoles(AspxCommonInfo aspxCommonObj)
{
try
{
List<PortalRole> lstPortalRole = AspxCommonController.GetPortalRoles(aspxCommonObj.PortalID, true, aspxCommonObj.UserName);
return lstPortalRole;
}
catch (Exception ex)
{
throw ex;
}
}
//--------------------Store Lists------------------------
public List<StoreInfo> GetAllStores(AspxCommonInfo aspxCommonObj)
{
List<StoreInfo> lstStore = AspxCommonController.GetAllStores(aspxCommonObj);
return lstStore;
}
//----------------country list------------------------------
public List<CountryInfo> BindCountryList()
{
try
{
List<CountryInfo> lstCountry = AspxCommonController.BindCountryList();
return lstCountry;
}
catch (Exception ex)
{
throw ex;
}
}
//----------------state list--------------------------
public List<StateInfo> BindStateList(string countryCode)
{
try
{
List<StateInfo> lstState = AspxCommonController.BindStateList(countryCode);
return lstState;
}
catch (Exception ex)
{
throw ex;
}
}
public ItemCommonInfo GetItemInfoFromSKU(string SKU,AspxCommonInfo aspxCommonObj)
{
ItemCommonInfo lstItem = AspxCommonController.GetItemInfoFromSKU(SKU, aspxCommonObj);
return lstItem;
}
#endregion
#region Bind Users DropDown
public List<UserInRoleInfo> BindRoles(bool isAll, AspxCommonInfo aspxCommonObj)
{
try
{
List<UserInRoleInfo> lstUserInRole = AspxItemMgntController.BindRoles(isAll, aspxCommonObj);
return lstUserInRole;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Item Details Module
public ItemBasicDetailsInfo GetItemBasicInfoByitemSKU(string itemSKU, AspxCommonInfo aspxCommonObj)
{
ItemBasicDetailsInfo frmItemAttributes = AspxItemMgntController.GetItemBasicInfo(itemSKU, aspxCommonObj);
return frmItemAttributes;
}
public List<ItemBasicDetailsInfo> GetGroupedItemsByGroupSKU(string groupSKU, AspxCommonInfo aspxCommonObj)
{
List<ItemBasicDetailsInfo> groupedProducts = AspxItemMgntController.GetGroupedItemsByGroupSKU(groupSKU, aspxCommonObj);
return groupedProducts;
}
public decimal GetStartPriceOfGroupAfterDeletion(string groupItems, AspxCommonInfo aspxCommonObj)
{
decimal startPrice = AspxItemMgntController.GetStartPriceOfGroupAfterDeletion(groupItems, aspxCommonObj);
return startPrice;
}
public List<AttributeFormInfo> GetItemDetailsByitemSKU(string itemSKU, int attributeSetID, int itemTypeID, AspxCommonInfo aspxCommonObj)
{
List<AttributeFormInfo> frmItemAttributes = AspxItemMgntController.GetItemDetailsInfoByItemSKU(itemSKU, attributeSetID, itemTypeID, aspxCommonObj);
return frmItemAttributes;
}
//---------------------Get rating/ review of Item Per User ------------------
public List<ItemRatingByUserInfo> GetItemRatingPerUser(int offset, int limit, string itemSKU, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemRatingByUserInfo> lstItemRating = AspxRatingReviewController.GetItemRatingPerUser(offset, limit, itemSKU, aspxCommonObj);
return lstItemRating;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Get rating/ review of Item Per User ------------------
public List<ItemReviewDetailsInfo> GetItemRatingByReviewID(int itemReviewID, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemReviewDetailsInfo> lstItemRVDetail = AspxCommonProvider.GetItemRatingByReviewID(itemReviewID, aspxCommonObj);
return lstItemRVDetail;
}
catch (Exception e)
{
throw e;
}
}
public List<RatingCriteriaInfo> GetItemRatingCriteriaByReviewID(AspxCommonInfo aspxCommonObj, int itemReviewID, bool isFlag)
{
try
{
List<RatingCriteriaInfo> rating = AspxRatingReviewController.GetItemRatingCriteriaByReviewID(aspxCommonObj, itemReviewID, isFlag);
return rating;
}
catch (Exception ex)
{
throw ex;
}
}
//public static List<RatingCriteriaInfo> GetItemRatingCriteria(AspxCommonInfo aspxCommonObj, bool isFlag)
//{
// try
// {
// List<RatingCriteriaInfo> lstRating = AspxCommonProvider.GetItemRatingCriteria(aspxCommonObj, isFlag);
// return lstRating;
// }
// catch (Exception e)
// {
// throw e;
// }
//}
//------------------------Item single rating management------------------------
public void DeleteSingleItemRating(string itemReviewID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCommonController.DeleteSingleItemRating(itemReviewID, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
//---------------Delete multiple item rating informations--------------------------
public void DeleteMultipleItemRatings(string itemReviewIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxRatingReviewController.DeleteMultipleItemRatings(itemReviewIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public string GetItemVideos(string SKU, AspxCommonInfo aspxCommonObj)
{
string lstItem = AspxItemMgntController.GetItemVideos(SKU, aspxCommonObj);
return lstItem;
}
#region NeW CostVariant Combination
public List<VariantCombination> GetCostVariantCombinationbyItemSku(string itemSku, AspxCommonInfo aspxCommonObj)
{
try
{
List<VariantCombination> lstVarCom = AspxItemMgntController.GetCostVariantCombinationbyItemSku(itemSku, aspxCommonObj);
return lstVarCom;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ItemCostVariantsInfo> GetCostVariantsByItemSKU(string itemSku, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemCostVariantsInfo> lstItemCostVar = AspxItemMgntController.GetCostVariantsByItemSKU(itemSku, aspxCommonObj);
return lstItemCostVar;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CostVariantInfo> GetCostVariantForItem(AspxCommonInfo aspxCommonObj) //not used in ItemDetailPage
{
try
{
List<CostVariantInfo> lstCostVar = AspxItemMgntController.GetCostVariantForItem(aspxCommonObj);
return lstCostVar;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CostVariantValuesInfo> GetCostVariantValues(int costVariantID, AspxCommonInfo aspxCommonObj) // not ussed in ItemDetailPage
{
try
{
List<CostVariantValuesInfo> lstCostVarValue = AspxItemMgntController.GetCostVariantValues(costVariantID, aspxCommonObj);
return lstCostVarValue;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteCostVariantForItem(int itemId, AspxCommonInfo aspxCommonObj) // not used in ItemDetailPage
{
try
{
AspxItemMgntController.DeleteCostVariantForItem(itemId, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<VariantCombination> GetCostVariantsOfItem(int itemId, AspxCommonInfo aspxCommonObj) // not used in ItemDetailPage
{
try
{
List<VariantCombination> lstVarComb = AspxItemMgntController.GetCostVariantsOfItem(itemId, aspxCommonObj);
return lstVarComb;
}
catch (Exception ex)
{
throw ex;
}
}
public void SaveAndUpdateItemCostVariantCombination(CostVariantsCombination itemCostVariants, AspxCommonInfo aspxCommonObj) // not used in ItemDetailPage
{
try
{
string cvCombinations = string.Empty;
foreach (var objCombination in itemCostVariants.VariantOptions)
{
cvCombinations += objCombination.CombinationIsActive;
cvCombinations += "," + objCombination.ImageFile;
cvCombinations += "," + objCombination.CombinationPriceModifier;
cvCombinations += "," + objCombination.CombinationPriceModifierType;
cvCombinations += "," + objCombination.CombinationQuantity;
cvCombinations += "," + objCombination.CombinationType;
cvCombinations += "," + objCombination.CombinationValues;
cvCombinations += "," + objCombination.CombinationValuesName;
cvCombinations += "," + objCombination.CombinationWeightModifier;
cvCombinations += "," + objCombination.CombinationWeightModifierType;
cvCombinations += "," + objCombination.DisplayOrder;
if (itemCostVariants.VariantOptions.Count - 1 != 0)
cvCombinations += "%";
}
// cvCombinations = cvCombinations.Replace("Upload/temp/", "Modules/AspxCommerce/AspxItemsManagement/uploads/");
FileHelperController Fch = new FileHelperController();
string tempFolder = @"Upload\temp";
string destPath = @"Modules/AspxCommerce/AspxItemsManagement/uploads/";
Fch.MoveVariantsImageFile(tempFolder, destPath, itemCostVariants, aspxCommonObj);
AspxItemMgntController.SaveAndUpdateItemCostVariantCombination(itemCostVariants, aspxCommonObj, cvCombinations);
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region RecentlyViewedItems
public void AddUpdateRecentlyViewedItems(RecentlyAddedItemInfo addUpdateRecentObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemMgntController.AddUpdateRecentlyViewedItems(addUpdateRecentObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region PriceList In Item Detail Page
public List<PriceHistoryInfo> GetPriceHistoryList(int itemId, AspxCommonInfo aspxCommerceObj)
{
try
{
List<PriceHistoryInfo> lstPriceHistory = PriceHistoryController.GetPriceHistory(itemId, aspxCommerceObj);
return lstPriceHistory;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Item Rating In Item Detail Page
public List<RatingCriteriaInfo> GetItemRatingCriteria(AspxCommonInfo aspxCommonObj, bool isFlag)
{
try
{
List<RatingCriteriaInfo> lstRating = AspxCommonProvider.GetItemRatingCriteria(aspxCommonObj, isFlag);
return lstRating;
}
catch (Exception e)
{
throw e;
}
}
//---------------------save rating/ review Items-----------------------
public void SaveItemRating(ItemReviewBasicInfo ratingSaveObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxRatingReviewController.SaveItemRating(ratingSaveObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<ItemRatingAverageInfo> GetItemAverageRating(string itemSKU, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemRatingAverageInfo> avgRating = AspxRatingReviewController.GetItemAverageRating(itemSKU, aspxCommonObj);
return avgRating;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
public List<AttributeFormInfo> GetItemFormAttributesByitemSKUOnly(string itemSKU, AspxCommonInfo aspxCommonObj)
{
List<AttributeFormInfo> frmItemFieldList = AspxItemMgntController.GetItemFormAttributesByItemSKUOnly(itemSKU, aspxCommonObj);
return frmItemFieldList;
}
#region User Tags
public List<ItemTagsInfo> GetItemTags(string itemSKU, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemTagsInfo> lstItemTags = AspxTagsController.GetItemTags(itemSKU, aspxCommonObj);
return lstItemTags;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteUserOwnTag(string itemTagID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTagsController.DeleteUserOwnTag(itemTagID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void AddTagsOfItem(string itemSKU, string tags, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTagsController.AddTagsOfItem(itemSKU, tags, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<TagDetailsInfo> GetTagsByUserName(AspxCommonInfo aspxCommonObj)
{
try
{
List<TagDetailsInfo> lstTagDetail = AspxTagsController.GetTagsByUserName(aspxCommonObj);
return lstTagDetail;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
public bool CheckReviewByIP(int itemID, AspxCommonInfo aspxCommonObj, string userIP)
{
bool isReviewExist = AspxRatingReviewController.CheckReviewByIP(itemID, aspxCommonObj, userIP);
return isReviewExist;
}
public bool CheckReviewByUser(int itemID, AspxCommonInfo aspxCommonObj)
{
bool isReviewExist = AspxRatingReviewController.CheckReviewByUser(itemID, aspxCommonObj);
return isReviewExist;
}
#region Front Image Gallery
public List<ItemsInfoSettings> GetItemsImageGalleryInfoBySKU(string itemSKU, AspxCommonInfo aspxCommonObj, string combinationId)
{
List<ItemsInfoSettings> itemsInfoContainer = AspxImageGalleryController.GetItemsImageGalleryInfoByItemSKU(itemSKU, aspxCommonObj, combinationId);
return itemsInfoContainer;
}
public List<ImageGalleryItemsInfo> GetItemsImageGalleryInfo(Int32 storeID, Int32 portalID, string userName, string culture) // not used In Item Detail page
{
List<ImageGalleryItemsInfo> itemsInfoList = AspxImageGalleryController.GetItemsImageGalleryList(storeID, portalID, userName, culture);
return itemsInfoList;
}
public List<ImageGalleryItemsInfo> GetItemsGalleryInfo(Int32 storeID, Int32 portalID, string culture) // not used in ItemDetail Page
{
List<ImageGalleryItemsInfo> itemsInfoList = AspxImageGalleryController.GetItemInfoList(storeID, portalID, culture);
return itemsInfoList;
}
public ImageGalleryInfo ReturnSettings(Int32 userModuleID, AspxCommonInfo aspxCommonObj) // not Used In ItemDetail page
{
ImageGalleryInfo infoObject = AspxImageGalleryController.GetGallerySettingValues(userModuleID, aspxCommonObj);
return infoObject;
}
public List<int> ReturnDimension(Int32 userModuleID, AspxCommonInfo aspxCommonObj)
{
List<int> param = new List<int>();
ImageGalleryInfo info = new ImageGalleryInfo();
ImageGallerySqlProvider settings = new ImageGallerySqlProvider();
info = AspxImageGalleryController.GetGallerySettingValues(userModuleID, aspxCommonObj);
param.Add(int.Parse(info.ImageWidth));
param.Add(int.Parse(info.ImageHeight));
param.Add(int.Parse(info.ThumbWidth));
param.Add(int.Parse(info.ThumbHeight));
//param.Add(int.Parse(info.ZoomShown));
return param;
}
#endregion
#region "For Out of Stock Notification"
public List<Notification> GetNotificationList(int offset, int limit, GetAllNotificationInfo getAllNotificationObj, AspxCommonInfo aspxCommonObj) // not used In Item Detail Page
{
try
{
List<Notification> lstNotification = AspxOutStockNotifyController.GetNotificationList(offset, limit, getAllNotificationObj, aspxCommonObj);
return lstNotification;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteNotification(string notificationID, AspxCommonInfo aspxCommonObj) // not used In Item Detail Page
{
try
{
AspxOutStockNotifyController.DeleteNotification(notificationID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<NotifictionMail> GetEmail(string SKU, AspxCommonInfo aspxCommonObj) // not used In Item Detail Page
{
try
{
List<NotifictionMail> lstNotifMail = AspxOutStockNotifyController.GetEmail(SKU, aspxCommonObj);
return lstNotifMail;
}
catch (Exception ex)
{
throw ex;
}
}
public void SendEmailNotification(SendEmailInfo emailInfo, string VariantId, string VarinatValue, string sku, string ProductUrl, AspxCommonInfo aspxCommonObj) // not used In Item Detail Page
{
try
{
AspxOutStockNotifyController.SendEmailNotification(emailInfo, VariantId, VarinatValue, sku, ProductUrl, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void InsertNotification(AspxCommonInfo aspxCommonObj, InsertNotificationInfo insertNotificationObj)
{
AspxOutStockNotifyController.InsertNotification(aspxCommonObj, insertNotificationObj);
}
public List<Notification> GetAllNotification(AspxCommonInfo aspxCommonObj, InsertNotificationInfo getNotificationObj)
{
List<Notification> lstNotification = AspxOutStockNotifyController.GetAllNotification(aspxCommonObj, getNotificationObj);
return lstNotification;
}
#endregion
#endregion
#region MyCart
#region Estimate Shipping Rate
public List<CountryList> LoadCountry()
{
List<CountryList> lstCountry = AspxShipRateController.LoadCountry();
return lstCountry; ;
}
public string GetStateCode(string cCode, string stateName)
{
string stateCode = AspxCommonController.GetStateCode(cCode, stateName);
return stateCode;
}
public List<States> GetStatesByCountry(string countryCode)
{
List<States> lstState = AspxShipRateController.GetStatesByCountry(countryCode);
return lstState;
}
public List<CommonRateList> GetRate(ItemListDetails itemsDetail)
{
List<CommonRateList> lstCommonRate = AspxShipRateController.GetRate(itemsDetail);
return lstCommonRate;
}
#endregion
#region MiniCart Display
//----------------------Count my cart items--------------------
public int GetCartItemsCount(AspxCommonInfo aspxCommonObj)
{
try
{
int cartItemCount = AspxCommonProvider.GetCartItemsCount(aspxCommonObj);
return cartItemCount;
}
catch (Exception ex)
{
throw ex;
}
}
public decimal GetTotalCartItemPrice(AspxCommonInfo aspxCommonObj) // on click of check out from shopping bag
{
try
{
decimal cartPrice = AspxCommonController.GetTotalCartItemPrice(aspxCommonObj);
return cartPrice;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
//public decimal CheckItemQuantityInCart(int itemID, AspxCommonInfo aspxCommonObj, string itemCostVariantIDs)
//{
// try
// {
// decimal retValue = AspxCartController.CheckItemQuantityInCart(itemID, aspxCommonObj, itemCostVariantIDs);
// return retValue;
// }
// catch (Exception e)
// {
// throw e;
// }
//}
public static List<CartInfo> GetCartDetails(AspxCommonInfo aspxCommonObj)
{
try
{
List<CartInfo> lstCart = AspxCartProvider.GetCartDetails(aspxCommonObj);
return lstCart;
}
catch (Exception e)
{
throw e;
}
}
public static DataSet GetCartDetailsDataset(AspxCommonInfo aspxCommonObj)
{
try
{
DataSet lstCart = AspxCartProvider.GetCartDetailsDataSet(aspxCommonObj);
return lstCart;
}
catch (Exception e)
{
throw e;
}
}
//------------------------------Delete Cart Items--------------------------
public static void DeleteCartItem(int cartID, int cartItemID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCartProvider.DeleteCartItem(cartID, cartItemID, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region Check Out Page
public CartExistInfo CheckCustomerCartExist(AspxCommonInfo aspxCommonObj)
{
CartExistInfo objCartExist = AspxCartController.CheckCustomerCartExist(aspxCommonObj);
return objCartExist;
}
public List<CartTaxInfo> GetCartTax(CartDataInfo cartTaxObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<CartTaxInfo> lstCartTax = AspxCartController.GetCartTax(cartTaxObj, aspxCommonObj);
return lstCartTax;
}
catch (Exception ex)
{
throw ex;
}
}
public string GetDiscountPriceRule(int cartID, AspxCommonInfo aspxCommonObj, decimal shippingCost)
{
try
{
string discount = AspxCartController.GetDiscountPriceRule(cartID, aspxCommonObj, shippingCost);
return discount;
}
catch (Exception e)
{
throw e;
}
}
public static decimal GetDiscountQuantityAmount(AspxCommonInfo aspxCommonObj)
{
try
{
decimal qtyDiscount = AspxCartController.GetDiscountQuantityAmount(aspxCommonObj);
return qtyDiscount;
}
catch (Exception e)
{
throw e;
}
}
public List<CartInfo> GetCartCheckOutDetails(AspxCommonInfo aspxCommonObj)
{
try
{
List<CartInfo> lstCart = AspxCartController.GetCartCheckOutDetails(aspxCommonObj);
return lstCart;
}
catch (Exception e)
{
throw e;
}
}
public List<CartTaxforOrderInfo> GetCartTaxforOrder(CartDataInfo cartTaxOrderObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<CartTaxforOrderInfo> lstCartTaxOrder = AspxCartController.GetCartTaxforOrder(cartTaxOrderObj, aspxCommonObj);
return lstCartTaxOrder;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CartUnitTaxInfo> GetCartUnitTax(CartDataInfo cartUnitTaxObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<CartUnitTaxInfo> lstCartUnitTax = AspxCartProvider.GetCartUnitTax(cartUnitTaxObj, aspxCommonObj);
return lstCartUnitTax;
}
catch (Exception ex)
{
throw ex;
}
}
public List<OrderItemsInfo> GetAllOrderDetailsForView(int orderId, AspxCommonInfo aspxCommonObj)
{
try
{
List<OrderItemsInfo> lstOrderItem = AspxPaymentController.GetAllOrderDetailsForView(orderId, aspxCommonObj);
return lstOrderItem;
}
catch (Exception ex)
{
throw ex;
}
}
public List<OrderItemsTaxInfo> GetTaxDetailsByOrderID(int orderId, AspxCommonInfo aspxCommonObj)
{
try
{
List<OrderItemsTaxInfo> lstOrderItem = AspxPaymentController.GetTaxDetailsByOrderID(orderId, aspxCommonObj);
return lstOrderItem;
}
catch (Exception ex)
{
throw ex;
}
}
public void AddUpdateUserAddress(AddressInfo addressObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxUserDashController.AddUpdateUserAddress(addressObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<AddressInfo> GetAddressBookDetails(AspxCommonInfo aspxCommonObj)
{
try
{
List<AddressInfo> lstAddress = AspxUserDashController.GetUserAddressDetails(aspxCommonObj);
return lstAddress;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteAddressBook(int addressID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxUserDashController.DeleteAddressBookDetails(addressID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckAddressAlreadyExist(AspxCommonInfo aspxCommonObj)
{
try
{
bool isExist = AspxCommonController.CheckAddressAlreadyExist(aspxCommonObj);
return isExist;
}
catch (Exception ex)
{
throw ex;
}
}
public List<PaymentGatewayListInfo> GetPGList(AspxCommonInfo aspxCommonObj)
{
List<PaymentGatewayListInfo> pginfo = AspxCartController.GetPGList(aspxCommonObj);
return pginfo;
}
#region CheckOUt Gift Card
//public int GetGiftCardType(AspxCommonInfo aspxCommonObj, int cartitemId)
//{
// try
// {
// int strType = AspxGiftCardController.GetGiftCardType(aspxCommonObj, cartitemId);
// return strType;
// }
// catch (Exception e)
// {
// throw e;
// }
//}
//public bool CheckGiftCardUsed(AspxCommonInfo aspxCommonObj, string giftCardCode, decimal amount)
//{
// try
// {
// bool allowToCheckout = AspxGiftCardController.CheckGiftCardUsed(aspxCommonObj, giftCardCode, amount);
// return allowToCheckout;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
#endregion
#region CheckOut Email Subscribtion
public string GetUserBillingEmail(int addressID, AspxCommonInfo aspxCommonObj)
{
try
{
string userEmail = AspxCommonController.GetUserBillingEmail(addressID, aspxCommonObj);
return userEmail;
}
catch (Exception e)
{
throw e;
}
}
public void SaveEmailSubscriber(string email, int userModuleID, int portalID, string userName, string clientIP)
{
try
{
NL_Provider cont = new NL_Provider();
cont.SaveEmailSubscriber(email, userModuleID, portalID, userName, clientIP);
}
catch (Exception e)
{
throw e;
}
}
public List<NL_Info> CheckPreviousEmailSubscription(string email)
{
try
{
NL_Provider cont = new NL_Provider();
return cont.CheckPreviousEmailSubscription(email);
}
catch (Exception e)
{
throw e;
}
}
#endregion
#endregion
#region Session Setting/Getting
public void SetSessionVariableCoupon(string key, int value)
{
if (System.Web.HttpContext.Current.Session[key] != null)
{
value = int.Parse(System.Web.HttpContext.Current.Session[key].ToString()) + 1;
}
else
{
value = value + 1;
}
System.Web.HttpContext.Current.Session[key] = value;
// string asdf = System.Web.HttpContext.Current.Session["OrderID"].ToString();
// return System.Web.HttpContext.Current.Session["MySessionObject"] = "OderID";
}
public void SetSessionVariable(string key, object value)
{
HttpContext.Current.Session[key] = value;
//HttpContext.Current.Session[key] = value;
// string asdf = System.Web.HttpContext.Current.Session["OrderID"].ToString();
// return System.Web.HttpContext.Current.Session["MySessionObject"] = "OderID";
}
public void ClearSessionVariable(string key)
{
var keys = key.Split(',');
for (int i = 0; i < keys.Length; i++)
{
var keycode = keys[i];
if (System.Web.HttpContext.Current.Session[keycode] != null)
{
System.Web.HttpContext.Current.Session.Remove(keycode);
// return System.Web.HttpContext.Current.Session["MySessionObject"] = "OderID";
}
}
}
public void ClearALLSessionVariable()
{
System.Web.HttpContext.Current.Session.Clear();
// return System.Web.HttpContext.Current.Session["MySessionObject"] = "OderID";
}
public Decimal GetSessionVariable(string key)
{
if (System.Web.HttpContext.Current.Session[key] != null)
{
string i = System.Web.HttpContext.Current.Session[key].ToString();
return Convert.ToDecimal(i.ToString());
}
else
{
return 0;
}
// return System.Web.HttpContext.Current.Session["MySessionObject"] = "OderID";
}
public object GetSessionGiftCard(string key)
{
if (System.Web.HttpContext.Current.Session[key] != null)
{
return System.Web.HttpContext.Current.Session[key];
}
else
{
return "";
}
}
public string GetSessionCouponCode(string key)
{
if (System.Web.HttpContext.Current.Session[key] != null)
{
string i = System.Web.HttpContext.Current.Session[key].ToString();
return i;
}
else
{
return "";
}
}
public string GetSessionVariableCart(string key)
{
string val = string.Empty;
if (System.Web.HttpContext.Current.Session[key] != null)
{
val = System.Web.HttpContext.Current.Session[key].ToString();
}
return val;
// return System.Web.HttpContext.Current.Session["MySessionObject"] = "OderID";
}
#endregion
#region Save Order Details From Success Page
public int SaveOrderDetails(OrderDetailsCollection orderDetail)
{
try
{
if (orderDetail.ObjOrderDetails.OrderStatusID == 0)
orderDetail.ObjOrderDetails.OrderStatusID = 7;
int orderID = AddOrderDetails(orderDetail);
return orderID;
}
catch (Exception ex)
{
throw ex;
}
}
public int AddOrderDetails(OrderDetailsCollection orderData)
{
SQLHandler sqlH = new SQLHandler();
SqlTransaction tran;
tran = (SqlTransaction)sqlH.GetTransaction();
//AspxCommerceSession sn = new AspxCommerceSession();
orderData.Coupons = CheckOutSessions.Get<List<CouponSession>>("CouponSession");
if (orderData.ObjOrderDetails.InvoiceNumber == null || orderData.ObjOrderDetails.InvoiceNumber == "")
{
orderData.ObjOrderDetails.InvoiceNumber = DateTime.Now.ToString("yyyyMMddhhmmss");
}
try
{
int billingAddressID = 0;
int shippingAddressId = 0;
int orderID = 0;
if (orderData.ObjOrderDetails.IsMultipleCheckOut == false)
{
if (int.Parse(orderData.ObjBillingAddressInfo.AddressID) == 0 &&
int.Parse(orderData.ObjShippingAddressInfo.AddressID) == 0)
{
billingAddressID = AspxOrderController.AddBillingAddress(orderData, tran);
if (!orderData.ObjOrderDetails.IsShippingAddressRequired)
{
shippingAddressId = AspxOrderController.AddShippingAddress(orderData, tran);
}
}
else
{
billingAddressID = AspxOrderController.AddBillingAddress(orderData, tran, int.Parse(orderData.ObjBillingAddressInfo.AddressID));
if (!orderData.ObjOrderDetails.IsDownloadable && !orderData.ObjOrderDetails.IsShippingAddressRequired)
{
shippingAddressId = AspxOrderController.AddShippingAddress(orderData, tran, int.Parse(orderData.ObjShippingAddressInfo.AddressID));
}
}
}
int paymentMethodID = AspxOrderController.AddPaymentInfo(orderData, tran);
if (billingAddressID > 0)
{
orderID = AspxOrderController.AddOrder(orderData, tran, billingAddressID, paymentMethodID);
//sn.SetSessionVariable("OrderID", orderID);
SetSessionVariable("OrderID", orderID);
orderData.ObjOrderDetails.OrderID = orderID;
SetSessionVariable("OrderCollection", orderData);
}
else
{
orderID = AspxOrderController.AddOrderWithMultipleCheckOut(orderData, tran, paymentMethodID);
//sn.SetSessionVariable("OrderID", orderID);
SetSessionVariable("OrderID", orderID);
orderData.ObjOrderDetails.OrderID = orderID;
SetSessionVariable("OrderCollection", orderData);
}
foreach (OrderTaxInfo item in orderData.ObjOrderTaxInfo)
{
int itemID = item.ItemID;
int taxManageRuleID = item.TaxManageRuleID;
decimal taxSubTotal = item.TaxSubTotal;
int storeID = item.StoreID;
int portalID = item.PortalID;
string addedBy = item.AddedBy;
string costVariantValueIDs = item.CostVariantsValueIDs;
OrderTaxRuleMapping(itemID, orderID, taxManageRuleID, taxSubTotal, storeID, portalID, addedBy, costVariantValueIDs);
}
if (shippingAddressId > 0)
AspxOrderController.AddOrderItems(orderData, tran, orderID, shippingAddressId);
else
AspxOrderController.AddOrderItemsList(orderData, tran, orderID);
//add every paymentgateway
// GiftCardController.IssueGiftCard(orderData.LstOrderItemsInfo, orderData.ObjCommonInfo.StoreID,
// orderData.ObjCommonInfo.PortalID,orderData.ObjCommonInfo.AddedBy, orderData.ObjCommonInfo.CultureName);
tran.Commit();
return orderID;
}
catch (SqlException sqlEX)
{
throw new ArgumentException(sqlEX.Message);
}
catch (Exception ex)
{
tran.Rollback();
throw ex;
}
}
public void OrderTaxRuleMapping(int itemID, int orderID, int taxManageRuleID, decimal taxSubTotal, int storeID, int portalID, string addedBy, string costVariantValueIDs)
{
try
{
AspxPaymentController.OrderTaxRuleMapping(itemID, orderID, taxManageRuleID, taxSubTotal, storeID, portalID, addedBy, costVariantValueIDs);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region "GroupItems"
public static ItemCartInfo CheckItemQuantityInCart(int itemID, AspxCommonInfo aspxCommonObj, string itemCostVariantIDs)
{
try
{
ItemCartInfo itemCartObj = AspxCartProvider.CheckItemQuantityInCart(itemID, aspxCommonObj, itemCostVariantIDs);
return itemCartObj;
}
catch (Exception e)
{
throw e;
}
}
public static List<GroupItemsQtyInfo> GetGroupItemQuantityInCart(string itemIDs, AspxCommonInfo aspxCommonObj, string itemCostVariantIDs)
{
try
{
string UserName = aspxCommonObj.UserName;
string[] itemArray = itemIDs.Split(',');
string[] itemCostVariantIDsArray = itemCostVariantIDs.Split(',');
List<GroupItemsQtyInfo> listItems = new List<GroupItemsQtyInfo>();
for (int count = 0; count < itemArray.Length; count++)
{
int ItemID;
string ItemCostVariant;
if ((itemArray[count].Trim() != "") && (itemCostVariantIDsArray[count].Trim() != ""))
{
ItemID = Convert.ToInt32(itemArray[count]);
ItemCostVariant = itemCostVariantIDsArray[count].ToString();
ItemCartInfo itemCartObj = AspxCartProvider.CheckItemQuantityInCart(ItemID, aspxCommonObj, ItemCostVariant);
listItems.Add(new GroupItemsQtyInfo(ItemID, itemCartObj.ItemQuantityInCart, itemCartObj.UserItemQuantityInCart));
}
}
return listItems;
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region filter
public List<Filter> GetShoppingFilter(AspxCommonInfo aspxCommonObj, string categoryName, bool isByCategory)
{
List<Filter> lstFilter = AspxFilterController.GetShoppingFilter(aspxCommonObj, categoryName, isByCategory);
return lstFilter;
}
public List<CategoryDetailFilter> GetCategoryDetailFilter(string categorykey, AspxCommonInfo aspxCommonObj)
{
try
{
List<CategoryDetailFilter> lstCatDetFilter = AspxFilterController.GetCategoryDetailFilter(categorykey, aspxCommonObj);
return lstCatDetFilter;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ItemBasicDetailsInfo> GetShoppingFilterItemsResult(int offset, int limit, string brandIds, string attributes, decimal priceFrom, decimal priceTo, string categoryName, bool isByCategory, int sortBy, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemBasicDetailsInfo> lstItemBasic = AspxFilterController.GetShoppingFilterItemsResult(offset, limit, brandIds, attributes, priceFrom, priceTo, categoryName, isByCategory, sortBy, aspxCommonObj);
return lstItemBasic;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CategoryDetailFilter> GetAllSubCategoryForFilter(string categorykey, AspxCommonInfo aspxCommonObj)
{
try
{
List<CategoryDetailFilter> lstCatDet = AspxFilterController.GetAllSubCategoryForFilter(categorykey, aspxCommonObj);
return lstCatDet;
}
catch (Exception ex)
{
throw ex;
}
}
public List<BrandItemsInfo> GetAllBrandForCategory(string categorykey, bool isByCategory, AspxCommonInfo aspxCommonObj)
{
try
{
List<BrandItemsInfo> lstBrandItem = AspxFilterController.GetAllBrandForCategory(categorykey, isByCategory, aspxCommonObj);
return lstBrandItem;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Order Management
public List<StatusInfo> GetStatusList(AspxCommonInfo aspxCommonObj)
{
try
{
List<StatusInfo> lstStatus = AspxCommonController.GetStatusList(aspxCommonObj);
return lstStatus;
}
catch (Exception ex)
{
throw ex;
}
}
public List<MyOrderListInfo> GetOrderDetails(int offset, System.Nullable<int> limit, System.Nullable<int> orderStatusName, AspxCommonInfo aspxCommonObj)
{
try
{
List<MyOrderListInfo> lstMyOrder = AspxOrderController.GetOrderDetails(offset, limit, orderStatusName, aspxCommonObj);
return lstMyOrder;
}
catch (Exception ex)
{
throw ex;
}
}
public bool SaveOrderStatus(AspxCommonInfo aspxCommonObj, int orderStatusID, int orderID)
{
try
{
bool chkMsg = AspxOrderController.SaveOrderStatus(aspxCommonObj, orderStatusID, orderID);
return chkMsg;
}
catch (Exception ex)
{
throw ex;
}
}
//-----------------------Send Email for status update-----------------------
public void NotifyOrderStatusUpdate(AspxCommonInfo aspxCommonObj, string receiverEmail, string billingShipping, string itemTable, string additionalFields, string templateName)
{
try
{
EmailTemplate.SendEmailForOrderStatus(aspxCommonObj, receiverEmail, billingShipping, itemTable, additionalFields, templateName);
if (additionalFields != null)
{
string[] fields = additionalFields.Split('#');
int orderID = Int32.Parse(fields[4]);
string orderstatus = (fields[0]);
if (orderstatus == "Complete")
{
AspxGiftCardProvider.NotifyUserForGiftCardActivation(orderID, aspxCommonObj);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
//-----------------------Get Items Involved In Order-----------------------
public List<ItemCommonInfo> GetItemsInvolvedInOrder(AspxCommonInfo aspxCommonObj, int orderID)
{
try
{
List<ItemCommonInfo> lstMyItems = AspxOrderController.GetItemsInvolvedInOrder(aspxCommonObj, orderID);
return lstMyItems;
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region OrderStatusManagement
//------------------------bind Allorder status name list-------------------------------
public List<OrderStatusListInfo> GetAllStatusList(int offset, int limit, AspxCommonInfo aspxCommonObj, string orderStatusName, System.Nullable<bool> isActive)
{
try
{
List<OrderStatusListInfo> lstOrderStat = AspxOrderStatusMgntController.GetAllStatusList(offset, limit, aspxCommonObj, orderStatusName, isActive);
return lstOrderStat;
}
catch (Exception ex)
{
throw ex;
}
}
public List<OrderStatusListInfo> AddUpdateOrderStatus(AspxCommonInfo aspxCommonObj, SaveOrderStatusInfo SaveOrderStatusObj)
{
try
{
List<OrderStatusListInfo> lstOrderStat = AspxOrderStatusMgntController.AddUpdateOrderStatus(aspxCommonObj, SaveOrderStatusObj);
return lstOrderStat;
}
catch (Exception ex)
{
throw ex;
}
}
public OrderStatusListInfo GetOrderStatusDetailByOrderStatusID(AspxCommonInfo aspxCommonObj,int OrderStatusID)
{
try
{
OrderStatusListInfo lstOrderStat = AspxOrderStatusMgntController.GetOrderStatusDetailByOrderStatusID(aspxCommonObj, OrderStatusID);
return lstOrderStat;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteOrderStatusByID(int orderStatusID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxOrderStatusMgntController.DeleteOrderStatusByID(orderStatusID, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteOrderStatusMultipleSelected(string orderStatusIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxOrderStatusMgntController.DeleteOrderStatusMultipleSelected(orderStatusIDs, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public bool CheckOrderStatusUniqueness(AspxCommonInfo aspxCommonObj, int orderStatusId, string orderStatusAliasName)
{
try
{
bool isUnique = AspxOrderStatusMgntController.CheckOrderStatusUniqueness(aspxCommonObj, orderStatusId, orderStatusAliasName);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Invoice Management
// InvoiceListMAnagement -----------------------get invoice details-----------------------
public List<InvoiceDetailsInfo> GetInvoiceDetailsList(int offset, System.Nullable<int> limit, InvoiceBasicInfo invoiceObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<InvoiceDetailsInfo> lstInvoiceDetail = AspxInvoiceMgntProvider.GetInvoiceDetailsList(offset, limit, invoiceObj, aspxCommonObj);
return lstInvoiceDetail;
}
catch (Exception ex)
{
throw ex;
}
}
//Get Invoice Details
public List<InvoiceDetailByorderIDInfo> GetInvoiceDetailsByOrderID(int orderID, AspxCommonInfo aspxCommonObj)
{
try
{
List<InvoiceDetailByorderIDInfo> info = AspxInvoiceMgntProvider.GetInvoiceDetailsByOrderID(orderID, aspxCommonObj);
return info;
}
catch (Exception ex)
{
throw ex;
}
}
//-----------------------Send Email for invoice-----------------------
public void EmailInvoice(AspxCommonInfo aspxCommonObj, string receiverEmail, string billingShipping, string itemTable, string additionalFields, string templateName)
{
try
{
EmailTemplate.SendEmailForOrderStatus(aspxCommonObj, receiverEmail, billingShipping, itemTable, additionalFields, templateName);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Shipment Management
//--ShipmentsListManagement
public List<ShipmentsDetailsInfo> GetShipmentsDetails(int offset, System.Nullable<int> limit, ShipmentsBasicinfo shipmentObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShipmentsDetailsInfo> lstShipmentDet = AspxShipMethodMgntController.GetShipmentsDetails(offset, limit, shipmentObj, aspxCommonObj);
return lstShipmentDet;
}
catch (Exception ex)
{
throw ex;
}
}
//-----------View Shipments Details--------------------------
public List<ShipmentsDetailsViewInfo> BindAllShipmentsDetails(int orderID, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShipmentsDetailsViewInfo> lstShipDetView = AspxShipMethodMgntController.BindAllShipmentsDetails(orderID, aspxCommonObj);
return lstShipDetView;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Return and Policy
public decimal CheckItemQuantity(int itemID, AspxCommonInfo aspxCommonObj, string itemCostVariantIDs)
{
try
{
decimal retValue = AspxUserDashController.CheckItemQuantity(itemID, aspxCommonObj, itemCostVariantIDs);
return retValue;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ReturnReasonListInfo> BindReturnReasonList(AspxCommonInfo aspxCommonObj)
{
try
{
List<ReturnReasonListInfo> lstRRList = AspxUserDashController.BindReturnReasonList(aspxCommonObj);
return lstRRList;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ProductStatusListInfo> BindProductStatusList(AspxCommonInfo aspxCommonObj)
{
try
{
List<ProductStatusListInfo> lstPdtStatus = AspxUserDashController.BindProductStatusList(aspxCommonObj);
return lstPdtStatus;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ReturnStatusInfo> GetReturnStatusList(AspxCommonInfo aspxCommonObj)
{
try
{
List<ReturnStatusInfo> lstRetStatus = AspxUserDashController.GetReturnStatusList(aspxCommonObj);
return lstRetStatus;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ReturnActionInfo> GetReturnActionList(AspxCommonInfo aspxCommonObj)
{
try
{
List<ReturnActionInfo> lstRetAction = AspxUserDashController.GetReturnActionList(aspxCommonObj);
return lstRetAction;
}
catch (Exception ex)
{
throw ex;
}
}
public List<MyOrderListForReturnInfo> GetMyOrderListForReturn(int orderID, AspxCommonInfo aspxCommonObj)
{
try
{
List<MyOrderListForReturnInfo> lstMyOrder = AspxUserDashController.GetMyOrderListForReturn(orderID, aspxCommonObj);
return lstMyOrder;
}
catch (Exception ex)
{
throw ex;
}
}
public void ReturnSaveUpdate(ReturnSaveUpdateInfo ReturnSaveUpdateObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxUserDashController.ReturnSaveUpdate(ReturnSaveUpdateObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void ReturnUpdate(RetunDetailsBasicInfo returnDetailObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxUserDashController.ReturnUpdate(returnDetailObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void ReturnSaveComments(RetunDetailsBasicInfo returnDetailObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxUserDashController.ReturnSaveComments(returnDetailObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<ReturnCommentsInfo> GetMyReturnsComment(RetunDetailsBasicInfo returnDetailObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ReturnCommentsInfo> info = AspxUserDashController.GetMyReturnsComment(returnDetailObj, aspxCommonObj);
return info;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ReturnsShippingInfo> GetMyReturnsShippingMethod(RetunDetailsBasicInfo returnDetailObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ReturnsShippingInfo> info;
info = AspxUserDashController.GetMyReturnsShippingMethod(returnDetailObj, aspxCommonObj);
return info;
}
catch (Exception ex)
{
throw ex;
}
}
public List<RetunReportInfo> GetReturnReport(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj, ReturnReportBasicInfo returnReportObj)
{
try
{
List<RetunReportInfo> lstRtnReport = AspxUserDashController.GetReturnReport(offset, limit, aspxCommonObj, returnReportObj);
return lstRtnReport;
}
catch (Exception ex)
{
throw ex;
}
}
public void ReturnShippingAddressSaveUpdate(AddressBasicInfo addressObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxUserDashController.ReturnShippingAddressSaveUpdate(addressObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<MyReturnListInfo> GetMyReturnsList(int offset, int limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<MyReturnListInfo> lstMyReturn = AspxUserDashController.GetMyReturnsList(offset, limit, aspxCommonObj);
return lstMyReturn;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ReturnItemsInfo> GetMyReturnsDetails(RetunDetailsBasicInfo returnDetailObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ReturnItemsInfo> info = AspxUserDashController.GetMyReturnsDetails(returnDetailObj, aspxCommonObj);
return info;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ReturnDetailsInfo> GetReturnDetails(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj, RetunDetailsBasicInfo returnDetailObj)
{
try
{
List<ReturnDetailsInfo> info = AspxUserDashController.GetReturnDetails(offset, limit, aspxCommonObj, returnDetailObj);
return info;
}
catch (Exception ex)
{
throw ex;
}
}
public void ReturnSendEmail(AspxCommonInfo aspxCommonObj, SendEmailInfo sendEmailObj)
{
try
{
EmailTemplate.SendEmailForReturns(aspxCommonObj, sendEmailObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void ReturnSaveUpdateSettings(AspxCommonInfo aspxCommonObj, int expiresInDays)
{
try
{
AspxReturnRequestMgntController.ReturnSaveUpdateSettings(aspxCommonObj, expiresInDays);
}
catch (Exception ex)
{
throw ex;
}
}
public List<ReturnsSettingsInfo> ReturnGetSettings(AspxCommonInfo aspxCommonObj)
{
try
{
List<ReturnsSettingsInfo> info = AspxReturnRequestMgntController.ReturnGetSettings(aspxCommonObj);
return info;
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region "For Brand"
public List<BrandInfo> GetAllBrandList(int offset, int limit, AspxCommonInfo aspxCommonObj, string brandName)
{
try
{
List<BrandInfo> lstBrand = AspxBrandController.GetAllBrandList(offset, limit, aspxCommonObj, brandName);
return lstBrand;
}
catch (Exception e)
{
throw e;
}
}
public List<BrandInfo> GetAllBrandForItem(AspxCommonInfo aspxCommonObj)
{
try
{
List<BrandInfo> lstBrand = AspxBrandController.GetAllBrandForItem(aspxCommonObj);
return lstBrand;
}
catch (Exception e)
{
throw e;
}
}
public void InsertNewBrand(string prevFilePath, AspxCommonInfo aspxCommonObj, BrandInfo brandInsertObj)
{
try
{
FileHelperController fileObj = new FileHelperController();
string uplodedValue = string.Empty;
string imagePath;
if (brandInsertObj.BrandImageUrl != null && prevFilePath != brandInsertObj.BrandImageUrl)
{
string tempFolder = @"Upload\temp";
uplodedValue = fileObj.MoveFileToSpecificFolder(tempFolder, prevFilePath, brandInsertObj.BrandImageUrl, @"Modules\AspxCommerce\AspxBrandManagement\uploads\", aspxCommonObj.StoreID, aspxCommonObj, "store_");
}
imagePath = uplodedValue.Length > 0 ? uplodedValue : "";
AspxBrandController.InsertNewBrand(prevFilePath, aspxCommonObj, brandInsertObj, imagePath);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteBrand(string BrandID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxBrandController.DeleteBrand(BrandID, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public List<BrandInfo> GetBrandByItemID(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
List<BrandInfo> lstBrand = AspxBrandController.GetBrandByItemID(ItemID, aspxCommonObj);
return lstBrand;
}
catch (Exception e)
{
throw e;
}
}
public void ActivateBrand(int brandID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxBrandController.ActivateBrand(brandID, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void DeActivateBrand(int brandID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxBrandController.DeActivateBrand(brandID, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public List<ItemBasicDetailsInfo> GetBrandItemsByBrandID(int offset, int limit, string brandName, int SortBy, int rowTotal, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemBasicDetailsInfo> lstItem = AspxBrandController.GetBrandItemsByBrandID(offset, limit, brandName, SortBy, rowTotal, aspxCommonObj);
return lstItem;
}
catch (Exception e)
{
throw e;
}
}
public List<BrandInfo> GetBrandDetailByBrandID(string brandName, AspxCommonInfo aspxCommonObj)
{
try
{
List<BrandInfo> lstBrand = AspxBrandController.GetBrandDetailByBrandID(brandName, aspxCommonObj);
return lstBrand;
}
catch (Exception e)
{
throw e;
}
}
public bool CheckBrandUniqueness(string brandName, AspxCommonInfo aspxCommonObj)
{
try
{
bool isUnique = AspxBrandController.CheckBrandUniqueness(brandName, aspxCommonObj);
return isUnique;
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region Search Term Management
public void AddUpdateSearchTerm(bool? hasData, string searchTerm, AspxCommonInfo aspxCommonObj)
{
try
{
AspxSearchTermMgntController.AddUpdateSearchTerm(hasData, searchTerm, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<SearchTermInfo> ManageSearchTerms(int offset, int? limit, AspxCommonInfo aspxCommonObj, string searchTerm)
{
try
{
List<SearchTermInfo> lstSearchTerm = AspxSearchTermMgntController.ManageSearchTerm(offset, limit, aspxCommonObj, searchTerm);
return lstSearchTerm;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteSearchTerm(string searchTermID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxSearchTermMgntController.DeleteSearchTerm(searchTermID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region GiftCard Method
public bool CheckGiftCardUsed(AspxCommonInfo aspxCommonObj, string giftCardCode, decimal amount)
{
try
{
bool allowToCheckout = AspxGiftCardController.CheckGiftCardUsed(aspxCommonObj, giftCardCode, amount);
return allowToCheckout;
}
catch (Exception ex)
{
throw ex;
}
}
public List<GiftCardType> GetGiftCardTypes(AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCardType> lstGiftCard = AspxGiftCardController.GetGiftCardTypes(aspxCommonObj);
return lstGiftCard;
}
catch (Exception ex)
{
throw ex;
}
}
public int GetGiftCardType(AspxCommonInfo aspxCommonObj, int cartitemId)
{
try
{
int strType = AspxGiftCardController.GetGiftCardType(aspxCommonObj, cartitemId);
return strType;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardType> GetGiftCardTypeId(AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCardType> lstGiftCardType = AspxGiftCardController.GetGiftCardTypeId(aspxCommonObj);
return lstGiftCardType;
}
catch (Exception e)
{
throw e;
}
}
public Vefification VerifyGiftCard(string giftcardCode, string pinCode, AspxCommonInfo aspxCommonObj)
{
try
{
Vefification objVerify = AspxGiftCardController.VerifyGiftCard(giftcardCode, pinCode, aspxCommonObj);
return objVerify;
}
catch (Exception e)
{
throw e;
}
}
public List<BalanceInquiry> CheckGiftCardBalance(string giftcardCode, string giftCardPinCode, AspxCommonInfo aspxCommonObj)
{
try
{
List<BalanceInquiry> lstBalanceInq = AspxGiftCardController.CheckGiftCardBalance(giftcardCode, giftCardPinCode, aspxCommonObj);
return lstBalanceInq;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardHistory> GetGiftCardHistory(int giftcardId, AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCardHistory> lstGCHistory = AspxGiftCardController.GetGiftCardHistory(giftcardId, aspxCommonObj);
return lstGCHistory;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCard> GetGiftCardDetailById(int giftcardId, AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCard> lstGiftCard = AspxGiftCardController.GetGiftCardDetailById(giftcardId, aspxCommonObj);
return lstGiftCard;
}
catch (Exception e)
{
throw e;
}
}
public void SaveGiftCardByAdmin(int giftCardId, GiftCard giftCardDetail, bool isActive, AspxCommonInfo aspxCommonObj)
{
try
{
AspxGiftCardController.SaveGiftCardByAdmin(giftCardId, giftCardDetail, isActive, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardGrid> GetAllPaidGiftCard(int offset, int limit, AspxCommonInfo aspxCommonObj, GiftCardDataInfo giftCardDataObj)
{
try
{
List<GiftCardGrid> ii = AspxGiftCardController.GetAllPaidGiftCard(offset, limit, aspxCommonObj, giftCardDataObj);
return ii;
}
catch (Exception e)
{
throw e;
}
}
public void DeleteGiftCard(string giftCardId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxGiftCardController.DeleteGiftCard(giftCardId, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteTempFile(string path)
{
if (path.Contains("GiftCard_Graphic"))
{
var filePath = HttpContext.Current.Server.MapPath("~/" + path);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
public bool CheckGiftCardCategory(AspxCommonInfo aspxCommonObj, string giftcardCategoryName)
{
try
{
bool isGiftCard = AspxGiftCardController.CheckGiftCardCategory(aspxCommonObj, giftcardCategoryName);
return isGiftCard;
}
catch (Exception e)
{
throw e;
}
}
public void SaveNewGiftCardCategory(string giftCardGraphicId, AspxCommonInfo aspxCommonObj, string giftcardCategoryName, bool isActive)
{
try
{
AspxGiftCardController.SaveNewGiftCardCategory(giftCardGraphicId, aspxCommonObj, giftcardCategoryName, isActive);
}
catch(Exception e)
{ throw e; }
}
public void SaveGiftCardCategory(int giftCardCategoryId, AspxCommonInfo aspxCommonObj, string giftcardCategoryName, bool isActive)
{
try
{
AspxGiftCardController.SaveGiftCardCategory(giftCardCategoryId, aspxCommonObj, giftcardCategoryName, isActive);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteGiftCardCategory(int giftCardCategoryId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxGiftCardController.DeleteGiftCardCategory(giftCardCategoryId, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteGiftCardThemeImage(int giftCardGraphicId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxGiftCardController.DeleteGiftCardThemeImage(giftCardGraphicId, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public string SaveGiftCardItemCategory(int itemId, string ids, AspxCommonInfo aspxCommonObj)
{
try
{
string strValue = AspxGiftCardController.SaveGiftCardItemCategory(itemId, ids, aspxCommonObj);
return strValue;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardInfo> GetGiftCardThemeImagesByItem(int itemId, AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCardInfo> lstGiftCard = AspxGiftCardController.GetGiftCardThemeImagesByItem(itemId, aspxCommonObj);
return lstGiftCard;
}
catch (Exception e)
{
throw e;
}
}
public string GetGiftCardItemCategory(int itemId, AspxCommonInfo aspxCommonObj)
{
try
{
string strValue = AspxGiftCardController.GetGiftCardItemCategory(itemId, aspxCommonObj);
return strValue;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardCategoryInfo> GetAllGiftCardCategoryGrid(int offset, int limit, AspxCommonInfo aspxCommonObj, string categoryName, DateTime? addedon, bool? status)
{
try
{
List<GiftCardCategoryInfo> lstGCCat = AspxGiftCardController.GetAllGiftCardCategoryGrid(offset, limit, aspxCommonObj, categoryName, addedon, status);
return lstGCCat;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardCategoryInfo> GetGiftCardCategoryDetailByID(int categoryID, AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCardCategoryInfo> lstGCCat = AspxGiftCardController.GetGiftCardCategoryDetailByID(categoryID, aspxCommonObj);
return lstGCCat;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardInfo> GetAllGiftCardCategory(AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCardInfo> lstGiftCard = AspxGiftCardController.GetAllGiftCardCategory(aspxCommonObj);
return lstGiftCard;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardInfo> GetAllGiftCardThemeImageByCategory(int giftCardCategoryId, AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCardInfo> lstGiftCard = AspxGiftCardController.GetAllGiftCardThemeImageByCategory(giftCardCategoryId, aspxCommonObj);
return lstGiftCard;
}
catch (Exception e)
{
throw e;
}
}
public List<GiftCardInfo> GetAllGiftCardThemeImage(AspxCommonInfo aspxCommonObj, int categoryId)
{
try
{
List<GiftCardInfo> lstGiftCard = AspxGiftCardController.GetAllGiftCardThemeImage(aspxCommonObj, categoryId);
return lstGiftCard;
}
catch (Exception e)
{
throw e;
}
}
public void SaveGiftCardThemeImage(string graphicThemeName, string graphicImage, int giftCardCategoryId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxGiftCardController.SaveGiftCardThemeImage(graphicThemeName, graphicImage, giftCardCategoryId, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public int SaveGiftCardThemeImageReturnGiftCardGraphicId(string graphicThemeName, string graphicImage, AspxCommonInfo aspxCommonObj)
{
try
{
return AspxGiftCardController.SaveGiftCardThemeImageReturnGiftCardGraphicId(graphicThemeName, graphicImage, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public List<LatestItemsInfo> GetAllGiftCards(int offset, int limit, int rowTotal, AspxCommonInfo aspxCommonObj)
{
try
{
List<LatestItemsInfo> lstGiftItems = AspxItemMgntController.GetAllGiftCards(offset, limit, rowTotal, aspxCommonObj);
return lstGiftItems;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Index Management
public List<IndexManagement> GetIndexedTables(int offset, int limit)
{
try
{
List<IndexManagement> lstCustDetail = AspxIndexManagement.GetIndexedTables(offset, limit);
return lstCustDetail;
}
catch (Exception ex)
{
throw ex;
}
}
public void ReBuild(string tableName)
{
try
{
AspxIndexManagement.ReOrganizeTable(tableName);
}
catch (Exception ex)
{
throw ex;
}
}
public void ReIndex(string tableName)
{
try
{
AspxIndexManagement.ReIndexTable(tableName);
}
catch (Exception ex)
{
throw ex;
}
}
public void ReIndexAllTables()
{
try
{
AspxIndexManagement.ReIndexAllTables();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region CustomerDetails
public List<CustomerDetailsInfo> GetCustomerDetails(string customerName, int offset, int limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<CustomerDetailsInfo> lstCustDetail = AspxCustomerMgntController.GetCustomerDetails(customerName, offset, limit, aspxCommonObj);
return lstCustDetail;
}
catch (Exception ex)
{
throw ex;
}
}
public CustomerPersonalInfo GetCustomerDetailsByCustomerID(int customerID, AspxCommonInfo aspxCommonObj)
{
try
{
return AspxCustomerMgntController.GetCustomerDetailsByCustomerID(customerID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<CustomerRecentOrders> GetCustomerRecentOrdersByCustomerID(int offset, int limit, int customerID, AspxCommonInfo aspxCommonObj)
{
try
{
return AspxCustomerMgntController.GetCustomerRecentOrdersByCustomerID(offset, limit, customerID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<CustCartInfo> GetCustomerShoppingCartByCustomerID(int customerID, AspxCommonInfo aspxCommonObj)
{
try
{
return AspxCustomerMgntController.GetCustomerShopingCartByCustomerID(customerID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteCustShoppingCartByShopID(string shoppingID, int customerID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCustomerMgntController.DeleteCustShoppingCartByShopID(shoppingID, customerID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<CustomerWishList> GetCustomerWishListByCustomerID(int offset, int limit, int customerID, AspxCommonInfo aspxCommonObj)
{
try
{
return AspxCustomerMgntController.GetCustomerWishListByCustomerID(offset, limit, customerID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteCustWishlistByWishID(string wishID, string userName, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCustomerMgntController.DeleteCustWishlistByWishID(wishID, userName, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteMultipleCustomersByCustomerID(string customerIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCustomerMgntController.DeleteMultipleCustomers(customerIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteCustomerByCustomerID(int customerId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCustomerMgntController.DeleteCustomer(customerId, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public static List<CustomerOnlineInfo> CheckIfCustomerExists(AspxCommonInfo aspxCommonObj)
{
try
{
List<CustomerOnlineInfo> isExistInfo = AspxCustomerMgntController.CheckIfCustomerExists(aspxCommonObj);
return isExistInfo;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Reportng Module
#region Customer Reports By Order Total
//--------------------bind Customer Order Total Roports-------------------------
public List<CustomerOrderTotalInfo> GetCustomerOrderTotal(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj, string user)
{
try
{
List<CustomerOrderTotalInfo> lstCustOrderTot = AspxCustomerMgntController.GetCustomerOrderTotal(offset, limit, aspxCommonObj, user);
return lstCustOrderTot;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
//--------------- New Account Reports--------------------------
public List<NewAccountReportInfo> GetNewAccounts(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj, bool monthly, bool weekly, bool hourly)
{
try
{
List<NewAccountReportInfo> lstNewAccounts = AspxCustomerMgntController.GetNewAccounts(offset, limit, aspxCommonObj, monthly, weekly, hourly);
return lstNewAccounts;
}
catch (Exception ex)
{
throw ex;
}
}
#region Online Users
public List<OnLineUserBaseInfo> GetRegisteredUserOnlineCount(int offset, int limit, string searchUserName, string searchHostAddress, string searchBrowser, AspxCommonInfo aspxCommonObj)
{
try
{
List<OnLineUserBaseInfo> lstOnlineUser = AspxCustomerMgntController.GetRegisteredUserOnlineCount(offset, limit, searchUserName, searchHostAddress, searchBrowser, aspxCommonObj);
return lstOnlineUser;
}
catch (Exception ex)
{
throw ex;
}
}
public List<OnLineUserBaseInfo> GetAnonymousUserOnlineCount(int offset, int limit, string searchHostAddress, string searchBrowser, AspxCommonInfo aspxCommonObj)
{
try
{
List<OnLineUserBaseInfo> lst = AspxCustomerMgntController.GetAnonymousUserOnlineCount(offset, limit, searchHostAddress, searchBrowser, aspxCommonObj);
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#endregion
#region Live and Abandoned Cart
//---------------------bind Abandoned cart details-------------------------
public List<AbandonedCartInfo> GetAbandonedCartDetails(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj, decimal timeToAbandonCart)
{
try
{
List<AbandonedCartInfo> bind = AspxCartController.GetAbandonedCartDetails(offset, limit, aspxCommonObj, timeToAbandonCart);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ShoppingCartInfo> GetShoppingCartItemsDetails(int offset, System.Nullable<int> limit, string itemName, string quantity, AspxCommonInfo aspxCommonObj, decimal timeToAbandonCart)
{
// quantity = quantity == "" ? null : quantity;
try
{
List<ShoppingCartInfo> lstShopCart = AspxCartController.GetShoppingCartItemsDetails(offset, limit, itemName, quantity, aspxCommonObj, timeToAbandonCart);
return lstShopCart;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Catalog Pricing Rule
public bool CheckCatalogPriorityUniqueness(int catalogPriceRuleID, int priority, AspxCommonInfo aspxCommonObj)
{
try
{
bool isUnique = AspxCatalogPriceRuleController.CheckCatalogPriorityUniqueness(catalogPriceRuleID, priority, aspxCommonObj);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public List<PricingRuleAttributeInfo> GetPricingRuleAttributes(AspxCommonInfo aspxCommonObj)
{
try
{
List<PricingRuleAttributeInfo> lstPriceRuleAttr = AspxCatalogPriceRuleController.GetPricingRuleAttributes(aspxCommonObj);
return lstPriceRuleAttr;
}
catch (Exception e)
{
throw e;
}
}
public List<CatalogPriceRulePaging> GetPricingRules(string ruleName, System.Nullable<DateTime> startDate, System.Nullable<DateTime> endDate, System.Nullable<bool> isActive, AspxCommonInfo aspxCommonObj, int offset, int limit)
{
List<CatalogPriceRulePaging> lstCatalogPriceRule = AspxCatalogPriceRuleController.GetCatalogPricingRules(ruleName, startDate, endDate, isActive, aspxCommonObj, offset, limit);
return lstCatalogPriceRule;
}
public CatalogPricingRuleInfo GetPricingRule(Int32 catalogPriceRuleID, AspxCommonInfo aspxCommonObj)
{
CatalogPricingRuleInfo catalogPricingRuleInfo;
catalogPricingRuleInfo = AspxCatalogPriceRuleController.GetCatalogPricingRule(catalogPriceRuleID, aspxCommonObj);
return catalogPricingRuleInfo;
}
//public async void RefreshCatalogPriceRules(CatalogPricingRuleInfo objCatalogPricingRuleInfo, AspxCommonInfo aspxCommonObj, List<int> parentID)
//{
// await SavePricingRuleAsync(objCatalogPricingRuleInfo, aspxCommonObj, parentID);
//}
public string SavePricingRule(CatalogPricingRuleInfo objCatalogPricingRuleInfo, AspxCommonInfo aspxCommonObj, List<int> parentID)
{
try
{
List<KeyValuePair<string, object>> p1 = new List<KeyValuePair<string, object>>();
p1.Add(new KeyValuePair<string, object>("@StoreID", aspxCommonObj.StoreID));
p1.Add(new KeyValuePair<string, object>("@PortalID", aspxCommonObj.PortalID));
SQLHandler sql = new SQLHandler();
int count = sql.ExecuteAsScalar<int>("usp_Aspx_CatalogPriceRuleCount", p1);
int maxAllowed = 3;
int catalogPriceRuleId = objCatalogPricingRuleInfo.CatalogPriceRule.CatalogPriceRuleID;
if (catalogPriceRuleId > 0)
{
maxAllowed++;
}
if (count < maxAllowed)
{
AspxCatalogPriceRuleController.SaveCatalogPricingRule(objCatalogPricingRuleInfo, aspxCommonObj, parentID);
//return "({ \"returnStatus\" : 1 , \"Message\" : \"Saving catalog pricing rule successfully.\" })";
return "success";
}
else
{
//return "({ \"returnStatus\" : -1 , \"Message\" : \"No more than 3 rules are allowed in Free version of AspxCommerce!\" })";
return "notify";
}
}
catch (Exception ex)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(ex))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + ex.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while saving catalog pricing rule!\" })";
}
}
}
public string SaveAndApplyPricingRule(CatalogPricingRuleInfo objCatalogPricingRuleInfo, AspxCommonInfo aspxCommonObj, List<int> parentID)
{
try
{
List<KeyValuePair<string, object>> p1 = new List<KeyValuePair<string, object>>();
p1.Add(new KeyValuePair<string, object>("@StoreID", aspxCommonObj.StoreID));
p1.Add(new KeyValuePair<string, object>("@PortalID", aspxCommonObj.PortalID));
SQLHandler sql = new SQLHandler();
int count = sql.ExecuteAsScalar<int>("usp_Aspx_CatalogPriceRuleCount", p1);
int maxAllowed = 3;
int catalogPriceRuleId = objCatalogPricingRuleInfo.CatalogPriceRule.CatalogPriceRuleID;
if (catalogPriceRuleId > 0)
{
maxAllowed++;
}
if (count < maxAllowed)
{
AspxCatalogPriceRuleController.SaveCatalogPricingRule(objCatalogPricingRuleInfo, aspxCommonObj, parentID);
AppyCatalogRules(aspxCommonObj);
//objCatalog.ApplyCatalogPricingRule(aspxCommonObj);
//return "({ \"returnStatus\" : 1 , \"Message\" : \"Saving catalog pricing rule successfully.\" })";
return "success";
}
else
{
//return "({ \"returnStatus\" : -1 , \"Message\" : \"No more than 3 rules are allowed in Free version of AspxCommerce!\" })";
return "notify";
}
}
catch (Exception ex)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(ex))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + ex.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while saving catalog pricing rule!\" })";
}
}
}
//public Task<string> SavePricingRuleAsync(CatalogPricingRuleInfo objCatalogPricingRuleInfo, AspxCommonInfo aspxCommonObj, List<int> parentID)
//{
// Task<string> result = new Task<string>();
// try
// {
// List<KeyValuePair<string, object>> p1 = new List<KeyValuePair<string, object>>();
// p1.Add(new KeyValuePair<string, object>("@StoreID", aspxCommonObj.StoreID));
// p1.Add(new KeyValuePair<string, object>("@PortalID", aspxCommonObj.PortalID));
// SQLHandler sql = new SQLHandler();
// int count = sql.ExecuteAsScalar<int>("usp_Aspx_CatalogPriceRuleCount", p1);
// int maxAllowed = 3;
// int catalogPriceRuleId = objCatalogPricingRuleInfo.CatalogPriceRule.CatalogPriceRuleID;
// if (catalogPriceRuleId > 0)
// {
// maxAllowed++;
// }
// if (count < maxAllowed)
// {
// AspxCatalogPriceRuleController.SaveCatalogPricingRule(objCatalogPricingRuleInfo, aspxCommonObj, parentID);
// //return "({ \"returnStatus\" : 1 , \"Message\" : \"Saving catalog pricing rule successfully.\" })";
// result = Task<string>.Factory.StartNew(() => "success");
// return result;
// }
// else
// {
// //return "({ \"returnStatus\" : -1 , \"Message\" : \"No more than 3 rules are allowed in Free version of AspxCommerce!\" })";
// result = Task<string>.Factory.StartNew(() => "notify");
// return result;
// }
// }
// catch (Exception ex)
// {
// ErrorHandler errHandler = new ErrorHandler();
// if (errHandler.LogWCFException(ex))
// {
// result = Task<string>.Factory.StartNew(() => "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + ex.Message + "\" })");
// return result;
// }
// else
// {
// result = Task<string>.Factory.StartNew(() => "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while saving catalog pricing rule!\" })");
// return result;
// }
// }
//}
public string DeletePricingRule(Int32 catalogPricingRuleID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCatalogPriceRuleController.CatalogPriceRuleDelete(catalogPricingRuleID, aspxCommonObj);
return "({ \"returnStatus\" : 1 , \"Message\" : \"Deleting catalog pricing rule successfully.\" })";
}
catch (Exception ex)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(ex))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + ex.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while deleting catalog pricing rule!\" })";
}
}
}
public void AppyCatalogRules(AspxCommonInfo aspxCommonObj)
{
try
{
AspxCatalogPriceRuleController objCatalog = new AspxCatalogPriceRuleController();
catalogThread = new Thread(() => objCatalog.ApplyCatalogPricingRule(aspxCommonObj));
catalogThread.Name = "CatalagPriceRule";
catalogThread.Start();
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckCatalogRuleExist(AspxCommonInfo aspxCommonObj)
{
try
{
AspxCatalogPriceRuleController objCatalog = new AspxCatalogPriceRuleController();
return objCatalog.CheckCatalogRuleExist(aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public string DeleteMultipleCatPricingRules(string catRulesIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCatalogPriceRuleController.CatalogPriceMultipleRulesDelete(catRulesIds, aspxCommonObj);
return "({ \"returnStatus\" : 1 , \"Message\" : \"Deleting multiple catalog pricing rules successfully.\" })";
}
catch (Exception ex)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(ex))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + ex.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while deleting pricing rule!\" })";
}
}
}
#endregion
#region Cart Pricing Rule
public bool CheckCartPricePriorityUniqueness(int cartPriceRuleID, int priority, int portalID)
{
try
{
bool isUnique = AspxCartPriceRuleProvider.CheckCartPricePriorityUniqueness(cartPriceRuleID, priority, portalID);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ShippingMethodInfo> GetShippingMethods(System.Nullable<bool> isActive, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShippingMethodInfo> lstShipMethod = AspxCartPriceRuleController.GetShippingMethods(isActive, aspxCommonObj);
return lstShipMethod;
}
catch (Exception e)
{
throw e;
}
}
public List<CartPricingRuleAttributeInfo> GetCartPricingRuleAttributes(AspxCommonInfo aspxCommonObj)
{
try
{
List<CartPricingRuleAttributeInfo> lst = AspxCartPriceRuleController.GetCartPricingRuleAttributes(aspxCommonObj);
return lst;
}
catch (Exception e)
{
throw e;
}
}
public string SaveCartPricingRule(CartPricingRuleInfo objCartPriceRule, AspxCommonInfo aspxCommonObj, List<int> parentID)
{
try
{
List<KeyValuePair<string, object>> p1 = new List<KeyValuePair<string, object>>();
//P1.Add(new KeyValuePair<string,object>("@StoreID", storeID));
p1.Add(new KeyValuePair<string, object>("PortalID", aspxCommonObj.PortalID));
SQLHandler sql = new SQLHandler();
int count = sql.ExecuteAsScalar<int>("usp_Aspx_CartPrincingRuleCount", p1);
int maxAllowed = 3;
int cartPriceRuleId = objCartPriceRule.CartPriceRule.CartPriceRuleID;
if (cartPriceRuleId > 0)
{
maxAllowed++;
}
if (count < maxAllowed)
{
AspxCartPriceRuleController.SaveCartPricingRule(objCartPriceRule, aspxCommonObj, parentID);
//return "({ \"returnStatus\" : 1 , \"Message\" : \"Saving cart pricing rule successfully.\" })";
return "success";
}
else
{
//return "({ \"returnStatus\" : -1 , \"Message\" : \"No more than 3 rules are allowed in Free version of AspxCommerce!\" })";
return "notify";
}
}
catch (Exception ex)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(ex))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + ex.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while saving cart pricing rule!\" })";
}
}
}
public List<CartPriceRulePaging> GetCartPricingRules(string ruleName, System.Nullable<DateTime> startDate, System.Nullable<DateTime> endDate, System.Nullable<bool> isActive, AspxCommonInfo aspxCommonObj, int offset, int limit)
{
List<CartPriceRulePaging> lstCartPriceRule = AspxCartPriceRuleController.GetCartPricingRules(ruleName, startDate, endDate, isActive, aspxCommonObj, offset, limit);
return lstCartPriceRule;
}
public CartPricingRuleInfo GetCartPricingRule(Int32 cartPriceRuleID, AspxCommonInfo aspxCommonObj)
{
CartPricingRuleInfo cartPricingRuleInfo;
cartPricingRuleInfo = AspxCartPriceRuleController.GetCartPriceRules(cartPriceRuleID, aspxCommonObj);
return cartPricingRuleInfo;
}
public string DeleteCartPricingRule(Int32 cartPricingRuleID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCartPriceRuleController.CartPriceRuleDelete(cartPricingRuleID, aspxCommonObj);
return "({ \"returnStatus\" : 1 , \"Message\" : \"Deleting cart pricing rule successfully.\" })";
}
catch (Exception ex)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(ex))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + ex.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while deleting cart pricing rule!\" })";
}
}
}
public string DeleteMultipleCartPricingRules(string cartRulesIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCartPriceRuleController.CartPriceMultipleRulesDelete(cartRulesIds, aspxCommonObj);
return "({ \"returnStatus\" : 1 , \"Message\" : \"Deleting multiple cart pricing rules successfully.\" })";
}
catch (Exception ex)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(ex))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + ex.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while deleting cart pricing rule!\" })";
}
}
}
#endregion
#region Category Management
public bool CheckUniqueCategoryName(string catName, int catId, AspxCommonInfo aspxCommonObj)
{
try
{
bool isUnique = AspxCategoryManageController.CheckUniqueCategoryName(catName, catId, aspxCommonObj);
return isUnique;
}
catch (Exception e)
{
throw e;
}
}
public bool IsUnique(Int32 storeID, Int32 portalID, Int32 itemID, Int32 attributeID, Int32 attributeType, string attributeValue)
{
try
{
/*
1 TextField
2 TextArea
3 Date
4 Boolean
5 MultipleSelect
6 DropDown
7 Price
8 File
9 Radio
10 RadioButtonList
11 CheckBox
12 CheckBoxList
*/
bool isUnique = AspxCategoryManageController.IsUnique(storeID, portalID, itemID, attributeID, attributeType, attributeValue);
return isUnique;
}
catch (Exception e)
{
ErrorHandler errHandler = new ErrorHandler();
errHandler.LogWCFException(e);
return false;
}
}
public List<AttributeFormInfo> GetCategoryFormAttributes(Int32 categoryID, AspxCommonInfo aspxCommonObj)
{
try
{
List<AttributeFormInfo> frmFieldList = AspxCategoryManageController.GetCategoryFormAttributes(categoryID, aspxCommonObj);
return frmFieldList;
}
catch (Exception e)
{
ErrorHandler errHandler = new ErrorHandler();
errHandler.LogWCFException(e);
throw e;
}
}
public List<CategoryInfo> GetCategoryAll(bool isActive, AspxCommonInfo aspxCommonObj)
{
try
{
List<CategoryInfo> catList = AspxCategoryManageController.GetCategoryAll(isActive, aspxCommonObj);
return catList;
}
catch (Exception e)
{
ErrorHandler errHandler = new ErrorHandler();
errHandler.LogWCFException(e);
throw e;
}
}
public List<CategoryAttributeInfo> GetCategoryByCategoryID(Int32 categoryID, AspxCommonInfo aspxCommonObj)
{
List<CategoryAttributeInfo> catList = AspxCategoryManageController.GetCategoryByCategoryID(categoryID, aspxCommonObj);
return catList;
}
public string SaveCategory(CategoryInfo.CategorySaveBasicInfo categoryObj, AspxCommonInfo aspxCommonObj)
{
try
{
int categoryId = AspxCategoryManageController.SaveCategory(categoryObj, aspxCommonObj);
CacheHelper.Clear("CategoryInfo" + aspxCommonObj.StoreID + aspxCommonObj.PortalID + "_" + aspxCommonObj.CultureName);
CacheHelper.Clear("CategoryForSearch" + aspxCommonObj.StoreID + aspxCommonObj.PortalID + "_" + aspxCommonObj.CultureName);
if (categoryObj.ParentId > 0)
{
return
"({\"returnStatus\":1,\"Message\":\"Sub category has been saved successfully.\",\"categoryID\":" +
categoryId + "})";
}
else
{
return "({\"returnStatus\":1,\"Message\":\"Category has been saved successfully.\",\"categoryID\":" +
categoryId + "})";
}
}
catch (Exception e)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(e))
{
return "({\"returnStatus\":-1,\"errorMessage\":'" + e.Message + "'})";
}
else
{
return "({\"returnStatus\":-1,\"errorMessage\":\"Error while saving category!\"})";
}
}
}
public string DeleteCategory(Int32 storeID, Int32 portalID, Int32 categoryID, string userName, string culture)
{
try
{
AspxCategoryManageController.DeleteCategory(storeID, portalID, categoryID, userName, culture);
CacheHelper.Clear("CategoryInfo" + storeID.ToString() + portalID.ToString());
CacheHelper.Clear("CategoryForSearch" + storeID.ToString() + portalID.ToString());
return "({ \"returnStatus\" : 1 , \"Message\" : \"Category has been deleted successfully.\" })";
}
catch (Exception e)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(e))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + e.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while deleting category!\" })";
}
}
}
public List<CategoryItemInfo> GetCategoryItems(Int32 offset, System.Nullable<int> limit, GetCategoryItemInfo categoryItemsInfo, AspxCommonInfo aspxCommonObj, bool serviceBit)
{
try
{
List<CategoryItemInfo> listCategoryItem = AspxCategoryManageController.GetCategoryItems(offset, limit, categoryItemsInfo, aspxCommonObj, serviceBit);
return listCategoryItem;
}
catch (Exception e)
{
ErrorHandler errHandler = new ErrorHandler();
errHandler.LogWCFException(e);
throw e;
}
}
public string GetCategoryCheckedItems(int CategoryID, AspxCommonInfo aspxCommonObj)
{
try
{
string categoryItem = AspxCategoryManageController.GetCategoryCheckedItems(CategoryID, aspxCommonObj);
return categoryItem;
}
catch (Exception e)
{
ErrorHandler errHandler = new ErrorHandler();
errHandler.LogWCFException(e);
throw e;
}
}
public string SaveChangesCategoryTree(string categoryIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCategoryManageController.SaveChangesCategoryTree(categoryIDs, aspxCommonObj);
CacheHelper.Clear("CategoryInfo" + aspxCommonObj.StoreID + aspxCommonObj.PortalID + "_" + aspxCommonObj.CultureName);
CacheHelper.Clear("CategoryForSearch" + aspxCommonObj.StoreID + aspxCommonObj.PortalID + "_" + aspxCommonObj.CultureName);
return "({ \"returnStatus\" : 1 , \"Message\" : \"Category tree saved successfully.\" })";
}
catch (Exception e)
{
ErrorHandler errHandler = new ErrorHandler();
if (errHandler.LogWCFException(e))
{
return "({ \"returnStatus\" : -1 , \"errorMessage\" : \"" + e.Message + "\" })";
}
else
{
return "({ \"returnStatus\" : -1, \"errorMessage\" : \"Error while saving category tree!\" })";
}
}
}
public void ActivateCategory(int categoryID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCategoryManageController.ActivateCategory(categoryID, aspxCommonObj);
CacheHelper.Clear("CategoryInfo" + aspxCommonObj.StoreID + aspxCommonObj.PortalID + "_" + aspxCommonObj.CultureName);
CacheHelper.Clear("CategoryForSearch" + aspxCommonObj.StoreID + aspxCommonObj.PortalID + "_" + aspxCommonObj.CultureName);
}
catch (Exception e)
{
throw e;
}
}
public void DeActivateCategory(int categoryID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCategoryManageController.DeActivateCategory(categoryID, aspxCommonObj);
CacheHelper.Clear("CategoryInfo" + aspxCommonObj.StoreID + aspxCommonObj.PortalID + "_" + aspxCommonObj.CultureName);
CacheHelper.Clear("CategoryForSearch" + aspxCommonObj.StoreID + aspxCommonObj.PortalID + "_" + aspxCommonObj.CultureName);
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region Shipping method management
//---------------------Shipping Reports--------------------
public List<ShippedReportInfo> GetShippedDetails(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj, ShippedReportBasicInfo ShippedReportObj)
{
try
{
List<ShippedReportInfo> lstShipReport = AspxShipMethodMgntController.GetShippedDetails(offset, limit, aspxCommonObj, ShippedReportObj);
return lstShipReport;
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckUniquenessForDisplayOrder(AspxCommonInfo aspxCommonObj, int value, int shippingMethodID)
{
try
{
bool isUnique = AspxShipMethodMgntController.CheckUniquenessForDisplayOrder(aspxCommonObj, value, shippingMethodID);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
//-----------Bind Shipping methods In grid-----------------------------
public List<ShippingMethodInfo> GetStoreProvidersAvailableMethod(int providerId, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShippingMethodInfo> lstShipMethod = AspxShipMethodMgntController.GetStoreProvidersAvailableMethod(providerId, aspxCommonObj);
return lstShipMethod;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ShippingMethodInfoByProvider> GetShippingMethodListByProvider(int offset, int limit, int shippingProviderId, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShippingMethodInfoByProvider> shipping = AspxShipMethodMgntController.GetShippingMethodsByProvider(offset, limit, shippingProviderId, aspxCommonObj);
return shipping;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ShippingMethodInfo> GetShippingMethodList(int offset, int limit, ShippingMethodInfoByProvider shippingMethodObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShippingMethodInfo> shipping = AspxShipMethodMgntController.GetShippingMethods(offset, limit, shippingMethodObj, aspxCommonObj);
return shipping;
}
catch (Exception ex)
{
throw ex;
}
}
//-----------------delete multiple shipping methods----------------------
public void DeleteShippingByShippingMethodID(string shippingMethodIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipMethodMgntController.DeleteShippings(shippingMethodIds, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//----------------bind shipping service list---------------
public List<ShippingProviderListInfo> GetShippingProviderList(AspxCommonInfo aspxCommonObj)
{
try
{
List<ShippingProviderListInfo> lstShipProvider = AspxShipMethodMgntController.GetShippingProviderList(aspxCommonObj);
return lstShipProvider;
}
catch (Exception ex)
{
throw ex;
}
}
//--------------------------SaveAndUpdate shipping methods-------------------
public void SaveAndUpdateShippingMethods(int shippingMethodID, string shippingMethodName, string prevFilePath, string newFilePath, string alternateText, int displayOrder, string deliveryTime,
decimal weightLimitFrom, decimal weightLimitTo, int shippingProviderID, bool isActive, AspxCommonInfo aspxCommonObj)
{
try
{
FileHelperController fileObj = new FileHelperController();
string uplodedValue = string.Empty;
if (newFilePath != null && prevFilePath != newFilePath)
{
string tempFolder = @"Upload\temp";
uplodedValue = fileObj.MoveFileToSpecificFolder(tempFolder, prevFilePath, newFilePath, @"Modules\AspxCommerce\AspxShippingManagement\uploads\", shippingMethodID, aspxCommonObj, "ship_");
}
else
{
uplodedValue = prevFilePath;
}
AspxShipMethodMgntController.SaveAndUpdateShippings(shippingMethodID, shippingMethodName, uplodedValue, alternateText, displayOrder, deliveryTime, weightLimitFrom, weightLimitTo, shippingProviderID, isActive, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//--------------------bind Cost dependencies in Grid--------------------------
public List<ShippingCostDependencyInfo> GetCostDependenciesListInfo(int offset, int limit, AspxCommonInfo aspxCommonObj, int shippingMethodId)
{
try
{
List<ShippingCostDependencyInfo> bind = AspxShipMethodMgntController.GetCostDependenciesListInfo(offset, limit, aspxCommonObj, shippingMethodId);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//--------------------bind Weight dependencies in Grid--------------------------
public List<ShippingWeightDependenciesInfo> GetWeightDependenciesListInfo(int offset, int limit, AspxCommonInfo aspxCommonObj, int shippingMethodId)
{
try
{
List<ShippingWeightDependenciesInfo> bind = AspxShipMethodMgntController.GetWeightDependenciesListInfo(offset, limit, aspxCommonObj, shippingMethodId);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//--------------------bind Item dependencies in Grid--------------------------
public List<ShippingItemDependenciesInfo> GetItemDependenciesListInfo(int offset, int limit, AspxCommonInfo aspxCommonObj, int shippingMethodId)
{
try
{
List<ShippingItemDependenciesInfo> bind = AspxShipMethodMgntController.GetItemDependenciesListInfo(offset, limit, aspxCommonObj, shippingMethodId);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------Delete multiple cost Depandencies --------------------------
public void DeleteCostDependencies(string shippingProductCostIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipMethodMgntController.DeleteCostDependencies(shippingProductCostIds, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//---------------Delete multiple weight Depandencies --------------------------
public void DeleteWeightDependencies(string shippingProductWeightIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipMethodMgntController.DeleteWeightDependencies(shippingProductWeightIds, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//---------------Delete multiple item Depandencies --------------------------
public void DeleteItemDependencies(string shippingItemIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipMethodMgntController.DeleteItemDependencies(shippingItemIds, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//------------------save cost dependencies----------------
public void SaveCostDependencies(int shippingProductCostID, int shippingMethodID, string costDependenciesOptions, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipMethodMgntController.AddCostDependencies(shippingProductCostID, shippingMethodID, costDependenciesOptions, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//---------------- save weight dependencies-------------------------------
public void SaveWeightDependencies(int shippingProductWeightID, int shippingMethodID, string weightDependenciesOptions, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipMethodMgntController.AddWeightDependencies(shippingProductWeightID, shippingMethodID, weightDependenciesOptions, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//---------------- save item dependencies-------------------------------
public void SaveItemDependencies(int shippingItemID, int shippingMethodID, string itemDependenciesOptions, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipMethodMgntController.AddItemDependencies(shippingItemID, shippingMethodID, itemDependenciesOptions, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Shipping Service Providers management
public void DeactivateShippingMethod(int shippingMethodId, AspxCommonInfo aspxCommonObj, bool isActive)
{
AspxShipProviderMgntController.DeactivateShippingMethod(shippingMethodId, aspxCommonObj, isActive);
}
public List<ProviderShippingMethod> GetProviderRemainingMethod(int shippingProviderId, AspxCommonInfo aspxCommonObj)
{
try
{
List<ProviderShippingMethod> services = AspxShipProviderMgntController.GetProviderRemainingMethod(shippingProviderId, aspxCommonObj);
return services;
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckShippingProviderUniqueness(AspxCommonInfo aspxCommonObj, int shippingProviderId, string shippingProviderName)
{
try
{
bool isUnique = AspxShipProviderMgntController.CheckShippingProviderUniqueness(aspxCommonObj, shippingProviderId, shippingProviderName);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ShippingProviderNameListInfo> GetShippingProviderNameList(int offset, int limit, AspxCommonInfo aspxCommonObj, string shippingProviderName, System.Nullable<bool> isActive)
{
try
{
List<ShippingProviderNameListInfo> lstShipProvider = AspxShipProviderMgntController.GetShippingProviderNameList(offset, limit, aspxCommonObj, shippingProviderName, isActive);
return lstShipProvider;
}
catch (Exception ex)
{
throw ex;
}
}
public string LoadProviderSetting(int providerId, AspxCommonInfo aspxCommonObj)
{
string retStr = AspxShipProviderMgntController.LoadProviderSetting(providerId, aspxCommonObj);
return retStr;
}
public void ShippingProviderAddUpdate(List<ShippingMethod> methods,
ShippingProvider provider, bool isAddedZip, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipProviderMgntController.ShippingProviderAddUpdate(methods, provider, isAddedZip, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteShippingProviderByID(int shippingProviderID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipProviderMgntController.DeleteShippingProviderByID(shippingProviderID, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteShippingProviderMultipleSelected(string shippingProviderIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxShipProviderMgntController.DeleteShippingProviderMultipleSelected(shippingProviderIDs, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region Ware house
public List<WareHouse> GetAllWareHouse(int offset, int limit, AspxCommonInfo aspxCommonObj)
{
List<WareHouse> wList = AspxWareHouseController.GetAllWareHouse(offset, limit, aspxCommonObj);
return wList;
}
public List<WareHouseAddress> GetAllWareHouseById(int wareHouseID, AspxCommonInfo aspxCommonObj)
{
List<WareHouseAddress> wList = AspxWareHouseController.GetAllWareHouseById(wareHouseID, aspxCommonObj);
return wList;
}
public void DeleteWareHouse(int wareHouseId, AspxCommonInfo aspxCommonObj)
{
AspxWareHouseController.DeleteWareHouse(wareHouseId, aspxCommonObj);
}
public void AddUpDateWareHouse(WareHouseAddress wareHouse, AspxCommonInfo aspxCommonObj)
{
AspxWareHouseController.AddUpDateWareHouse(wareHouse, aspxCommonObj);
}
#endregion
#region Tax management
//--------------item tax classes------------------
public List<TaxItemClassInfo> GetTaxItemClassDetails(int offset, int limit, string itemClassName, AspxCommonInfo aspxCommonObj)
{
try
{
List<TaxItemClassInfo> lstTaxItem = AspxTaxMgntController.GetTaxItemClassDetails(offset, limit, itemClassName, aspxCommonObj);
return lstTaxItem;
}
catch (Exception ex)
{
throw ex;
}
}
//-------------------save item tax class--------------------
public void SaveAndUpdateTaxItemClass(int taxItemClassID, string taxItemClassName, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTaxMgntController.SaveAndUpdateTaxItemClass(taxItemClassID, taxItemClassName, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckTaxClassUniqueness(AspxCommonInfo aspxCommonObj, string taxItemClassName)
{
try
{
bool isUnique = AspxTaxMgntController.CheckTaxClassUniqueness(aspxCommonObj, taxItemClassName);
return isUnique;
}
catch (Exception e)
{
throw e;
}
}
//-----------------Delete tax item classes --------------------------------
public void DeleteTaxItemClass(string taxItemClassIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTaxMgntController.DeleteTaxItemClass(taxItemClassIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//--------------customer tax classes------------------
public List<TaxCustomerClassInfo> GetTaxCustomerClassDetails(int offset, int limit, string className, AspxCommonInfo aspxCommonObj)
{
try
{
List<TaxCustomerClassInfo> lstTaxCtClass = AspxTaxMgntController.GetTaxCustomerClassDetails(offset, limit, className, aspxCommonObj);
return lstTaxCtClass;
}
catch (Exception ex)
{
throw ex;
}
}
//-------------------save customer tax class--------------------
public void SaveAndUpdateTaxCustmerClass(int taxCustomerClassID, string taxCustomerClassName, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTaxMgntController.SaveAndUpdateTaxCustmerClass(taxCustomerClassID, taxCustomerClassName, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//-----------------Delete tax customer classes --------------------------------
public void DeleteTaxCustomerClass(string taxCustomerClassIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTaxMgntController.DeleteTaxCustomerClass(taxCustomerClassIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//--------------tax rates------------------
public List<TaxRateInfo> GetTaxRateDetails(int offset, System.Nullable<int> limit, TaxRateDataTnfo taxRateDataObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<TaxRateInfo> lstTaxRate = AspxTaxMgntController.GetTaxRateDetails(offset, limit, taxRateDataObj, aspxCommonObj);
return lstTaxRate;
}
catch (Exception ex)
{
throw ex;
}
}
//----------------- save and update tax rates--------------------------
public void SaveAndUpdateTaxRates(TaxRateDataTnfo taxRateDataObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTaxMgntController.SaveAndUpdateTaxRates(taxRateDataObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//-------------dalete Tax rates-----------------------
public void DeleteTaxRates(string taxRateIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTaxMgntController.DeleteTaxRates(taxRateIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//--------------------------get customer class----------------
public List<TaxManageRulesInfo> GetTaxRules(int offset, int limit, TaxRuleDataInfo taxRuleDataObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<TaxManageRulesInfo> lstTaxManage = AspxTaxMgntController.GetTaxRules(offset, limit, taxRuleDataObj, aspxCommonObj);
return lstTaxManage;
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------bind tax customer class name list-------------------------------
public List<TaxCustomerClassInfo> GetCustomerTaxClass(int storeID, int portalID)
{
try
{
List<TaxCustomerClassInfo> lstTaxCtClass = AspxTaxMgntController.GetCustomerTaxClass(storeID, portalID);
return lstTaxCtClass;
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------bind tax item class name list-------------------------------
public List<TaxItemClassInfo> GetItemTaxClass(AspxCommonInfo aspxCommonObj)
{
try
{
List<TaxItemClassInfo> lstTaxItClass = AspxTaxMgntController.GetItemTaxClass(aspxCommonObj);
return lstTaxItClass;
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------bind tax rate list-------------------------------
public List<TaxRateInfo> GetTaxRate(AspxCommonInfo aspxCommonObj)
{
try
{
List<TaxRateInfo> lstTaxRate = AspxTaxMgntController.GetTaxRate(aspxCommonObj);
return lstTaxRate;
}
catch (Exception ex)
{
throw ex;
}
}
//-------------------save and update tax rules--------------------------------------
public void SaveAndUpdateTaxRule(TaxRuleDataInfo taxRuleDataObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTaxMgntController.SaveAndUpdateTaxRule(taxRuleDataObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//-------------- delete Tax Rules----------------------------
public void DeleteTaxManageRules(string taxManageRuleIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTaxMgntController.DeleteTaxManageRules(taxManageRuleIDs, aspxCommonObj);
}
catch (Exception exe)
{
throw exe;
}
}
public bool CheckTaxUniqueness(AspxCommonInfo aspxCommonObj, int value, int taxRuleID)
{
try
{
bool isUnique = AspxTaxMgntController.CheckTaxUniqueness(aspxCommonObj, value, taxRuleID);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
#region Sales Tax Report
public List<StoreTaxesInfo> GetStoreSalesTaxes(int offset, int limit, TaxDateData taxDataObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<StoreTaxesInfo> lstStoreTax = AspxTaxMgntController.GetStoreSalesTaxes(offset, limit, taxDataObj, aspxCommonObj);
return lstStoreTax;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#endregion
#region Coupon Management
#region Coupon Type Manage
public bool CheckCouponTypeUniqueness(AspxCommonInfo aspxCommonObj, int couponTypeId, string couponType)
{
try
{
bool isUnique = AspxCouponManageController.CheckCouponTypeUniqueness(aspxCommonObj, couponTypeId, couponType);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CouponTypeInfo> GetCouponTypeDetails(int offset, int limit, string couponTypeName, AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponTypeInfo> lstCoupType = AspxCouponManageController.GetCouponTypeDetails(offset, limit, couponTypeName, aspxCommonObj);
return lstCoupType;
}
catch (Exception ex)
{
throw ex;
}
}
public void AddUpdateCouponType(CouponTypeInfo couponTypeObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCouponManageController.AddUpdateCouponType(couponTypeObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteCouponType(string IDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCouponManageController.DeleteCouponType(IDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Coupon Manage
public List<CouponInfo> GetCouponDetails(int offset, int limit, GetCouponDetailsInfo couponDetailObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponInfo> lstCoupon = AspxCouponManageController.BindAllCouponDetails(offset, limit, couponDetailObj, aspxCommonObj);
return lstCoupon;
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckUniqueCouponCode(string couponCode, AspxCommonInfo aspxCommonObj)
{
try
{
bool isExists = AspxCouponManageProvider.CheckUniqueCouponCode(couponCode, aspxCommonObj);
return isExists;
}
catch (Exception ex)
{
throw ex;
}
}
public string AddUpdateCouponDetails(CouponSaveObj couponSaveObj, CouponEmailInfo couponEmailObj, AspxCommonInfo aspxCommonObj)
{
string checkMessage = string.Empty;
try
{
try
{
AspxCouponManageController.AddUpdateCoupons(couponSaveObj, aspxCommonObj);
checkMessage += "dataSave" + ",";
}
catch (Exception)
{
checkMessage += "dataSaveFail" + ",";
}
if (checkMessage == "dataSave,")
{
//if (portalUserEmailID != "")
if (couponEmailObj.ReceiverEmail != "")
{
try
{
// cmSQLProvider.SendCouponCodeEmail(senderEmail, portalUserEmailID, subject, messageBody);
AspxCouponManageController.SendCouponCodeEmail(couponEmailObj);
checkMessage += "emailSend";
}
catch (Exception)
{
checkMessage += "emailSendFail";
}
}
else
{
checkMessage += "emailIDBlank";
}
}
else
{
checkMessage += "emailSendFail";
}
return checkMessage;
}
catch (Exception ex)
{
throw ex;
}
}
public void AddUpdatePromoCodeDetails(PromoCodeSaveObj promoSaveObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCouponManageController.AddUpdatPromoCode(promoSaveObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<CouponStatusInfo> GetCouponStatus(AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponStatusInfo> lstCoupStat = AspxCouponManageController.BindCouponStatus(aspxCommonObj);
return lstCoupStat;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CouponSettingKeyValueInfo> GetSettinKeyValueByCouponID(int couponID, AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponSettingKeyValueInfo> lstCoupKeyVal = AspxCouponManageController.GetCouponSettingKeyValueInfo(couponID, aspxCommonObj);
return lstCoupKeyVal;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CouponPortalUserListInfo> GetPortalUsersByCouponID(int offset, int limit, int couponID, string customerName, AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponPortalUserListInfo> lstCoupUser = AspxCouponManageController.GetPortalUsersList(offset, limit, couponID, customerName, aspxCommonObj);
return lstCoupUser;
}
catch (Exception ex)
{
throw ex;
}
}
//----------------delete coupons(admin)-----------
public void DeleteCoupons(string couponIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCouponManageController.DeleteCoupons(couponIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
////-------------------Verify Coupon Code-----------------------------
//[WebMethod]
//public CouponVerificationInfo VerifyCouponCode(decimal totalCost, string couponCode, string itemIds, string cartItemIds, AspxCommonInfo aspxCommonObj, int appliedCount)
//{
// try
// {
// CouponVerificationInfo objCoupVeri = AspxCouponManageController.VerifyUserCoupon(totalCost, couponCode, itemIds, cartItemIds, aspxCommonObj, appliedCount);
// return objCoupVeri;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//--------update wherever necessary after coupon verification is successful----------
public void UpdateCouponUserRecord(CouponSession coupon, int storeID, int portalID, string userName, int orderID)
{
try
{
AspxCouponManageController.UpdateCouponUserRecord(coupon, storeID, portalID, userName, orderID);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Coupons Per Sales Management
public List<CouponPerSales> GetCouponDetailsPerSales(int offset, int? limit, string couponCode, AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponPerSales> lstCoupPerSale = AspxCouponManageController.GetCouponDetailsPerSales(offset, limit, couponCode, aspxCommonObj);
return lstCoupPerSale;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CouponPerSalesViewDetailInfo> GetCouponPerSalesDetailView(int offset, int? limit, CouponPerSalesGetInfo couponPerSaesObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponPerSalesViewDetailInfo> lstCoupPSVDetail = AspxCouponManageController.GetCouponPerSalesDetailView(offset, limit, couponPerSaesObj, aspxCommonObj);
return lstCoupPSVDetail;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Coupon User Management
public List<CouponUserInfo> GetCouponUserDetails(int offset, int? limit, GetCouponUserDetailInfo couponUserObj, AspxCommonInfo aspxCommonObj, string userName)
{
try
{
List<CouponUserInfo> lstCoupUser = AspxCouponManageController.GetCouponUserDetails(offset, limit, couponUserObj, aspxCommonObj, userName);
return lstCoupUser;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CouponUserListInfo> GetCouponUserList(int offset, int limit, CouponCommonInfo bindCouponUserObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponUserListInfo> lstCoupUser = AspxCouponManageController.GetCouponUserList(offset, limit, bindCouponUserObj, aspxCommonObj);
return lstCoupUser;
}
catch (Exception ex)
{
throw ex;
}
}
public string GetPromoItemCheckIDs(int CouponID, AspxCommonInfo aspxCommonObj)
{
try
{
string lstItems = AspxCouponManageController.GetPromoItemCheckIDs(CouponID, aspxCommonObj);
return lstItems;
}
catch (Exception ex)
{
throw ex;
}
}
public List<PromoItemsInfo> GetPromoItemList(int offset, int limit, int couponTypeId, int couponId, AspxCommonInfo aspxCommonObj)
{
try
{
List<PromoItemsInfo> lstItems = AspxCouponManageController.GetAllPromoItems(offset, limit, couponTypeId, couponId,
aspxCommonObj);
return lstItems;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ItemsForPromoInfo> ItemsForPromoCode(int offset, int limit, AspxCommonInfo aspxCommonObj, string itemName, int? couponId)
{
try
{
List<ItemsForPromoInfo> lst = AspxCouponManageController.ItemsForPromoCode(offset, limit, aspxCommonObj, itemName, couponId);
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteCouponUser(string couponUserID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCouponManageController.DeleteCouponUser(couponUserID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdateCouponUser(int couponUserID, int couponStatusID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCouponManageController.UpdateCouponUser(couponUserID, couponStatusID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Coupon Status Management
public List<CouponStatusInfo> GetAllCouponStatusList(int offset, int limit, AspxCommonInfo aspxCommonObj, string couponStatusName, System.Nullable<bool> isActive)
{
try
{
List<CouponStatusInfo> lstCouponStat = AspxCouponStatusMgmtController.GetAllCouponStatusList(offset, limit, aspxCommonObj, couponStatusName, isActive);
return lstCouponStat;
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckCouponStatusUniqueness(AspxCommonInfo aspxCommonObj, int couponStatusId, string couponStatusName)
{
try
{
bool isUnique = AspxCouponStatusMgmtController.CheckCouponStatusUniqueness(aspxCommonObj, couponStatusId, couponStatusName);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CouponStatusInfo> AddUpdateCouponStatus(AspxCommonInfo aspxCommonObj, CouponStatusInfo SaveCouponStatusObj)
{
try
{
List<CouponStatusInfo> lstCouponStat = AspxCouponStatusMgmtController.AddUpdateCouponStatus(aspxCommonObj, SaveCouponStatusObj);
return lstCouponStat;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Coupon Setting Manage/Admin
public void DeleteCouponSettingsKey(string settingID, int storeID, int portalID, string userName)
{
try
{
AspxCouponManageController.DeleteCouponSettingsKey(settingID, storeID, portalID, userName);
}
catch (Exception ex)
{
throw ex;
}
}
public List<CouponSettingKeyInfo> CouponSettingManageKey()
{
try
{
List<CouponSettingKeyInfo> lstCoupSetting = AspxCouponManageController.CouponSettingManageKey();
return lstCoupSetting;
}
catch (Exception ex)
{
throw ex;
}
}
public void AddUpdateCouponSettingKey(int ID, string settingKey, int validationTypeID, string isActive, int storeID, int portalID, string cultureName, string userName)
{
try
{
AspxCouponManageController.AddUpdateCouponSettingKey(ID, settingKey, validationTypeID, isActive, storeID, portalID, cultureName, userName);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Front Coupon Show
public List<CouponDetailFrontInfo> GetCouponDetailListFront(int count, AspxCommonInfo aspxCommonObj)
{
try
{
List<CouponDetailFrontInfo> lstCoupDetail = AspxCouponManageController.GetCouponDetailListFront(count, aspxCommonObj);
return lstCoupDetail;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#endregion
#region PopularTags Module
#region Status Management
//------------------Status DropDown-------------------
public List<StatusInfo> GetStatus(AspxCommonInfo aspxCommonObj)
{
try
{
List<StatusInfo> lstStatus = AspxCommonController.GetStatus(aspxCommonObj);
return lstStatus;
}
catch (Exception e)
{
throw e;
}
}
#endregion
//public void AddTagsOfItem(string itemSKU, string tags, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// AspxTagsController.AddTagsOfItem(itemSKU, tags, aspxCommonObj);
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//public List<ItemTagsInfo> GetItemTags(string itemSKU, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<ItemTagsInfo> lstItemTags = AspxTagsController.GetItemTags(itemSKU, aspxCommonObj);
// return lstItemTags;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//public void DeleteUserOwnTag(string itemTagID, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// AspxTagsController.DeleteUserOwnTag(itemTagID, aspxCommonObj);
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
public void DeleteMultipleTag(string itemTagIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTagsController.DeleteMultipleTag(itemTagIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<TagDetailsInfo> GetTagDetailsListPending(int offset, int limit, string tag, AspxCommonInfo aspxCommonObj)
{
try
{
List<TagDetailsInfo> lstTagDetail = AspxTagsController.GetTagDetailsListPending(offset, limit, tag, aspxCommonObj);
return lstTagDetail;
}
catch (Exception ex)
{
throw ex;
}
}
public List<TagDetailsInfo> GetTagDetailsList(int offset, int limit, string tag, string tagStatus, AspxCommonInfo aspxCommonObj)
{
try
{
List<TagDetailsInfo> lstTagDetail = AspxTagsController.GetTagDetailsList(offset, limit, tag, tagStatus, aspxCommonObj);
return lstTagDetail;
}
catch (Exception ex)
{
throw ex;
}
}
//public List<TagDetailsInfo> GetAllPopularTags(AspxCommonInfo aspxCommonObj, int count)
//{
// try
// {
// List<TagDetailsInfo> lstTagDetail = AspxTagsController.GetAllPopularTags(aspxCommonObj, count);
// return lstTagDetail;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//public List<TagDetailsInfo> GetTagsByUserName(AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<TagDetailsInfo> lstTagDetail = AspxTagsController.GetTagsByUserName(aspxCommonObj);
// return lstTagDetail;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
#region Tags Reports
//---------------------Customer tags------------
public List<CustomerTagInfo> GetCustomerTagDetailsList(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<CustomerTagInfo> lstCustomerTag = AspxTagsController.GetCustomerTagDetailsList(offset, limit, aspxCommonObj);
return lstCustomerTag;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Show Customer tags list------------
public List<ShowCustomerTagsListInfo> ShowCustomerTagList(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShowCustomerTagsListInfo> lstCustTag = AspxTagsController.ShowCustomerTagList(offset, limit, aspxCommonObj);
return lstCustTag;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Item tags details------------
public List<ItemTagsDetailsInfo> GetItemTagDetailsList(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemTagsDetailsInfo> lstItemTags = AspxTagsController.GetItemTagDetailsList(offset, limit, aspxCommonObj);
return lstItemTags;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Show Item tags list------------
public List<ShowItemTagsListInfo> ShowItemTagList(int offset, System.Nullable<int> limit, int itemID, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShowItemTagsListInfo> lstShowItemTags = AspxTagsController.ShowItemTagList(offset, limit, itemID, aspxCommonObj);
return lstShowItemTags;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Popular tags details------------
public List<PopularTagsInfo> GetPopularTagDetailsList(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<PopularTagsInfo> lstPopTags = AspxTagsController.GetPopularTagDetailsList(offset, limit, aspxCommonObj);
return lstPopTags;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Show Popular tags list------------
public List<ShowpopulartagsDetailsInfo> ShowPopularTagList(int offset, System.Nullable<int> limit, string tagName, AspxCommonInfo aspxCommonObj)
{
try
{
List<ShowpopulartagsDetailsInfo> lstShowPopTag = AspxTagsController.ShowPopularTagList(offset, limit, tagName, aspxCommonObj);
return lstShowPopTag;
}
catch (Exception ex)
{
throw ex;
}
}
//public List<ItemBasicDetailsInfo> GetUserTaggedItems(int offset, int limit, string tagIDs, int SortBy, int rowTotal, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<ItemBasicDetailsInfo> lstItemBasic = AspxTagsController.GetUserTaggedItems(offset, limit, tagIDs, SortBy, rowTotal, aspxCommonObj);
// return lstItemBasic;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
#endregion
#endregion
#region Tags Management
public void UpdateTag(string itemTagIDs, int? itemId, int statusID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTagsController.UpdateTag(itemTagIDs, itemId, statusID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteTag(string itemTagIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxTagsController.DeleteTag(itemTagIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<ItemBasicDetailsInfo> GetItemsByMultipleItemID(string itemIDs, string tagName, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemBasicDetailsInfo> lstItemBasic = AspxTagsController.GetItemsByMultipleItemID(itemIDs, tagName, aspxCommonObj);
return lstItemBasic;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Rating/Reviews
#region rating/ review
//---------------------save rating/ review Items-----------------------
//[WebMethod]
//public List<ItemRatingAverageInfo> GetItemAverageRating(string itemSKU, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<ItemRatingAverageInfo> avgRating = AspxRatingReviewController.GetItemAverageRating(itemSKU, aspxCommonObj);
// return avgRating;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//---------------------rating/ review Items criteria--------------------------
//[WebMethod]
//public List<RatingCriteriaInfo> GetItemRatingCriteria(AspxCommonInfo aspxCommonObj, bool isFlag)
//{
// try
// {
// List<RatingCriteriaInfo> lstRating = AspxCommonController.GetItemRatingCriteria(aspxCommonObj, isFlag);
// return lstRating;
// }
// catch (Exception e)
// {
// throw e;
// }
//}
//[WebMethod]
//public List<RatingCriteriaInfo> GetItemRatingCriteriaByReviewID(AspxCommonInfo aspxCommonObj, int itemReviewID, bool isFlag)
//{
// try
// {
// List<RatingCriteriaInfo> rating = AspxRatingReviewController.GetItemRatingCriteriaByReviewID(aspxCommonObj, itemReviewID, isFlag);
// return rating;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
////---------------------save rating/ review Items-----------------------
//[WebMethod]
//public void SaveItemRating(ItemReviewBasicInfo ratingSaveObj, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// AspxRatingReviewController.SaveItemRating(ratingSaveObj, aspxCommonObj);
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//---------------------update rating/ review Items-----------------------
public void UpdateItemRating(ItemReviewBasicInfo ratingManageObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCommonController.UpdateItemRating(ratingManageObj, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
////---------------------Get rating/ review of Item Per User ------------------
//[WebMethod]
//public List<ItemRatingByUserInfo> GetItemRatingPerUser(int offset, int limit, string itemSKU, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<ItemRatingByUserInfo> lstItemRating = AspxRatingReviewController.GetItemRatingPerUser(offset, limit, itemSKU, aspxCommonObj);
// return lstItemRating;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//---------------------Get rating/ review of Item Per User ------------------
public List<RatingLatestInfo> GetRecentItemReviewsAndRatings(int offset, int limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<RatingLatestInfo> lstRatingNew = AspxCommonController.GetRecentItemReviewsAndRatings(offset, limit, aspxCommonObj);
return lstRatingNew;
}
catch (Exception e)
{
throw e;
}
}
////---------------------Get rating/ review of Item Per User ------------------
//[WebMethod]
//public List<ItemReviewDetailsInfo> GetItemRatingByReviewID(int itemReviewID, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<ItemReviewDetailsInfo> lstItemRVDetail = AspxCommonController.GetItemRatingByReviewID(itemReviewID, aspxCommonObj);
// return lstItemRVDetail;
// }
// catch (Exception e)
// {
// throw e;
// }
//}
////------------------------Item single rating management------------------------
//[WebMethod]
//public void DeleteSingleItemRating(string itemReviewID, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// AspxCommonController.DeleteSingleItemRating(itemReviewID, aspxCommonObj);
// }
// catch (Exception e)
// {
// throw e;
// }
//}
////---------------Delete multiple item rating informations--------------------------
//[WebMethod]
//public void DeleteMultipleItemRatings(string itemReviewIDs, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// AspxRatingReviewController.DeleteMultipleItemRatings(itemReviewIDs, aspxCommonObj);
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//---------------------Bind in Item Rating Information in grid-------------------------
public List<UserRatingInformationInfo> GetAllUserReviewsAndRatings(int offset, int limit, UserRatingBasicInfo userRatingObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<UserRatingInformationInfo> bind = AspxRatingReviewController.GetAllUserReviewsAndRatings(offset, limit, userRatingObj, aspxCommonObj);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//-------------------------list item names in dropdownlist/item rating management---------------------
public List<ItemsReviewInfo> GetAllItemList(string searchText, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemsReviewInfo> items = AspxRatingReviewController.GetAllItemList(searchText, aspxCommonObj);
return items;
}
catch (Exception ex)
{
throw ex;
}
}
//[WebMethod]
//public bool CheckReviewByUser(int itemID, AspxCommonInfo aspxCommonObj)
//{
// bool isReviewExist = AspxRatingReviewController.CheckReviewByUser(itemID, aspxCommonObj);
// return isReviewExist;
//}
//[WebMethod]
//public bool CheckReviewByIP(int itemID, AspxCommonInfo aspxCommonObj, string userIP)
//{
// bool isReviewExist = AspxRatingReviewController.CheckReviewByIP(itemID, aspxCommonObj, userIP);
// return isReviewExist;
//}
#endregion
#region Item Rating Criteria Manage/Admin
//--------------------Item Rating Criteria Manage/Admin--------------------------
//public List<ItemRatingCriteriaInfo> ItemRatingCriteriaManage(int offset, int limit, string criteria, System.Nullable<bool> isActive, AspxCommonInfo aspxCommonObj)
//{
public List<ItemRatingCriteriaInfo> ItemRatingCriteriaManage(int offset, int limit, ItemRatingCriteriaInfo itemCriteriaObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemRatingCriteriaInfo> lstRatingCriteria = AspxRatingReviewController.ItemRatingCriteriaManage(offset, limit, itemCriteriaObj, aspxCommonObj);
return lstRatingCriteria;
}
catch (Exception ex)
{
throw ex;
}
}
//--------------- ItemRating Criteria Manage-------------------------------
public void AddUpdateItemCriteria(ItemRatingCriteriaInfo itemCriteriaObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxRatingReviewController.AddUpdateItemCriteria(itemCriteriaObj, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//--------------- ItemRating Criteria Manage-------------------------------
public void DeleteItemRatingCriteria(string IDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxRatingReviewController.DeleteItemRatingCriteria(IDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Rating Reviews Reporting
//--------------------bind Customer Reviews Roports-------------------------
public List<CustomerReviewReportsInfo> GetCustomerReviews(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<CustomerReviewReportsInfo> bind = AspxRatingReviewController.GetCustomerReviews(offset, limit, aspxCommonObj);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Show All Customer Reviews-------------------------
public List<UserRatingInformationInfo> GetAllCustomerReviewsList(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj, UserRatingBasicInfo customerReviewObj)
{
try
{
List<UserRatingInformationInfo> bind = AspxRatingReviewController.GetAllCustomerReviewsList(offset, limit, aspxCommonObj, customerReviewObj);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//------------------Bind User List------------------------------
public List<UserListInfo> GetUserList(int portalID)
{
try
{
List<UserListInfo> lstUser = AspxRatingReviewController.GetUserList(portalID);
return lstUser;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Item Reviews Reports-------------------------
public List<ItemReviewsInfo> GetItemReviews(int offset, System.Nullable<int> limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemReviewsInfo> bind = AspxRatingReviewController.GetItemReviews(offset, limit, aspxCommonObj);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------------Show All Item Reviews-------------------------
public List<UserRatingInformationInfo> GetAllItemReviewsList(int offset, System.Nullable<int> limit, UserRatingBasicInfo itemReviewObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<UserRatingInformationInfo> bind = AspxRatingReviewController.GetAllItemReviewsList(offset, limit, itemReviewObj, aspxCommonObj);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#endregion
#region Branch Management
public bool CheckBranchNameUniqueness(AspxCommonInfo aspxCommonObj, int storeBranchId, string storeBranchName)
{
try
{
bool isUnique = AspxStoreBranchMgntController.CheckBranchNameUniqueness(aspxCommonObj, storeBranchId, storeBranchName);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public void SaveAndUpdateStorebranch(string branchName, string branchImage, AspxCommonInfo aspxCommonObj, int storeBranchId)
{
try
{
AspxStoreBranchMgntController.SaveAndUpdateStorebranch(branchName, branchImage, aspxCommonObj, storeBranchId);
}
catch (Exception ex)
{
throw ex;
}
}
public List<BranchDetailsInfo> GetStoreBranchList(int offset, int limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<BranchDetailsInfo> lstBrDetail = AspxStoreBranchMgntController.GetStoreBranchList(offset, limit, aspxCommonObj);
return lstBrDetail;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteStoreBranches(string storeBranchIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxStoreBranchMgntController.DeleteStoreBranches(storeBranchIds, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Store Locator
public List<StoreLocatorInfo> GetAllStoresLocation(AspxCommonInfo aspxCommonObj)
{
try
{
List<StoreLocatorInfo> lstStoreLocate = AspxStoreLocateController.GetAllStoresLocation(aspxCommonObj);
return lstStoreLocate;
}
catch (Exception ex)
{
throw ex;
}
}
public List<StoreLocatorInfo> GetLocationsNearBy(double latitude, double longitude, double searchDistance, AspxCommonInfo aspxCommonObj)
{
try
{
List<StoreLocatorInfo> lstStoreLocate = AspxStoreLocateController.GetLocationsNearBy(latitude, longitude, searchDistance, aspxCommonObj);
return lstStoreLocate;
}
catch (Exception ex)
{
throw ex;
}
}
public bool UpdateStoreLocation(AspxCommonInfo aspxCommonObj, string storeName, String storeDescription, string streetName, string localityName, string city, string state, string country, string zip, double latitude, double longitude)
{
try
{
bool retValue = AspxStoreLocateController.UpdateStoreLocation(aspxCommonObj, storeName, storeDescription, streetName, localityName, city, state, country, zip, latitude, longitude);
return retValue;
}
catch (Exception ex)
{
return false;
throw ex;
}
}
public void AddStoreLocatorSettings(string settingKey, string settingValue, string cultureName, int storeID, int portalID, string userName)
{
try
{
AspxStoreLocateController.AddStoreLocatorSettings(settingKey, settingValue, cultureName, storeID, portalID, userName);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Store Access Management
public bool CheckExisting(AspxCommonInfo aspxCommonObj, int storeAccesskeyId, string accessData)
{
try
{
bool isUnique = AspxStoreAccessMgntController.CheckExisting(aspxCommonObj, storeAccesskeyId, accessData);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public List<StoreAccessAutocomplete> SearchStoreAccess(string text, int keyID)
{
try
{
List<StoreAccessAutocomplete> lstStoreAccess = AspxStoreAccessMgntController.SearchStoreAccess(text, keyID);
return lstStoreAccess;
}
catch (Exception ex)
{
throw ex;
}
}
public void SaveUpdateStoreAccess(int edit, int storeAccessKeyID, string storeAccessData, string reason, bool isActive, AspxCommonInfo aspxCommonObj)
{
try
{
AspxStoreAccessMgntController.SaveUpdateStoreAccess(edit, storeAccessKeyID, storeAccessData, reason, isActive, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeletStoreAccess(int storeAccessID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxStoreAccessMgntController.DeletStoreAccess(storeAccessID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<AspxUserList> GetAspxUser(string userName, AspxCommonInfo aspxCommonObj)
{
try
{
List<AspxUserList> lstUser = AspxStoreAccessMgntController.GetAspxUser(userName, aspxCommonObj);
return lstUser;
}
catch (Exception ex)
{
throw ex;
}
}
public List<AspxUserList> GetAspxUserEmail(string email, AspxCommonInfo aspxCommonObj)
{
try
{
List<AspxUserList> lstUserEmail = AspxStoreAccessMgntController.GetAspxUserEmail(email, aspxCommonObj);
return lstUserEmail;
}
catch (Exception ex)
{
throw ex;
}
}
public List<StoreAccessKey> GetStoreKeyID()
{
try
{
List<StoreAccessKey> lstStAccessKey = AspxStoreAccessMgntController.GetStoreKeyID();
return lstStAccessKey;
}
catch (Exception ex)
{
throw ex;
}
}
public List<StoreAccessInfo> LoadStoreAccessCustomer(int offset, int limit, string search, System.Nullable<DateTime> startDate, System.Nullable<DateTime> endDate, System.Nullable<bool> status, AspxCommonInfo aspxCommonObj)
{
try
{
List<StoreAccessInfo> lstStoreAccess = AspxStoreAccessMgntController.LoadStoreAccessCustomer(offset, limit, search, startDate, endDate, status, aspxCommonObj);
return lstStoreAccess;
}
catch (Exception ex)
{
throw ex;
}
}
public List<StoreAccessInfo> LoadStoreAccessEmails(int offset, int limit, string search, System.Nullable<DateTime> startDate, System.Nullable<DateTime> endDate, System.Nullable<bool> status, AspxCommonInfo aspxCommonObj)
{
try
{
List<StoreAccessInfo> lstStoreAccess = AspxStoreAccessMgntController.LoadStoreAccessEmails(offset, limit, search, startDate, endDate, status, aspxCommonObj);
return lstStoreAccess;
}
catch (Exception ex)
{
throw ex;
}
}
public List<StoreAccessInfo> LoadStoreAccessIPs(int offset, int limit, string search, System.Nullable<DateTime> startDate, System.Nullable<DateTime> endDate, System.Nullable<bool> status, AspxCommonInfo aspxCommonObj)
{
try
{
List<StoreAccessInfo> lstStoreAccess = AspxStoreAccessMgntController.LoadStoreAccessIPs(offset, limit, search, startDate, endDate, status, aspxCommonObj);
return lstStoreAccess;
}
catch (Exception ex)
{
throw ex;
}
}
public List<StoreAccessInfo> LoadStoreAccessDomains(int offset, int limit, string search, System.Nullable<DateTime> startDate, System.Nullable<DateTime> endDate, System.Nullable<bool> status, AspxCommonInfo aspxCommonObj)
{
try
{
List<StoreAccessInfo> lstStoreAccess = AspxStoreAccessMgntController.LoadStoreAccessDomains(offset, limit, search, startDate, endDate, status, aspxCommonObj);
return lstStoreAccess;
}
catch (Exception ex)
{
throw ex;
}
}
public List<StoreAccessInfo> LoadStoreAccessCreditCards(int offset, int limit, string search, System.Nullable<DateTime> startDate, System.Nullable<DateTime> endDate, System.Nullable<bool> status, AspxCommonInfo aspxCommonObj)
{
try
{
List<StoreAccessInfo> lstStoreAccess = AspxStoreAccessMgntController.LoadStoreAccessCreditCards(offset, limit, search, startDate, endDate, status, aspxCommonObj);
return lstStoreAccess;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region CardType_Management
//------------------------bind All CardType name list-------------------------------
public List<CardTypeInfo> GetAllCardTypeList(int offset, int limit, AspxCommonInfo aspxCommonObj, string cardTypeName, bool? isActive)
{
try
{
List<CardTypeInfo> lstCardType = AspxCardTypeController.GetAllCardTypeList(offset, limit, aspxCommonObj, cardTypeName, isActive);
return lstCardType;
}
catch (Exception e)
{
throw e;
}
}
public List<CardTypeInfo> AddUpdateCardType(AspxCommonInfo aspxCommonObj, CardTypeSaveInfo cardTypeSaveObj)
{
FileHelperController imageObj = new FileHelperController();
string uploadedFile;
if (cardTypeSaveObj.NewFilePath != "" && cardTypeSaveObj.PrevFilePath != cardTypeSaveObj.NewFilePath)
{
string tempFolder = @"Upload\temp";
uploadedFile = imageObj.MoveFileToSpecificFolder(tempFolder, cardTypeSaveObj.PrevFilePath,
cardTypeSaveObj.NewFilePath,
@"Modules\AspxCommerce\AspxCardTypeManagement\uploads\",
cardTypeSaveObj.CardTypeID, aspxCommonObj, "cardType_");
}
else
{
uploadedFile = cardTypeSaveObj.PrevFilePath;
}
try
{
List<CardTypeInfo> lstCardType = AspxCardTypeController.AddUpdateCardType(aspxCommonObj, cardTypeSaveObj, uploadedFile);
return lstCardType;
}
catch (Exception e)
{
throw e;
}
}
public void DeleteCardTypeByID(int cardTypeID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCardTypeController.DeleteCardTypeByID(cardTypeID, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteCardTypeMultipleSelected(string cardTypeIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCardTypeController.DeleteCardTypeMultipleSelected(cardTypeIDs, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region Payment Gateway and CheckOUT PROCESS
public bool CheckDownloadableItemOnly(int storeID, int portalID, int customerID, string sessionCode)
{
try
{
bool isAllDownload = AspxCartController.CheckDownloadableItemOnly(storeID, portalID, customerID, sessionCode);
return isAllDownload;
}
catch (Exception ex)
{
throw ex;
}
}
public List<PaymentGateway> GetPaymentGateway(int portalID, string cultureName, string userName)
{
try
{
List<PaymentGateway> lstPayGateWay = AspxCartController.GetPaymentGateway(portalID, cultureName, userName);
return lstPayGateWay;
}
catch (Exception ex)
{
throw ex;
}
}
public List<UserAddressInfo> GetUserAddressForCheckOut(int storeID, int portalID, string userName, string cultureName)
{
try
{
List<UserAddressInfo> lstUserAddress = AspxCartController.GetUserAddressForCheckOut(storeID, portalID, userName, cultureName);
return lstUserAddress;
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckCreditCard(AspxCommonInfo aspxCommonObj, string creditCardNo)
{
try
{
bool isExist = AspxCartController.CheckCreditCard(aspxCommonObj, creditCardNo);
return isExist;
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckEmailAddress(string email, AspxCommonInfo aspxCommonObj)
{
try
{
bool isExist = AspxCartController.CheckEmailAddress(email, aspxCommonObj);
return isExist;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Payment Gateway Installation
//public void OrderTaxRuleMapping(int itemID, int orderID, int taxManageRuleID, decimal taxSubTotal, int storeID, int portalID, string addedBy, string costVariantValueIDs)
//{
// try
// {
// AspxPaymentController.OrderTaxRuleMapping(itemID, orderID, taxManageRuleID, taxSubTotal, storeID, portalID, addedBy, costVariantValueIDs);
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
public List<PaymentGateWayInfo> GetAllPaymentMethod(int offset, int limit, AspxCommonInfo aspxCommonObj, PaymentGateWayBasicInfo paymentMethodObj)
{
try
{
List<PaymentGateWayInfo> lstPayGateWay = AspxPaymentController.GetAllPaymentMethod(offset, limit, aspxCommonObj, paymentMethodObj);
return lstPayGateWay;
}
catch (Exception ex)
{
throw ex;
}
}
public List<TransactionInfoList> GetAllTransactionDetail(AspxCommonInfo aspxCommonObj, int paymentGatewayID, System.Nullable<int> orderID)
{
try
{
List<TransactionInfoList> lstTransaction = AspxPaymentController.GetAllTransactionDetail(aspxCommonObj, paymentGatewayID, orderID);
return lstTransaction;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeletePaymentMethod(string paymentGatewayID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxPaymentController.DeletePaymentMethod(paymentGatewayID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdatePaymentMethod(AspxCommonInfo aspxCommonObj, PaymentGateWayBasicInfo updatePaymentObj)
{
try
{
AspxPaymentController.UpdatePaymentMethod(aspxCommonObj, updatePaymentObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void AddUpdatePaymentGateWaySettings(int paymentGatewaySettingValueID, int paymentGatewayID, string settingKeys, string settingValues, bool isActive, AspxCommonInfo aspxCommonObj)
{
try
{
AspxPaymentController.AddUpdatePaymentGateWaySettings(paymentGatewaySettingValueID, paymentGatewayID, settingKeys, settingValues, isActive, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<GetOrderdetailsByPaymentGatewayIDInfo> GetOrderDetailsbyPayID(int offset, int limit, PaymentGateWayBasicInfo bindOrderObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<GetOrderdetailsByPaymentGatewayIDInfo> lstOrderDetail = AspxPaymentController.GetOrderDetailsbyPayID(offset, limit, bindOrderObj, aspxCommonObj);
return lstOrderDetail;
}
catch (Exception ex)
{
throw ex;
}
}
public List<OrderDetailsByOrderIDInfo> GetAllOrderDetailsByOrderID(int orderId, int storeId, int portalId)
{
try
{
List<OrderDetailsByOrderIDInfo> lstOrderDetail = AspxPaymentController.GetAllOrderDetailsByOrderID(orderId, storeId, portalId);
return lstOrderDetail;
}
catch (Exception ex)
{
throw ex;
}
}
//[WebMethod]
//public List<OrderItemsInfo> GetAllOrderDetailsForView(int orderId, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<OrderItemsInfo> lstOrderItem = AspxPaymentController.GetAllOrderDetailsForView(orderId, aspxCommonObj);
// return lstOrderItem;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//[WebMethod]
//public List<OrderItemsTaxInfo> GetTaxDetailsByOrderID(int orderId, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<OrderItemsTaxInfo> lstOrderItem = AspxPaymentController.GetTaxDetailsByOrderID(orderId, aspxCommonObj);
// return lstOrderItem;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
#endregion
#region "Currency conversion"
public List<CurrencyInfo> BindCurrencyList(AspxCommonInfo aspxCommonObj)
{
try
{
List<CurrencyInfo> lstCurrency = AspxCurrencyController.BindCurrencyList(aspxCommonObj);
return lstCurrency;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CurrencyInfo> BindCurrencyAddedLists(int offset, int limit, AspxCommonInfo aspxCommonObj)
{
try
{
List<CurrencyInfo> lstCurrency = AspxCurrencyController.BindCurrencyAddedLists(offset, limit, aspxCommonObj);
return lstCurrency;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CurrencyInfoByCode> GetDetailsByCountryCode(string countryCode, string countryName, AspxCommonInfo aspxCommonObj)
{
try
{
List<CurrencyInfoByCode> lstCountryDetails = AspxCurrencyController.GetDetailsByCountryCode(countryCode, countryName, aspxCommonObj);
return lstCountryDetails;
}
catch (Exception ex)
{
throw ex;
}
}
public void InsertNewCurrency(AspxCommonInfo aspxCommonObj, CurrencyInfo currencyInsertObj)
{
try
{
AspxCurrencyController.InsertNewCurrency(aspxCommonObj, currencyInsertObj);
HttpContext.Current.Cache.Remove("AspxCurrencyRate" + aspxCommonObj.PortalID.ToString() + aspxCommonObj.StoreID.ToString());
}
catch (Exception e)
{
throw e;
}
}
public bool CheckUniquenessForDisplayOrderForCurrency(AspxCommonInfo aspxCommonObj, int value, int currencyID)
{
try
{
bool isUnique = AspxCurrencyController.CheckUniquenessForDisplayOrderForCurrency(aspxCommonObj, value, currencyID);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckCurrencyCodeUniqueness(AspxCommonInfo aspxCommonObj, string currencyCode, int currencyID)
{
try
{
bool isUnique = AspxCurrencyController.CheckCurrencyCodeUniqueness(aspxCommonObj, currencyCode, currencyID);
return isUnique;
}
catch (Exception e)
{
throw e;
}
}
public double GetCurrencyRateOnChange(AspxCommonInfo aspxCommonObj, string from, string to, string region)
{
try
{
double result = 0.0;
result = AspxCurrencyProvider.GetRatefromTable(aspxCommonObj, to);
HttpContext.Current.Session["CurrencyCode"] = to;
HttpContext.Current.Session["CurrencyRate"] = result;
HttpContext.Current.Session["Region"] = region;
return Math.Round(double.Parse(result.ToString()), 4);
}
catch (Exception ex)
{
throw ex;
}
}
public double GetCurrencyRate(string from, string to)
{
System.Net.ServicePointManager.Expect100Continue = false;
try
{
double result = 0.0;
result = AspxCommerce.Core.CurrencyConverter.GetRate(from, to);
HttpContext.Current.Session["CurrencyRate"] = result;
return result;
}
catch (Exception)
{
return 1;
}
}
public void RealTimeUpdate(AspxCommonInfo aspxCommonObj)
{
List<CurrencyInfo> lstCurrency = AspxCurrencyController.BindCurrencyList(aspxCommonObj);
int currencyCount = lstCurrency.Count;
CurrencyInfo DefaultStoreCurrency = lstCurrency.SingleOrDefault(x => x.IsPrimaryForStore == true);
for (int i = 0; i < currencyCount; i++)
{
CurrencyInfo info = lstCurrency[i];
if (info.CurrencyCode != DefaultStoreCurrency.CurrencyCode)
{
double result = 0.0;
result = AspxCommerce.Core.CurrencyConverter.GetRate(DefaultStoreCurrency.CurrencyCode, info.CurrencyCode);
AspxCurrencyController.UpdateRealTimeRate(aspxCommonObj, info.CurrencyCode, result);
HttpContext.Current.Cache.Remove("AspxCurrencyRate" + aspxCommonObj.PortalID.ToString() + aspxCommonObj.StoreID.ToString());
}
}
}
public void SetStorePrimary(AspxCommonInfo aspxCommonObj, string currencyCode)
{
try
{
AspxCurrencyController.SetStorePrimary(aspxCommonObj, currencyCode);
HttpContext.Current.Session["CurrencyCode"] = null;
HttpContext.Current.Session["Region"] = null;
StoreSettingConfig ssc = new StoreSettingConfig();
HttpContext.Current.Cache.Remove("AspxStoreSetting" + aspxCommonObj.PortalID.ToString() + aspxCommonObj.StoreID.ToString());
HttpContext.Current.Cache.Remove("AspxCurrencyRate" + aspxCommonObj.PortalID.ToString() + aspxCommonObj.StoreID.ToString());
ssc.ResetStoreSettingKeys(aspxCommonObj.StoreID, aspxCommonObj.PortalID, aspxCommonObj.CultureName);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteMultipleCurrencyByCurrencyID(string currencyIDs, AspxCommonInfo aspxCommonObj)
{
AspxCurrencyController.DeleteMultipleCurrencyByCurrencyID(currencyIDs, aspxCommonObj);
}
public List<CurrrencyRateInfo> GetCountryCodeRates(AspxCommonInfo aspxCommonObj)
{
try
{
List<CurrrencyRateInfo> currencyList = AspxCurrencyController.GetCountryCodeRates(aspxCommonObj);
return currencyList;
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region "StoreSetings"
public StoreSettingInfo GetAllStoreSettings(AspxCommonInfo aspxCommonObj)
{
try
{
StoreSettingInfo DefaultStoreSettings;
DefaultStoreSettings = AspxStoreSetController.GetAllStoreSettings(aspxCommonObj);
HttpContext.Current.Session["DefaultStoreSettings"] = DefaultStoreSettings;
return DefaultStoreSettings;
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdateStoreSettings(string settingKeys, string settingValues, string prevFilePath, string newFilePath, string prevStoreLogoPath, string newStoreLogoPath, AspxCommonInfo aspxCommonObj)
{
try
{
AspxStoreSetController.UpdateStoreSettings(settingKeys, settingValues, prevFilePath, newFilePath, prevStoreLogoPath, newStoreLogoPath, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<DisplayItemsOptionsInfo> BindItemsViewAsList()
{
try
{
List<DisplayItemsOptionsInfo> bind = AspxStoreSetController.BindItemsViewAsList();
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Items Reporting
//----------------------GetMostViewedItems----------------------
public List<MostViewedItemsInfo> GetMostViewedItemsList(int offset, int? limit, string name, string currencySymbol, AspxCommonInfo aspxCommonObj)
{
try
{
List<MostViewedItemsInfo> lstMostView = AspxItemMgntController.GetAllMostViewedItems(offset, limit, name, currencySymbol, aspxCommonObj);
return lstMostView;
}
catch (Exception ex)
{
throw ex;
}
}
// --------------------------Get Low Stock Items----------------------------------------------------
public List<LowStockItemsInfo> GetLowStockItemsList(int offset, int? limit, ItemSmallCommonInfo lowStockObj, AspxCommonInfo aspxCommonObj, int lowStock)
{
try
{
List<LowStockItemsInfo> lstLowStockItem = AspxItemMgntController.GetAllLowStockItems(offset, limit, lowStockObj, aspxCommonObj, lowStock);
return lstLowStockItem;
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------------------Get Ordered Items List-----------------------------------
public List<OrderItemsGroupByItemIDInfo> GetOrderedItemsList(int offset, System.Nullable<int> limit, string name, AspxCommonInfo aspxCommonObj)
{
try
{
List<OrderItemsGroupByItemIDInfo> lstOrderItem = AspxItemMgntController.GetOrderedItemsList(offset, limit, name, aspxCommonObj);
return lstOrderItem;
}
catch (Exception ex)
{
throw ex;
}
}
// --------------------------Get DownLoadable Items----------------------------------------------------
public List<DownLoadableItemGetInfo> GetDownLoadableItemsList(int offset, int? limit, GetDownloadableItemInfo downloadableObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<DownLoadableItemGetInfo> lstDownItem = AspxItemMgntController.GetDownLoadableItemsList(offset, limit, downloadableObj, aspxCommonObj);
return lstDownItem;
}
catch (Exception ex)
{
throw ex;
}
}
// --------------------------Get DownLoadable Items----------------------------------------------------
public List<GiftCardReport> GetGiftCardReport(int offset, int? limit, GiftCardReport objGiftcard, AspxCommonInfo aspxCommonObj)
{
try
{
List<GiftCardReport> giftCardReports = AspxGiftCardController.GetGiftCardReport(offset, limit, objGiftcard,
aspxCommonObj);
return giftCardReports;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Cost Variants Management
//--------------------bind Cost Variants in Grid--------------------------
public List<CostVariantInfo> GetCostVariants(int offset, int limit, string variantName, AspxCommonInfo aspxCommonObj)
{
try
{
List<CostVariantInfo> bind = AspxCostVarMgntController.GetCostVariants(offset, limit, variantName, aspxCommonObj);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//---------------Delete multiple cost variants --------------------------
public void DeleteMultipleCostVariants(string costVariantIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCostVarMgntController.DeleteMultipleCostVariants(costVariantIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------ single Cost Variants management------------------------
public void DeleteSingleCostVariant(string costVariantID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCostVarMgntController.DeleteSingleCostVariant(costVariantID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<AttributesInputTypeInfo> GetCostVariantInputTypeList()
{
try
{
List<AttributesInputTypeInfo> ml = AspxCostVarMgntController.GetCostVariantInputTypeList();
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
//--------------- bind (edit) cost Variant management--------------------
public List<CostVariantsGetByCostVariantIDInfo> GetCostVariantInfoByCostVariantID(int costVariantID, AspxCommonInfo aspxCommonObj)
{
try
{
List<CostVariantsGetByCostVariantIDInfo> lstCostVar = AspxCostVarMgntController.GetCostVariantInfoByCostVariantID(costVariantID, aspxCommonObj);
return lstCostVar;
}
catch (Exception ex)
{
throw ex;
}
}
//--------------- bind (edit) cost Variant values for cost variant ID --------------------
public List<CostVariantsvalueInfo> GetCostVariantValuesByCostVariantID(int costVariantID, AspxCommonInfo aspxCommonObj)
{
try
{
List<CostVariantsvalueInfo> lstCVValue = AspxCostVarMgntController.GetCostVariantValuesByCostVariantID(costVariantID, aspxCommonObj);
return lstCVValue;
}
catch (Exception ex)
{
throw ex;
}
}
public List<CostVariantsvalueInfo> GetCostVariantValuesByCostVariantIDForAdmin(int costVariantID, AspxCommonInfo aspxCommonObj)
{
try
{
List<CostVariantsvalueInfo> lstCVValue = AspxCostVarMgntController.GetCostVariantValuesByCostVariantIDForAdmin(costVariantID, aspxCommonObj);
return lstCVValue;
}
catch (Exception ex)
{
throw ex;
}
}
//-----------Save and update Costvariant options-------------------------
public void SaveAndUpdateCostVariant(CostVariantsGetByCostVariantIDInfo variantObj, string variantOptions, AspxCommonInfo aspxCommonObj)
{
try
{
AspxCostVarMgntController.SaveAndUpdateCostVariant(variantObj, variantOptions, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
//---------------- Added for unique name check ---------------------
public bool CheckUniqueCostVariantName(string costVariantName, int costVariantId, AspxCommonInfo aspxCommonObj)
{
try
{
bool isUnique = AspxCostVarMgntController.CheckUniqueCostVariantName(costVariantName, costVariantId, aspxCommonObj);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Admin DashBoard
public List<CategoryQuantityStatics> GetTopCategoryByItemSell(int top, int day, AspxCommonInfo aspxCommonObj)
{
List<CategoryQuantityStatics> lstCat = AspxAdminDashProvider.GetTopCategoryByItemSell(top, day, aspxCommonObj);
return lstCat;
}
public List<CategoryRevenueStatics> GetTopCategoryByHighestRevenue(int top, int day, AspxCommonInfo aspxCommonObj)
{
List<CategoryRevenueStatics> lstCat = AspxAdminDashProvider.GetTopCategoryByHighestRevenue(top, day, aspxCommonObj);
return lstCat;
}
public List<VisitorOrderStatics> GetVisitorsOrder(int day, AspxCommonInfo aspxCommonObj)
{
List<VisitorOrderStatics> lstVisitor = AspxAdminDashProvider.GetVisitorsOrder(day, aspxCommonObj);
return lstVisitor;
}
public List<VisitorNewAccountStatics> GetVisitorsNewAccount(int day, AspxCommonInfo aspxCommonObj)
{
List<VisitorNewAccountStatics> lstVisitor = AspxAdminDashProvider.GetVisitorsNewAccount(day, aspxCommonObj);
return lstVisitor;
}
public List<VisitorNewOrderStatics> GetVisitorsNewOrder(int day, AspxCommonInfo aspxCommonObj)
{
List<VisitorNewOrderStatics> lstVisitor = AspxAdminDashProvider.GetVisitorsNewOrder(day, aspxCommonObj);
return lstVisitor;
}
public List<RefundStatics> GetTotalRefund(int day, AspxCommonInfo aspxCommonObj)
{
List<RefundStatics> lstRefund = AspxAdminDashProvider.GetTotalRefund(day, aspxCommonObj);
return lstRefund;
}
public List<RefundReasonStatics> GetTopRefundReason(int day, AspxCommonInfo aspxCommonObj)
{
List<RefundReasonStatics> lstRefund = AspxAdminDashProvider.GetTopRefundReason(day, aspxCommonObj);
return lstRefund;
}
public List<SearchTermInfo> GetSearchStatistics(int count, string commandName, AspxCommonInfo aspxCommonObj)
{
List<SearchTermInfo> lstSearchTerm = AspxCommonController.GetSearchStatistics(count, commandName, aspxCommonObj);
return lstSearchTerm;
}
public List<LatestOrderStaticsInfo> GetLatestOrderItems(int count, AspxCommonInfo aspxCommonObj)
{
List<LatestOrderStaticsInfo> lstLOSI = AspxAdminDashController.GetLatestOrderItems(count, aspxCommonObj);
return lstLOSI;
}
public List<MostViewItemInfoAdminDash> GetMostViwedItemAdmindash(int count, AspxCommonInfo aspxCommonObj)
{
List<MostViewItemInfoAdminDash> lstMVI = AspxAdminDashController.GetMostViwedItemAdmindash(count, aspxCommonObj);
return lstMVI;
}
public List<StaticOrderStatusAdminDashInfo> GetStaticOrderStatusAdminDash(int day, AspxCommonInfo aspxCommonObj)
{
try
{
List<StaticOrderStatusAdminDashInfo> lstSOS = AspxAdminDashController.GetStaticOrderStatusAdminDash(day, aspxCommonObj);
return lstSOS;
}
catch (Exception e)
{
throw e;
}
}
public List<TopCustomerOrdererInfo> GetTopCustomerOrderAdmindash(int count, AspxCommonInfo aspxCommonObj)
{
List<TopCustomerOrdererInfo> lstTCO = AspxAdminDashController.GetTopCustomerOrderAdmindash(count, aspxCommonObj);
return lstTCO;
}
public List<TotalOrderAmountInfo> GetTotalOrderAmountAdmindash(AspxCommonInfo aspxCommonObj)
{
List<TotalOrderAmountInfo> lstTOAmount = AspxAdminDashController.GetTotalOrderAmountAdmindash(aspxCommonObj);
return lstTOAmount;
}
public List<InventoryDetailAdminDashInfo> GetInventoryDetails(int count, AspxCommonInfo aspxCommonObj)
{
List<InventoryDetailAdminDashInfo> lstInvDetail = AspxAdminDashController.GetInventoryDetails(count, aspxCommonObj);
return lstInvDetail;
}
public StoreQuickStaticsInfo GetStoreQuickStatics(AspxCommonInfo aspxCommonObj)
{
StoreQuickStaticsInfo lstInvDetail = AspxAdminDashController.GetStoreQuickStatics(aspxCommonObj);
return lstInvDetail;
}
#region Admin DashBoard Chart
//------------------------bind order Chart by last week-------------------------------
public List<OrderChartInfo> GetOrderChartDetailsByLastWeek(AspxCommonInfo aspxCommonObj)
{
try
{
List<OrderChartInfo> lstOrderChart = AspxAdminDashController.GetOrderChartDetailsByLastWeek(aspxCommonObj);
return lstOrderChart;
}
catch (Exception e)
{
throw e;
}
}
//------------------------bind order Chart by current month-------------------------------
public List<OrderChartInfo> GetOrderChartDetailsBycurentMonth(AspxCommonInfo aspxCommonObj)
{
try
{
List<OrderChartInfo> lstOrderChart = AspxAdminDashController.GetOrderChartDetailsBycurentMonth(aspxCommonObj);
return lstOrderChart;
}
catch (Exception e)
{
throw e;
}
}
//------------------------bind order Chart by one year-------------------------------
public List<OrderChartInfo> GetOrderChartDetailsByOneYear(AspxCommonInfo aspxCommonObj)
{
try
{
List<OrderChartInfo> lstOrderChart = AspxAdminDashController.GetOrderChartDetailsByOneYear(aspxCommonObj);
return lstOrderChart;
}
catch (Exception e)
{
throw e;
}
}
//------------------------bind order Chart by last 24 hours-------------------------------
public List<OrderChartInfo> GetOrderChartDetailsBy24Hours(AspxCommonInfo aspxCommonObj)
{
try
{
List<OrderChartInfo> lstOrderChart = AspxAdminDashController.GetOrderChartDetailsBy24Hours(aspxCommonObj);
return lstOrderChart;
}
catch (Exception e)
{
throw e;
}
}
#endregion
#endregion
#region Attributes Management
public bool CheckUniqueAttributeName(AttributeBindInfo attrbuteUniqueObj, AspxCommonInfo aspxCommonObj)
{
try
{
bool isUnique = AspxItemAttrMgntController.CheckUniqueName(attrbuteUniqueObj, aspxCommonObj);
return isUnique;
}
catch (Exception e)
{
throw e;
}
}
public List<AttributesInputTypeInfo> GetAttributesInputTypeList()
{
try
{
List<AttributesInputTypeInfo> lstAttrInputType = AspxItemAttrMgntController.GetAttributesInputType();
return lstAttrInputType;
}
catch (Exception e)
{
throw e;
}
}
public List<AttributesItemTypeInfo> GetAttributesItemTypeList(AspxCommonInfo aspxCommonObj)
{
try
{
List<AttributesItemTypeInfo> lstAttrItemType = AspxItemAttrMgntController.GetAttributesItemType(aspxCommonObj);
return lstAttrItemType;
}
catch (Exception e)
{
throw e;
}
}
public List<AttributesValidationTypeInfo> GetAttributesValidationTypeList()
{
try
{
List<AttributesValidationTypeInfo> lstAttrValidType = AspxItemAttrMgntController.GetAttributesValidationType();
return lstAttrValidType;
}
catch (Exception e)
{
throw e;
}
}
public List<AttributesBasicInfo> GetAttributesList(int offset, int limit, AttributeBindInfo attrbuteBindObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<AttributesBasicInfo> lstAttrBasic = AspxItemAttrMgntController.GetItemAttributes(offset, limit, attrbuteBindObj, aspxCommonObj);
return lstAttrBasic;
}
catch (Exception e)
{
throw e;
}
}
public List<AttributesGetByAttributeIdInfo> GetAttributeDetailsByAttributeID(int attributeId, AspxCommonInfo aspxCommonObj)
{
try
{
List<AttributesGetByAttributeIdInfo> lstAttr = AspxItemAttrMgntController.GetAttributesInfoByAttributeID(attributeId, aspxCommonObj);
return lstAttr;
}
catch (Exception e)
{
throw e;
}
}
public void DeleteMultipleAttributesByAttributeID(string attributeIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemAttrMgntController.DeleteMultipleAttributes(attributeIds, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteAttributeByAttributeID(int attributeId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemAttrMgntController.DeleteAttribute(attributeId, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void UpdateAttributeIsActiveByAttributeID(int attributeId, AspxCommonInfo aspxCommonObj, bool isActive)
{
try
{
AspxItemAttrMgntController.UpdateAttributeIsActive(attributeId, aspxCommonObj, isActive);
}
catch (Exception e)
{
throw e;
}
}
public void SaveUpdateAttribute(AttributesGetByAttributeIdInfo attributeInfo)
{
try
{
AspxItemAttrMgntController.SaveAttribute(attributeInfo);
}
catch (Exception e)
{
throw e;
}
}
public AttributeFormInfo SaveUpdateAttributeInfo(AttributesGetByAttributeIdInfo attributeInfo, AttributeConfig config)
{
try
{
return AspxItemAttrMgntController.SaveAttribute(attributeInfo, config);
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region AttributeSet Management
public List<AttributeSetBaseInfo> GetAttributeSetGrid(int offset, int limit, AttributeSetBindInfo AttributeSetBindObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<AttributeSetBaseInfo> lstAttrSet = AspxItemAttrMgntController.GetAttributeSetGrid(offset, limit, AttributeSetBindObj, aspxCommonObj);
return lstAttrSet;
}
catch (Exception e)
{
throw e;
}
}
public List<AttributeSetInfo> GetAttributeSetList(AspxCommonInfo aspxCommonObj)
{
try
{
List<AttributeSetInfo> lstAttrSet = AspxItemAttrMgntController.GetAttributeSet(aspxCommonObj);
return lstAttrSet;
}
catch (Exception e)
{
throw e;
}
}
public int SaveUpdateAttributeSetInfo(AttributeSetInfo attributeSetObj, AspxCommonInfo aspxCommonObj)
{
try
{
int retValue = AspxItemAttrMgntController.SaveUpdateAttributeSet(attributeSetObj, aspxCommonObj);
return retValue;
}
catch (Exception e)
{
throw e;
}
}
public int CheckAttributeSetUniqueness(AttributeSaveInfo checkUniqueAttrSet, AspxCommonInfo aspxCommonObj)
{
try
{
int retValue = AspxItemAttrMgntController.CheckAttributeSetUniqueName(checkUniqueAttrSet, aspxCommonObj);
return retValue;
}
catch (Exception e)
{
throw e;
}
}
public List<AttributeSetGetByAttributeSetIdInfo> GetAttributeSetDetailsByAttributeSetID(int attributeSetId, AspxCommonInfo aspxCommonObj)
{
try
{
List<AttributeSetGetByAttributeSetIdInfo> lstAttrSetDetail = AspxItemAttrMgntController.GetAttributeSetInfoByAttributeSetID(attributeSetId, aspxCommonObj);
return lstAttrSetDetail;
}
catch (Exception e)
{
throw e;
}
}
public void DeleteAttributeSetByAttributeSetID(int attributeSetId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemAttrMgntController.DeleteAttributeSet(attributeSetId, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void UpdateAttributeSetIsActiveByAttributeSetID(int attributeSetId, AspxCommonInfo aspxCommonObj, bool isActive)
{
try
{
AspxItemAttrMgntController.UpdateAttributeSetIsActive(attributeSetId, aspxCommonObj, isActive);
}
catch (Exception e)
{
throw e;
}
}
public void SaveUpdateAttributeGroupInfo(AttributeSaveInfo attributeSaveObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemAttrMgntController.UpdateAttributeGroup(attributeSaveObj, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public void DeleteAttributeSetGroupByAttributeSetID(AttributeSaveInfo deleteGroupObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemAttrMgntController.DeleteAttributeSetGroup(deleteGroupObj, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
public List<AttributeSetGroupAliasInfo> RenameAttributeSetGroupAliasByGroupID(AttributeSetGroupAliasInfo attributeSetInfoToUpdate)
{
try
{
List<AttributeSetGroupAliasInfo> lstAttrSetGroup = AspxItemAttrMgntController.RenameAttributeSetGroupAlias(attributeSetInfoToUpdate);
return lstAttrSetGroup;
}
catch (Exception e)
{
throw e;
}
}
public void DeleteAttributeByAttributeSetID(AttributeSaveInfo deleteGroupObj, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemAttrMgntController.DeleteAttribute(deleteGroupObj, aspxCommonObj);
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region Refer-A-Friend
//-------------------------Save AND SendEmail Messages For Refer-A-Friend----------------
public void SaveAndSendEmailMessage(AspxCommonInfo aspxCommonObj, ReferToFriendEmailInfo referToFriendObj, WishItemEmailInfo messageBodyDetail)
{
try
{
AspxReferFriendController.SaveAndSendEmailMessage(aspxCommonObj, referToFriendObj, messageBodyDetail);
}
catch (Exception ex)
{
throw ex;
}
}
//--------------------bind Email list in Grid--------------------------
public List<ReferToFriendInfo> GetAllReferToAFriendEmailList(int offset, int limit, string senderName, string senderEmail, string receiverName, string receiverEmail, string subject, int storeID, int portalID, string userName)
{
try
{
List<ReferToFriendInfo> bind = AspxReferFriendController.GetAllReferToAFriendEmailList(offset, limit, senderName, senderEmail, receiverName, receiverEmail, subject, storeID, portalID, userName);
return bind;
}
catch (Exception ex)
{
throw ex;
}
}
//-----------------Delete Email list --------------------------------
public void DeleteReferToFriendEmailUser(string emailAFriendIDs, AspxCommonInfo aspxCommonObj)
{
try
{
AspxReferFriendController.DeleteReferToFriendEmailUser(emailAFriendIDs, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//---------------Get UserReferred Friends--------------------------
//[WebMethod]
//public List<ReferToFriendInfo> GetUserReferredFriends(int offset, int limit, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<ReferToFriendInfo> lstReferFriend = AspxReferFriendController.GetUserReferredFriends(offset, limit, aspxCommonObj);
// return lstReferFriend;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
#endregion
#region Items Management
public bool CheckKitComponentExist(string ComponentName, AspxCommonInfo aspxCommonObj)
{
try
{
AspxKitController controller = new AspxKitController();
bool isUnique = controller.CheckKitComponentExist(ComponentName, aspxCommonObj);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteKit(string kitIds, AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
controller.DeleteKit(kitIds, commonInfo);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteKitComponent(string kitComponentIds, AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
controller.DeleteKitComponent(kitComponentIds, commonInfo);
}
catch (Exception ex)
{
throw ex;
}
}
public List<KitInfo> GetKitsGrid(int offset, int limit, string kitname, AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
return controller.LoadKits(offset, limit, kitname, commonInfo);
}
catch (Exception)
{
throw;
}
}
public List<ItemKit> GetItemKits(int itemID, AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
return controller.GetItemKits(itemID, commonInfo);
}
catch (Exception e)
{
throw e;
}
}
public void SaveItemKits(List<ItemKit> mappedKits, int itemID, AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
controller.SaveItemKits(mappedKits, itemID, commonInfo);
}
catch (Exception ex)
{
throw ex;
}
}
public int SaveComponent(KitComponent kitcomponent, AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
return controller.SaveComponent(kitcomponent, commonInfo);
}
catch (Exception ex)
{
throw ex;
}
}
public int SaveKit(Kit kit, AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
return controller.SaveKit(kit, commonInfo);
}
catch (Exception ex)
{
throw ex;
}
}
public List<KitComponent> GetComponents(AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
return controller.GetComponents(commonInfo);
}
catch (Exception)
{
throw;
}
}
public List<Kit> GetKits(AspxCommonInfo commonInfo)
{
try
{
AspxKitController controller = new AspxKitController();
return controller.GetKits(commonInfo);
}
catch (Exception)
{
throw;
}
}
public ItemSetting GetItemSetting(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
ItemSetting lstItemSetting = AspxItemMgntController.GetItemSetting(ItemID, aspxCommonObj);
return lstItemSetting;
}
catch (Exception e)
{
throw e;
}
}
public List<ItemPriceGroupInfo> GetItemGroupPrices(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemPriceGroupInfo> lstGroupPrice = AspxItemMgntController.GetItemGroupPrices(ItemID, aspxCommonObj);
return lstGroupPrice;
}
catch (Exception e)
{
throw e;
}
}
public List<ItemsInfo> GetItemsList(int offset, int limit, GetItemListInfo getItemListObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemsInfo> ml;
ml = AspxItemMgntController.GetAllItems(offset, limit, getItemListObj, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteMultipleItemsByItemID(string itemIds, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemMgntController.DeleteMultipleItems(itemIds, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteItemByItemID(string itemId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemMgntController.DeleteSingleItem(itemId, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
public List<AttributeFormInfo> GetItemFormAttributes(int attributeSetID, int itemTypeID, AspxCommonInfo aspxCommonObj)
{
List<AttributeFormInfo> formAttributeList;
formAttributeList = AspxItemMgntController.GetItemFormAttributes(attributeSetID, itemTypeID, aspxCommonObj);
return formAttributeList;
}
//[WebMethod]
//public List<AttributeFormInfo> GetItemFormAttributesByitemSKUOnly(string itemSKU, AspxCommonInfo aspxCommonObj)
//{
// List<AttributeFormInfo> frmItemFieldList = AspxItemMgntController.GetItemFormAttributesByItemSKUOnly(itemSKU, aspxCommonObj);
// return frmItemFieldList;
//}
public List<AttributeFormInfo> GetItemFormAttributesValuesByItemID(int itemID, int attributeSetID, int itemTypeID, AspxCommonInfo aspxCommonObj)
{
List<AttributeFormInfo> frmItemAttributes = AspxItemMgntController.GetItemAttributesValuesByItemID(itemID, attributeSetID, itemTypeID, aspxCommonObj);
return frmItemAttributes;
}
public int SaveItemAndAttributes(ItemsInfo.ItemSaveBasicInfo itemObj, AspxCommonInfo aspxCommonObj)
{
try
{
string uplodedDownlodableFormValue = string.Empty;
if (itemObj.ItemTypeId == 2 && itemObj.DownloadItemsValue != "")
{
FileHelperController downLoadableObj = new FileHelperController();
string tempFolder = @"Upload\temp";
uplodedDownlodableFormValue = downLoadableObj.MoveFileToDownlodableItemFolder(tempFolder,
itemObj.DownloadItemsValue,
@"Modules/AspxCommerce/AspxItemsManagement/DownloadableItems/",
itemObj.ItemId, "item_");
itemObj.DownloadItemsValue = uplodedDownlodableFormValue;
}
int itemID = AspxItemMgntController.SaveUpdateItemAndAttributes(itemObj, aspxCommonObj);
//kit produtct
if (itemObj.ItemTypeId == 6)
{
AspxKitController _kitCtl = new AspxKitController();
_kitCtl.SaveKits(itemObj.KitConfig, itemID, aspxCommonObj);
}
//return "({\"returnStatus\":1,\"Message\":'Item saved successfully.'})";
int storeId = aspxCommonObj.StoreID;
int portalId = aspxCommonObj.PortalID;
string culture = aspxCommonObj.CultureName;
// if (itemID > 0 && sourceFileCol != "" && dataCollection != "")
if (itemID > 0 && itemObj.SourceFileCol != "" && itemObj.DataCollection != "")
{
StoreSettingConfig ssc = new StoreSettingConfig();
int itemLargeThumbNailHeight = Convert.ToInt32(ssc.GetStoreSettingsByKey(StoreSetting.ItemLargeThumbnailImageHeight, storeId, portalId, culture));
int itemLargeThumbNailWidth = Convert.ToInt32(ssc.GetStoreSettingsByKey(StoreSetting.ItemLargeThumbnailImageWidth, storeId, portalId, culture));
int itemMediumThumbNailHeight = Convert.ToInt32(ssc.GetStoreSettingsByKey(StoreSetting.ItemMediumThumbnailImageHeight, storeId, portalId, culture));
int itemMediumThumbNailWidth = Convert.ToInt32(ssc.GetStoreSettingsByKey(StoreSetting.ItemMediumThumbnailImageWidth, storeId, portalId, culture));
int itemSmallThumbNailHeight = Convert.ToInt32(ssc.GetStoreSettingsByKey(StoreSetting.ItemSmallThumbnailImageHeight, storeId, portalId, culture));
int itemSmallThumbNailWidth = Convert.ToInt32(ssc.GetStoreSettingsByKey(StoreSetting.ItemSmallThumbnailImageWidth, storeId, portalId, culture));
var dataCollection = itemObj.DataCollection;
dataCollection = dataCollection.Replace("../", "");
SaveImageContents(itemID, @"Modules/AspxCommerce/AspxItemsManagement/uploads/", itemObj.SourceFileCol,
dataCollection, itemLargeThumbNailHeight, itemLargeThumbNailWidth, itemMediumThumbNailHeight, itemMediumThumbNailWidth,
itemSmallThumbNailHeight, itemSmallThumbNailWidth, "item_", aspxCommonObj.CultureName, aspxCommonObj.PortalID);
}
else if (itemID > 0 && itemObj.SourceFileCol == "" && itemObj.DataCollection == "")
{
DeleteImageContents(itemID);
}
return itemID;
//if (itemID == 0)
//{
// //SaveImageContents(itemID, @"Modules/AspxCommerce/AspxItemsManagement/uploads/", sourceFileCol, dataCollection, "item_");
// //TODO:: DELTE UPLOADED FILE FROM DOWNLOAD FOLDER
//}
}
catch (Exception ex)
{
throw ex;
//ErrorHandler errHandler = new ErrorHandler();
//if (errHandler.LogWCFException(ex))
//{
// return "({\"returnStatus\":-1,\"errorMessage\":'" + ex.Message + "'})";
//}
//else
//{
// return "({\"returnStatus\":-1,\"errorMessage\":'Error while saving item!'})";
//}
}
}
public void UpdateItemIsActiveByItemID(int itemId, AspxCommonInfo aspxCommonObj, bool isActive)
{
try
{
AspxItemMgntController.UpdateItemIsActive(itemId, aspxCommonObj, isActive);
}
catch (Exception ex)
{
throw ex;
}
}
//public bool CheckUniqueAttributeName(AttributeBindInfo attrbuteUniqueObj, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// bool isUnique = AspxItemAttrMgntController.CheckUniqueName(attrbuteUniqueObj, aspxCommonObj);
// return isUnique;
// }
// catch (Exception e)
// {
// throw e;
// }
//}
public List<CategoryInfo> GetCategoryList(string prefix, bool isActive, AspxCommonInfo aspxCommonObj, int itemId, bool serviceBit)
{
List<CategoryInfo> catList = AspxItemMgntController.GetCategoryList(prefix, isActive, aspxCommonObj, itemId, serviceBit);
return catList;
}
public bool CheckIsItemInGroupItem(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
bool isUnique = AspxItemMgntController.CheckIsItemInGroupItem(ItemID, aspxCommonObj);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
public bool CheckUniqueItemSKUCode(string SKU, int itemId, AspxCommonInfo aspxCommonObj)
{
try
{
bool isUnique = AspxItemMgntController.CheckUniqueSKUCode(SKU, itemId, aspxCommonObj);
return isUnique;
}
catch (Exception ex)
{
throw ex;
}
}
#region Multiple Image Uploader
public string SaveImageContents(int itemID, string imageRootPath, string sourceFileCol, string dataCollection, int itemLargeThumbNailHeight, int itemLargeThumbNailWidth, int itemMediumThumbNailHeight, int itemMediumThumbNailWidth,
int itemSmallThumbNailHeight, int itemSmallThumbNailWidth, string imgPreFix, string cultureName, int portalID)
{
if (dataCollection.Contains("#"))
{
dataCollection = dataCollection.Remove(dataCollection.LastIndexOf("#"));
}
SQLHandler sageSql = new SQLHandler();
string[] individualRow = dataCollection.Split('#');
string[] words;
StringBuilder sbPathList = new StringBuilder();
StringBuilder sbIsActiveList = new StringBuilder();
StringBuilder sbImageType = new StringBuilder();
StringBuilder sbDescription = new StringBuilder();
StringBuilder sbDisplayOrder = new StringBuilder();
StringBuilder sbSourcePathList = new StringBuilder();
StringBuilder sbItemImageId = new StringBuilder();
foreach (string str in individualRow)
{
words = str.Split('%');
sbPathList.Append(words[0] + "%");
sbIsActiveList.Append(words[1] + "%");
sbImageType.Append(words[2] + "%");
sbDescription.Append(words[3] + "%");
sbDisplayOrder.Append(words[4] + "%");
sbItemImageId.Append(words[5] + "%");
}
string pathList = string.Empty;
string isActive = string.Empty;
string imageType = string.Empty;
string description = string.Empty;
string displayOrder = string.Empty;
string itemImageIds = string.Empty;
pathList = sbPathList.ToString();
isActive = sbIsActiveList.ToString();
imageType = sbImageType.ToString();
description = sbDescription.ToString();
displayOrder = sbDisplayOrder.ToString();
itemImageIds = sbItemImageId.ToString();
if (pathList.Contains("%"))
{
pathList = pathList.Remove(pathList.LastIndexOf("%"));
}
if (isActive.Contains("%"))
{
isActive = isActive.Remove(isActive.LastIndexOf("%"));
}
if (imageType.Contains("%"))
{
imageType = imageType.Remove(imageType.LastIndexOf("%"));
}
if (itemImageIds.Contains("%"))
{
itemImageIds = itemImageIds.Remove(itemImageIds.LastIndexOf("%"));
}
if (sourceFileCol.Contains("%"))
{
sourceFileCol = sourceFileCol.Remove(sourceFileCol.LastIndexOf("%"));
}
try
{
FileHelperController fhc = new FileHelperController();
//TODO:: delete all previous files infos lists
fhc.FileMover(itemID, imageRootPath, sourceFileCol, pathList, isActive, imageType, itemImageIds, description, displayOrder, imgPreFix, itemLargeThumbNailHeight, itemLargeThumbNailWidth, itemMediumThumbNailHeight, itemMediumThumbNailWidth,
itemSmallThumbNailHeight, itemSmallThumbNailWidth, cultureName, portalID);
}
catch (Exception ex)
{
throw ex;
}
return "Success";
}
public List<ItemsInfoSettings> GetImageContents(int itemID, AspxCommonInfo aspxCommonObj)
{
List<ItemsInfoSettings> itemsImages = AspxImageGalleryController.GetItemsImageGalleryInfoByItemID(itemID, aspxCommonObj);
return itemsImages;
}
public void DeleteImageContents(Int32 itemID)
{
try
{
AspxItemMgntController.DeleteItemImageByItemID(itemID);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Related, Cross Sell, Up sell Items
public List<ItemsInfo> GetAssociatedItemsList(int offset, int limit, ItemDetailsCommonInfo IDCommonObj, int categoryID, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemsInfo> ml;
ml = AspxItemMgntController.GetAssociatedItemsByItemID(offset, limit, IDCommonObj, categoryID, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ItemsInfo> GetRelatedItemsList(int offset, int limit, ItemDetailsCommonInfo IDCommonObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemsInfo> ml;
ml = AspxItemMgntController.GetRelatedItemsByItemID(offset, limit, IDCommonObj, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ItemsInfo> GetUpSellItemsList(int offset, int limit, ItemDetailsCommonInfo UpSellCommonObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemsInfo> ml;
ml = AspxItemMgntController.GetUpSellItemsByItemID(offset, limit, UpSellCommonObj, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
public List<ItemsInfo> GetCrossSellItemsList(int offset, int limit, ItemDetailsCommonInfo CrossSellCommonObj, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemsInfo> ml;
ml = AspxItemMgntController.GetCrossSellItemsByItemID(offset, limit, CrossSellCommonObj, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
public string GetAssociatedCheckIDs(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
string ml;
ml = AspxItemMgntController.GetAssociatedCheckIDs(ItemID, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
public string GetRelatedCheckIDs(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
string ml;
ml = AspxItemMgntController.GetRelatedCheckIDs(ItemID, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
public string GetUpSellCheckIDs(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
string ml;
ml = AspxItemMgntController.GetUpSellCheckIDs(ItemID, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
public string GetCrossSellCheckIDs(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
string ml;
ml = AspxItemMgntController.GetCrossSellCheckIDs(ItemID, aspxCommonObj);
return ml;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Item Cost Variants Management
public List<CostVariantInfo> GetCostVariantsOptionsList(int itemId, AspxCommonInfo aspxCommonObj)
{
try
{
List<CostVariantInfo> lstCostVar = AspxItemMgntController.GetAllCostVariantOptions(itemId, aspxCommonObj);
return lstCostVar;
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------ delete Item Cost Variants management------------------------
public void DeleteSingleItemCostVariant(string itemCostVariantID, int itemId, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemMgntController.DeleteSingleItemCostVariant(itemCostVariantID, itemId, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//#region NeW CostVariant Combination
//[WebMethod]
//public List<VariantCombination> GetCostVariantCombinationbyItemSku(string itemSku, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<VariantCombination> lstVarCom = AspxItemMgntController.GetCostVariantCombinationbyItemSku(itemSku, aspxCommonObj);
// return lstVarCom;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//[WebMethod]
//public List<ItemCostVariantsInfo> GetCostVariantsByItemSKU(string itemSku, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<ItemCostVariantsInfo> lstItemCostVar = AspxItemMgntController.GetCostVariantsByItemSKU(itemSku, aspxCommonObj);
// return lstItemCostVar;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//public List<CostVariantInfo> GetCostVariantForItem(AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<CostVariantInfo> lstCostVar = AspxItemMgntController.GetCostVariantForItem(aspxCommonObj);
// return lstCostVar;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//public List<CostVariantValuesInfo> GetCostVariantValues(int costVariantID, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<CostVariantValuesInfo> lstCostVarValue = AspxItemMgntController.GetCostVariantValues(costVariantID, aspxCommonObj);
// return lstCostVarValue;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//public void DeleteCostVariantForItem(int itemId, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// AspxItemMgntController.DeleteCostVariantForItem(itemId, aspxCommonObj);
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//public List<VariantCombination> GetCostVariantsOfItem(int itemId, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// List<VariantCombination> lstVarComb = AspxItemMgntController.GetCostVariantsOfItem(itemId, aspxCommonObj);
// return lstVarComb;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
//public void SaveAndUpdateItemCostVariantCombination(CostVariantsCombination itemCostVariants, AspxCommonInfo aspxCommonObj)
//{
// try
// {
// string cvCombinations = string.Empty;
// foreach (var objCombination in itemCostVariants.VariantOptions)
// {
// cvCombinations += objCombination.CombinationIsActive;
// cvCombinations += "," + objCombination.ImageFile;
// cvCombinations += "," + objCombination.CombinationPriceModifier;
// cvCombinations += "," + objCombination.CombinationPriceModifierType;
// cvCombinations += "," + objCombination.CombinationQuantity;
// cvCombinations += "," + objCombination.CombinationType;
// cvCombinations += "," + objCombination.CombinationValues;
// cvCombinations += "," + objCombination.CombinationValuesName;
// cvCombinations += "," + objCombination.CombinationWeightModifier;
// cvCombinations += "," + objCombination.CombinationWeightModifierType;
// cvCombinations += "," + objCombination.DisplayOrder;
// if (itemCostVariants.VariantOptions.Count - 1 != 0)
// cvCombinations += "%";
// }
// // cvCombinations = cvCombinations.Replace("Upload/temp/", "Modules/AspxCommerce/AspxItemsManagement/uploads/");
// FileHelperController Fch = new FileHelperController();
// string tempFolder = @"Upload\temp";
// string destPath = @"Modules/AspxCommerce/AspxItemsManagement/uploads/";
// Fch.MoveVariantsImageFile(tempFolder, destPath, itemCostVariants, aspxCommonObj);
// AspxItemMgntController.SaveAndUpdateItemCostVariantCombination(itemCostVariants, aspxCommonObj, cvCombinations);
// }
// catch (Exception e)
// {
// throw e;
// }
//}
#endregion
#region Item Management Setting
public ItemTabSettingInfo ItemTabSettingGet(AspxCommonInfo aspxCommonObj)
{
try
{
ItemTabSettingInfo lstItem = AspxItemMgntController.ItemTabSettingGet(aspxCommonObj);
return lstItem;
}
catch (Exception ex)
{
throw ex;
}
}
public void ItemTabSettingSave(string SettingKeys, string SettingValues, AspxCommonInfo aspxCommonObj)
{
try
{
AspxItemMgntController.ItemTabSettingSave(SettingKeys, SettingValues, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Item Tax Class Name
public List<TaxItemClassInfo> GetAllTaxItemClass(AspxCommonInfo aspxCommonObj, bool isActive)
{
try
{
List<TaxItemClassInfo> lstTaxItemClass = AspxItemMgntController.GetAllTaxItemClass(aspxCommonObj, isActive);
return lstTaxItemClass;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Quantity Discount Management
public List<ItemQuantityDiscountInfo> GetItemQuantityDiscountsByItemID(int itemId, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemQuantityDiscountInfo> lstIQtyDiscount = AspxQtyDiscountMgntController.GetItemQuantityDiscountsByItemID(itemId, aspxCommonObj);
return lstIQtyDiscount;
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------save quantity discount------------------
public void SaveItemDiscountQuantity(string discountQuantity, int itemID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxQtyDiscountMgntController.SaveItemDiscountQuantity(discountQuantity, itemID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------delete quantity discount------------------
public void DeleteItemQuantityDiscount(int quantityDiscountID, int itemID, AspxCommonInfo aspxCommonObj)
{
try
{
AspxQtyDiscountMgntController.DeleteItemQuantityDiscount(quantityDiscountID, itemID, aspxCommonObj);
}
catch (Exception ex)
{
throw ex;
}
}
//------------------------quantity discount shown in Item deatils ------------------
public List<ItemQuantityDiscountInfo> GetItemQuantityDiscountByUserName(AspxCommonInfo aspxCommonObj, string itemSKU)
{
try
{
List<ItemQuantityDiscountInfo> lstIQtyDiscount = AspxQtyDiscountMgntController.GetItemQuantityDiscountByUserName(aspxCommonObj, itemSKU);
return lstIQtyDiscount;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region "For Item Videos"
public List<ItemsInfo.ItemSaveBasicInfo> GetItemVideoContents(int ItemID, AspxCommonInfo aspxCommonObj)
{
try
{
List<ItemsInfo.ItemSaveBasicInfo> lstItemVideo = AspxItemMgntController.GetItemVideoContents(ItemID, aspxCommonObj);
return lstItemVideo;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Downloadable Item Details
public List<DownLoadableItemInfo> GetDownloadableItem(int itemId, AspxCommonInfo aspxCommonObj)
{
try
{
List<DownLoadableItemInfo> lstDownItem = AspxItemMgntController.GetDownloadableItem(itemId, aspxCommonObj);
return lstDownItem;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#endregion
}
}
| 34.719631
| 254
| 0.541622
|
[
"MIT"
] |
AspxCommerce/AspxCommerce2.7
|
AspxCommerce.Core/Controller/AspxCoreController.cs
| 252,379
|
C#
|
using Microsoft.Maui.Graphics;
namespace ScottPlot.Axes;
public class BottomAxis : AxisBase, IAxis
{
public BottomAxis(string text, bool ticks) : base(Edge.Bottom, text)
{
Ticks(ticks);
}
public void DrawAxisLabel(ICanvas canvas, PlotConfig info, float size, float offset)
{
float xCenter = info.DataRect.HorizontalCenter;
float yBottom = info.DataRect.Bottom + size + offset;
Label.Draw(canvas, xCenter, yBottom, HorizontalAlignment.Center, VerticalAlignment.Bottom);
}
public void DrawGridLines(ICanvas canvas, PlotConfig info, Tick[] ticks)
{
DrawVerticalGridLines(canvas, info, ticks);
}
public void DrawSpine(ICanvas canvas, PlotConfig config, float offset)
{
canvas.StrokeColor = SpineColor;
canvas.StrokeSize = SpineLineWidth;
canvas.DrawLine(
config.DataRect.Left,
config.DataRect.Bottom + offset,
config.DataRect.Right,
config.DataRect.Bottom + offset);
}
public void DrawTicks(ICanvas canvas, PlotConfig info, Tick[] ticks, float offset)
{
foreach (Tick tick in ticks)
{
float x = info.GetPixelX(tick.Position);
PointF pt1 = new(x, info.DataRect.Bottom + offset);
PointF pt2 = new(pt1.X, pt1.Y + tick.TickMarkLength);
canvas.StrokeColor = tick.TickMarkColor;
canvas.DrawLine(pt1, pt2);
PointF pt3 = new(pt2.X, pt2.Y + tick.TextPadding);
tick.Label.Draw(canvas, pt3.X, pt3.Y, HorizontalAlignment.Center, VerticalAlignment.Top);
}
}
}
| 32.019608
| 101
| 0.637477
|
[
"MIT"
] |
Glepooek/ScottPlot
|
dev/ScottPlot5/ScottPlot/Axes/BottomAxis.cs
| 1,635
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программным средством.
// Версия среды выполнения: 4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
// код создан повторно.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Collision.Properties
{
/// <summary>
/// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
/// </summary>
// Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
// класс с помощью таких средств, как ResGen или Visual Studio.
// Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
// с параметром /str или заново постройте свой VS-проект.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Collision.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Переопределяет свойство CurrentUICulture текущего потока для всех
/// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 40.888889
| 176
| 0.602242
|
[
"MIT"
] |
Aizhan1202/Proga-2017
|
Collision/Collision/Properties/Resources.Designer.cs
| 3,475
|
C#
|
namespace MilanWebStore.Web.Areas.Administration.Controllers
{
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MilanWebStore.Services.Data.Contracts;
using MilanWebStore.Web.ViewModels.Administration.Orders;
using MilanWebStore.Web.ViewModels.Orders;
public class OrdersController : AdministrationController
{
private readonly IOrdersService ordersService;
public OrdersController(IOrdersService ordersService)
{
this.ordersService = ordersService;
}
public IActionResult Index()
{
var ordersViewModel = new IndexOrdersViewModel()
{
ProcessedOrders = this.ordersService.GetProcessedOrders<MyOrderViewModel>(),
UnProcessedOrders = this.ordersService.GetUnProcessedOrders<MyOrderViewModel>(),
};
return this.View(ordersViewModel);
}
public async Task<IActionResult> Process(int id)
{
await this.ordersService.ProcessOrder(id);
return this.RedirectToAction(nameof(this.Index));
}
public async Task<IActionResult> Deliver(int id)
{
await this.ordersService.DeliverOrder(id);
return this.RedirectToAction(nameof(this.Index));
}
public IActionResult Delivered()
{
var viewModel = new DeliveredOrdersViewModel()
{
Orders = this.ordersService.GetDeliveredOrders<MyOrderViewModel>(),
};
return this.View(viewModel);
}
}
}
| 29.254545
| 96
| 0.63207
|
[
"MIT"
] |
MihailKarabashev/MilanWebStore
|
Web/MilanWebStore.Web/Areas/Administration/Controllers/OrdersController.cs
| 1,611
|
C#
|
using UnityEngine;
using System.Collections;
namespace YounGenTech.HealthScript {
[AddComponentMenu("YounGen Tech/Health/Other/Restart Scene")]
public class RestartScene : MonoBehaviour {
public void Restart() {
Application.LoadLevel(Application.loadedLevel);
}
}
}
| 25.583333
| 65
| 0.700326
|
[
"MIT"
] |
michelsara/GameDevelopment
|
SlimeTime/Assets/YounGen Tech/Health Script/Scripts/Other Examples/RestartScene.cs
| 307
|
C#
|
namespace ChromeDevTools.Host.Runtime.Page
{
using Newtonsoft.Json;
/// <summary>
/// LoadEventFired
/// </summary>
public sealed class LoadEventFiredEvent : IEvent
{
/// <summary>
/// Gets or sets the timestamp
/// </summary>
[JsonProperty("timestamp")]
public double Timestamp
{
get;
set;
}
}
}
| 20.25
| 52
| 0.520988
|
[
"MIT"
] |
fforjan/ChromeDevTools.Host
|
ChromeDevTools.Host/Runtime/Page/LoadEventFiredEvent.cs
| 405
|
C#
|
using SFA.DAS.Location.Domain.Interfaces;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
namespace SFA.DAS.Location.Application.Postcode.Queries.GetByOutcode
{
public class GetOutcodeQueryHandler : IRequestHandler<GetOutcodeQuery, GetOutcodeQueryResult>
{
private readonly IPostcodeService _service;
public GetOutcodeQueryHandler(IPostcodeService service)
{
_service = service;
}
public async Task<GetOutcodeQueryResult> Handle(GetOutcodeQuery request, CancellationToken cancellationToken)
{
var result = await _service.GetDistrictNameByOutcodeQuery(request.Outcode );
return new GetOutcodeQueryResult
{
Outcode = result
};
}
}
}
| 28.571429
| 117
| 0.685
|
[
"MIT"
] |
SkillsFundingAgency/das-location-api
|
src/SFA.DAS.Location.Application/Postcode/Queries/GetByOutcode/GetOutcodeQueryHandler.cs
| 800
|
C#
|
/**
* Implementation of the net.sf.geographiclib.GnomonicData class
*
* Copyright (c) BMW Car IT GmbH (2014-2016) <sebastian.mattheis@bmw-carit.de>
* and licensed under the MIT/X11 License. For more information, see
* https://geographiclib.sourceforge.io/
**********************************************************************/
using System;
namespace GeographicLib
{
/**
* The results of gnomonic projection.
* <p>
* This is used to return the results for a gnomonic projection of a point
* (<i>lat</i>, <i>lon</i>) given a center point of projection (<i>lat0</i>,
* <i>lon0</i>). The returned GnomonicData objects always include the
* parameters provided to
* {@link Gnomonic#Forward Gnomonic.Forward}
* and
* {@link Gnomonic#Reverse Gnomonic.Reverse}
* and it always includes the fields <i>x</i>, <i>y</i>, <i>azi</i>. and
* <i>rk</i>.
**********************************************************************/
public readonly struct GnomonicData
{
/**
* latitude of center point of projection (degrees).
**********************************************************************/
public double lat0 { get; }
/**
* longitude of center point of projection (degrees).
**********************************************************************/
public double lon0 { get; }
/**
* latitude of point (degrees).
**********************************************************************/
public double lat { get; }
/**
* longitude of point (degrees).
**********************************************************************/
public double lon { get; }
/**
* easting of point (meters).
**********************************************************************/
public double x { get; }
/**
* northing of point (meters).
**********************************************************************/
public double y { get; }
/**
* azimuth of geodesic at point (degrees).
**********************************************************************/
public double azi { get; }
/**
* reciprocal of azimuthal scale at point.
**********************************************************************/
public double rk { get; }
/**
* Constructor initializing all the fields for gnomonic projection of a point
* (<i>lat</i>, <i>lon</i>) given a center point of projection (<i>lat0</i>,
* <i>lon0</i>).
* <p>
* @param lat0
* latitude of center point of projection (degrees).
* @param lon0
* longitude of center point of projection (degrees).
* @param lat
* latitude of point (degrees).
* @param lon
* longitude of point (degrees).
* @param x
* easting of point (meters).
* @param y
* northing of point (meters).
* @param azi
* azimuth of geodesic at point (degrees).
* @param rk
* reciprocal of azimuthal scale at point.
*/
public GnomonicData(double lat0 = double.NaN, double lon0 = double.NaN, double lat = double.NaN, double lon = double.NaN,
double x = double.NaN, double y = double.NaN, double azi = double.NaN, double rk = double.NaN)
{
this.lat0 = lat0;
this.lon0 = lon0;
this.lat = lat;
this.lon = lon;
this.x = x;
this.y = y;
this.azi = azi;
this.rk = rk;
}
}
}
| 38.979381
| 129
| 0.422111
|
[
"MIT"
] |
oldrev/GeographicLib
|
GeographicLib/GnomonicData.cs
| 3,783
|
C#
|
using System;
using Goguma.Game.Console;
using Goguma.Game.Object.Skill.Attack;
namespace Goguma.Game.Object.Skill.Skills.Mob.TestMonster
{
[Serializable]
public class Fireball : AMagicAttackSkill
{
public override string Name => "파이어 볼";
public override CTexts Text => CTexts.Make("{빠이아 뽈!!}");
public override CTexts Descriptions => CTexts.Make("{테스트 몬스터가 사용하는 화염구 공격이다.}}");
public override AttackEffect Effect => new()
{
MagicDamage = 1,
MagicPenetration = 1
};
}
}
| 23.5
| 85
| 0.682785
|
[
"Apache-2.0"
] |
hellun205/Goguma
|
Game/Object/Skill/Skills/Mob/TestMonster/Fireball.cs
| 569
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("dp2Router")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("dp2Router")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7210c4da-4ef2-4142-ae88-da021f51b9f1")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.9.*")]
[assembly: AssemblyFileVersion("1.9.0.0")]
// 1.1 (2016/9/16) 第一个可以被 chordInstaller 安装的版本
// 1.2 (2016/10/13) 在日志中记载 HTTP request,对方的 IP。以观察 CPU 耗用过高情况的原因
// 1.3 (2016/10/15) 修正 GetConnection() 时 name 参数的 bug。自动清理(空闲时间超过一个小时的)空闲通道
// 1.4 (2016/10/30) 请求的 HTTP 中携带 _dp2router_clientip 头字段
// 1.5 (2016/11/13) 改用 Logger 写入错误日志
// 1.6 (2016/11/14) 对进入的 HTTP 请求做了 headers 行数、每行字符数、Content-Length 配额限制。
// 对进入的请求,和响应都改造为 XXXAsync 形式。定时自动清理闲置的 HttpChannel
// 1.7 (2016/11/18) 使用 MessageConnectionCollection 中的通道 UseCount 机制,让并发的请求分散使用 MessageConnection 通道
// 1.8 (2016/11/20) 改进 ReadLineAsync() 为一次尽可能多地读入。自动在错误日志中定时写入 CPU 使用率。
// 1.9 (2016/11/20) 捕获了全局异常,写入错误日志文件。增加了崩溃后自动重启的 Recovery 属性设置(安装 Commit 阶段)
// 能处理 HTTP 协议的 Connection: Keep-Alive 了。验证请求的 User-Agent 头字段值必须为 dp2LibraryClient,否则拒绝请求。
| 35.244898
| 107
| 0.715113
|
[
"Apache-2.0"
] |
919506114/chord
|
dp2Router/Properties/AssemblyInfo.cs
| 2,564
|
C#
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Kore.Caching;
using Kore.Collections;
using Kore.Data;
using Kore.Data.Services;
using Kore.Web.Configuration;
using Kore.Web.ContentManagement.Areas.Admin.Pages.Domain;
namespace Kore.Web.ContentManagement.Areas.Admin.Pages.Services
{
public interface IPageVersionService : IGenericDataService<PageVersion>
{
PageVersion GetCurrentVersion(
int tenantId,
Guid pageId,
string cultureCode = null,
bool enabledOnly = true,
bool shownOnMenusOnly = true,
bool allowReturnDraftVersion = false,
bool forceGetInvariantIfLocalizedUnavailable = false);
IEnumerable<PageVersion> GetCurrentVersions(
int tenantId,
string cultureCode = null,
bool enabledOnly = true,
bool shownOnMenusOnly = true,
bool topLevelOnly = false,
Guid? parentId = null,
bool allowReturnDraftVersion = false,
bool forceGetInvariantIfLocalizedUnavailable = false);
}
public class PageVersionService : GenericDataService<PageVersion>, IPageVersionService
{
private readonly IRepository<Page> pageRepository;
private readonly PageSettings pageSettings;
private readonly KoreSiteSettings siteSettings;
public PageVersionService(
ICacheManager cacheManager,
IRepository<PageVersion> repository,
IRepository<Page> pageRepository,
PageSettings pageSettings,
KoreSiteSettings siteSettings)
: base(cacheManager, repository)
{
this.pageRepository = pageRepository;
this.pageSettings = pageSettings;
this.siteSettings = siteSettings;
}
#region IPageVersionService Members
/// <summary>
/// Gets the most recent localized version of a page in the specified culture
/// </summary>
/// <param name="tenantId">Tenant ID</param>
/// <param name="pageId">Page ID</param>
/// <param name="cultureCode">Culture Code</param>
/// <param name="enabledOnly">Only search enabled pages.</param>
/// <param name="shownOnMenusOnly">Only search for pages that are shown on the menu.</param>
/// <param name="forceGetInvariantIfLocalizedUnavailable">Only use this for admin purposes (example: create new localized version of a page)</param>
/// <returns></returns>
public PageVersion GetCurrentVersion(
int tenantId,
Guid pageId,
string cultureCode = null,
bool enabledOnly = true,
bool shownOnMenusOnly = true,
bool allowReturnDraftVersion = false,
bool forceGetInvariantIfLocalizedUnavailable = false)
{
using (var pageVersionConnection = OpenConnection())
{
var query = pageVersionConnection.Query(x => x.TenantId == tenantId).Include(x => x.Page);
if (enabledOnly)
{
query = query.Where(x => x.Page.IsEnabled);
}
return GetCurrentVersionInternal(
pageId,
query,
cultureCode,
shownOnMenusOnly: shownOnMenusOnly,
allowReturnDraftVersion: allowReturnDraftVersion,
forceGetInvariantIfLocalizedUnavailable: forceGetInvariantIfLocalizedUnavailable);
}
}
public IEnumerable<PageVersion> GetCurrentVersions(
int tenantId,
string cultureCode = null,
bool enabledOnly = true,
bool shownOnMenusOnly = true,
bool topLevelOnly = false,
Guid? parentId = null,
bool allowReturnDraftVersion = false,
bool forceGetInvariantIfLocalizedUnavailable = false)
{
ICollection<Page> pages = null;
using (var pageConnection = pageRepository.OpenConnection())
{
var query = pageConnection.Query(x => x.TenantId == tenantId);
if (enabledOnly)
{
query = query.Where(x => x.IsEnabled);
}
if (topLevelOnly)
{
query = query.Where(x => x.ParentId == null);
}
else if (parentId.HasValue)
{
query = query.Where(x => x.ParentId == parentId);
}
pages = query.ToHashSet();
}
using (var pageVersionConnection = OpenConnection())
{
var pageVersions = pageVersionConnection
.Query(x => x.TenantId == tenantId)
.Include(x => x.Page)
.ToHashSet();
return pages
.Select(x => GetCurrentVersionInternal(
x.Id,
pageVersions,
cultureCode,
shownOnMenusOnly: shownOnMenusOnly,
allowReturnDraftVersion: allowReturnDraftVersion,
forceGetInvariantIfLocalizedUnavailable: forceGetInvariantIfLocalizedUnavailable))
.Where(x => x != null);
}
}
#endregion IPageVersionService Members
/// <summary>
/// Gets the most recent localized version of a page in the specified culture
/// </summary>
/// <param name="pageId">Page ID</param>
/// <param name="pageVersions">A collection of page versions to search through.</param>
/// <param name="cultureCode">Culture Code</param>
/// <param name="forceGetInvariantIfLocalizedUnavailable">Only use this for admin purposes (example: create new localized version of a page)</param>
/// <returns></returns>
private PageVersion GetCurrentVersionInternal(
Guid pageId,
IEnumerable<PageVersion> pageVersions,
string cultureCode = null,
bool shownOnMenusOnly = true,
bool allowReturnDraftVersion = false,
bool forceGetInvariantIfLocalizedUnavailable = false)
{
IEnumerable<PageVersion> versions = pageVersions;
if (shownOnMenusOnly)
{
versions = versions.Where(x => x.ShowOnMenus);
}
// The default culture is ALWAYS treated as the invariant, so if the requested culture is the same as the default, then
// we skip this section and go straight to the invariant version below
if (!string.IsNullOrEmpty(cultureCode) && cultureCode != siteSettings.DefaultLanguage)
{
var localizedVersions = versions
.Where(x =>
x.PageId == pageId &&
x.CultureCode == cultureCode &&
x.Status != VersionStatus.Archived);
var localizedVersion = localizedVersions
.Where(x => x.Status == VersionStatus.Published)
.OrderByDescending(x => x.DateModifiedUtc)
.FirstOrDefault();
if (localizedVersion == null && allowReturnDraftVersion)
{
localizedVersion = localizedVersions
.Where(x => x.Status == VersionStatus.Draft)
.OrderByDescending(x => x.DateModifiedUtc)
.FirstOrDefault();
}
if (localizedVersion != null)
{
return localizedVersion;
}
if (!pageSettings.ShowInvariantVersionIfLocalizedUnavailable && !forceGetInvariantIfLocalizedUnavailable)
{
return null;
}
}
// Get invariant version
var invariantVersions = versions
.Where(x =>
x.PageId == pageId &&
x.CultureCode == null &&
x.Status != VersionStatus.Archived);
var publishedVersion = invariantVersions
.Where(x => x.Status == VersionStatus.Published)
.OrderByDescending(x => x.DateModifiedUtc)
.FirstOrDefault();
if (publishedVersion == null && allowReturnDraftVersion)
{
return invariantVersions
.Where(x => x.Status == VersionStatus.Draft)
.OrderByDescending(x => x.DateModifiedUtc)
.FirstOrDefault();
}
return publishedVersion;
}
}
}
| 39.877729
| 157
| 0.541283
|
[
"MIT"
] |
artinite21/KoreCMS
|
Kore.Web.ContentManagement/Areas/Admin/Pages/Services/IPageVersionService.cs
| 9,134
|
C#
|
using Aware.Util;
using Aware.Util.Constants;
using Aware.Util.Enum;
using Aware.Util.Exceptions;
using System;
namespace Aware.Model
{
public class User : BaseEntity
{
public int CompanyID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
public int Gender { get; set; }
public DateTime LastVisit { get; set; }
public CustomerRole Role { get; set; }
public override bool IsValid()
{
if (!Email.ValidEmail())
{
throw new AwareException(ResultCodes.Error.InvalidEmail);
}
return Password.Valid() && Name.Valid();
}
}
}
| 21.621622
| 73
| 0.57
|
[
"MIT"
] |
asetil/ArzTalep
|
Aware/Model/UserModel.cs
| 802
|
C#
|
//******************************************************************************************************
// AssemblyInfo.cs - Gbtc
//
// Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 08/26/2013 - Ritchie
// Generated original version of source code.
//
//******************************************************************************************************
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GSFSetupActions")]
[assembly: AssemblyDescription("Grid Solutions Framework Setup Installer Actions")]
[assembly: AssemblyCompany("Grid Protection Alliance")]
[assembly: AssemblyCopyright("Copyright © GPA, 2013. All Rights Reserved.")]
[assembly: AssemblyProduct("Grid Solutions Framework")]
[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("07ce1660-18cb-4595-808d-7256019a16bc")]
// 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("2.3.226.0")]
[assembly: AssemblyVersion("2.3.226.0")]
[assembly: AssemblyFileVersion("2.3.226.0")]
[assembly: AssemblyInformationalVersion("2.3.226-beta")]
| 47.016949
| 105
| 0.663663
|
[
"MIT"
] |
zobo/gsf
|
Source/Libraries/GSF.InstallerActions/Properties/AssemblyInfo.cs
| 2,778
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace _08_ViewFirst.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("_08_ViewFirst.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 39.638889
| 180
| 0.588648
|
[
"Unlicense"
] |
Slesa/Poseidon
|
sketches/wpf/caliburn/08_ViewFirst/Properties/Resources.Designer.cs
| 2,856
|
C#
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CompositeModel3D.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// <summary>
// Represents a composite Model3D.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Markup;
#if COREWPF
using HelixToolkit.SharpDX.Core;
using HelixToolkit.SharpDX.Core.Model.Scene;
#endif
namespace HelixToolkit.Wpf.SharpDX
{
#if !COREWPF
using Model.Scene;
#endif
/// <summary>
/// Represents a composite Model3D.
/// </summary>
[ContentProperty("Children")]
public class CompositeModel3D : Element3D, IHitable, ISelectable, IMouse3D
{
public static readonly DependencyProperty IsSelectedProperty =
DependencyProperty.Register("IsSelected", typeof(bool), typeof(CompositeModel3D), new PropertyMetadata(false));
public bool IsSelected
{
get
{
return (bool)this.GetValue(IsSelectedProperty);
}
set
{
this.SetValue(IsSelectedProperty, value);
}
}
/// <summary>
/// Gets the children.
/// </summary>
/// <value>
/// The children.
/// </value>
public ObservableElement3DCollection Children { get; } = new ObservableElement3DCollection();
/// <summary>
/// Initializes a new instance of the <see cref="CompositeModel3D" /> class.
/// </summary>
public CompositeModel3D()
{
Children.CollectionChanged += this.ChildrenChanged;
Loaded += GroupElement3D_Loaded;
}
private void GroupElement3D_Loaded(object sender, RoutedEventArgs e)
{
foreach (Element3D c in Children)
{
if (c.Parent == this)
{
this.RemoveLogicalChild(c);
}
}
foreach (Element3D c in Children)
{
if (c.Parent == null)
{
this.AddLogicalChild(c);
}
}
}
/// <summary>
/// Handles changes in the Children collection.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.
/// </param>
private void ChildrenChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var node = SceneNode as GroupNode;
switch (e.Action)
{
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Replace:
if (e.OldItems != null)
{
foreach (Element3D item in e.OldItems)
{
if (item.Parent == this)
{
this.RemoveLogicalChild(item);
}
node.RemoveChildNode(item.SceneNode);
}
}
break;
case NotifyCollectionChangedAction.Reset:
if (e.OldItems != null)
{
foreach (Element3D item in e.OldItems)
{
if (item.Parent == this)
{
this.RemoveLogicalChild(item);
}
}
}
node.Clear();
break;
}
switch (e.Action)
{
case NotifyCollectionChangedAction.Reset:
foreach (Element3D item in Children)
{
if (item.Parent == null)
{
this.AddLogicalChild(item);
}
node.AddChildNode(item.SceneNode);
}
break;
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Replace:
foreach (Element3D item in e.NewItems)
{
if (item.Parent == null)
{
this.AddLogicalChild(item);
}
node.AddChildNode(item.SceneNode);
}
break;
case NotifyCollectionChangedAction.Move:
node.MoveChildNode(e.OldStartingIndex, e.NewStartingIndex);
break;
}
}
protected override SceneNode OnCreateSceneNode()
{
return new GroupNode();
}
}
}
| 33.602564
| 123
| 0.441244
|
[
"MIT"
] |
B3zaleel/helix-toolkit
|
Source/HelixToolkit.Wpf.SharpDX.Shared/Model/Elements3D/CompositeModel3D.cs
| 5,244
|
C#
|
using Expressive.Expressions;
namespace Expressive.Functions.Conversion
{
internal sealed class StringFunction : FunctionBase
{
#region FunctionBase Members
public override string Name => "String";
public override object Evaluate(IExpression[] parameters, ExpressiveOptions options)
{
this.ValidateParameterCount(parameters, -1, 1);
var objectToConvert = parameters[0].Evaluate(this.Variables);
// No point converting if there is nothing to convert.
if (objectToConvert == null) return null;
// Safely check for a format parameter.
if (parameters.Length > 1)
{
var format = parameters[1].Evaluate(this.Variables);
if (format is string formatString)
{
return string.Format($"{{0:{formatString}}}", objectToConvert);
}
}
return objectToConvert.ToString();
}
#endregion
}
}
| 28.243243
| 92
| 0.574163
|
[
"MIT"
] |
denispakizh/expressive
|
Source/CSharp/Expressive/Expressive/Functions/Conversion/StringFunction.cs
| 1,047
|
C#
|
namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201
{
using static Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Extensions;
/// <summary>Request from client to check resource name availability.</summary>
public partial class NameAvailabilityRequest
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.INameAvailabilityRequest.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.INameAvailabilityRequest.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.INameAvailabilityRequest FromJson(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject json ? new NameAvailabilityRequest(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject into a new instance of <see cref="NameAvailabilityRequest" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject instance to deserialize from.</param>
internal NameAvailabilityRequest(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_type = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonString>("type"), out var __jsonType) ? (string)__jsonType : (string)Type;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="NameAvailabilityRequest" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="NameAvailabilityRequest" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add );
AfterToJson(ref container);
return container;
}
}
}
| 68.650485
| 254
| 0.680526
|
[
"MIT"
] |
3quanfeng/azure-powershell
|
src/MySql/generated/api/Models/Api20171201/NameAvailabilityRequest.json.cs
| 6,969
|
C#
|
using Project1.UI.Controls;
namespace ProjectEye.Views
{
/// <summary>
/// UpdateWindow.xaml 的交互逻辑
/// </summary>
public partial class UpdateWindow : Project1UIWindow
{
public UpdateWindow()
{
InitializeComponent();
}
}
}
| 17.75
| 56
| 0.580986
|
[
"MIT"
] |
Planshit/projecteye
|
src/Local/ProjectEye/Views/UpdateWindow.xaml.cs
| 296
|
C#
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.Outputs
{
[OutputType]
public sealed class TrafficAnalyticsPropertiesResponse
{
/// <summary>
/// Parameters that define the configuration of traffic analytics.
/// </summary>
public readonly Outputs.TrafficAnalyticsConfigurationPropertiesResponse? NetworkWatcherFlowAnalyticsConfiguration;
[OutputConstructor]
private TrafficAnalyticsPropertiesResponse(Outputs.TrafficAnalyticsConfigurationPropertiesResponse? networkWatcherFlowAnalyticsConfiguration)
{
NetworkWatcherFlowAnalyticsConfiguration = networkWatcherFlowAnalyticsConfiguration;
}
}
}
| 34.892857
| 149
| 0.752303
|
[
"Apache-2.0"
] |
pulumi/pulumi-azure-nextgen
|
sdk/dotnet/Network/Outputs/TrafficAnalyticsPropertiesResponse.cs
| 977
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace LionFire.Events
{
public class ObjectPropertyChangedListener
{
#region (Static) Dependency Acquisition
static Type[] PropertyChangedListenerTypes;
static ObjectPropertyChangedListener()
{
PropertyChangedListenerTypes = new[]
{
typeof(PropertyChangedListener),
typeof(NotifyPropertyChangedListener),
};
}
#endregion
public object Target
{
get
{
return target;
}
set
{
if (target == value) return;
if (target != null)
{
foreach (var listener in Listeners)
{
if (listener.HasFastChangedTo)
{
listener.PropertyChangedTo -= OnPropertyChangedTo;
}
else
{
listener.PropertyChanged -= OnPropertyChanged;
}
}
}
target = value;
if (target != null)
{
Listeners.Clear();
foreach (Type type in PropertyChangedListenerTypes)
{
var listener = (IPropertyChangedListener)Activator.CreateInstance(type);
listener.Target = target;
if (listener.IsTargetSupported)
{
Listeners.Add(listener);
}
}
foreach (var listener in Listeners)
{
if (listener.HasFastChangedTo)
{
listener.PropertyChangedTo += OnPropertyChangedTo;
}
else
{
listener.PropertyChanged += OnPropertyChanged;
}
}
}
}
}
private object target;
void OnPropertyChangedTo(PropertyInfo pi, object newValue)
{
{
var ev = PropertyChanged;
if (ev != null) ev(pi);
}
{
var ev = PropertyChangedTo;
if (ev != null) ev(pi, newValue);
}
}
void OnPropertyChanged(PropertyInfo pi)
{
{
var ev = PropertyChanged;
if (ev != null) ev(pi);
}
{
var ev = PropertyChangedTo;
// REVIEW - Why did this Get work on MSVC / .NET 4?
// if (ev != null) ev(pi, pi.Get(Target));
if (ev != null) ev(pi, pi.GetValue(Target, null));
}
}
public event Action<PropertyInfo> PropertyChanged;
public event Action<PropertyInfo, object> PropertyChangedTo;
List<IPropertyChangedListener> Listeners = new List<IPropertyChangedListener>();
public bool IsAttached
{
get
{
return Listeners.Count > 0;
}
}
public bool HasFastChangedTo
{
get
{
foreach (var listener in Listeners)
{
if (listener.HasFastChangedTo) return true;
}
return false;
}
}
}
}
| 29.125926
| 97
| 0.403611
|
[
"MIT"
] |
LionFire/Core
|
src/LionFire.Core.Extras/Events/ObjectPropertyChangedListener.cs
| 3,934
|
C#
|
using Subscriber.Models;
using System.Collections.Generic;
using EventDriven.EventBus.Abstractions;
namespace Subscriber.Events
{
public record WeatherForecastEvent(IEnumerable<WeatherForecast> WeatherForecasts) : IntegrationEvent;
}
| 26.666667
| 105
| 0.8375
|
[
"MIT"
] |
dapr-dotnet-extensions/dapr-event-bus
|
samples/SimplePubSub/Subscriber/Events/WeatherForecastEvent.cs
| 242
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TSQL.Statements;
using TSQL.Statements.Parsers;
using TSQL.Tokens;
namespace TSQL.Clauses.Parsers
{
internal class TSQLFromClauseParser : ITSQLClauseParser
{
public TSQLFromClause Parse(ITSQLTokenizer tokenizer)
{
TSQLFromClause from = new TSQLFromClause();
if (!tokenizer.Current.IsKeyword(TSQLKeywords.FROM))
{
throw new InvalidOperationException("FROM expected.");
}
from.Tokens.Add(tokenizer.Current);
// derived tables
// TVF
int nestedLevel = 0;
while (
tokenizer.MoveNext() &&
!(
tokenizer.Current.Type == TSQLTokenType.Character &&
tokenizer.Current.AsCharacter.Character == TSQLCharacters.Semicolon
) &&
!(
nestedLevel == 0 &&
tokenizer.Current.Type == TSQLTokenType.Character &&
tokenizer.Current.AsCharacter.Character == TSQLCharacters.CloseParentheses
) &&
(
nestedLevel > 0 ||
tokenizer.Current.Type != TSQLTokenType.Keyword ||
(
tokenizer.Current.Type == TSQLTokenType.Keyword &&
tokenizer.Current.AsKeyword.Keyword.In
(
TSQLKeywords.JOIN,
TSQLKeywords.ON,
TSQLKeywords.INNER,
TSQLKeywords.LEFT,
TSQLKeywords.RIGHT,
TSQLKeywords.OUTER,
TSQLKeywords.CROSS,
TSQLKeywords.FULL,
TSQLKeywords.AS,
TSQLKeywords.PIVOT,
TSQLKeywords.UNPIVOT,
TSQLKeywords.WITH,
TSQLKeywords.MERGE,
TSQLKeywords.TABLESAMPLE,
TSQLKeywords.FOR,
TSQLKeywords.FROM, // FOR SYSTEM_TIME FROM
TSQLKeywords.BETWEEN,
TSQLKeywords.AND,
TSQLKeywords.IN,
TSQLKeywords.REPEATABLE,
TSQLKeywords.ALL
)
)
))
{
from.Tokens.Add(tokenizer.Current);
if (tokenizer.Current.Type == TSQLTokenType.Character)
{
TSQLCharacters character = tokenizer.Current.AsCharacter.Character;
if (character == TSQLCharacters.OpenParentheses)
{
// should we recurse for derived tables?
nestedLevel++;
if (tokenizer.MoveNext())
{
if (
tokenizer.Current.Type == TSQLTokenType.Keyword &&
tokenizer.Current.AsKeyword.Keyword == TSQLKeywords.SELECT)
{
TSQLSelectStatement selectStatement = new TSQLSelectStatementParser().Parse(tokenizer);
from.Tokens.AddRange(selectStatement.Tokens);
if (
tokenizer.Current != null &&
tokenizer.Current.Type == TSQLTokenType.Character &&
tokenizer.Current.AsCharacter.Character == TSQLCharacters.CloseParentheses)
{
nestedLevel--;
from.Tokens.Add(tokenizer.Current);
}
}
else if (tokenizer.Current.IsCharacter(
TSQLCharacters.CloseParentheses))
{
nestedLevel--;
from.Tokens.Add(tokenizer.Current);
}
else
{
from.Tokens.Add(tokenizer.Current);
}
}
}
else if (character == TSQLCharacters.CloseParentheses)
{
nestedLevel--;
}
}
}
return from;
}
TSQLClause ITSQLClauseParser.Parse(ITSQLTokenizer tokenizer)
{
return Parse(tokenizer);
}
}
}
| 25.646154
| 96
| 0.619076
|
[
"Apache-2.0"
] |
pjnreis/tsql-parser
|
TSQL_Parser/TSQL_Parser/Clauses/Parsers/TSQLFromClauseParser.cs
| 3,334
|
C#
|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System.Linq.Expressions;
using System;
using System.Dynamic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Linq;
using Microsoft.Scripting.Actions.Calls;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace Microsoft.Scripting.Actions {
using Ast = Expression;
public partial class DefaultBinder : ActionBinder {
/// <summary>
/// Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod
/// GetBoundMember, and StrongBox instances.
/// </summary>
/// <param name="name">
/// The name of the member to retrieve. This name is not processed by the DefaultBinder and
/// is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc...
/// </param>
/// <param name="target">
/// The MetaObject from which the member is retrieved.
/// </param>
/// <returns>
/// Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed.
///
/// The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being
/// returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing
/// so that it has an opportunity to perform custom boxing.
/// </returns>
public DynamicMetaObject GetMember(string name, DynamicMetaObject target) {
return GetMember(
name,
target,
new DefaultOverloadResolverFactory(this),
false,
null
);
}
/// <summary>
/// Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod
/// GetBoundMember, and StrongBox instances.
/// </summary>
/// <param name="name">
/// The name of the member to retrieve. This name is not processed by the DefaultBinder and
/// is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc...
/// </param>
/// <param name="target">
/// The MetaObject from which the member is retrieved.
/// </param>
/// <param name="resolverFactory">
/// Provides overload resolution and method binding for any calls which need to be performed for the GetMember.
/// </param>
/// <returns>
/// Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed.
///
/// The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being
/// returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing
/// so that it has an opportunity to perform custom boxing.
/// </returns>
public DynamicMetaObject GetMember(string name, DynamicMetaObject target, OverloadResolverFactory resolverFactory) {
return GetMember(
name,
target,
resolverFactory,
false,
null
);
}
/// <summary>
/// Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod
/// GetBoundMember, and StrongBox instances.
/// </summary>
/// <param name="name">
/// The name of the member to retrieve. This name is not processed by the DefaultBinder and
/// is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc...
/// </param>
/// <param name="target">
/// The MetaObject from which the member is retrieved.
/// </param>
/// <param name="resolverFactory">
/// An OverloadResolverFactory which can be used for performing overload resolution and method binding.
/// </param>
/// <param name="isNoThrow">
/// True if the operation should return Operation.Failed on failure, false if it
/// should return the exception produced by MakeMissingMemberError.
/// </param>
/// <param name="errorSuggestion">
/// The meta object to be used if the get results in an error.
/// </param>
/// <returns>
/// Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed.
///
/// The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being
/// returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing
/// so that it has an opportunity to perform custom boxing.
/// </returns>
public DynamicMetaObject GetMember(string name, DynamicMetaObject target, OverloadResolverFactory resolverFactory, bool isNoThrow, DynamicMetaObject errorSuggestion) {
ContractUtils.RequiresNotNull(name, "name");
ContractUtils.RequiresNotNull(target, "target");
ContractUtils.RequiresNotNull(resolverFactory, "resolverFactory");
return MakeGetMemberTarget(
new GetMemberInfo(
name,
resolverFactory,
isNoThrow,
errorSuggestion
),
target
);
}
/// <summary>
/// Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod
/// GetBoundMember, and StrongBox instances.
/// </summary>
/// <param name="name">
/// The name of the member to retrieve. This name is not processed by the DefaultBinder and
/// is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc...
/// </param>
/// <param name="target">
/// The MetaObject from which the member is retrieved.
/// </param>
/// <param name="isNoThrow">
/// True if the operation should return Operation.Failed on failure, false if it
/// should return the exception produced by MakeMissingMemberError.
/// </param>
/// <param name="errorSuggestion">
/// The meta object to be used if the get results in an error.
/// </param>
/// <returns>
/// Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed.
///
/// The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being
/// returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing
/// so that it has an opportunity to perform custom boxing.
/// </returns>
public DynamicMetaObject GetMember(string name, DynamicMetaObject target, bool isNoThrow, DynamicMetaObject errorSuggestion) {
ContractUtils.RequiresNotNull(name, "name");
ContractUtils.RequiresNotNull(target, "target");
return MakeGetMemberTarget(
new GetMemberInfo(
name,
new DefaultOverloadResolverFactory(this),
isNoThrow,
errorSuggestion
),
target
);
}
private DynamicMetaObject MakeGetMemberTarget(GetMemberInfo getMemInfo, DynamicMetaObject target) {
Type targetType = target.GetLimitType();
BindingRestrictions restrictions = target.Restrictions;
DynamicMetaObject self = target;
target = target.Restrict(target.GetLimitType());
// Specially recognized types: TypeTracker, NamespaceTracker, and StrongBox.
// TODO: TypeTracker and NamespaceTracker should technically be IDO's.
MemberGroup members = MemberGroup.EmptyGroup;
if (typeof(TypeTracker).IsAssignableFrom(targetType)) {
restrictions = restrictions.Merge(
BindingRestrictions.GetInstanceRestriction(target.Expression, target.Value)
);
TypeGroup tg = target.Value as TypeGroup;
Type nonGen;
if (tg == null || tg.TryGetNonGenericType(out nonGen)) {
members = GetMember(MemberRequestKind.Get, ((TypeTracker)target.Value).Type, getMemInfo.Name);
if (members.Count > 0) {
// we have a member that's on the type associated w/ the tracker, return that...
targetType = ((TypeTracker)target.Value).Type;
self = null;
}
}
}
if (members.Count == 0) {
// Get the members
members = GetMember(MemberRequestKind.Get, targetType, getMemInfo.Name);
}
if (members.Count == 0) {
if (typeof(TypeTracker).IsAssignableFrom(targetType)) {
// Throws an exception if we don't have a non-generic type, and if we do report an error now. This matches
// the rule version of the default binder but should probably be removed long term.
EnsureTrackerRepresentsNonGenericType((TypeTracker)target.Value);
} else if (targetType.IsInterface()) {
// all interfaces have object members
targetType = typeof(object);
members = GetMember(MemberRequestKind.Get, targetType, getMemInfo.Name);
}
}
DynamicMetaObject propSelf = self;
// if lookup failed try the strong-box type if available.
if (members.Count == 0 && typeof(IStrongBox).IsAssignableFrom(targetType) && propSelf != null) {
// properties/fields need the direct value, methods hold onto the strong box.
propSelf = new DynamicMetaObject(
Ast.Field(AstUtils.Convert(propSelf.Expression, targetType), targetType.GetInheritedFields("Value").First()),
propSelf.Restrictions,
((IStrongBox)propSelf.Value).Value
);
targetType = targetType.GetGenericArguments()[0];
members = GetMember(
MemberRequestKind.Get,
targetType,
getMemInfo.Name
);
}
MakeBodyHelper(getMemInfo, self, propSelf, targetType, members);
getMemInfo.Body.Restrictions = restrictions;
return getMemInfo.Body.GetMetaObject(target);
}
private static Type EnsureTrackerRepresentsNonGenericType(TypeTracker tracker) {
// might throw an exception
return tracker.Type;
}
private void MakeBodyHelper(GetMemberInfo getMemInfo, DynamicMetaObject self, DynamicMetaObject propSelf, Type targetType, MemberGroup members) {
if (self != null) {
MakeOperatorGetMemberBody(getMemInfo, propSelf, targetType, "GetCustomMember");
}
Expression error;
TrackerTypes memberType = GetMemberType(members, out error);
if (error == null) {
MakeSuccessfulMemberAccess(getMemInfo, self, propSelf, targetType, members, memberType);
} else {
getMemInfo.Body.FinishError(getMemInfo.ErrorSuggestion != null ? getMemInfo.ErrorSuggestion.Expression : error);
}
}
private void MakeSuccessfulMemberAccess(GetMemberInfo getMemInfo, DynamicMetaObject self, DynamicMetaObject propSelf, Type selfType, MemberGroup members, TrackerTypes memberType) {
switch (memberType) {
case TrackerTypes.TypeGroup:
case TrackerTypes.Type:
MakeTypeBody(getMemInfo, selfType, members);
break;
case TrackerTypes.Method:
// turn into a MethodGroup
MakeGenericBodyWorker(getMemInfo, selfType, ReflectionCache.GetMethodGroup(getMemInfo.Name, members), self);
break;
case TrackerTypes.Event:
case TrackerTypes.Field:
case TrackerTypes.Property:
case TrackerTypes.Constructor:
case TrackerTypes.Custom:
MakeGenericBody(getMemInfo, selfType, members, propSelf);
break;
case TrackerTypes.All:
// no members were found
if (self != null) {
MakeOperatorGetMemberBody(getMemInfo, propSelf, selfType, "GetBoundMember");
}
MakeMissingMemberRuleForGet(getMemInfo, self, selfType);
break;
default:
throw new InvalidOperationException(memberType.ToString());
}
}
private void MakeGenericBody(GetMemberInfo getMemInfo, Type instanceType, MemberGroup members, DynamicMetaObject instance) {
MemberTracker bestMember = members[0];
if (members.Count > 1) {
// if we were given multiple members pick the member closest to the type...
Type bestMemberDeclaringType = members[0].DeclaringType;
for (int i = 1; i < members.Count; i++) {
MemberTracker mt = members[i];
if (!IsTrackerApplicableForType(instanceType, mt)) {
continue;
}
if (members[i].DeclaringType.IsSubclassOf(bestMemberDeclaringType) ||
!IsTrackerApplicableForType(instanceType, bestMember)) {
bestMember = members[i];
bestMemberDeclaringType = members[i].DeclaringType;
}
}
}
MakeGenericBodyWorker(getMemInfo, instanceType, bestMember, instance);
}
private static bool IsTrackerApplicableForType(Type type, MemberTracker mt) {
return mt.DeclaringType == type || type.IsSubclassOf(mt.DeclaringType);
}
private void MakeTypeBody(GetMemberInfo getMemInfo, Type instanceType, MemberGroup members) {
TypeTracker typeTracker = (TypeTracker)members[0];
for (int i = 1; i < members.Count; i++) {
typeTracker = TypeGroup.UpdateTypeEntity(typeTracker, (TypeTracker)members[i]);
}
getMemInfo.Body.FinishCondition(typeTracker.GetValue(getMemInfo.ResolutionFactory, this, instanceType));
}
private void MakeGenericBodyWorker(GetMemberInfo getMemInfo, Type instanceType, MemberTracker tracker, DynamicMetaObject instance) {
if (instance != null) {
tracker = tracker.BindToInstance(instance);
}
DynamicMetaObject val = tracker.GetValue(getMemInfo.ResolutionFactory, this, instanceType);
if (val != null) {
getMemInfo.Body.FinishCondition(val);
} else {
ErrorInfo ei = tracker.GetError(this, instanceType);
if (ei.Kind != ErrorInfoKind.Success && getMemInfo.IsNoThrow) {
getMemInfo.Body.FinishError(MakeOperationFailed());
} else {
getMemInfo.Body.FinishError(MakeError(ei, typeof(object)));
}
}
}
/// <summary> if a member-injector is defined-on or registered-for this type call it </summary>
private void MakeOperatorGetMemberBody(GetMemberInfo getMemInfo, DynamicMetaObject instance, Type instanceType, string name) {
MethodInfo getMem = GetMethod(instanceType, name);
if (getMem != null) {
ParameterExpression tmp = Ast.Variable(typeof(object), "getVal");
getMemInfo.Body.AddVariable(tmp);
getMemInfo.Body.AddCondition(
Ast.NotEqual(
Ast.Assign(
tmp,
MakeCallExpression(
getMemInfo.ResolutionFactory,
getMem,
new DynamicMetaObject(
Expression.Convert(instance.Expression, instanceType),
instance.Restrictions,
instance.Value
),
new DynamicMetaObject(
Expression.Constant(getMemInfo.Name),
BindingRestrictions.Empty,
getMemInfo.Name
)
).Expression
),
Ast.Field(null, typeof(OperationFailed).GetDeclaredField("Value"))
),
tmp
);
}
}
private void MakeMissingMemberRuleForGet(GetMemberInfo getMemInfo, DynamicMetaObject self, Type type) {
if (getMemInfo.ErrorSuggestion != null) {
getMemInfo.Body.FinishError(getMemInfo.ErrorSuggestion.Expression);
} else if (getMemInfo.IsNoThrow) {
getMemInfo.Body.FinishError(MakeOperationFailed());
} else {
getMemInfo.Body.FinishError(
MakeError(MakeMissingMemberError(type, self, getMemInfo.Name), typeof(object))
);
}
}
private static MemberExpression MakeOperationFailed() {
return Ast.Field(null, typeof(OperationFailed).GetDeclaredField("Value"));
}
/// <summary>
/// Helper class for flowing information about the GetMember request.
/// </summary>
private sealed class GetMemberInfo {
public readonly string Name;
public readonly OverloadResolverFactory ResolutionFactory;
public readonly bool IsNoThrow;
public readonly ConditionalBuilder Body = new ConditionalBuilder();
public readonly DynamicMetaObject ErrorSuggestion;
public GetMemberInfo(string name, OverloadResolverFactory resolutionFactory, bool noThrow, DynamicMetaObject errorSuggestion) {
Name = name;
ResolutionFactory = resolutionFactory;
IsNoThrow = noThrow;
ErrorSuggestion = errorSuggestion;
}
}
}
}
| 47.047733
| 188
| 0.582255
|
[
"MIT"
] |
IMaeland/IronSmalltalk
|
DLR/Microsoft.Dynamic/Actions/DefaultBinder.GetMember.cs
| 19,715
|
C#
|
/*
* Copyright 2013 ThirdMotion, 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.
*/
/**
* @interface strange.extensions.mediation.api.IMediationBinding
*
* Interface for MediationBindings
*
* Adds porcelain method to clarify View/Mediator binding.
*/
using System;
using strange.framework.api;
namespace strange.extensions.mediation.api
{
public interface IMediationBinding : IBinding
{
/// Porcelain for To<T> providing a little extra clarity and security.
IMediationBinding ToMediator<T>();
}
}
| 27.972973
| 76
| 0.742995
|
[
"Apache-2.0"
] |
Lenovezhou/Screenshow
|
Assets/Scripts/StrangeIoC/scripts/strange/extensions/mediation/api/IMediationBinding.cs
| 1,035
|
C#
|
/******************************************************************************
* Compilation: javac EdgeWeightedDigraph.java
* Execution: java EdgeWeightedDigraph digraph.txt
* Dependencies: Bag.java DirectedEdge.java
* Data files: https://algs4.cs.princeton.edu/44st/tinyEWD.txt
* https://algs4.cs.princeton.edu/44st/mediumEWD.txt
* https://algs4.cs.princeton.edu/44st/largeEWD.txt
*
* An edge-weighted digraph, implemented using adjacency lists.
*
******************************************************************************/
using System;
namespace edu.princeton.cs.algs4
{
/**
* The {@code EdgeWeightedDigraph} class represents a edge-weighted
* digraph of vertices named 0 through <em>V</em> - 1, where each
* directed edge is of type {@link DirectedEdge} and has a real-valued weight.
* It supports the following two primary operations: add a directed edge
* to the digraph and iterate over all of edges incident from a given vertex.
* It also provides
* methods for returning the number of vertices <em>V</em> and the number
* of edges <em>E</em>. Parallel edges and self-loops are permitted.
* <p>
* This implementation uses an adjacency-lists representation, which
* is a vertex-indexed array of {@link Bag} objects.
* All operations take constant time (in the worst case) except
* iterating over the edges incident from a given vertex, which takes
* time proportional to the number of such edges.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class EdgeWeightedDigraph {
private static final String NEWLINE = System.getProperty("line.separator");
private final int V; // number of vertices in this digraph
private int E; // number of edges in this digraph
private Bag<DirectedEdge>[] adj; // adj[v] = adjacency list for vertex v
private int[] indegree; // indegree[v] = indegree of vertex v
/**
* Initializes an empty edge-weighted digraph with {@code V} vertices and 0 edges.
*
* @param V the number of vertices
* @throws IllegalArgumentException if {@code V < 0}
*/
public EdgeWeightedDigraph(int V) {
if (V < 0) throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative");
this.V = V;
this.E = 0;
this.indegree = new int[V];
adj = (Bag<DirectedEdge>[]) new Bag[V];
for (int v = 0; v < V; v++)
adj[v] = new Bag<DirectedEdge>();
}
/**
* Initializes a random edge-weighted digraph with {@code V} vertices and <em>E</em> edges.
*
* @param V the number of vertices
* @param E the number of edges
* @throws IllegalArgumentException if {@code V < 0}
* @throws IllegalArgumentException if {@code E < 0}
*/
public EdgeWeightedDigraph(int V, int E) {
this(V);
if (E < 0) throw new IllegalArgumentException("Number of edges in a Digraph must be nonnegative");
for (int i = 0; i < E; i++) {
int v = StdRandom.uniform(V);
int w = StdRandom.uniform(V);
double weight = 0.01 * StdRandom.uniform(100);
DirectedEdge e = new DirectedEdge(v, w, weight);
addEdge(e);
}
}
/**
* Initializes an edge-weighted digraph from the specified input stream.
* The format is the number of vertices <em>V</em>,
* followed by the number of edges <em>E</em>,
* followed by <em>E</em> pairs of vertices and edge weights,
* with each entry separated by whitespace.
*
* @param in the input stream
* @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range
* @throws IllegalArgumentException if the number of vertices or edges is negative
*/
public EdgeWeightedDigraph(In in) {
this(in.readInt());
int E = in.readInt();
if (E < 0) throw new IllegalArgumentException("Number of edges must be nonnegative");
for (int i = 0; i < E; i++) {
int v = in.readInt();
int w = in.readInt();
validateVertex(v);
validateVertex(w);
double weight = in.readDouble();
addEdge(new DirectedEdge(v, w, weight));
}
}
/**
* Initializes a new edge-weighted digraph that is a deep copy of {@code G}.
*
* @param G the edge-weighted digraph to copy
*/
public EdgeWeightedDigraph(EdgeWeightedDigraph G) {
this(G.V());
this.E = G.E();
for (int v = 0; v < G.V(); v++)
this.indegree[v] = G.indegree(v);
for (int v = 0; v < G.V(); v++) {
// reverse so that adjacency list is in same order as original
Stack<DirectedEdge> reverse = new Stack<DirectedEdge>();
for (DirectedEdge e : G.adj[v]) {
reverse.push(e);
}
for (DirectedEdge e : reverse) {
adj[v].add(e);
}
}
}
/**
* Returns the number of vertices in this edge-weighted digraph.
*
* @return the number of vertices in this edge-weighted digraph
*/
public int V() {
return V;
}
/**
* Returns the number of edges in this edge-weighted digraph.
*
* @return the number of edges in this edge-weighted digraph
*/
public int E() {
return E;
}
// throw an IllegalArgumentException unless {@code 0 <= v < V}
private void validateVertex(int v) {
if (v < 0 || v >= V)
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
}
/**
* Adds the directed edge {@code e} to this edge-weighted digraph.
*
* @param e the edge
* @throws IllegalArgumentException unless endpoints of edge are between {@code 0}
* and {@code V-1}
*/
public void addEdge(DirectedEdge e) {
int v = e.from();
int w = e.to();
validateVertex(v);
validateVertex(w);
adj[v].add(e);
indegree[w]++;
E++;
}
/**
* Returns the directed edges incident from vertex {@code v}.
*
* @param v the vertex
* @return the directed edges incident from vertex {@code v} as an Iterable
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public Iterable<DirectedEdge> adj(int v) {
validateVertex(v);
return adj[v];
}
/**
* Returns the number of directed edges incident from vertex {@code v}.
* This is known as the <em>outdegree</em> of vertex {@code v}.
*
* @param v the vertex
* @return the outdegree of vertex {@code v}
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public int outdegree(int v) {
validateVertex(v);
return adj[v].size();
}
/**
* Returns the number of directed edges incident to vertex {@code v}.
* This is known as the <em>indegree</em> of vertex {@code v}.
*
* @param v the vertex
* @return the indegree of vertex {@code v}
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public int indegree(int v) {
validateVertex(v);
return indegree[v];
}
/**
* Returns all directed edges in this edge-weighted digraph.
* To iterate over the edges in this edge-weighted digraph, use foreach notation:
* {@code for (DirectedEdge e : G.edges())}.
*
* @return all edges in this edge-weighted digraph, as an iterable
*/
public Iterable<DirectedEdge> edges() {
Bag<DirectedEdge> list = new Bag<DirectedEdge>();
for (int v = 0; v < V; v++) {
for (DirectedEdge e : adj(v)) {
list.add(e);
}
}
return list;
}
/**
* Returns a string representation of this edge-weighted digraph.
*
* @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>,
* followed by the <em>V</em> adjacency lists of edges
*/
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V + " " + E + NEWLINE);
for (int v = 0; v < V; v++) {
s.append(v + ": ");
for (DirectedEdge e : adj[v]) {
s.append(e + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
/**
* Unit tests the {@code EdgeWeightedDigraph} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
In in = new In(args[0]);
EdgeWeightedDigraph G = new EdgeWeightedDigraph(in);
StdOut.println(G);
}
}
/******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar 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.
*
* algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
| 36.091873
| 109
| 0.574408
|
[
"MIT"
] |
franklzt/DataStruct
|
algs/EdgeWeightedDigraph.cs
| 10,214
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Fancy.Data.Data;
using Fancy.Data.Models.Models;
using Fancy.Services.Data.Contracts;
using Fancy.Common.Enums;
using Fancy.Common.Validator;
using Fancy.Common.Constants;
namespace Fancy.Services.Data
{
public class OrderService : IOrderService
{
private IEfFancyData data;
public OrderService(IEfFancyData data)
{
Validator.ValidateNullArgument(data, "data");
this.data = data;
}
public Order GetOrderInBasket(string userId)
{
Validator.ValidateNullArgument(userId, "userId");
var user = this.data.Users.GetById(userId);
Validator.ValidateNullDatabaseObject(user, "User");
var order = this.data.Orders.GetSingleOrDefault(o => o.UserId == userId && o.OrderStatus == OrderStatusType.InBasket);
if (order == null)
{
order = new Order();
order.User = user;
order.OrderStatus = OrderStatusType.InBasket;
this.data.Orders.Add(order);
this.data.Commit();
}
return order;
}
public void AddItemToBasket(int itemId, string userId)
{
Validator.ValidateRange(itemId, ServerConstants.IdMinValue, ServerConstants.IdMaxValue, "itemId");
Validator.ValidateNullArgument(userId, "userId");
var item = this.data.Items.GetById(itemId);
var user = this.data.Users.GetById(userId);
var order = this.GetOrderInBasket(userId);
Validator.ValidateNullDatabaseObject(item, "Item");
Validator.ValidateNullDatabaseObject(user, "User");
order.Items.Add(item);
item.Quantity--;
this.data.Commit();
}
public void RemoveItemFromBasket(int itemId, string userId)
{
Validator.ValidateRange(itemId, ServerConstants.IdMinValue, ServerConstants.IdMaxValue, "itemId");
Validator.ValidateNullArgument(userId, "userId");
var item = this.data.Items.GetById(itemId);
var user = this.data.Users.GetById(userId);
var order = this.data.Orders.GetSingleOrDefault(o => o.UserId == userId && o.OrderStatus == OrderStatusType.InBasket);
Validator.ValidateNullDatabaseObject(item, "Item");
Validator.ValidateNullDatabaseObject(user, "User");
Validator.ValidateNullDatabaseObject(order, "Order");
order.Items.Remove(item);
item.Quantity++;
if(order.Items.Count == 0)
{
order.OrderStatus = OrderStatusType.Discarded;
}
this.data.Commit();
}
public void ExecuteOrder(int orderId, decimal totalPrice)
{
Validator.ValidateRange(orderId, ServerConstants.IdMinValue, ServerConstants.IdMaxValue, "orderId");
Validator.ValidateRange(totalPrice, 0, decimal.MaxValue, "totalPrice");
var order = this.data.Orders.GetById(orderId);
Validator.ValidateNullDatabaseObject(order, "Order");
order.OrderStatus = OrderStatusType.Shipped;
order.TotalPrice = totalPrice;
order.PurchaseDate = DateTime.Today;
this.data.Commit();
}
public IEnumerable<Order> PreviousOrders(string userId)
{
Validator.ValidateNullArgument(userId, "userId");
var previousOrders = this.data.Orders.GetAll(o => o.UserId == userId && o.OrderStatus == OrderStatusType.Shipped).ToList();
return previousOrders;
}
}
}
| 31.677966
| 135
| 0.611022
|
[
"MIT"
] |
Telerik-Fancy/Project
|
Fancy/Fancy.Services/Data/OrderService.cs
| 3,740
|
C#
|
// <auto-generated />
using DotnetMVCBaslangic.EntityFramework;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace DotnetMVCBaslangic.Migrations
{
[DbContext(typeof(DotnetMVCBaslangicDbContext))]
[Migration("20190420072757_InitialDatabase")]
partial class InitialDatabase
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.4-servicing-10062")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("DotnetMVCBaslangic.Models.Ogrenci", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Adi");
b.Property<int>("OgrenciNo");
b.Property<string>("Soyadi");
b.HasKey("Id");
b.ToTable("Ogrenciler");
});
#pragma warning restore 612, 618
}
}
}
| 35.186047
| 125
| 0.648381
|
[
"BSD-3-Clause"
] |
Kodluyoruz/dotnet-core-mvc-web-api-course
|
DotnetMVCBaslangic/DotnetMVCBaslangic/Migrations/20190420072757_InitialDatabase.Designer.cs
| 1,515
|
C#
|
// GraphView
//
// Copyright (c) 2015 Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net.Configuration;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using GraphView.TSQL_Syntax_Tree;
using Microsoft.SqlServer.TransactSql.ScriptDom;
namespace GraphView
{
internal class TranslateDataModificationVisitor : WSqlFragmentVisitor
{
public SqlTransaction Tx { get; private set; }
public TranslateDataModificationVisitor(SqlTransaction tx)
{
this.Tx = tx;
}
public void Invoke(WSqlFragment fragment)
{
fragment.Accept(this);
}
public override void Visit(WSqlBatch node)
{
base.Visit(node);
node.Statements = Translate(node.Statements);
}
public override void Visit(WProcedureStatement node)
{
base.Visit(node);
node.StatementList = Translate(node.StatementList);
}
public override void Visit(WBeginEndBlockStatement node)
{
base.Visit(node);
node.StatementList = Translate(node.StatementList);
}
private List<WSqlStatement> Translate(IList<WSqlStatement> statements)
{
var result = new List<WSqlStatement>();
var index = 0;
for (var count = statements.Count; index < count; ++index)
{
var insertEdgeStatement = statements[index] as WInsertEdgeSpecification;
if (insertEdgeStatement != null)
{
//result.Add(new WBeginTransactionStatement
//{
// Name = new WIdentifierOrValueExpression
// {
// Identifier = new Identifier { Value = "InsertEdgeTran" }
// }
//});
//result.Add(TranslateInsertEdge(insertEdgeStatement, false));
//result.Add(TranslateInsertEdge(insertEdgeStatement, true));
var stmts = new List<WSqlStatement>();
TranslateEdgeInsert(insertEdgeStatement, stmts);
result.Add(new WBeginEndBlockStatement() {StatementList = stmts,});
//result.Add(new WCommitTransactionStatement
//{
// Name = new WIdentifierOrValueExpression
// {
// Identifier = new Identifier { Value = "InsertEdgeTran" }
// }
//});
continue;
}
var deleteEdgeStatement = statements[index] as WDeleteEdgeSpecification;
if (deleteEdgeStatement != null)
{
//result.Add(new WBeginTransactionStatement
//{
// Name = new WIdentifierOrValueExpression
// {
// Identifier = new Identifier { Value = "DeleteEdgeTran" }
// }
//});
//result.Add(TranslateDeleteEdge(deleteEdgeStatement, true));
//result.Add(TranslateDeleteEdge(deleteEdgeStatement, false));
var stmts = new List<WSqlStatement>();
TranslateEdgeDelete(deleteEdgeStatement, stmts);
result.Add(new WBeginEndBlockStatement() {StatementList = stmts,});
//result.Add(new WCommitTransactionStatement
//{
// Name = new WIdentifierOrValueExpression
// {
// Identifier = new Identifier { Value = "DeleteEdgeTran" }
// }
//});
continue;
}
var deleteNodeStatement = statements[index] as WDeleteNodeSpecification;
if (deleteNodeStatement != null)
{
TranslateNodeDelete(deleteNodeStatement, result);
continue;
}
result.Add(statements[index]);
}
return result;
}
private void CheckInsertEdgeValidity(string tableSchema, string sourceTableName, string columnName, string sinkTableName, out bool hasReversedEdge)
{
using (var command = Tx.Connection.CreateCommand())
{
command.Transaction = Tx;
command.Parameters.AddWithValue("@schema", tableSchema);
command.Parameters.AddWithValue("@tableName", sourceTableName);
command.Parameters.AddWithValue("@colName", columnName);
command.Parameters.AddWithValue("@role", WNodeTableColumnRole.Edge);
command.CommandText = string.Format(@"
SELECT NodeColumn.Reference, NodeColumn.HasReversedEdge
FROM [{0}] as NodeTable JOIN [{1}] AS NodeColumn
ON NodeTable.TableId = NodeColumn.TableId
WHERE NodeTable.TableSchema = @schema and
NodeTable.TableName = @tableName and
NodeColumn.ColumnName = @colName and
NodeColumn.ColumnRole = @role", GraphViewConnection.MetadataTables[0],
GraphViewConnection.MetadataTables[1]);
using (var reader = command.ExecuteReader())
{
if (!reader.Read())
throw new GraphViewException(
string.Format("Node table {0} not exists or edge {1} not exists in node table {0}",
sourceTableName, columnName));
string sinkReference = reader[0].ToString();
if (string.Compare(sinkTableName, sinkReference, StringComparison.OrdinalIgnoreCase) != 0)
throw new GraphViewException(string.Format("Mismatch sink node table reference {0}",
sinkTableName));
hasReversedEdge = bool.Parse(reader[1].ToString());
}
}
}
/// <summary>
/// Translates insert edge statement into update statement.
/// Uses common table expression to record the inserting adjacency-list,
/// then inserts result into a table variable with soucrc id as its primary to ensure the order,
/// finally update node tables.
/// </summary>
/// <param name="node">Insert edge specification</param>
/// <param name="res">Resulting statements</param>
private void TranslateEdgeInsert(WInsertEdgeSpecification node,List<WSqlStatement> res)
{
const string insertEdgeTableName = "GraphView_InsertEdgeInternalTable";
string insertEdgeTempTable = "InsertTmp_"+Path.GetRandomFileName().Replace(".", "").Substring(0, 8);
var sourceNameTable = node.Target as WNamedTableReference;
if (sourceNameTable == null)
throw new GraphViewException("Source table of INSERT EDGE statement should be a named table reference.");
List<WScalarExpression> encodeParameters;
WTableReference sinkTable;
// Wraps the select statement in a common table expression
var edgeSelectQueryVisitor = new InsertEdgeSelectVisitor();
var insertCommonTableExpr = edgeSelectQueryVisitor.Invoke(node.SelectInsertSource.Select,
insertEdgeTempTable, sourceNameTable.TableObjectName.BaseIdentifier.Value, out sinkTable,
out encodeParameters);
var reversedEncodeParameters = new List<WScalarExpression>(encodeParameters.ToArray());
reversedEncodeParameters.RemoveAt(0);
reversedEncodeParameters.Insert(0,
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier { Value = "src" })
});
var sinkNameTable = sinkTable as WNamedTableReference;
if (sinkNameTable == null)
throw new GraphViewException("Sink table of INSERT EDGE statement should be a named table reference.");
var edgeName = node.EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value;
var tableSchema =
sourceNameTable.TableObjectName.SchemaIdentifier != null
? sourceNameTable.TableObjectName.SchemaIdentifier.Value
: "dbo";
var tableName = sourceNameTable.TableObjectName.BaseIdentifier.Value;
bool hasReversedEdge;
CheckInsertEdgeValidity(tableSchema, tableName, edgeName, sinkNameTable.TableObjectName.BaseIdentifier.Value, out hasReversedEdge);
// Select Into TempTable
//res.Add(insertCommonTableExpr);
// Get edge select query and reversed edge select query
WSelectQueryBlock edgeSelectQuery = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>
{
new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "src"})
},
ColumnName = "source"
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
CallTarget = new WMultiPartIdentifierCallTarget
{
Identifiers = new WMultiPartIdentifier(new Identifier {Value = "dbo"})
},
FunctionName = new Identifier {Value = tableSchema + '_' + tableName +'_' + edgeName + '_' + "Encoder"},
Parameters = encodeParameters,
},
ColumnName = "binary1"
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName = new Identifier{Value = "COUNT"},
Parameters = new List<WScalarExpression>
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "sink"})
},
},
},
ColumnName = "sinkCnt"
}
},
FromClause = new WFromClause
{
TableReferences = new List<WTableReference>
{
new WSpecialNamedTableReference()
{
TableObjectName = new WSchemaObjectName(new Identifier{Value = insertEdgeTempTable })
}
}
},
GroupByClause = new WGroupByClause
{
GroupingSpecifications = new List<WGroupingSpecification>
{
new WExpressionGroupingSpec
{
Expression = new WValueExpression("src",false)
}
}
}
};
WSelectQueryBlock reversedEdgeSelectQuery = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>
{
new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "sink"})
},
ColumnName = "source"
},
new WSelectScalarExpression
{
SelectExpr = hasReversedEdge ?
new WFunctionCall
{
CallTarget = new WMultiPartIdentifierCallTarget
{
Identifiers = new WMultiPartIdentifier(new Identifier {Value = "dbo"})
},
FunctionName = new Identifier {Value = tableSchema + '_' + tableName +'_' + edgeName + '_' + "Encoder"},
Parameters = reversedEncodeParameters,
} :
(WScalarExpression)new WValueExpression
{
Value = "0x"
},
ColumnName = "binary2"
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName =
new Identifier
{
//Value = GraphViewConnection.GraphViewUdfAssemblyName + "GlobalNodeIdEncoder"
Value = "COUNT"
},
Parameters = new List<WScalarExpression>
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "src"})
},
}
},
ColumnName = "srcCnt"
},
},
FromClause = edgeSelectQuery.FromClause,
GroupByClause = new WGroupByClause
{
GroupingSpecifications = new List<WGroupingSpecification>
{
new WExpressionGroupingSpec
{
Expression = new WValueExpression("sink", false)
}
}
}
};
//Check src & sink
string sourceTableName = sourceNameTable.TableObjectName.ToString();
string sinkTableName = sinkNameTable.TableObjectName.ToString();
int compare = string.CompareOrdinal(sourceTableName, sinkTableName);
WSetClause[] setClauses = new WSetClause[]
{
new WFunctionCallSetClause()
{
MutatorFuction = new WFunctionCall
{
CallTarget = new WMultiPartIdentifierCallTarget()
{
Identifiers = node.EdgeColumn.MultiPartIdentifier
},
FunctionName = new Identifier {Value = "WRITE"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(
new Identifier {Value = insertEdgeTableName},
new Identifier {Value = "binary1"})
},
new WValueExpression("null", false),
new WValueExpression("null", false)
}
}
},
new WAssignmentSetClause()
{
AssignmentKind = AssignmentKind.Equals,
Column = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = "InDegree"
})
},
NewValue = new WBinaryExpression
{
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = "InDegree"
})
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "srcCnt"})
},
ExpressionType = BinaryExpressionType.Add
}
},
new WAssignmentSetClause()
{
AssignmentKind = AssignmentKind.Equals,
Column = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = node.EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value + "OutDegree"
})
},
NewValue = new WBinaryExpression
{
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = node.EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value + "OutDegree"
})
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "sinkCnt"})
},
ExpressionType = BinaryExpressionType.Add
}
},
new WFunctionCallSetClause()
{
MutatorFuction = new WFunctionCall
{
CallTarget = new WMultiPartIdentifierCallTarget()
{
Identifiers = new WMultiPartIdentifier(new Identifier
{
Value = tableName +'_' + edgeName + "Reversed"
})
},
FunctionName = new Identifier {Value = "WRITE"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(
new Identifier {Value = insertEdgeTableName},
new Identifier {Value = "binary2"})
},
new WValueExpression("null", false),
new WValueExpression("null", false)
}
}
},
new WAssignmentSetClause()
{
AssignmentKind = AssignmentKind.Equals,
Column = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = tableName +'_' + edgeName + "Reversed" + "OutDegree"
})
},
NewValue = new WBinaryExpression
{
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = tableName +'_' + edgeName + "Reversed" + "OutDegree"
})
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "srcCnt"})
},
ExpressionType = BinaryExpressionType.Add
}
},
};
WWhereClause whereClause = new WWhereClause
{
SearchCondition = new WBooleanComparisonExpression
{
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "GlobalNodeId"})
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(
new Identifier {Value = insertEdgeTableName},
new Identifier {Value = "source"}
)
},
ComparisonType = BooleanComparisonType.Equals
}
};
if (compare == 0)
{
res.Add(new WDeclareTableVariable
{
VariableName = new Identifier { Value = "@"+insertEdgeTempTable},
Definition = new WTableDefinition
{
ColumnDefinitions = new WColumnDefinition[]
{
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "source"},
DataType = new WParameterizedDataTypeReference{Name = new WSchemaObjectName(new Identifier{Value = "bigint"})},
Constraints = new List<WConstraintDefinition>
{
new WUniqueConstraintDefinition
{
Clustered = true,
IsPrimaryKey = true
}
}
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "binary1"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier{Value = "varbinary"}),
Parameters = new List<Literal>{new MaxLiteral{Value = "max"}}
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "binary2"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier{Value = "varbinary"}),
Parameters = new List<Literal>{new MaxLiteral{Value = "max"}}
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "sinkCnt"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier{Value = "int"}),
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "srcCnt"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier{Value = "int"}),
},
},
},
Indexes = new List<WIndexDefinition>(),
TableConstraints = new List<WConstraintDefinition>()
}
});
res.Add(insertCommonTableExpr);
var tableVar = new WSpecialNamedTableReference
{
TableObjectName = new WSchemaObjectName(new Identifier {Value = "@" + insertEdgeTempTable})
};
res.Add(new WInsertSpecification
{
Target =tableVar,
InsertSource = new WSelectInsertSource
{
Select = new WSelectQueryBlock
{
SelectElements = new WSelectElement[]
{
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName = new Identifier {Value = "ISNULL"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = insertEdgeTableName + "_1"},
new Identifier {Value = "source"}
}),
},
new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = insertEdgeTableName + "_2"},
new Identifier {Value = "source"}
}),
},
}
},
ColumnName = "source"
},
new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[] {new Identifier {Value = "binary1"}}),
}
},
new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[] {new Identifier {Value = "binary2"}}),
}
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName = new Identifier {Value = "ISNULL"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = insertEdgeTableName + "_1"},
new Identifier {Value = "sinkCnt"}
}),
},
new WValueExpression
{
Value = "0"
},
}
},
ColumnName = "sinkCnt"
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName = new Identifier {Value = "ISNULL"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = insertEdgeTableName + "_2"},
new Identifier {Value = "srcCnt"}
}),
},
new WValueExpression
{
Value = "0"
},
}
},
ColumnName = "srcCnt"
},
},
FromClause = new WFromClause
{
TableReferences = new WTableReference[]
{
new WQualifiedJoin
{
QualifiedJoinType = QualifiedJoinType.FullOuter,
FirstTableRef = new WQueryDerivedTable
{
Alias = new Identifier {Value = insertEdgeTableName + "_1"},
QueryExpr = edgeSelectQuery
},
SecondTableRef = new WQueryDerivedTable
{
Alias = new Identifier {Value = insertEdgeTableName + "_2"},
QueryExpr = reversedEdgeSelectQuery
},
JoinCondition = new WBooleanComparisonExpression()
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = insertEdgeTableName + "_1"},
new Identifier {Value = "source"}
}),
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = insertEdgeTableName + "_2"},
new Identifier {Value = "source"}
}),
}
}
},
}
}
}
}
});
res.Add(new WUpdateSpecification
{
Target = node.Target,
SetClauses = hasReversedEdge ? setClauses.ToList() : new List<WSetClause>{setClauses[0], setClauses[1], setClauses[2]},
FromClause = new WFromClause
{
TableReferences = new WTableReference[]
{
new WQueryDerivedTable
{
Alias = new Identifier{Value = insertEdgeTableName},
QueryExpr = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>()
{
new WSelectStarExpression()
},
FromClause = new WFromClause
{
TableReferences = new List<WTableReference>{tableVar}
}
}
},
}
},
WhereClause = whereClause,
TopRowFilter = node.TopRowFilter,
});
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}", insertEdgeTempTable)
});
}
else
{
// Declare table variables
res.Add(new WDeclareTableVariable
{
VariableName = new Identifier {Value = "@" + insertEdgeTempTable+"_1"},
Definition = new WTableDefinition
{
ColumnDefinitions = new WColumnDefinition[]
{
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "source"},
DataType =
new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "bigint"})
},
Constraints = new List<WConstraintDefinition>
{
new WUniqueConstraintDefinition
{
Clustered = true,
IsPrimaryKey = true
}
}
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "binary1"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "varbinary"}),
Parameters = new List<Literal> {new MaxLiteral {Value = "max"}}
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "sinkCnt"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "int"}),
},
},
},
Indexes = new List<WIndexDefinition>(),
TableConstraints = new List<WConstraintDefinition>()
}
});
res.Add(new WDeclareTableVariable
{
VariableName = new Identifier {Value = "@" + insertEdgeTempTable+"_2"},
Definition = new WTableDefinition
{
ColumnDefinitions = new WColumnDefinition[]
{
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "source"},
DataType =
new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "bigint"})
},
Constraints = new List<WConstraintDefinition>
{
new WUniqueConstraintDefinition
{
Clustered = true,
IsPrimaryKey = true
}
}
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "binary2"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "varbinary"}),
Parameters = new List<Literal> {new MaxLiteral {Value = "max"}}
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "srcCnt"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "int"}),
},
},
},
Indexes = new List<WIndexDefinition>(),
TableConstraints = new List<WConstraintDefinition>()
}
});
var tableVar = new WSpecialNamedTableReference
{
TableObjectName = new WSchemaObjectName(new Identifier { Value = "@" + insertEdgeTempTable+"_1" })
};
var reversedTableVar = new WSpecialNamedTableReference
{
TableObjectName = new WSchemaObjectName(new Identifier { Value = "@" + insertEdgeTempTable + "_2" })
};
WInsertSpecification[] insertStat = new WInsertSpecification[]
{
new WInsertSpecification
{
Target = tableVar,
InsertSource = new WSelectInsertSource
{
Select = edgeSelectQuery
}
},
new WInsertSpecification
{
Target = reversedTableVar,
InsertSource = new WSelectInsertSource
{
Select = reversedEdgeSelectQuery
}
}
};
// Update statments for edge and reversed edge
WUpdateSpecification[] updateStat = new WUpdateSpecification[]
{
new WUpdateSpecification
{
Target = node.Target,
SetClauses = new List<WSetClause> {setClauses[0], setClauses[2]},
FromClause = new WFromClause
{
TableReferences = new WTableReference[]
{
new WQueryDerivedTable
{
Alias = new Identifier {Value = insertEdgeTableName},
QueryExpr = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>()
{
new WSelectStarExpression()
},
FromClause = new WFromClause
{
TableReferences = new List<WTableReference> {tableVar}
}
}
},
}
},
WhereClause = whereClause,
TopRowFilter = node.TopRowFilter
},
new WUpdateSpecification
{
Target = new WNamedTableReference
{
TableObjectName = sinkNameTable.TableObjectName
},
SetClauses = hasReversedEdge ? new List<WSetClause> {setClauses[1], setClauses[3], setClauses[4]} :
new List<WSetClause> {setClauses[1]},
FromClause = new WFromClause
{
TableReferences = new WTableReference[]
{
new WQueryDerivedTable
{
Alias = new Identifier {Value = insertEdgeTableName},
QueryExpr = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>()
{
new WSelectStarExpression()
},
FromClause = new WFromClause
{
TableReferences = new List<WTableReference> {reversedTableVar}
}
}
},
}
},
WhereClause = whereClause,
TopRowFilter = node.TopRowFilter
},
};
bool sourceFirst = compare<0;
if (sourceFirst)
{
// With expression
res.Add(insertCommonTableExpr);
res.Add(insertStat[0]);
res.Add(updateStat[0]);
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}_1", insertEdgeTempTable)
});
// With expression
res.Add(insertCommonTableExpr);
res.Add(insertStat[1]);
res.Add(updateStat[1]);
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}_2", insertEdgeTempTable)
});
}
else
{
// With expression
res.Add(insertCommonTableExpr);
res.Add(insertStat[1]);
res.Add(updateStat[1]);
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}_2", insertEdgeTempTable)
});
// With expression
res.Add(insertCommonTableExpr);
res.Add(insertStat[0]);
res.Add(updateStat[0]);
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}_1", insertEdgeTempTable)
});
}
}
//res.Add(new WSqlUnknownStatement { Statement = "DROP TABLE " + insertEdgeTempTable });
}
private void TranslateEdgeDelete(WDeleteEdgeSpecification node, List<WSqlStatement> res)
{
const string deleteEdgeTableName = "GraphView_DeleteEdgeInternalTable";
string deleteEdgeTempTable = "DeleteTmp_" + Path.GetRandomFileName().Replace(".", "").Substring(0, 8);
bool hasReversedEdge = true;
// Wraps the select statement in a common table expression
WTableReference sinkTable, sourceTable;
var deleteCommonTableExpr = ConstructDeleteEdgeSelect(node.SelectDeleteExpr, node.EdgeColumn, deleteEdgeTempTable,
out sinkTable, out sourceTable, ref hasReversedEdge);
var sourceNameTable = sourceTable as WNamedTableReference;
if (sourceNameTable == null)
throw new GraphViewException("Source table of DELETE EDGE statement should be a named table reference.");
var sinkNameTable = sinkTable as WNamedTableReference;
if (sinkNameTable == null)
throw new GraphViewException("Sink table of DELETE EDGE statement should be a named table reference.");
var reversedEdgeName = sourceNameTable.TableObjectName.Identifiers.Last().Value +
"_" + node.EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value + "Reversed";
//Check src & sink
string sourceTableName = sourceNameTable.TableObjectName.ToString();
string sinkTableName = sinkNameTable.TableObjectName.ToString();
int compare = string.CompareOrdinal(sourceTableName, sinkTableName);
// Get edge select query and reversed edge select query
WSelectQueryBlock edgeSelectQuery = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>
{
new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "src"})
},
ColumnName = "source"
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
CallTarget = new WMultiPartIdentifierCallTarget
{
Identifiers = new WMultiPartIdentifier(new Identifier {Value = "dbo"})
},
FunctionName = new Identifier {Value = GraphViewConnection.GraphViewUdfAssemblyName + "EdgeIdEncoder"},
Parameters = new List<WScalarExpression>
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "edgeid"})
},
},
},
ColumnName = "binary1"
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName = new Identifier{Value = "COUNT"},
Parameters = new List<WScalarExpression>
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "sink"})
},
},
},
ColumnName = "sinkCnt"
}
},
FromClause = new WFromClause
{
TableReferences = new List<WTableReference>
{
new WSpecialNamedTableReference
{
TableObjectName = new WSchemaObjectName(new Identifier
{
Value = hasReversedEdge && compare == 0 ? deleteEdgeTempTable + "_1" : deleteEdgeTempTable
})
}
}
},
GroupByClause = new WGroupByClause
{
GroupingSpecifications = new List<WGroupingSpecification>
{
new WExpressionGroupingSpec
{
Expression = new WValueExpression("src",false)
}
}
}
};
WSelectQueryBlock reversedEdgeSelectQuery = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>
{
new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "sink"})
},
ColumnName = "source"
},
new WSelectScalarExpression
{
SelectExpr = hasReversedEdge ?
new WFunctionCall
{
CallTarget = new WMultiPartIdentifierCallTarget
{
Identifiers = new WMultiPartIdentifier(new Identifier {Value = "dbo"})
},
FunctionName = new Identifier {Value = GraphViewConnection.GraphViewUdfAssemblyName + "EdgeIdEncoder"},
Parameters = new List<WScalarExpression>
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "edgeid"})
},
},
} : (WScalarExpression)new WValueExpression{Value = "0x",},
ColumnName = "binary2"
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName =
new Identifier
{
Value = "COUNT"
},
Parameters = new List<WScalarExpression>
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "src"})
},
}
},
ColumnName = "srcCnt"
},
},
FromClause = hasReversedEdge && compare == 0 ?
new WFromClause
{
TableReferences = new List<WTableReference>
{
new WSpecialNamedTableReference
{
TableObjectName = new WSchemaObjectName(new Identifier
{
Value = deleteEdgeTempTable + "_2",
})
}
}
}
: edgeSelectQuery.FromClause,
GroupByClause = new WGroupByClause
{
GroupingSpecifications = new List<WGroupingSpecification>
{
new WExpressionGroupingSpec
{
Expression = new WValueExpression("sink", false)
}
}
}
};
WSetClause[] setClauses = new WSetClause[]
{
new WFunctionCallSetClause()
{
MutatorFuction = new WFunctionCall
{
CallTarget = new WMultiPartIdentifierCallTarget()
{
Identifiers =
new WMultiPartIdentifier(new Identifier
{
Value = node.EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value + "DeleteCol"
})
},
FunctionName = new Identifier {Value = "WRITE"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(
new Identifier {Value = deleteEdgeTableName},
new Identifier {Value = "binary1"})
},
new WValueExpression("null", false),
new WValueExpression("null", false)
}
}
},
new WAssignmentSetClause()
{
AssignmentKind = AssignmentKind.Equals,
Column = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = "InDegree"
})
},
NewValue = new WBinaryExpression
{
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = "InDegree"
})
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "srcCnt"})
},
ExpressionType = BinaryExpressionType.Subtract
}
},
new WAssignmentSetClause()
{
AssignmentKind = AssignmentKind.Equals,
Column = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = node.EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value + "OutDegree"
})
},
NewValue = new WBinaryExpression
{
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = node.EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value + "OutDegree"
})
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "sinkCnt"})
},
ExpressionType = BinaryExpressionType.Subtract
}
},
new WFunctionCallSetClause()
{
MutatorFuction = new WFunctionCall
{
CallTarget = new WMultiPartIdentifierCallTarget()
{
Identifiers =
new WMultiPartIdentifier(new Identifier
{
Value = reversedEdgeName + "DeleteCol"
})
},
FunctionName = new Identifier {Value = "WRITE"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(
new Identifier {Value = deleteEdgeTableName},
new Identifier {Value = "binary2"})
},
new WValueExpression("null", false),
new WValueExpression("null", false)
}
}
},
new WAssignmentSetClause()
{
AssignmentKind = AssignmentKind.Equals,
Column = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = reversedEdgeName + "OutDegree"
})
},
NewValue = new WBinaryExpression
{
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WMultiPartIdentifier(new Identifier
{
Value = reversedEdgeName + "OutDegree"
})
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "srcCnt"})
},
ExpressionType = BinaryExpressionType.Subtract
}
},
};
WWhereClause whereClause = new WWhereClause
{
SearchCondition = new WBooleanComparisonExpression
{
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier { Value = "GlobalNodeId" })
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(
new Identifier { Value = deleteEdgeTableName },
new Identifier { Value = "source" }
)
},
ComparisonType = BooleanComparisonType.Equals
}
};
if (compare == 0)
{
res.Add(new WDeclareTableVariable
{
VariableName = new Identifier { Value = "@" + deleteEdgeTempTable},
Definition = new WTableDefinition
{
ColumnDefinitions = new WColumnDefinition[]
{
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "source"},
DataType = new WParameterizedDataTypeReference{Name = new WSchemaObjectName(new Identifier{Value = "bigint"})},
Constraints = new List<WConstraintDefinition>
{
new WUniqueConstraintDefinition
{
Clustered = true,
IsPrimaryKey = true
}
}
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "binary1"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier{Value = "varbinary"}),
Parameters = new List<Literal>{new MaxLiteral{Value = "max"}}
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "binary2"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier{Value = "varbinary"}),
Parameters = new List<Literal>{new MaxLiteral{Value = "max"}}
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "sinkCnt"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier{Value = "int"}),
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier{Value = "srcCnt"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier{Value = "int"}),
},
},
},
Indexes = new List<WIndexDefinition>(),
TableConstraints = new List<WConstraintDefinition>()
}
});
var tableVar = new WSpecialNamedTableReference
{
TableObjectName = new WSchemaObjectName(new Identifier { Value = "@" + deleteEdgeTempTable })
};
res.Add(hasReversedEdge ? deleteCommonTableExpr : (WSqlStatement)deleteCommonTableExpr.WCommonTableExpressions[0]);
res.Add(new WInsertSpecification
{
Target = tableVar,
InsertSource = new WSelectInsertSource
{
Select = new WSelectQueryBlock
{
SelectElements = new WSelectElement[]
{
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName = new Identifier {Value = "ISNULL"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = deleteEdgeTableName + "_1"},
new Identifier {Value = "source"}
}),
},
new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = deleteEdgeTableName + "_2"},
new Identifier {Value = "source"}
}),
},
}
},
ColumnName = "source"
},
new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[] {new Identifier {Value = "binary1"}}),
}
},
new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[] {new Identifier {Value = "binary2"}}),
}
},
//new WSelectScalarExpression
//{
// SelectExpr = new WColumnReferenceExpression
// {
// MultiPartIdentifier = new WSchemaObjectName(new Identifier[]{new Identifier{Value = "binary2"}}),
// }
//},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName = new Identifier {Value = "ISNULL"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = deleteEdgeTableName + "_1"},
new Identifier {Value = "sinkCnt"}
}),
},
new WValueExpression
{
Value = "0"
},
}
},
ColumnName = "sinkCnt"
},
new WSelectScalarExpression
{
SelectExpr = new WFunctionCall
{
FunctionName = new Identifier {Value = "ISNULL"},
Parameters = new WScalarExpression[]
{
new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = deleteEdgeTableName + "_2"},
new Identifier {Value = "srcCnt"}
}),
},
new WValueExpression
{
Value = "0"
},
}
},
ColumnName = "srcCnt"
},
},
FromClause = new WFromClause
{
TableReferences = new WTableReference[]
{
new WQualifiedJoin
{
QualifiedJoinType = QualifiedJoinType.FullOuter,
FirstTableRef = new WQueryDerivedTable
{
Alias = new Identifier {Value = deleteEdgeTableName + "_1"},
QueryExpr = edgeSelectQuery
},
SecondTableRef = new WQueryDerivedTable
{
Alias = new Identifier {Value = deleteEdgeTableName + "_2"},
QueryExpr = reversedEdgeSelectQuery
},
JoinCondition = new WBooleanComparisonExpression()
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = deleteEdgeTableName + "_1"},
new Identifier {Value = "source"}
}),
},
SecondExpr = new WColumnReferenceExpression
{
MultiPartIdentifier =
new WSchemaObjectName(new Identifier[]
{
new Identifier {Value = deleteEdgeTableName + "_2"},
new Identifier {Value = "source"}
}),
}
}
},
}
}
}
}
});
res.Add(new WUpdateSpecification
{
Target = new WNamedTableReference
{
TableObjectName = sourceNameTable.TableObjectName
},
SetClauses = hasReversedEdge ? setClauses.ToList() : new List<WSetClause> { setClauses[0], setClauses[1], setClauses[2] },
FromClause = new WFromClause
{
TableReferences = new WTableReference[]
{
new WQueryDerivedTable
{
Alias = new Identifier {Value = deleteEdgeTableName},
QueryExpr = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>()
{
new WSelectStarExpression()
},
FromClause = new WFromClause
{
TableReferences = new List<WTableReference> {tableVar}
}
}
},
}
},
WhereClause = whereClause,
TopRowFilter = node.TopRowFilter,
});
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}", deleteEdgeTempTable)
});
}
else
{
// Declare table variables
res.Add(new WDeclareTableVariable
{
VariableName = new Identifier { Value = "@" + deleteEdgeTempTable + "_1" },
Definition = new WTableDefinition
{
ColumnDefinitions = new WColumnDefinition[]
{
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "source"},
DataType =
new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "bigint"})
},
Constraints = new List<WConstraintDefinition>
{
new WUniqueConstraintDefinition
{
Clustered = true,
IsPrimaryKey = true
}
}
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "binary1"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "varbinary"}),
Parameters = new List<Literal> {new MaxLiteral {Value = "max"}}
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "sinkCnt"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "int"}),
},
},
},
Indexes = new List<WIndexDefinition>(),
TableConstraints = new List<WConstraintDefinition>()
}
});
res.Add(new WDeclareTableVariable
{
VariableName = new Identifier { Value = "@" + deleteEdgeTempTable + "_2" },
Definition = new WTableDefinition
{
ColumnDefinitions = new WColumnDefinition[]
{
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "source"},
DataType =
new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "bigint"})
},
Constraints = new List<WConstraintDefinition>
{
new WUniqueConstraintDefinition
{
Clustered = true,
IsPrimaryKey = true
}
}
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "binary2"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "varbinary"}),
Parameters = new List<Literal> {new MaxLiteral {Value = "max"}}
},
},
new WColumnDefinition
{
ColumnIdentifier = new Identifier {Value = "srcCnt"},
DataType = new WParameterizedDataTypeReference
{
Name = new WSchemaObjectName(new Identifier {Value = "int"}),
},
},
},
Indexes = new List<WIndexDefinition>(),
TableConstraints = new List<WConstraintDefinition>()
}
});
var tableVar = new WSpecialNamedTableReference
{
TableObjectName = new WSchemaObjectName(new Identifier { Value = "@" + deleteEdgeTempTable + "_1" })
};
var reversedTableVar = new WSpecialNamedTableReference
{
TableObjectName = new WSchemaObjectName(new Identifier { Value = "@" + deleteEdgeTempTable + "_2" })
};
WInsertSpecification[] insertStat = new WInsertSpecification[]
{
new WInsertSpecification
{
Target = tableVar,
InsertSource = new WSelectInsertSource
{
Select = edgeSelectQuery
}
},
new WInsertSpecification
{
Target = reversedTableVar,
InsertSource = new WSelectInsertSource
{
Select = reversedEdgeSelectQuery
}
}
};
// Update statments for edge and reversed edge
WUpdateSpecification[] updateStat = new WUpdateSpecification[]
{
new WUpdateSpecification
{
Target = new WNamedTableReference
{
TableObjectName = sourceNameTable.TableObjectName
},
SetClauses = new List<WSetClause> {setClauses[0], setClauses[2]},
FromClause = new WFromClause
{
TableReferences = new WTableReference[]
{
new WQueryDerivedTable
{
QueryExpr = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>()
{
new WSelectStarExpression()
},
FromClause = new WFromClause
{
TableReferences = new List<WTableReference> {tableVar}
}
},
Alias = new Identifier {Value = deleteEdgeTableName},
},
}
},
WhereClause = whereClause,
TopRowFilter = node.TopRowFilter
},
new WUpdateSpecification
{
Target = new WNamedTableReference
{
TableObjectName = sinkNameTable.TableObjectName
},
SetClauses = hasReversedEdge ? new List<WSetClause> {setClauses[1], setClauses[3], setClauses[4]} :
new List<WSetClause> {setClauses[1]},
FromClause = new WFromClause
{
TableReferences = new WTableReference[]
{
new WQueryDerivedTable
{
Alias = new Identifier {Value = deleteEdgeTableName},
QueryExpr = new WSelectQueryBlock
{
SelectElements = new List<WSelectElement>()
{
new WSelectStarExpression()
},
FromClause = new WFromClause
{
TableReferences = new List<WTableReference> {reversedTableVar}
}
}
},
}
},
WhereClause = whereClause,
TopRowFilter = node.TopRowFilter
},
};
bool sourceFirst = compare < 0;
if (sourceFirst)
{
// With expression
res.Add(deleteCommonTableExpr.WCommonTableExpressions[0]);
res.Add(insertStat[0]);
res.Add(updateStat[0]);
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}_1", deleteEdgeTempTable)
});
// With expression
res.Add(deleteCommonTableExpr.WCommonTableExpressions[1]);
res.Add(insertStat[1]);
res.Add(updateStat[1]);
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}_2", deleteEdgeTempTable)
});
}
else
{
// With expression
res.Add(deleteCommonTableExpr.WCommonTableExpressions[1]);
res.Add(insertStat[1]);
res.Add(updateStat[1]);
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}_2", deleteEdgeTempTable)
});
// With expression
res.Add(deleteCommonTableExpr.WCommonTableExpressions[0]);
res.Add(insertStat[0]);
res.Add(updateStat[0]);
res.Add(new WSqlUnknownStatement
{
Statement = String.Format("DELETE FROM @{0}_1", deleteEdgeTempTable)
});
}
}
}
private WMatchClause ConstructReversedMatchClause(WSelectQueryBlock node, WSqlTableContext context)
{
var result = new WMatchClause()
{
Paths = new List<WMatchPath>(),
};
foreach (var path in node.MatchClause.Paths)
{
var reversedEdgeNameList = new List<string>();
var nodeList = new List<Tuple<WSchemaObjectName, WEdgeColumnReferenceExpression>>();
var edgeList = path.PathEdgeList;
for (var i = 0; i < edgeList.Count; ++i)
{
var sourceTableName = edgeList[i].Item1.Identifiers.Last().Value;
var edgeName = edgeList[i].Item2.MultiPartIdentifier.Identifiers.Last().Value;
WTableReference sourceTable = context[sourceTableName];
var sourceTableObjectName =
(sourceTable as WNamedTableReference).TableObjectName.Identifiers.Last().Value;
reversedEdgeNameList.Add(sourceTableObjectName + "_" + edgeName + "Reversed");
}
var sinkIdentifier = path.Tail.Identifiers.Last();
for (var i = edgeList.Count - 1; i >= 0; --i)
{
var nodeName = new WSchemaObjectName()
{
Identifiers = new List<Identifier>
{
new Identifier()
{
Value = sinkIdentifier.Value,
QuoteType = sinkIdentifier.QuoteType,
}
},
};
var originalPath = edgeList[i].Item2;
var edgeCol = new WEdgeColumnReferenceExpression()
{
ColumnType = ColumnType.Regular,
Alias = originalPath.Alias,
MaxLength = originalPath.MaxLength,
MinLength = originalPath.MinLength,
AttributeValueDict = originalPath.AttributeValueDict,
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier()
{
QuoteType = originalPath.MultiPartIdentifier.Identifiers.Last().QuoteType,
Value = reversedEdgeNameList[i],
}),
};
nodeList.Add(new Tuple<WSchemaObjectName, WEdgeColumnReferenceExpression>(nodeName, edgeCol));
sinkIdentifier = edgeList[i].Item1.Identifiers.Last();
}
result.Paths.Add(new WMatchPath
{
PathEdgeList = nodeList,
Tail = edgeList[0].Item1,
IsReversed = true,
});
}
return result;
}
private WMultiCommonTableExpression ConstructDeleteEdgeSelect(WSelectQueryBlock node, WEdgeColumnReferenceExpression edgeCol, string tempTableName
,out WTableReference sinkTable, out WTableReference sourceTable, ref bool hasReversedEdge)
{
sourceTable = null;
sinkTable = null;
string sourceTableName = null;
string sinkTableName = null;
var sourceTableScalar = node.SelectElements[0] as WSelectScalarExpression;
if (sourceTableScalar == null)
return null;
var sourceTableColumn = sourceTableScalar.SelectExpr as WColumnReferenceExpression;
if (sourceTableColumn == null)
return null;
sourceTableName = sourceTableColumn.MultiPartIdentifier.Identifiers.Last().Value;
var sourceNodeIdExpr = new WColumnReferenceExpression();
foreach (var identifier in sourceTableColumn.MultiPartIdentifier.Identifiers)
sourceNodeIdExpr.Add(identifier);
sourceNodeIdExpr.AddIdentifier("GlobalNodeId");
var collectVarVisitor = new CollectVariableVisitor();
var context = collectVarVisitor.Invoke(node);
if (!context.NodeTableDictionary.Any())
{
throw new GraphViewException("Missing From Clause in Delete Edge statement");
}
WColumnReferenceExpression sinkNodeIdExpr = null;
sourceTable = context[sourceTableName];
var groupByParams = new List<WScalarExpression>();
for (var index = 1; index < node.SelectElements.Count; ++index)
{
var element = node.SelectElements[index] as WSelectScalarExpression;
if (element == null)
return null;
//sink table
if (index == 1)
{
var sinkTableColumn = element.SelectExpr as WColumnReferenceExpression;
if (sinkTableColumn == null)
return null;
sinkTableName = sinkTableColumn.MultiPartIdentifier.Identifiers.Last().Value;
sinkTable = context[sinkTableName];
sinkNodeIdExpr = new WColumnReferenceExpression();
foreach (var identifier in sinkTableColumn.MultiPartIdentifier.Identifiers)
sinkNodeIdExpr.Add(identifier);
sinkNodeIdExpr.AddIdentifier("GlobalNodeId");
}
}
var sourceNodeId = new WSelectScalarExpression
{
SelectExpr = sourceNodeIdExpr,
ColumnName = "src",
};
var sinkNodeId = new WSelectScalarExpression
{
SelectExpr = sinkNodeIdExpr,
ColumnName = "sink"
};
var edgeId = new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(
new Identifier[]
{
new Identifier {Value = edgeCol.Alias??string.Format("{0}_{1}_{2}",sourceTableName,edgeCol.MultiPartIdentifier.Identifiers.Last().Value,sinkTableName)},
new Identifier {Value = "Edgeid"}
})
},
ColumnName = "edgeid"
};
var sourceTableNameRef = sourceTable as WNamedTableReference;
if (sourceTableNameRef == null)
throw new GraphViewException("Source table of DELETE EDGE statement should be a named table reference.");
var sinkTableNameRef = sinkTable as WNamedTableReference;
if (sinkTableNameRef == null)
throw new GraphViewException("Sink table of DELETE EDGE statement should be a named table reference.");
int compare = string.CompareOrdinal(sourceTableNameRef.TableObjectName.ToString(), sinkTableNameRef.TableObjectName.ToString());
using (var command = Tx.Connection.CreateCommand())
{
command.Transaction = Tx;
command.Parameters.AddWithValue("@schema", WNamedTableReference.SchemaNameToTuple(sourceTableNameRef.TableObjectName).Item1);
command.Parameters.AddWithValue("@tableName", sourceTableNameRef.TableObjectName.Identifiers.Last().Value);
command.Parameters.AddWithValue("@colName", edgeCol.MultiPartIdentifier.Identifiers.Last().Value);
command.Parameters.AddWithValue("@role", WNodeTableColumnRole.Edge);
command.CommandText = string.Format(@"
SELECT NodeColumn.HasReversedEdge
FROM [{0}] AS NodeColumn
WHERE NodeColumn.TableSchema = @schema and
NodeColumn.TableName = @tableName and
NodeColumn.ColumnName = @colName and
NodeColumn.ColumnRole = @role",
GraphViewConnection.MetadataTables[1]);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
hasReversedEdge = bool.Parse(reader[0].ToString());
}
}
}
var reversedEdgeName = sourceTableNameRef.TableObjectName.Identifiers.Last().Value +
"_" + edgeCol.MultiPartIdentifier.Identifiers.Last().Value + "Reversed";
var reversedEdgeId = new WSelectScalarExpression
{
SelectExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(
new Identifier[]
{
new Identifier {Value = edgeCol.Alias??string.Format("{0}_{1}_{2}",sourceTableName,edgeCol.MultiPartIdentifier.Identifiers.Last().Value,sinkTableName)},
new Identifier {Value = "Edgeid"}
})
},
ColumnName = "edgeid"
};
var elements = new List<WSelectElement>
{
sourceNodeId,
sinkNodeId,
edgeId
};
var reversedElements = new List<WSelectElement>
{
sourceNodeId,
sinkNodeId,
reversedEdgeId,
};
return new WMultiCommonTableExpression
{
WCommonTableExpressions = new List<WCommonTableExpression>()
{
new WCommonTableExpression
{
ExpressionName = new Identifier
{
Value = hasReversedEdge && compare == 0 ? tempTableName + "_1" : tempTableName
},
QueryExpression = new WSelectQueryBlock
{
FromClause = node.FromClause,
WhereClause = new WWhereClause
{
SearchCondition = node.WhereClause.SearchCondition
},
HavingClause = node.HavingClause,
OrderByClause = node.OrderByClause,
TopRowFilter = node.TopRowFilter,
UniqueRowFilter = node.UniqueRowFilter,
SelectElements = elements,
MatchClause = node.MatchClause,
}
},
new WCommonTableExpression
{
ExpressionName = new Identifier
{
Value = hasReversedEdge && compare == 0 ? tempTableName + "_2" : tempTableName
},
QueryExpression = new WSelectQueryBlock
{
FromClause = node.FromClause,
WhereClause = hasReversedEdge ?
new WWhereClause { SearchCondition = ObjectExtensions.Copy(node.WhereClause.SearchCondition), }
: node.WhereClause,
HavingClause = node.HavingClause,
OrderByClause = node.OrderByClause,
TopRowFilter = node.TopRowFilter,
UniqueRowFilter = node.UniqueRowFilter,
SelectElements = hasReversedEdge ? reversedElements : elements,
MatchClause = hasReversedEdge? ConstructReversedMatchClause(node, context) : node.MatchClause,
}
},
}
};
}
private void TranslateNodeDelete(WDeleteNodeSpecification node, List<WSqlStatement> res)
{
var table = node.Target as WNamedTableReference;
if (table == null)
throw new GraphViewException("Target of DELETE NODE statement should be a named table reference.");
WBooleanExpression cond = new WBooleanComparisonExpression
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier { Value = "InDegree" })
},
SecondExpr = new WValueExpression
{
Value = "0"
}
};
var tableSchema = table.TableObjectName.SchemaIdentifier == null
? "dbo"
: table.TableObjectName.SchemaIdentifier.Value;
var tableName = table.TableObjectName.BaseIdentifier.Value;
using (var command = Tx.Connection.CreateCommand())
{
command.Transaction = Tx;
command.CommandText = string.Format(
@"SELECT [TableSchema], [TableName], [ColumnName] FROM [{3}] WHERE TableSchema = '{0}' and [TableName]='{1}' and ColumnRole={2}",
tableSchema, tableName, 1, GraphViewConnection.MetadataTables[1]);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var col = reader["ColumnName"].ToString();
cond = WBooleanBinaryExpression.Conjunction(cond, new WBooleanComparisonExpression
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier { Value = col + "OutDegree" })
},
SecondExpr = new WValueExpression
{
Value = "0"
}
});
}
}
}
WWhereClause checkDeleteNode = new WWhereClause
{
SearchCondition = new WBooleanNotExpression { Expression = new WBooleanParenthesisExpression { Expression = cond } }
};
if (node.WhereClause == null ||
node.WhereClause.SearchCondition == null)
{
node.WhereClause = new WWhereClause { SearchCondition = cond };
}
else
{
checkDeleteNode = new WWhereClause
{
SearchCondition = new WBooleanBinaryExpression
{
BooleanExpressionType = BooleanBinaryExpressionType.And,
FirstExpr = node.WhereClause.SearchCondition,
SecondExpr = checkDeleteNode.SearchCondition
}
};
node.WhereClause = new WWhereClause
{
SearchCondition = new WBooleanBinaryExpression
{
BooleanExpressionType = BooleanBinaryExpressionType.And,
FirstExpr = node.WhereClause.SearchCondition,
SecondExpr = cond
}
};
}
using (var command = Tx.Connection.CreateCommand())
{
command.Transaction = Tx;
command.CommandText = string.Format("SELECT InDegree FROM {0}.{1} {2}", tableSchema, tableName,
checkDeleteNode.ToString());
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
throw new GraphViewException(
string.Format(
"Node(s) of node table {0} being deleted still has/have ingoing or outdoing edge(s)",
tableName));
}
}
}
res.Add(new WDeleteSpecification
{
FromClause = node.FromClause,
Target = node.Target,
TopRowFilter = node.TopRowFilter,
WhereClause = node.WhereClause,
});
}
}
class InsertEdgeSelectVisitor : WSqlFragmentVisitor
{
private WCommonTableExpression _result;
private WTableReference _sinkTable;
private List<WScalarExpression> _edgeProperties;
private string _tempTableName;
private string _sourceTableName;
public WCommonTableExpression Invoke(WSqlFragment node, string tempTableName, string sourceTableName,
out WTableReference sinkTable, out List<WScalarExpression> edgeProperties)
{
_edgeProperties = new List<WScalarExpression>();
_tempTableName = tempTableName;
_sourceTableName = sourceTableName;
node.Accept(this);
sinkTable = _sinkTable;
_edgeProperties.Insert(0,
new WColumnReferenceExpression
{
MultiPartIdentifier = new WMultiPartIdentifier(new Identifier {Value = "sink"})
}
);
edgeProperties = _edgeProperties;
return _result;
}
//public override void Visit(WQueryParenthesisExpression node)
//{
// node.QueryExpr.Accept(this);
// _result = new WQueryParenthesisExpression
// {
// OrderByClause = node.OrderByClause,
// QueryExpr = _result
// };
//}
public override void Visit(WBinaryQueryExpression node)
{
throw new GraphViewException("Binary query expression is not allowed in INSERT EDGE statement.");
}
public override void Visit(WSelectQueryBlock node)
{
if (node.SelectElements == null || node.SelectElements.Count < 2)
{
throw new GraphViewException("Numbers of select elements mismatch.");
}
if (node.GroupByClause != null)
{
throw new GraphViewException("GROUP BY clause is not allowed in INSERT EDGE statement.");
}
var sourceTableScalar = node.SelectElements[0] as WSelectScalarExpression;
if (sourceTableScalar == null)
throw new GraphViewException("Source node id should be a scalar expression.");
var sourceTableColumn = sourceTableScalar.SelectExpr as WColumnReferenceExpression;
if (sourceTableColumn == null)
throw new GraphViewException("Source node id column should be a column reference expression.");
var sourceTableAlias = sourceTableColumn.MultiPartIdentifier.Identifiers.Last().Value;
var collectVarVisitor = new CollectVariableVisitor();
var context = collectVarVisitor.Invoke(node);
var sourceTable = context[sourceTableAlias] as WNamedTableReference;
if (sourceTable == null)
{
throw new GraphViewException("Source table of INSERT EDGE statement should be a named table reference.");
}
if (
string.Compare(_sourceTableName, sourceTable.TableObjectName.BaseIdentifier.Value,
StringComparison.OrdinalIgnoreCase) != 0)
throw new GraphViewException("Source node table in the SELECT is mismatched with the INSERT source");
var sourceNodeIdExpr = new WColumnReferenceExpression();
foreach (var identifier in sourceTableColumn.MultiPartIdentifier.Identifiers)
sourceNodeIdExpr.Add(identifier);
sourceNodeIdExpr.AddIdentifier("GlobalNodeId");
//if (node.SelectElements.Count < 2)
// throw new GraphViewException("Source and Sink tables should be specified in select elements.");
WColumnReferenceExpression sinkNodeIdExpr = null;
for (var index = 1; index < node.SelectElements.Count; ++index)
{
var element = node.SelectElements[index] as WSelectScalarExpression;
if (element == null)
throw new GraphViewException("Edge property should be a scalar expression.");
//sink table
if (index == 1)
{
var sinkTableColumn = element.SelectExpr as WColumnReferenceExpression;
if (sinkTableColumn == null)
throw new GraphViewException("Sink node id column should be a column reference expression.");
var sinkTableAlias = sinkTableColumn.MultiPartIdentifier.Identifiers.Last().Value;
_sinkTable = context[sinkTableAlias];
sinkNodeIdExpr = new WColumnReferenceExpression();
foreach (var identifier in sinkTableColumn.MultiPartIdentifier.Identifiers)
sinkNodeIdExpr.Add(identifier);
sinkNodeIdExpr.AddIdentifier("GlobalNodeId");
}
else
{
_edgeProperties.Add(element.SelectExpr);
}
}
var sourceNodeId = new WSelectScalarExpression
{
SelectExpr = sourceNodeIdExpr,
ColumnName = "src",
};
var sinkNodeId = new WSelectScalarExpression
{
SelectExpr = sinkNodeIdExpr,
ColumnName = "sink"
};
var elements = new List<WSelectElement>
{
sourceNodeId,
sinkNodeId
};
var result = new WCommonTableExpression
{
ExpressionName = new Identifier {Value = _tempTableName},
QueryExpression = new WSelectQueryBlock
{
FromClause = node.FromClause,
WhereClause = new WWhereClause
{
SearchCondition = node.WhereClause.SearchCondition
},
HavingClause = node.HavingClause,
OrderByClause = node.OrderByClause,
TopRowFilter = node.TopRowFilter,
UniqueRowFilter = node.UniqueRowFilter,
SelectElements = elements,
MatchClause = node.MatchClause
}
};
_result = result;
}
}
}
| 49.544212
| 181
| 0.393885
|
[
"MIT"
] |
Bhaskers-Blu-Org2/GraphView
|
GraphView/TranslateDataModificationVisitor.cs
| 115,985
|
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/d3d12.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("C36A797C-EC80-4F0A-8985-A7B2475082D1")]
public unsafe partial struct ID3D12CommandSignature
{
public void** lpVtbl;
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject)
{
return ((delegate* stdcall<ID3D12CommandSignature*, Guid*, void**, int>)(lpVtbl[0]))((ID3D12CommandSignature*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* stdcall<ID3D12CommandSignature*, uint>)(lpVtbl[1]))((ID3D12CommandSignature*)Unsafe.AsPointer(ref this));
}
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* stdcall<ID3D12CommandSignature*, uint>)(lpVtbl[2]))((ID3D12CommandSignature*)Unsafe.AsPointer(ref this));
}
[return: NativeTypeName("HRESULT")]
public int GetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT *")] uint* pDataSize, [NativeTypeName("void *")] void* pData)
{
return ((delegate* stdcall<ID3D12CommandSignature*, Guid*, uint*, void*, int>)(lpVtbl[3]))((ID3D12CommandSignature*)Unsafe.AsPointer(ref this), guid, pDataSize, pData);
}
[return: NativeTypeName("HRESULT")]
public int SetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT")] uint DataSize, [NativeTypeName("const void *")] void* pData)
{
return ((delegate* stdcall<ID3D12CommandSignature*, Guid*, uint, void*, int>)(lpVtbl[4]))((ID3D12CommandSignature*)Unsafe.AsPointer(ref this), guid, DataSize, pData);
}
[return: NativeTypeName("HRESULT")]
public int SetPrivateDataInterface([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("const IUnknown *")] IUnknown* pData)
{
return ((delegate* stdcall<ID3D12CommandSignature*, Guid*, IUnknown*, int>)(lpVtbl[5]))((ID3D12CommandSignature*)Unsafe.AsPointer(ref this), guid, pData);
}
[return: NativeTypeName("HRESULT")]
public int SetName([NativeTypeName("LPCWSTR")] ushort* Name)
{
return ((delegate* stdcall<ID3D12CommandSignature*, ushort*, int>)(lpVtbl[6]))((ID3D12CommandSignature*)Unsafe.AsPointer(ref this), Name);
}
[return: NativeTypeName("HRESULT")]
public int GetDevice([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvDevice)
{
return ((delegate* stdcall<ID3D12CommandSignature*, Guid*, void**, int>)(lpVtbl[7]))((ID3D12CommandSignature*)Unsafe.AsPointer(ref this), riid, ppvDevice);
}
}
}
| 48.484848
| 180
| 0.660625
|
[
"MIT"
] |
john-h-k/terrafx.interop.windows
|
sources/Interop/Windows/um/d3d12/ID3D12CommandSignature.cs
| 3,202
|
C#
|
// -----------------------------------------------------------------------
// <copyright file="Vertex.cs" company="">
// Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html
// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/
// </copyright>
// -----------------------------------------------------------------------
namespace TriangleNet.Geometry
{
using System;
using TriangleNet.Topology;
/// <summary>
/// The vertex data structure.
/// </summary>
public class Vertex : Point
{
// Hash for dictionary. Will be set by mesh instance.
internal int hash;
#if USE_ATTRIBS
internal double[] attributes;
#endif
internal VertexType type;
internal Otri tri;
/// <summary>
/// Initializes a new instance of the <see cref="Vertex" /> class.
/// </summary>
public Vertex()
: this(0, 0, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Vertex" /> class.
/// </summary>
/// <param name="x">The x coordinate of the vertex.</param>
/// <param name="y">The y coordinate of the vertex.</param>
public Vertex(double x, double y)
: this(x, y, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Vertex" /> class.
/// </summary>
/// <param name="x">The x coordinate of the vertex.</param>
/// <param name="y">The y coordinate of the vertex.</param>
/// <param name="mark">The boundary mark.</param>
public Vertex(double x, double y, int mark)
: base(x, y, mark)
{
this.type = VertexType.InputVertex;
}
#if USE_ATTRIBS
/// <summary>
/// Initializes a new instance of the <see cref="Vertex" /> class.
/// </summary>
/// <param name="x">The x coordinate of the vertex.</param>
/// <param name="y">The y coordinate of the vertex.</param>
/// <param name="mark">The boundary mark.</param>
/// <param name="attribs">The number of point attributes.</param>
public Vertex(double x, double y, int mark, int attribs)
: this(x, y, mark)
{
if (attribs > 0)
{
this.attributes = new double[attribs];
}
}
#endif
#region Public properties
#if USE_ATTRIBS
/// <summary>
/// Gets the vertex attributes (may be null).
/// </summary>
public double[] Attributes
{
get { return this.attributes; }
}
#endif
/// <summary>
/// Gets the vertex type.
/// </summary>
public VertexType Type
{
get { return this.type; }
}
/// <summary>
/// Gets the specified coordinate of the vertex.
/// </summary>
/// <param name="i">Coordinate index.</param>
/// <returns>X coordinate, if index is 0, Y coordinate, if index is 1.</returns>
public double this[int i]
{
get
{
if (i == 0)
{
return x;
}
if (i == 1)
{
return y;
}
throw new ArgumentOutOfRangeException("Index must be 0 or 1.");
}
}
#endregion
public override int GetHashCode()
{
return this.hash;
}
}
}
| 29.547619
| 99
| 0.466559
|
[
"MIT"
] |
BogdanAlexandru/Triangle.NET
|
Triangle.NET/Triangle/Geometry/Vertex.cs
| 3,725
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic;
using UnityEngine;
namespace HoloToolkit.Unity.InputModule.Utilities.Interactions
{
/// <summary>
/// Implements common logic for rotating holograms using a handlebar metaphor.
/// each frame, object_rotation_delta = rotation_delta(current_hands_vector, previous_hands_vector)
/// where hands_vector is the vector between two hand/controller positions.
///
/// Usage:
/// When a manipulation starts, call Setup.
/// Call Update any time to update the move logic and get a new rotation for the object.
/// </summary>
public class TwoHandRotateLogic
{
/// <summary>
/// Private variables
/// </summary>
private const float MinHandDistanceForPitchM = 0.1f;
/// <summary>
/// a scalar applied to Rotation angle generated by handlebar calculations.
/// </summary>
private const float RotationMultiplier = 2f;
/// <summary>
/// This enum value stores the initial constraint specified as an argument in the Constructor.
/// It may be overridden by runtime conditions. The actual constraint is stored in the
/// variable currentRotationConstraint.
/// </summary>
private AxisConstraint rotationConstraint;
/// <summary>
/// Vector storing last handlebar Rotation. The handlebar is the line imagined between the controllers/hands.
/// </summary>
private Vector3 previousHandlebarRotation;
/// <summary>
/// The current rotation constraint might be modified based on disambiguation logic, for example
/// XOrYBasedOnInitialHandPosition might change the current rotation constraint based on the
/// initial hand positions at the start
/// </summary>
private AxisConstraint currentRotationConstraint;
/// <summary>
/// ProjectHandlebarGivenConstraint internal function to account for axis constraint
/// </summary>
/// <param name="constraint">Enum value describing the axis to which the rotation is constrained/param>
/// <param name="handlebarRotation">A Vector3 describing the rotation of the line connecting the inputSources</param>
/// <param name="manipulationRoot">Transform of gameObject to be two hand manipulated</param>
/// <returns>a Vector3 describing handlebar after constraint is applied</returns>
private Vector3 ProjectHandlebarGivenConstraint(AxisConstraint constraint, Vector3 handlebarRotation, Transform manipulationRoot)
{
Vector3 result = handlebarRotation;
switch (constraint)
{
case AxisConstraint.XAxisOnly:
result.x = 0;
break;
case AxisConstraint.YAxisOnly:
result.y = 0;
break;
case AxisConstraint.ZAxisOnly:
result.z = 0;
break;
}
return CameraCache.Main.transform.TransformDirection(result);
}
/// <summary>
/// GetHandlebarDirection internal function to get rotation described by inputSources.
/// </summary>
/// <param name="handsPressedMap">Dictionary listing inputSourceStates</param>
/// <param name="manipulationRoot">Transform of gameObject to be two hand manipulated</param>
/// <returns>A Vector3 describing the direction of the line connecting the inputSources</returns>
private Vector3 GetHandlebarDirection(Dictionary<uint, Vector3> handsPressedMap, Transform manipulationRoot)
{
var handsEnumerator = handsPressedMap.Values.GetEnumerator();
handsEnumerator.MoveNext();
var hand1 = handsEnumerator.Current;
handsEnumerator.MoveNext();
var hand2 = handsEnumerator.Current;
// We project the handlebar direction into camera space because otherwise when we move our body the handlebard will move even
// though, relative to our heads, the handlebar is not moving.
hand1 = CameraCache.Main.transform.InverseTransformPoint(hand1);
hand2 = CameraCache.Main.transform.InverseTransformPoint(hand2);
return hand2 - hand1;
}
/// <summary>
/// TwoHandRotateLogic Constructor
/// </summary>
/// <param name="constrainRotation">Enum describing to which axis the rotation is constrained</param>
public TwoHandRotateLogic(AxisConstraint constrainRotation)
{
rotationConstraint = constrainRotation;
}
/// <summary>
/// Initializes twohand system with controller/hand source info:
/// the Dictionary collection already filled with controller/hand info,
/// and the Transform of the GameObject to be manipulated.
/// </summary>
/// <param name="handsPressedMap">Dictionary listing inputSourceStates</param>
/// <param name="manipulationRoot">Transform of gameObject to be two hand manipulated</param>
public void Setup(Dictionary<uint, Vector3> handsPressedMap, Transform manipulationRoot)
{
currentRotationConstraint = rotationConstraint;
previousHandlebarRotation = GetHandlebarDirection(handsPressedMap, manipulationRoot);
}
/// <summary>
/// Updates internal states based on current Controller/hand states.
/// </summary>
/// <param name="handsPressedMap">Dictionary listing inputSourceStates</param>
/// <param name="manipulationRoot">Transform of gameObject to be two hand manipulated</param>
/// <param name="currentRotation">New rotation to be applied</param>
/// <returns>Quaternion describing rotation based on position of inputSources - Controllers/Hands</returns>
public Quaternion Update(Dictionary<uint, Vector3> handsPressedMap, Transform manipulationRoot, Quaternion currentRotation)
{
var handlebarDirection = GetHandlebarDirection(handsPressedMap, manipulationRoot);
var handlebarDirectionProjected = ProjectHandlebarGivenConstraint(currentRotationConstraint, handlebarDirection, manipulationRoot);
var prevHandlebarDirectionProjected = ProjectHandlebarGivenConstraint(currentRotationConstraint, previousHandlebarRotation, manipulationRoot);
previousHandlebarRotation = handlebarDirection;
var rotationDelta = Quaternion.FromToRotation(prevHandlebarDirectionProjected, handlebarDirectionProjected);
var angle = 0f;
var axis = Vector3.zero;
rotationDelta.ToAngleAxis(out angle, out axis);
angle *= RotationMultiplier;
if (currentRotationConstraint == AxisConstraint.YAxisOnly)
{
// If we are rotating about Y axis, then make sure we rotate about global Y axis.
// Since the angle is obtained from a quaternion, we need to properly orient it (up or down) based
// on the original axis-angle representation.
axis = Vector3.up * Vector3.Dot(axis, Vector3.up);
}
return Quaternion.AngleAxis(angle, axis) * currentRotation;
}
}
}
| 49.846667
| 154
| 0.666176
|
[
"MIT"
] |
museum4punkt0/PMR-Victoria
|
Assets/vendor/HoloToolkit/Input/Scripts/Utilities/Interactions/TwoHandRotateLogic.cs
| 7,479
|
C#
|
// Copyright © 2017 Dmitry Sikorsky. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using ExtCore.Events;
using Platformus.Barebone;
using Platformus.Domain.Data.Entities;
namespace Platformus.Domain.Events
{
public interface IMemberEditedEventHandler : IEventHandler<IRequestHandler, Member>
{
}
}
| 30.230769
| 111
| 0.791349
|
[
"Apache-2.0"
] |
5118234/Platformus
|
src/Platformus.Domain/Events/IMemberEditedEventHandler.cs
| 396
|
C#
|
using System.Threading.Tasks;
using Orchard.Recipes.Models;
using YesSql;
namespace Orchard.Recipes.Services
{
/// <summary>
/// And implementation of <see cref="IRecipeStore"/> that stores the recipe<see cref="RecipeResult"/>
/// object in YesSql.
/// </summary>
public class RecipeStore : IRecipeStore
{
private readonly ISession _session;
public RecipeStore(ISession session)
{
_session = session;
}
public Task CreateAsync(RecipeResult recipeResult)
{
_session.Save(recipeResult);
return Task.CompletedTask;
}
public Task DeleteAsync(RecipeResult recipeResult)
{
_session.Delete(recipeResult);
return Task.CompletedTask;
}
public Task<RecipeResult> FindByExecutionIdAsync(string executionId)
{
return _session.QueryAsync<RecipeResult, RecipeResultIndex>(x => x.ExecutionId == executionId).FirstOrDefault();
}
public Task UpdateAsync(RecipeResult recipeResult)
{
_session.Save(recipeResult);
return Task.CompletedTask;
}
}
}
| 26.977273
| 124
| 0.621735
|
[
"BSD-3-Clause"
] |
ChipSoftTech/CST-CMS
|
src/OrchardCore.Modules/Orchard.Recipes/Services/RecipeStore.cs
| 1,189
|
C#
|
using System;
using EventStore.Core.Data;
using EventStore.Core.TransactionLog;
using EventStore.Core.TransactionLog.Checkpoint;
using EventStore.Core.TransactionLog.Chunks;
using EventStore.Core.TransactionLog.LogRecords;
using NUnit.Framework;
namespace EventStore.Core.Tests.TransactionLog.Chunks
{
[TestFixture]
public class when_having_scavenged_tfchunk_with_original_first_record_removed: SpecificationWithDirectoryPerTestFixture
{
private TFChunkDb _db;
private TFChunk _scavengedChunk;
private LogRecord _rec1, _rec2, _rec3;
private RecordWriteResult _res1, _res2, _res3;
public override void TestFixtureSetUp()
{
base.TestFixtureSetUp();
_db = new TFChunkDb(new TFChunkDbConfig(PathName,
new VersionedPatternFileNamingStrategy(PathName, "chunk-"),
16 * 1024,
0,
new InMemoryCheckpoint(),
new ICheckpoint[0]));
_db.OpenVerifyAndClean();
var chunk = _db.Manager.GetChunk(0);
_rec1 = LogRecord.SingleWrite(0, Guid.NewGuid(), Guid.NewGuid(), "es-to-scavenge", ExpectedVersion.Any, "et1",
new byte[] { 0, 1, 2 }, new byte[] { 5, 7 });
_res1 = chunk.TryAppend(_rec1);
_rec2 = LogRecord.SingleWrite(_res1.NewPosition,
Guid.NewGuid(), Guid.NewGuid(), "es1", ExpectedVersion.Any, "et1",
new byte[] { 0, 1, 2 }, new byte[] { 5, 7 });
_res2 = chunk.TryAppend(_rec2);
_rec3 = LogRecord.SingleWrite(_res2.NewPosition,
Guid.NewGuid(), Guid.NewGuid(), "es1", ExpectedVersion.Any, "et1",
new byte[] { 0, 1, 2 }, new byte[] { 5, 7 });
_res3 = chunk.TryAppend(_rec3);
chunk.Complete();
var scavenger = new TFChunkScavenger(_db, new FakeReadIndex(x => x == "es-to-scavenge"));
scavenger.Scavenge(alwaysKeepScavenged: true);
_scavengedChunk = _db.Manager.GetChunk(0);
}
public override void TestFixtureTearDown()
{
_db.Dispose();
base.TestFixtureTearDown();
}
[Test]
public void first_record_was_written()
{
Assert.IsTrue(_res1.Success);
Assert.AreEqual(0, _res1.OldPosition);
Assert.AreEqual(_rec1.GetSizeWithLengthPrefixAndSuffix(), _res1.NewPosition);
}
[Test]
public void second_record_was_written()
{
Assert.IsTrue(_res2.Success);
Assert.AreEqual(_res1.NewPosition, _res2.OldPosition);
Assert.AreEqual(_res1.NewPosition + _rec2.GetSizeWithLengthPrefixAndSuffix(), _res2.NewPosition);
}
[Test]
public void third_record_was_written()
{
Assert.IsTrue(_res3.Success);
Assert.AreEqual(_res2.NewPosition, _res3.OldPosition);
Assert.AreEqual(_res2.NewPosition + _rec3.GetSizeWithLengthPrefixAndSuffix(), _res3.NewPosition);
}
[Test]
public void original_record1_cant_be_read_at_position()
{
var res = _scavengedChunk.TryReadAt((int)_res1.OldPosition);
Assert.IsFalse(res.Success);
}
[Test]
public void original_record2_can_be_read_at_position()
{
var res = _scavengedChunk.TryReadAt((int)_res2.OldPosition);
Assert.IsTrue(res.Success);
Assert.AreEqual(_rec2, res.LogRecord);
}
[Test]
public void original_record3_can_be_read_at_position()
{
var res = _scavengedChunk.TryReadAt((int)_res3.OldPosition);
Assert.IsTrue(res.Success);
Assert.AreEqual(_rec3, res.LogRecord);
}
[Test]
public void the_first_record_read_is_record2()
{
var res = _scavengedChunk.TryReadFirst();
Assert.IsTrue(res.Success);
Assert.AreEqual(_rec2, res.LogRecord);
Assert.AreEqual(_res3.OldPosition, res.NextPosition);
}
[Test]
public void the_closest_forward_after_first_record_is_record3()
{
var res = _scavengedChunk.TryReadClosestForward((int)_res3.OldPosition);
Assert.IsTrue(res.Success);
Assert.AreEqual(_rec3, res.LogRecord);
Assert.AreEqual(_res3.NewPosition, res.NextPosition);
}
[Test]
public void the_next_closest_forward_cant_be_read()
{
var res = _scavengedChunk.TryReadClosestForward((int)_res3.NewPosition);
Assert.IsFalse(res.Success);
}
[Test]
public void the_last_record_read_is_record3()
{
var res = _scavengedChunk.TryReadLast();
Assert.IsTrue(res.Success);
Assert.AreEqual(_rec3, res.LogRecord);
Assert.AreEqual(_res3.OldPosition, res.NextPosition);
}
[Test]
public void the_closest_backward_after_last_record_is_record2()
{
var res = _scavengedChunk.TryReadClosestBackward((int)_res3.OldPosition);
Assert.IsTrue(res.Success);
Assert.AreEqual(_rec2, res.LogRecord);
Assert.AreEqual(_res2.OldPosition, res.NextPosition);
}
[Test]
public void the_next_closest_backward_cant_be_read()
{
var res = _scavengedChunk.TryReadClosestBackward((int)_res2.OldPosition);
Assert.IsFalse(res.Success);
}
}
}
| 37.201258
| 123
| 0.573964
|
[
"BSD-3-Clause"
] |
eleks/EventStore
|
src/EventStore/EventStore.Core.Tests/TransactionLog/Chunks/when_having_scavenged_tfchunk_with_original_first_record_removed.cs
| 5,915
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.