content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.ComponentModel;
using System.Reflection;
using QS.Dialog;
using QS.Navigation;
using QS.Services;
using QS.Tdi;
using QS.ViewModels.Dialog;
using QS.ViewModels.Extension;
namespace QS.ViewModels
{
[Obsolete("Эта ветка базовых кассов будет удалена с окончательным выпиливанием TDI из ViewModel. Может быть оставлена только для обратной совместимости Водовозовских диалогов.")]
public abstract class TabViewModelBase : DialogViewModelBase, ITdiTab, IDisposable
{
protected TabViewModelBase(IInteractiveService interactiveService, INavigationManager navigation) : base(navigation)
{
this.interactiveService = interactiveService ?? throw new ArgumentNullException(nameof(interactiveService));
}
public override string Title { get => TabName; set => TabName = value; }
#region ITdiTab implementation
public HandleSwitchIn HandleSwitchIn { get; private set; }
public HandleSwitchOut HandleSwitchOut { get; private set; }
private string tabName = string.Empty;
/// <summary>
/// Имя вкладки может быть автоматически получено из атрибута DisplayNameAttribute у класса диалога.
/// </summary>
public virtual string TabName {
get {
if(string.IsNullOrWhiteSpace(tabName)) {
return GetType().GetCustomAttribute<DisplayNameAttribute>(true)?.DisplayName;
}
return tabName;
}
set {
if(tabName == value)
return;
tabName = value;
OnTabNameChanged();
}
}
public ITdiTabParent TabParent { set; get; }
public bool FailInitialize { get; protected set; }
public event EventHandler<TdiTabNameChangedEventArgs> TabNameChanged;
public event EventHandler TabClosed;
public virtual bool CompareHashName(string hashName)
{
return GenerateHashName(this.GetType()) == hashName;
}
#endregion
/// <summary>
/// Отменяет открытие вкладки
/// </summary>
/// <param name="message">Сообщение пользователю при отмене открытия</param>
protected void AbortOpening(string message, string title = "Невозможно открыть вкладку")
{
ShowErrorMessage(message, title);
AbortOpening();
}
/// <summary>
/// Отменяет открытие вкладки
/// </summary>
protected void AbortOpening()
{
FailInitialize = true;
}
public static string GenerateHashName<TTab>() where TTab : TabViewModelBase
{
return GenerateHashName(typeof(TTab));
}
public static string GenerateHashName(Type tabType)
{
if(!typeof(TabViewModelBase).IsAssignableFrom(tabType))
throw new ArgumentException($"Тип должен наследоваться от {nameof(TabViewModelBase)}", nameof(tabType));
return string.Format("Tab_{0}", tabType.Name);
}
protected virtual void OnTabNameChanged()
{
TabNameChanged?.Invoke(this, new TdiTabNameChangedEventArgs(TabName));
OnPropertyChanged(nameof(Title));
}
public override void Close(bool askSave, CloseSource source)
{
if(askSave)
TabParent?.AskToCloseTab(this, source);
else
TabParent?.ForceCloseTab(this, source);
base.Close(askSave, source);
}
public void OnTabClosed()
{
TabClosed?.Invoke(this, EventArgs.Empty);
}
#region Перенесено из ViewModelBase для поддержания обратной совместимости. умрет здесь вместе с TabViewModelBase
private readonly IInteractiveService interactiveService;
protected virtual void ShowInfoMessage(string message, string title = null)
{
interactiveService.ShowMessage(ImportanceLevel.Info, message, title);
}
protected virtual void ShowWarningMessage(string message, string title = null)
{
interactiveService.ShowMessage(ImportanceLevel.Warning, message, title);
}
protected virtual void ShowErrorMessage(string message, string title = null)
{
interactiveService.ShowMessage(ImportanceLevel.Error, message, title);
}
protected virtual bool AskQuestion(string question, string title = null)
{
return interactiveService.Question(question, title);
}
#endregion
public virtual void Dispose() { }
}
}
| 27.713287
| 179
| 0.743629
|
[
"Apache-2.0"
] |
Iamposox/QSProjects
|
QS.Project/ViewModels/TabViewModelBase.cs
| 4,355
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyDemo.SiloHost
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
| 30.609756
| 122
| 0.631076
|
[
"MIT"
] |
wannvmi/MyLearning-Ocelot
|
MyLearning.Orleans/MyDemo.SiloHost/Startup.cs
| 1,255
|
C#
|
using Chayns.Backend.Api.Models.Data.Base;
namespace Chayns.Backend.Api.Models.Data
{
public class UacGroupDataChange : DefaultData
{
public UacGroupDataChange(int locationId) : base(locationId)
{
}
public UacGroupDataChange(string siteId) : base(siteId)
{
}
#region UacGroupId
private int _uacGroupId;
public int UacGroupId
{
get
{
return _uacGroupId;
}
set
{
_uacGroupId = value;
OnPropertyChanged();
}
}
#endregion UacGroupId
#region Name
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
OnPropertyChanged();
}
}
#endregion Name
#region ShowName
private string _showName;
public string ShowName
{
get
{
return _showName;
}
set
{
_showName = value;
OnPropertyChanged();
}
}
#endregion ShowName
#region Description
private string _description;
public string Description
{
get
{
return _description;
}
set
{
_description = value;
OnPropertyChanged();
}
}
#endregion Description
}
}
| 20.725
| 68
| 0.426417
|
[
"MIT"
] |
TobitSoftware/ChaynsBackendApiHelper
|
ChaynsBackendApiHelper/Api/Models/Data/UacGroupDataChange.cs
| 1,660
|
C#
|
// Copyright 2020 zmjack
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq.Expressions;
namespace LinqSharp.EFCore
{
public class UpdateOptions<TEntity> where TEntity : class
{
public delegate void UpdateDelegate(TEntity record, TEntity entity);
public UpdateDelegate Update { get; set; }
/// <summary>
/// If you want to optimize the search logic, you can specify the predicate.
/// (Note that the predicate must contain all possible records.)
/// </summary>
public Expression<Func<TEntity, bool>> Predicate { get; set; }
}
}
| 32.625
| 84
| 0.684547
|
[
"Apache-2.0"
] |
hnjm/LinqSharp
|
LinqSharp.EFCore/LinqSharp.EFCore - Shared/UpdateOptions.cs
| 785
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Calculador_Static
{
class Global
{
public Double Pi = 3.14;
public double Circunferencia(double r)
{
return 2.0 * Pi * r;
}
public double Volume(double r)
{
return 4.0 / 3.0 * Pi * Math.Pow(r, 3.0);
}
}
}
| 17.181818
| 53
| 0.529101
|
[
"MIT"
] |
P3nto5/curso-c-
|
c# poo/Calculador_Static/Global.cs
| 380
|
C#
|
namespace SFA.DAS.EmployerUsers.Domain.Auditing.Login
{
public class SuccessfulLoginAuditMessage : EmployerUsersAuditMessage
{
public SuccessfulLoginAuditMessage(User user)
{
Category = "SUCCESSFUL_LOGIN";
Description = $"User {user.Email} (id: {user.Id}) logged in";
AffectedEntity = new Audit.Types.Entity
{
Type = UserTypeName,
Id = user.Id
};
}
}
}
| 28.352941
| 73
| 0.564315
|
[
"MIT"
] |
SkillsFundingAgency/das-employerusers
|
src/SFA.DAS.EmployerUsers.Domain/Auditing/Login/SuccessfulLoginAuditMessage.cs
| 484
|
C#
|
using System;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
using MySqlConnector.Utilities;
namespace MySqlConnector.Protocol.Serialization
{
internal sealed class CompressedPayloadHandler : IPayloadHandler
{
public CompressedPayloadHandler(IByteHandler byteHandler)
{
m_uncompressedStream = new();
m_uncompressedStreamByteHandler = new StreamByteHandler(m_uncompressedStream);
m_byteHandler = byteHandler;
m_bufferedByteReader = new();
m_compressedBufferedByteReader = new();
}
public void Dispose()
{
Utility.Dispose(ref m_byteHandler);
Utility.Dispose(ref m_uncompressedStreamByteHandler);
Utility.Dispose(ref m_uncompressedStream);
}
public void StartNewConversation()
{
m_compressedSequenceNumber = 0;
m_uncompressedSequenceNumber = 0;
}
public IByteHandler ByteHandler
{
get => m_byteHandler!;
set => throw new NotSupportedException();
}
public ValueTask<ArraySegment<byte>> ReadPayloadAsync(ArraySegmentHolder<byte> cache, ProtocolErrorBehavior protocolErrorBehavior, IOBehavior ioBehavior)
{
using var compressedByteHandler = new CompressedByteHandler(this, protocolErrorBehavior);
return ProtocolUtility.ReadPayloadAsync(m_bufferedByteReader, compressedByteHandler, () => -1, cache, protocolErrorBehavior, ioBehavior);
}
public ValueTask<int> WritePayloadAsync(ReadOnlyMemory<byte> payload, IOBehavior ioBehavior)
{
// break the payload up into (possibly more than one) uncompressed packets
return ProtocolUtility.WritePayloadAsync(m_uncompressedStreamByteHandler!, GetNextUncompressedSequenceNumber, payload, ioBehavior).ContinueWith(_ =>
{
if (m_uncompressedStream!.Length == 0)
return default;
if (!m_uncompressedStream.TryGetBuffer(out var uncompressedData))
throw new InvalidOperationException("Couldn't get uncompressed stream buffer.");
return CompressAndWrite(uncompressedData, ioBehavior)
.ContinueWith(__ =>
{
// reset the uncompressed stream to accept more data
m_uncompressedStream.SetLength(0);
return default(ValueTask<int>);
});
});
}
private ValueTask<int> ReadBytesAsync(Memory<byte> buffer, ProtocolErrorBehavior protocolErrorBehavior, IOBehavior ioBehavior)
{
// satisfy the read from cache if possible
if (m_remainingData.Count > 0)
{
var bytesToRead = Math.Min(m_remainingData.Count, buffer.Length);
m_remainingData.AsSpan().Slice(0, bytesToRead).CopyTo(buffer.Span);
m_remainingData = m_remainingData.Slice(bytesToRead);
return new ValueTask<int>(bytesToRead);
}
// read the compressed header (seven bytes)
return m_compressedBufferedByteReader.ReadBytesAsync(m_byteHandler!, 7, ioBehavior)
.ContinueWith(headerReadBytes =>
{
if (headerReadBytes.Count < 7)
{
return protocolErrorBehavior == ProtocolErrorBehavior.Ignore ?
default :
ValueTaskExtensions.FromException<int>(new EndOfStreamException("Wanted to read 7 bytes but only read {0} when reading compressed packet header".FormatInvariant(headerReadBytes.Count)));
}
var payloadLength = (int) SerializationUtility.ReadUInt32(headerReadBytes.Array!, headerReadBytes.Offset, 3);
var packetSequenceNumber = headerReadBytes.Array![headerReadBytes.Offset + 3];
var uncompressedLength = (int) SerializationUtility.ReadUInt32(headerReadBytes.Array, headerReadBytes.Offset + 4, 3);
// verify the compressed packet sequence number
var expectedSequenceNumber = GetNextCompressedSequenceNumber();
if (packetSequenceNumber != expectedSequenceNumber)
{
if (protocolErrorBehavior == ProtocolErrorBehavior.Ignore)
return default;
var exception = MySqlProtocolException.CreateForPacketOutOfOrder(expectedSequenceNumber, packetSequenceNumber);
return ValueTaskExtensions.FromException<int>(exception);
}
// MySQL protocol resets the uncompressed sequence number back to the sequence number of this compressed packet.
// This isn't in the documentation, but the code explicitly notes that uncompressed packets are modified by compression:
// - https://github.com/mysql/mysql-server/blob/c28e258157f39f25e044bb72e8bae1ff00989a3d/sql/net_serv.cc#L276
// - https://github.com/mysql/mysql-server/blob/c28e258157f39f25e044bb72e8bae1ff00989a3d/sql/net_serv.cc#L225-L227
if (!m_isContinuationPacket)
m_uncompressedSequenceNumber = packetSequenceNumber;
// except this doesn't happen when uncompressed packets need to be broken up across multiple compressed packets
m_isContinuationPacket = payloadLength == ProtocolUtility.MaxPacketSize || uncompressedLength == ProtocolUtility.MaxPacketSize;
return m_compressedBufferedByteReader.ReadBytesAsync(m_byteHandler!, payloadLength, ioBehavior)
.ContinueWith(payloadReadBytes =>
{
if (payloadReadBytes.Count < payloadLength)
{
return protocolErrorBehavior == ProtocolErrorBehavior.Ignore ?
default :
ValueTaskExtensions.FromException<int>(new EndOfStreamException("Wanted to read {0} bytes but only read {1} when reading compressed payload".FormatInvariant(payloadLength, payloadReadBytes.Count)));
}
if (uncompressedLength == 0)
{
// data is uncompressed
m_remainingData = payloadReadBytes;
}
else
{
// check CMF (Compression Method and Flags) and FLG (Flags) bytes for expected values
var cmf = payloadReadBytes.Array![payloadReadBytes.Offset];
var flg = payloadReadBytes.Array[payloadReadBytes.Offset + 1];
if (cmf != 0x78 || ((flg & 0x20) == 0x20) || ((cmf * 256 + flg) % 31 != 0))
{
// CMF = 0x78: 32K Window Size + deflate compression
// FLG & 0x20: has preset dictionary (not supported)
// CMF*256+FLG is a multiple of 31: header checksum
return protocolErrorBehavior == ProtocolErrorBehavior.Ignore ?
default :
ValueTaskExtensions.FromException<int>(new NotSupportedException("Unsupported zlib header: {0:X2}{1:X2}".FormatInvariant(cmf, flg)));
}
// zlib format (https://www.ietf.org/rfc/rfc1950.txt) is: [two header bytes] [deflate-compressed data] [four-byte checksum]
// .NET implements the middle part with DeflateStream; need to handle header and checksum explicitly
const int headerSize = 2;
const int checksumSize = 4;
var uncompressedData = new byte[uncompressedLength];
using var compressedStream = new MemoryStream(payloadReadBytes.Array, payloadReadBytes.Offset + headerSize, payloadReadBytes.Count - headerSize - checksumSize);
using var decompressingStream = new DeflateStream(compressedStream, CompressionMode.Decompress);
var bytesRead = decompressingStream.Read(uncompressedData, 0, uncompressedLength);
m_remainingData = new(uncompressedData, 0, bytesRead);
var checksum = ComputeAdler32Checksum(uncompressedData, 0, bytesRead);
var adlerStartOffset = payloadReadBytes.Offset + payloadReadBytes.Count - 4;
if (payloadReadBytes.Array[adlerStartOffset + 0] != ((checksum >> 24) & 0xFF) ||
payloadReadBytes.Array[adlerStartOffset + 1] != ((checksum >> 16) & 0xFF) ||
payloadReadBytes.Array[adlerStartOffset + 2] != ((checksum >> 8) & 0xFF) ||
payloadReadBytes.Array[adlerStartOffset + 3] != (checksum & 0xFF))
{
return protocolErrorBehavior == ProtocolErrorBehavior.Ignore ?
default :
ValueTaskExtensions.FromException<int>(new NotSupportedException("Invalid Adler-32 checksum of uncompressed data."));
}
}
var bytesToRead = Math.Min(m_remainingData.Count, buffer.Length);
m_remainingData.AsSpan().Slice(0, bytesToRead).CopyTo(buffer.Span);
m_remainingData = m_remainingData.Slice(bytesToRead);
return new ValueTask<int>(bytesToRead);
});
});
}
private byte GetNextCompressedSequenceNumber() => m_compressedSequenceNumber++;
private int GetNextUncompressedSequenceNumber() => m_uncompressedSequenceNumber++;
private ValueTask<int> CompressAndWrite(ArraySegment<byte> remainingUncompressedData, IOBehavior ioBehavior)
{
var remainingUncompressedBytes = Math.Min(remainingUncompressedData.Count, ProtocolUtility.MaxPacketSize);
// don't compress small packets; 80 bytes is typically a good cutoff
var compressedData = default(ArraySegment<byte>);
if (remainingUncompressedBytes > 80)
{
using var compressedStream = new MemoryStream();
// write CMF: 32K window + deflate algorithm
compressedStream.WriteByte(0x78);
// write FLG: maximum compression + checksum
compressedStream.WriteByte(0xDA);
using (var deflateStream = new DeflateStream(compressedStream, CompressionLevel.Optimal, leaveOpen: true))
deflateStream.Write(remainingUncompressedData.Array!, remainingUncompressedData.Offset, remainingUncompressedBytes);
// write Adler-32 checksum to stream
var checksum = ComputeAdler32Checksum(remainingUncompressedData.Array!, remainingUncompressedData.Offset, remainingUncompressedBytes);
compressedStream.WriteByte((byte) ((checksum >> 24) & 0xFF));
compressedStream.WriteByte((byte) ((checksum >> 16) & 0xFF));
compressedStream.WriteByte((byte) ((checksum >> 8) & 0xFF));
compressedStream.WriteByte((byte) (checksum & 0xFF));
if (!compressedStream.TryGetBuffer(out compressedData))
throw new InvalidOperationException("Couldn't get compressed stream buffer.");
}
var uncompressedLength = (uint) remainingUncompressedBytes;
if (compressedData.Array is null || compressedData.Count >= remainingUncompressedBytes)
{
// setting the length to 0 indicates sending uncompressed data
uncompressedLength = 0;
compressedData = remainingUncompressedData.Slice(0, remainingUncompressedBytes);
}
var buffer = new byte[compressedData.Count + 7];
SerializationUtility.WriteUInt32((uint) compressedData.Count, buffer, 0, 3);
buffer[3] = GetNextCompressedSequenceNumber();
SerializationUtility.WriteUInt32(uncompressedLength, buffer, 4, 3);
Buffer.BlockCopy(compressedData.Array!, compressedData.Offset, buffer, 7, compressedData.Count);
remainingUncompressedData = remainingUncompressedData.Slice(remainingUncompressedBytes);
return m_byteHandler!.WriteBytesAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), ioBehavior)
.ContinueWith(_ => remainingUncompressedData.Count == 0 ? default :
CompressAndWrite(remainingUncompressedData, ioBehavior));
}
private uint ComputeAdler32Checksum(byte[] data, int offset, int length)
{
int s1 = 1, s2 = 0;
for (var i = 0; i < length; i++)
{
s1 = (s1 + data[offset + i]) % 65521;
s2 = (s2 + s1) % 65521;
}
return (((uint) s2) << 16) | (uint) s1;
}
// CompressedByteHandler implements IByteHandler and delegates reading bytes back to the CompressedPayloadHandler class.
private sealed class CompressedByteHandler : IByteHandler
{
public CompressedByteHandler(CompressedPayloadHandler compressedPayloadHandler, ProtocolErrorBehavior protocolErrorBehavior)
{
m_compressedPayloadHandler = compressedPayloadHandler;
m_protocolErrorBehavior = protocolErrorBehavior;
}
public void Dispose()
{
}
public int RemainingTimeout
{
get => m_compressedPayloadHandler.ByteHandler.RemainingTimeout;
set => m_compressedPayloadHandler.ByteHandler.RemainingTimeout = value;
}
public ValueTask<int> ReadBytesAsync(Memory<byte> buffer, IOBehavior ioBehavior) =>
m_compressedPayloadHandler.ReadBytesAsync(buffer, m_protocolErrorBehavior, ioBehavior);
public ValueTask<int> WriteBytesAsync(ReadOnlyMemory<byte> data, IOBehavior ioBehavior) => throw new NotSupportedException();
readonly CompressedPayloadHandler m_compressedPayloadHandler;
readonly ProtocolErrorBehavior m_protocolErrorBehavior;
}
MemoryStream? m_uncompressedStream;
IByteHandler? m_uncompressedStreamByteHandler;
IByteHandler? m_byteHandler;
readonly BufferedByteReader m_bufferedByteReader;
readonly BufferedByteReader m_compressedBufferedByteReader;
byte m_compressedSequenceNumber;
byte m_uncompressedSequenceNumber;
ArraySegment<byte> m_remainingData;
bool m_isContinuationPacket;
}
}
| 44.546763
| 207
| 0.74354
|
[
"MIT"
] |
BoBiene/MySqlConnector
|
src/MySqlConnector/Protocol/Serialization/CompressedPayloadHandler.cs
| 12,384
|
C#
|
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace KLog.Models
{
// 可以通过向 ApplicationUser 类添加更多属性来为用户添加配置文件数据。若要了解详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=317594。
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// 请注意,authenticationType 必须与 CookieAuthenticationOptions.AuthenticationType 中定义的相应项匹配
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// 在此处添加自定义用户声明
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
| 33.272727
| 117
| 0.701275
|
[
"MIT"
] |
ihambert/KLog
|
KLog/WebTest/Models/IdentityModels.cs
| 1,232
|
C#
|
using Amazon.IdentityManagement;
using MountAnything;
using MountAws.Services.Core;
namespace MountAws.Services.Iam;
public class PoliciesHandler : PathHandler, IGetChildItemParameters<ChildPolicyParameters>
{
private readonly IAmazonIdentityManagementService _iam;
public static IItem CreateItem(ItemPath parentPath)
{
return new GenericContainerItem(parentPath, "policies",
"Navigate IAM policies");
}
public PoliciesHandler(ItemPath path, IPathHandlerContext context, IAmazonIdentityManagementService iam) : base(path, context)
{
_iam = iam;
}
protected override IItem? GetItemImpl()
{
return CreateItem(ParentPath);
}
protected override IEnumerable<IItem> GetChildItemsImpl()
{
return _iam.ListChildPolicyItems(Path, scope: GetChildItemParameters.Scope);
}
public ChildPolicyParameters GetChildItemParameters { get; set; } = new();
}
| 28.727273
| 130
| 0.729958
|
[
"Apache-2.0"
] |
andyalm/mount-aws
|
MountAws/Services/Iam/PoliciesHandler.cs
| 948
|
C#
|
/// Created by Ferdowsur Asif @ Tiny Giant Studios
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace MText
{
[DisallowMultipleComponent]
[AddComponentMenu("Modular 3D Text/Horizontal Selector")]
public class MText_UI_HorizontalSelector : MonoBehaviour
{
/// <summary>
/// The 3D text used to show the current value
/// </summary>
[Tooltip("The 3D text used to show the current value")]
public Modular3DText text;
[Space]
/// <summary>
/// If keyboard control is enabled, selected = you can control via selected
/// <para>This value will be controlled by list, if it is in one</para>
/// </summary>
[Tooltip("If keyboard control is enabled, selected = you can control via selected. \nThis value will be controlled by list, if it is in one")]
public bool selected = false;
/// <summary>
/// Can this be interacted with. If disabled, can't be selected in list
/// </summary>
[Tooltip("If keyboard control is enabled, selected = you can control via selected\nOr selected/deselected in a List")]
public bool interactable = true;
[Space]
/// <summary>
/// Available options for horizontal selector
/// </summary>
[Tooltip("Available options for horizontal selector")]
public List<string> options = new List<string>
(
new string[] { "Option 1", "Option 2", "Option 3" }
);
[SerializeField]
private int value;
public int Value
{
get { return value; }
set
{
this.value = value;
UpdateText();
onValueChangedEvent.Invoke();
}
}
[Space]
public bool keyboardControl = true;
public KeyCode increaseKey = KeyCode.LeftArrow;
public KeyCode decreaseKey = KeyCode.RightArrow;
[Header("Audio")]
public AudioClip valueChangeSoundEffect;
public AudioSource audioSource;
[Header("Events")]
public UnityEvent onValueChangedEvent;
public UnityEvent onSelectEvent;
private void Awake()
{
if (selected && keyboardControl) this.enabled = true;
else this.enabled = false;
}
private void Update()
{
if (!keyboardControl)
{
this.enabled = false;
return;
}
if (Input.GetKeyDown(increaseKey))
{
Decrease();
}
else if (Input.GetKeyDown(decreaseKey))
{
Increase();
}
}
/// <summary>
/// Increases the selected number.
/// <para>If the number is greater/equal(>=) than the options count, sets it to 0</para>
/// </summary>
public void Increase()
{
value++;
if (value >= options.Count)
value = 0;
UpdateText();
onValueChangedEvent.Invoke();
if (audioSource && valueChangeSoundEffect)
audioSource.PlayOneShot(valueChangeSoundEffect);
}
/// <summary>
/// Decreases the selected number.
/// <para>If the number is less than zero, sets it to max</para>
/// </summary>
public void Decrease()
{
value--;
if (value < 0)
value = options.Count - 1;
UpdateText();
onValueChangedEvent.Invoke();
if (audioSource && valueChangeSoundEffect)
audioSource.PlayOneShot(valueChangeSoundEffect);
}
/// <summary>
/// Updates current text to match the currently selected value
/// </summary>
public void UpdateText()
{
if (options.Count == 0 || value < 0 || options.Count <= value)
return;
if (text)
text.UpdateText(options[value]);
else
Debug.LogError("No text is attached to Horizontal selector: " + gameObject.name, gameObject);
}
/// <summary>
/// Selects/Deselects the component
/// </summary>
/// <param name="Bool">true = selected, false = deselected</param>
public void Focus(bool Bool)
{
selected = Bool;
if (selected && interactable)
{
onSelectEvent.Invoke();
if (keyboardControl) this.enabled = true;
}
else this.enabled = false;
}
}
}
| 28.323353
| 150
| 0.530655
|
[
"MIT"
] |
tongji-cdi/AR-Studio2
|
Assets/Tiny Giant Studio/Modular 3D Text/Scripts/MText_UI_HorizontalSelector.cs
| 4,732
|
C#
|
// Copyright 2015-2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Reflection;
namespace NATS.Client
{
/// <summary>
/// This class is used to setup all NATs client options.
/// </summary>
public sealed class Options
{
string url = null;
string[] servers = null;
bool noRandomize = false;
string name = null;
bool verbose = false;
bool pedantic = false;
bool useOldRequestStyle = false;
bool secure = false;
bool allowReconnect = true;
int maxReconnect = Defaults.MaxReconnect;
int reconnectWait = Defaults.ReconnectWait;
int pingInterval = Defaults.PingInterval;
int timeout = Defaults.Timeout;
internal X509Certificate2Collection certificates = null;
/// <summary>
/// Represents the method that will handle an event raised
/// when a connection is closed.
/// </summary>
public EventHandler<ConnEventArgs> ClosedEventHandler = null;
/// <summary>
/// Represents the method that will handle an event raised
/// whenever a new server has joined the cluster.
/// </summary>
public EventHandler<ConnEventArgs> ServerDiscoveredEventHandler = null;
/// <summary>
/// Represents the method that will handle an event raised
/// when a connection has been disconnected from a server.
/// </summary>
public EventHandler<ConnEventArgs> DisconnectedEventHandler = null;
/// <summary>
/// Represents the method that will handle an event raised
/// when a connection has reconnected to a server.
/// </summary>
public EventHandler<ConnEventArgs> ReconnectedEventHandler = null;
/// <summary>
/// Represents the method that will handle an event raised
/// when an error occurs out of band.
/// </summary>
public EventHandler<ErrEventArgs> AsyncErrorEventHandler = null;
internal int maxPingsOut = Defaults.MaxPingOut;
internal int subChanLen = 65536;
internal int subscriberDeliveryTaskCount = 0;
// Must be greater than 0.
internal int subscriptionBatchSize = 64;
internal string user;
internal string password;
internal string token;
// Options can only be publicly created through
// ConnectionFactory.GetDefaultOptions();
internal Options() { }
// Copy constructor
internal Options(Options o)
{
allowReconnect = o.allowReconnect;
AsyncErrorEventHandler = o.AsyncErrorEventHandler;
ClosedEventHandler = o.ClosedEventHandler;
ServerDiscoveredEventHandler = o.ServerDiscoveredEventHandler;
DisconnectedEventHandler = o.DisconnectedEventHandler;
maxPingsOut = o.maxPingsOut;
maxReconnect = o.maxReconnect;
name = o.name;
noRandomize = o.noRandomize;
pedantic = o.pedantic;
useOldRequestStyle = o.useOldRequestStyle;
pingInterval = o.pingInterval;
ReconnectedEventHandler = o.ReconnectedEventHandler;
reconnectWait = o.reconnectWait;
secure = o.secure;
user = o.user;
password = o.password;
token = o.token;
verbose = o.verbose;
subscriberDeliveryTaskCount = o.subscriberDeliveryTaskCount;
subscriptionBatchSize = o.subscriptionBatchSize;
if (o.servers != null)
{
servers = new string[o.servers.Length];
Array.Copy(o.servers, servers, o.servers.Length);
}
subChanLen = o.subChanLen;
timeout = o.timeout;
TLSRemoteCertificationValidationCallback = o.TLSRemoteCertificationValidationCallback;
url = o.url;
if (o.certificates != null)
{
certificates = new X509Certificate2Collection(o.certificates);
}
}
internal void processUrlString(string url)
{
if (url == null)
return;
string[] urls = url.Split(',');
for (int i = 0; i < urls.Length; i++)
{
urls[i] = urls[i].Trim();
}
servers = urls;
}
/// <summary>
/// Gets or sets the url used to connect to the NATs server.
/// </summary>
/// <remarks>
/// This may contain username/password information.
/// </remarks>
public string Url
{
get { return url; }
set { url = value; }
}
/// <summary>
/// Gets or sets the array of servers that the NATs client will connect to.
/// </summary>
/// <remarks>
/// The individual URLs may contain username/password information.
/// </remarks>
public string[] Servers
{
get { return servers; }
set { servers = value; }
}
/// <summary>
/// Gets or sets a value indicating whether or not the server chosen for connection
/// should not be selected randomly.
/// </summary>
public bool NoRandomize
{
get { return noRandomize; }
set { noRandomize = value; }
}
/// <summary>
/// Gets or sets the name of this client.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// Gets or sets a value indicating whether or not logging information should be verbose.
/// </summary>
public bool Verbose
{
get { return verbose; }
set { verbose = value; }
}
/// <summary>
/// This option is not used by the NATS Client.
/// </summary>
public bool Pedantic
{
get { return pedantic; }
set { pedantic = value; }
}
/// <summary>
/// Gets or sets a value indicating whether or not the old
/// request pattern should be used.
/// </summary>
/// <remarks>
/// The old request pattern involved a separate subscription
/// per request inbox. The new style (default) involves creating
/// a single inbox subscription per connection, upon the first
/// request, and mapping outbound requests over that one
/// subscription.
/// </remarks>
public bool UseOldRequestStyle
{
get { return useOldRequestStyle; }
set { useOldRequestStyle = value; }
}
/// <summary>
/// Get or sets a value indicating whether or not a secure connection (TLS)
/// should be made to NATS servers.
/// </summary>
public bool Secure
{
get { return secure; }
set { secure = value; }
}
/// <summary>
/// Gets or sets a value indicating whether or not an <see cref="IConnection"/> will attempt
/// to reconnect to the NATS server if a connection has been lost.
/// </summary>
public bool AllowReconnect
{
get { return allowReconnect; }
set { allowReconnect = value; }
}
/// <summary>
/// Set <see cref="Options.MaxReconnect"/> to this value for the client to attempt to
/// connect indefinitely.
/// </summary>
public static int ReconnectForever = -1;
/// <summary>
/// Gets or sets the maxmimum number of times a connection will
/// attempt to reconnect. To reconnect indefinitely set this value to
/// <see cref="Options.ReconnectForever"/>
/// </summary>
public int MaxReconnect
{
get { return maxReconnect; }
set { maxReconnect = value; }
}
/// <summary>
/// Gets or sets the amount of time, in milliseconds, the client will
/// wait before attempting a reconnection.
/// </summary>
public int ReconnectWait
{
get { return reconnectWait; }
set { reconnectWait = value; }
}
/// <summary>
/// Gets or sets the interval, in milliseconds, pings will be sent to the server.
/// </summary>
/// <remarks>
/// Take care to coordinate this value with the server's interval.
/// </remarks>
public int PingInterval
{
get { return pingInterval; }
set { pingInterval = value; }
}
/// <summary>
/// Gets or sets the timeout, in milliseconds, when connecting to a NATS server.
/// </summary>
public int Timeout
{
get { return timeout; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(
"Timeout must be zero or greater.");
}
timeout = value;
}
}
/// <summary>
/// Gets or sets the maximum number of outstanding pings before
/// terminating a connection.
/// </summary>
public int MaxPingsOut
{
get { return maxPingsOut; }
set { maxPingsOut = value; }
}
/// <summary>
/// Gets or sets the size of the subscriber channel, or number
/// of messages the subscriber will buffer internally.
/// </summary>
public int SubChannelLength
{
get { return subChanLen; }
set { subChanLen = value; }
}
/// <summary>
/// Gets or sets the user name used when connecting to the NATs server,
/// when not included directly in the URLs.
/// </summary>
public string User
{
get { return user; }
set { user = value; }
}
/// <summary>
/// Sets the user password used when connecting to the NATs server,
/// when not included directly in the URLs.
/// </summary>
public string Password
{
set { password = value; }
}
/// <summary>
/// Gets or sets the token used when connecting to the NATs server
/// when not included directly in the URLs.
/// </summary>
public string Token
{
get { return token; }
set { token = value; }
}
/// <summary>
/// Adds an X.509 certifcate from a file for use with a secure connection.
/// </summary>
/// <param name="fileName">Path to the certificate file to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="fileName"/> is <c>null</c>.</exception>
/// <exception cref="System.Security.Cryptography.CryptographicException">An error with the certificate
/// ocurred. For example:
/// <list>
/// <item>The certificate file does not exist.</item>
/// <item>The certificate is invalid.</item>
/// <item>The certificate's password is incorrect.</item></list></exception>
public void AddCertificate(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
X509Certificate2 cert = new X509Certificate2(fileName);
AddCertificate(cert);
}
/// <summary>
/// Adds an X.509 certifcate for use with a secure connection.
/// </summary>
/// <param name="certificate">An X.509 certificate represented as an <see cref="X509Certificate2"/> object.</param>
/// <exception cref="ArgumentNullException"><paramref name="certificate"/> is <c>null</c>.</exception>
/// <exception cref="System.Security.Cryptography.CryptographicException">An error with the certificate
/// ocurred. For example:
/// <list>
/// <item>The certificate file does not exist.</item>
/// <item>The certificate is invalid.</item>
/// <item>The certificate's password is incorrect.</item></list></exception>
public void AddCertificate(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException("certificate");
if (certificates == null)
certificates = new X509Certificate2Collection();
certificates.Add(certificate);
}
/// <summary>
/// Overrides the default NATS RemoteCertificationValidationCallback.
/// </summary>
/// <remarks>
/// The default callback simply checks if there were any protocol
/// errors. Overriding this callback is useful during testing, or accepting self
/// signed certificates.
/// </remarks>
public RemoteCertificateValidationCallback TLSRemoteCertificationValidationCallback;
/// <summary>
/// Gets or sets the number of long running tasks to deliver messages
/// to asynchronous subscribers. The default is zero (<c>0</c>) indicating each
/// asynchronous subscriber has its own channel and task created to
/// deliver messages.
/// </summary>
/// <remarks>
/// The default where each subscriber has a delivery task is very
/// performant, but does not scale well when large numbers of
/// subscribers are required in an application. Setting this value
/// will limit the number of subscriber channels to the specified number
/// of long running tasks. These tasks will process messages for ALL
/// asynchronous subscribers rather than one task for each subscriber.
/// Delivery order by subscriber is still guaranteed. The shared message
/// processing channels are still each bounded by the SubChannelLength
/// option. Note, slow subscriber errors will flag the last subscriber
/// processed in the tasks, which may not actually be the slowest subscriber.
/// </remarks>
public int SubscriberDeliveryTaskCount
{
get
{
return subscriberDeliveryTaskCount;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("SubscriberDeliveryTaskCount must be 0 or greater.");
}
subscriberDeliveryTaskCount = value;
}
}
/// <summary>
/// Gets or sets the batch size for calling subscription handlers.
/// </summary>
/// <remarks>
/// When delivering messages to the subscriber, the batch size determines
/// how many messages could be retrieved from the internal subscription
/// queue at one time. This can allow higher performance from a single
/// subscriber by avoiding the locking overhead of one-at-a-time
/// retrieval from the queue.
/// </remarks>
public int SubscriptionBatchSize
{
get { return subscriptionBatchSize; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException("value", "Subscription batch size must be greater than 0");
}
subscriptionBatchSize = value;
}
}
private void appendEventHandler(StringBuilder sb, String name, Delegate eh)
{
if (eh != null)
sb.AppendFormat("{0}={1};", name, eh.GetMethodInfo().Name);
else
sb.AppendFormat("{0}=null;", name);
}
/// <summary>
/// Returns a string representation of the
/// value of this Options instance.
/// </summary>
/// <returns>String value of this instance.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.AppendFormat("AllowReconnect={0};", allowReconnect);
appendEventHandler(sb, "AsyncErrorEventHandler", AsyncErrorEventHandler);
appendEventHandler(sb, "ClosedEventHandler", ClosedEventHandler);
appendEventHandler(sb, "DisconnectedEventHandler", DisconnectedEventHandler);
sb.AppendFormat("MaxPingsOut={0};", MaxPingsOut);
sb.AppendFormat("MaxReconnect={0};", MaxReconnect);
sb.AppendFormat("Name={0};", Name != null ? Name : "null");
sb.AppendFormat("NoRandomize={0};", NoRandomize);
sb.AppendFormat("Pendantic={0};", Pedantic);
sb.AppendFormat("UseOldRequestStyle={0}", UseOldRequestStyle);
sb.AppendFormat("PingInterval={0};", PingInterval);
sb.AppendFormat("ReconnectWait={0};", ReconnectWait);
sb.AppendFormat("Secure={0};", Secure);
sb.AppendFormat("User={0};", User);
sb.AppendFormat("Token={0};", Token);
sb.AppendFormat("SubscriberDeliveryTaskCount={0};", SubscriberDeliveryTaskCount);
sb.AppendFormat("SubscriptionBatchSize={0};", SubscriptionBatchSize);
if (Servers == null)
{
sb.AppendFormat("Servers=null;");
}
else
{
sb.Append("Servers={");
foreach (string s in servers)
{
sb.AppendFormat("[{0}]", s);
if (s != servers[servers.Length-1])
sb.AppendFormat(",");
}
sb.Append("}");
}
sb.AppendFormat("SubChannelLength={0};", SubChannelLength);
sb.AppendFormat("Timeout={0};", Timeout);
sb.AppendFormat("Pendantic={0}", Pedantic);
sb.Append("}");
return sb.ToString();
}
}
}
| 36.007648
| 123
| 0.562341
|
[
"BSD-2-Clause"
] |
BretGui/GB28181.Platform2016
|
NATS.Client/Options.cs
| 18,834
|
C#
|
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Windows.Forms;
namespace SAModel.SAMDL
{
static class Program
{
static internal string[] Arguments { get; set; }
public static MainForm primaryForm;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Arguments = args;
Application.EnableVisualStyles();
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
Application.SetCompatibleTextRenderingDefault(false);
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
primaryForm = new MainForm();
Application.Run(primaryForm);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (primaryForm != null)
{
Exception ex = (Exception)e.ExceptionObject;
string errDesc = "SAMDL has crashed with the following error:\n" + ex.GetType().Name + ".\n\n" +
"If you wish to report a bug, please include the following in your report:";
SAEditorCommon.ErrorDialog report = new SAEditorCommon.ErrorDialog("SAMDL", errDesc, ex.ToString());
DialogResult dgresult = report.ShowDialog(primaryForm);
switch (dgresult)
{
case DialogResult.Abort:
case DialogResult.OK:
Application.Exit();
break;
}
}
else
{
string logPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SA Tools", "SAMDL.log");
if (!Directory.Exists(Path.GetDirectoryName(logPath)))
Directory.CreateDirectory(Path.GetDirectoryName(logPath));
File.WriteAllText(logPath, e.ExceptionObject.ToString());
MessageBox.Show("Unhandled Exception " + e.ExceptionObject.GetType().Name + "\nLog file has been saved to:\n" + logPath + ".", "SAMDL Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
| 36.964912
| 197
| 0.713336
|
[
"MIT",
"BSD-3-Clause"
] |
X-Hax/sa_tools
|
SAMDL/Program.cs
| 2,109
|
C#
|
// NClass - Free class diagram editor
// Copyright (C) 2006-2009 Balazs Tihanyi
//
// This program 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.
//
// This program 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
// this program; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using NClass.Translations;
using NClass.Core;
namespace NClass.DiagramEditor.ClassDiagram
{
public sealed partial class DiagramDynamicMenu : DynamicMenu
{
static DiagramDynamicMenu _default = new DiagramDynamicMenu();
ToolStripMenuItem[] menuItems;
Diagram diagram = null;
private DiagramDynamicMenu()
{
InitializeComponent();
UpdateTexts();
menuItems = new ToolStripMenuItem[2] { mnuDiagram, mnuFormat };
}
public static DiagramDynamicMenu Default
{
get { return _default; }
}
public override IEnumerable<ToolStripMenuItem> GetMenuItems()
{
return menuItems;
}
public override ToolStrip GetToolStrip()
{
return elementsToolStrip;
}
public override void SetReference(IDocument document)
{
if (diagram != null)
{
diagram.SelectionChanged -= new EventHandler(diagram_SelectionChanged);
}
if (document == null)
{
diagram = null;
}
else
{
diagram = document as Diagram;
diagram.SelectionChanged += new EventHandler(diagram_SelectionChanged);
mnuNewStructure.Visible = diagram.Language.SupportsStructures;
mnuNewDelegate.Visible = diagram.Language.SupportsDelegates;
toolNewStructure.Visible = diagram.Language.SupportsStructures;
toolNewDelegate.Visible = diagram.Language.SupportsDelegates;
toolDelete.Enabled = diagram.HasSelectedElement;
}
}
private void diagram_SelectionChanged(object sender, EventArgs e)
{
toolDelete.Enabled = (diagram != null && diagram.HasSelectedElement);
}
private void UpdateTexts()
{
// Diagram menu
mnuDiagram.Text = Strings.MenuDiagram;
mnuAddNewElement.Text = Strings.MenuNew;
mnuNewClass.Text = Strings.MenuClass;
mnuNewStructure.Text = Strings.MenuStruct;
mnuNewInterface.Text = Strings.MenuInterface;
mnuNewEnum.Text = Strings.MenuEnum;
mnuNewDelegate.Text = Strings.MenuDelegate;
mnuNewComment.Text = Strings.MenuComment;
mnuNewAssociation.Text = Strings.MenuAssociation;
mnuNewComposition.Text = Strings.MenuComposition;
mnuNewAggregation.Text = Strings.MenuAggregation;
mnuNewGeneralization.Text = Strings.MenuGeneralization;
mnuNewRealization.Text = Strings.MenuRealization;
mnuNewDependency.Text = Strings.MenuDependency;
mnuNewNesting.Text = Strings.MenuNesting;
mnuNewCommentRelationship.Text = Strings.MenuCommentRelationship;
mnuMembersFormat.Text = Strings.MenuMembersFormat;
mnuShowType.Text = Strings.MenuType;
mnuShowParameters.Text = Strings.MenuParameters;
mnuShowParameterNames.Text = Strings.MenuParameterNames;
mnuShowInitialValue.Text = Strings.MenuInitialValue;
mnuGenerateCode.Text = Strings.MenuGenerateCode;
mnuSaveAsImage.Text = Strings.MenuSaveAsImage;
// Format menu
mnuFormat.Text = Strings.MenuFormat;
mnuAlign.Text = Strings.MenuAlign;
mnuAlignTop.Text = Strings.MenuAlignTop;
mnuAlignLeft.Text = Strings.MenuAlignLeft;
mnuAlignBottom.Text = Strings.MenuAlignBottom;
mnuAlignRight.Text = Strings.MenuAlignRight;
mnuAlignHorizontal.Text = Strings.MenuAlignHorizontal;
mnuAlignVertical.Text = Strings.MenuAlignVertical;
mnuMakeSameSize.Text = Strings.MenuMakeSameSize;
mnuSameWidth.Text = Strings.MenuSameWidth;
mnuSameHeight.Text = Strings.MenuSameHeight;
mnuSameSize.Text = Strings.MenuSameSize;
mnuAutoSize.Text = Strings.MenuAutoSize;
mnuAutoWidth.Text = Strings.MenuAutoWidth;
mnuAutoHeight.Text = Strings.MenuAutoHeight;
mnuCollapseAll.Text = Strings.MenuCollapseAll;
mnuExpandAll.Text = Strings.MenuExpandAll;
// Toolbar
toolNewClass.Text = Strings.AddNewClass;
toolNewStructure.Text = Strings.AddNewStructure;
toolNewInterface.Text = Strings.AddNewInterface;
toolNewEnum.Text = Strings.AddNewEnum;
toolNewDelegate.Text = Strings.AddNewDelegate;
toolNewComment.Text = Strings.AddNewComment;
toolNewAssociation.Text = Strings.AddNewAssociation;
toolNewComposition.Text = Strings.AddNewComposition;
toolNewAggregation.Text = Strings.AddNewAggregation;
toolNewGeneralization.Text = Strings.AddNewGeneralization;
toolNewRealization.Text = Strings.AddNewRealization;
toolNewDependency.Text = Strings.AddNewDependency;
toolNewNesting.Text = Strings.AddNewNesting;
toolNewCommentRelationship.Text = Strings.AddNewCommentRelationship;
toolDelete.Text = Strings.DeleteSelectedItems;
}
#region Event handlers
private void mnuDiagram_DropDownOpening(object sender, EventArgs e)
{
bool hasContent = (diagram != null && !diagram.IsEmpty);
mnuGenerateCode.Enabled = hasContent;
mnuSaveAsImage.Enabled = hasContent;
}
private void mnuNewClass_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.CreateShape(EntityType.Class);
}
private void mnuNewStructure_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.CreateShape(EntityType.Structure);
}
private void mnuNewInterface_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.CreateShape(EntityType.Interface);
}
private void mnuNewEnum_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.CreateShape(EntityType.Enum);
}
private void mnuNewDelegate_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.CreateShape(EntityType.Delegate);
}
private void mnuNewComment_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.CreateShape(EntityType.Comment);
}
private void mnuNewAssociation_Click(object sender, EventArgs e)
{
diagram.CreateConnection(RelationshipType.Association);
//TODO: toolNewAssociation.Checked = true;
}
private void mnuNewComposition_Click(object sender, EventArgs e)
{
diagram.CreateConnection(RelationshipType.Composition);
//toolNewComposition.Checked = true;
}
private void mnuNewAggregation_Click(object sender, EventArgs e)
{
diagram.CreateConnection(RelationshipType.Aggregation);
//toolNewAggregation.Checked = true;
}
private void mnuNewGeneralization_Click(object sender, EventArgs e)
{
diagram.CreateConnection(RelationshipType.Generalization);
//toolNewGeneralization.Checked = true;
}
private void mnuNewRealization_Click(object sender, EventArgs e)
{
diagram.CreateConnection(RelationshipType.Realization);
//toolNewRealization.Checked = true;
}
private void mnuNewDependency_Click(object sender, EventArgs e)
{
diagram.CreateConnection(RelationshipType.Dependency);
//toolNewDependency.Checked = true;
}
private void mnuNewNesting_Click(object sender, EventArgs e)
{
diagram.CreateConnection(RelationshipType.Nesting);
//toolNewNesting.Checked = true;
}
private void mnuNewCommentRelationship_Click(object sender, EventArgs e)
{
diagram.CreateConnection(RelationshipType.Comment);
//toolNewCommentRelationship.Checked = true;
}
private void mnuMembersFormat_DropDownOpening(object sender, EventArgs e)
{
mnuShowType.Checked = DiagramEditor.Settings.Default.ShowType;
mnuShowParameters.Checked = DiagramEditor.Settings.Default.ShowParameters;
mnuShowParameterNames.Checked = DiagramEditor.Settings.Default.ShowParameterNames;
mnuShowInitialValue.Checked = DiagramEditor.Settings.Default.ShowInitialValue;
}
private void mnuShowType_Click(object sender, EventArgs e)
{
DiagramEditor.Settings.Default.ShowType = ((ToolStripMenuItem) sender).Checked;
if (diagram != null)
diagram.Redraw();
}
private void mnuShowParameters_Click(object sender, EventArgs e)
{
DiagramEditor.Settings.Default.ShowParameters = ((ToolStripMenuItem) sender).Checked;
if (diagram != null)
diagram.Redraw();
}
private void mnuShowParameterNames_Click(object sender, EventArgs e)
{
DiagramEditor.Settings.Default.ShowParameterNames = ((ToolStripMenuItem) sender).Checked;
if (diagram != null)
diagram.Redraw();
}
private void mnuShowInitialValue_Click(object sender, EventArgs e)
{
DiagramEditor.Settings.Default.ShowInitialValue = ((ToolStripMenuItem) sender).Checked;
if (diagram != null)
diagram.Redraw();
}
private void mnuGenerateCode_Click(object sender, EventArgs e)
{
if (diagram != null && diagram.Project != null)
{
using (CodeGenerator.Dialog dialog = new CodeGenerator.Dialog())
{
try
{
dialog.ShowDialog(diagram.Project);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.UnknownError,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void mnuSaveAsImage_Click(object sender, EventArgs e)
{
if (diagram != null && !diagram.IsEmpty)
diagram.SaveAsImage();
}
private void mnuFormat_DropDownOpening(object sender, EventArgs e)
{
bool shapeSelected = (diagram != null && diagram.SelectedShapeCount >= 1);
bool multiselection = (diagram != null && diagram.SelectedShapeCount >= 2);
mnuAutoWidth.Enabled = shapeSelected;
mnuAutoHeight.Enabled = shapeSelected;
mnuAlign.Enabled = multiselection;
mnuMakeSameSize.Enabled = multiselection;
}
private void mnuAlignTop_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AlignTop();
}
private void mnuAlignLeft_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AlignLeft();
}
private void mnuAlignBottom_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AlignBottom();
}
private void mnuAlignRight_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AlignRight();
}
private void mnuAlignHorizontal_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AlignHorizontal();
}
private void mnuAlignVertical_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AlignVertical();
}
private void mnuSameWidth_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AdjustToSameWidth();
}
private void mnuSameHeight_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AdjustToSameHeight();
}
private void mnuSameSize_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AdjustToSameSize();
}
private void mnuAutoSize_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AutoSizeOfSelectedShapes();
}
private void mnuAutoWidth_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AutoWidthOfSelectedShapes();
}
private void mnuAutoHeight_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.AutoHeightOfSelectedShapes();
}
private void mnuCollapseAll_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.CollapseAll();
}
private void mnuExpandAll_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.ExpandAll();
}
private void toolDelete_Click(object sender, EventArgs e)
{
if (diagram != null)
diagram.DeleteSelectedElements();
}
#endregion
}
}
| 29.417284
| 92
| 0.742572
|
[
"Apache-2.0"
] |
jdm7dv/visual-studio
|
Common7/Tools/NClass_v2.04/src/DiagramEditor/ClassDiagram/DiagramDynamicMenu.cs
| 11,914
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using GamesToGo.Editor.Project;
using GamesToGo.Editor.Project.Elements;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osuTK;
namespace GamesToGo.Editor.Graphics
{
public class ElementSelectionDescriptor<T> : DropdownEnabledSelectionDescriptor<ElementSelectionDropdown<T>> where T : ProjectElement
{
private SpriteText text;
private Sprite image;
[Resolved]
private WorkingProject project { get; set; }
[BackgroundDependencyLoader]
private void load()
{
SelectionContainer.Add(new FillFlowContainer
{
AutoSizeAxes = Axes.X,
Direction = FillDirection.Horizontal,
Height = 25,
Spacing = new Vector2(4),
Children = new Drawable[]
{
new Container
{
Size = new Vector2(25),
Child = image = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
},
},
text = new SpriteText
{
Font = FontUsage.Default.With(size: 25),
},
},
});
Current.BindValueChanged(v =>
{
ProjectElement element = project.ProjectElements.FirstOrDefault(e => e.ID == v.NewValue);
if (!(element is T))
{
if (v.NewValue != null)
throw new ArgumentException(
$"An argument looking for an element had it's result set to a non existent element or an argument type different to {typeof(T)}",
nameof(v.NewValue));
return;
}
text.Text = element.Name?.Value ?? string.Empty;
image.Texture = element.GetImageWithFallback().Texture;
}, true);
}
}
public class ElementSelectionDropdown<T> : ArgumentDropdown where T : ProjectElement
{
[Resolved]
private WorkingProject project { get; set; }
public ElementSelectionDropdown(Bindable<int?> target) : base(target)
{
}
protected override IEnumerable<ArgumentItem> CreateItems()
{
IEnumerable<ProjectElement> elements = new ProjectElement[0];
if (typeof(T) == typeof(Card))
elements = project.ProjectCards;
if (typeof(T) == typeof(Token))
elements = project.ProjectTokens;
if (typeof(T) == typeof(Board))
elements = project.ProjectBoards;
if (typeof(T) == typeof(Tile))
elements = project.ProjectTiles;
foreach (var element in elements)
{
yield return new ElementItem(element);
}
}
private class ElementItem : ArgumentItem
{
private readonly ProjectElement value;
private Sprite image;
public ElementItem(ProjectElement value) : base(value.ID)
{
this.value = value;
}
[BackgroundDependencyLoader]
private void load()
{
Add(new FillFlowContainer
{
AutoSizeAxes = Axes.X,
Direction = FillDirection.Horizontal,
Height = ARGUMENT_HEIGHT,
Spacing = new Vector2(4),
Children = new Drawable[]
{
new Container
{
Size = new Vector2(ARGUMENT_HEIGHT),
Child = image = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fit,
},
},
new SpriteText
{
Text = value.Name.Value,
Font = FontUsage.Default.With(size: ARGUMENT_HEIGHT),
},
},
});
image.Texture = value.GetImageWithFallback().Texture;
}
}
}
}
| 33.292517
| 157
| 0.469555
|
[
"MIT"
] |
ColdVolcano/GamesToGo
|
GamesToGo.Editor/Graphics/ElementSelectionDescriptor.cs
| 4,896
|
C#
|
using System;
namespace _01._Bank_Account
{
public class StartUp
{
public static void Main()
{
BankAccount acc = new BankAccount();
acc.Id = 1;
acc.Balance = 15;
Console.WriteLine($"Account {acc.Id}, balance {acc.Balance}");
}
}
}
| 17.722222
| 74
| 0.517241
|
[
"MIT"
] |
GitHarr/SoftUni
|
Homework/C#Fundamentals/C# OOP Basics/1. Defining Classes/Lab/01. Bank Account/StartUp.cs
| 321
|
C#
|
namespace Ryujinx.HLE.HOS.Services.Hid
{
public struct HidControllerSixAxisLayout
{
public HidCommonEntriesHeader Header;
public Array17<HidControllerSixAxisEntry> Entries;
}
}
| 25.5
| 58
| 0.735294
|
[
"MIT"
] |
Mattscreative/Ryujinx
|
Ryujinx.HLE/HOS/Services/Hid/Types/SharedMem/Npad/HidControllerSixAxisLayout.cs
| 204
|
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.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract partial class AbstractTriviaDataFactory
{
private const int SpaceCacheSize = 10;
private const int LineBreakCacheSize = 5;
private const int IndentationLevelCacheSize = 20;
protected readonly TreeData TreeInfo;
protected readonly SyntaxFormattingOptions Options;
private readonly Whitespace[] _spaces;
private readonly Whitespace?[,] _whitespaces = new Whitespace[LineBreakCacheSize, IndentationLevelCacheSize];
protected AbstractTriviaDataFactory(TreeData treeInfo, SyntaxFormattingOptions options)
{
Contract.ThrowIfNull(treeInfo);
TreeInfo = treeInfo;
Options = options;
_spaces = new Whitespace[SpaceCacheSize];
for (var i = 0; i < SpaceCacheSize; i++)
{
_spaces[i] = new Whitespace(Options, space: i, elastic: false, language: treeInfo.Root.Language);
}
}
protected TriviaData GetSpaceTriviaData(int space, bool elastic = false)
{
Contract.ThrowIfFalse(space >= 0);
// if result has elastic trivia in them, never use cache
if (elastic)
{
return new Whitespace(this.Options, space, elastic: true, language: this.TreeInfo.Root.Language);
}
if (space < SpaceCacheSize)
{
return _spaces[space];
}
// create a new space
return new Whitespace(this.Options, space, elastic: false, language: this.TreeInfo.Root.Language);
}
protected TriviaData GetWhitespaceTriviaData(int lineBreaks, int indentation, bool useTriviaAsItIs, bool elastic)
{
Contract.ThrowIfFalse(lineBreaks >= 0);
Contract.ThrowIfFalse(indentation >= 0);
// we can use cache
// #1. if whitespace trivia don't have any elastic trivia and
// #2. analysis (Item1) didn't find anything preventing us from using cache such as trailing whitespace before new line
// #3. number of line breaks (Item2) are under cache capacity (line breaks)
// #4. indentation (Item3) is aligned to indentation level
var canUseCache = !elastic &&
useTriviaAsItIs &&
lineBreaks > 0 &&
lineBreaks <= LineBreakCacheSize &&
indentation % Options.IndentationSize == 0;
if (canUseCache)
{
var indentationLevel = indentation / Options.IndentationSize;
if (indentationLevel < IndentationLevelCacheSize)
{
var lineIndex = lineBreaks - 1;
EnsureWhitespaceTriviaInfo(lineIndex, indentationLevel);
return _whitespaces[lineIndex, indentationLevel]!;
}
}
return
useTriviaAsItIs ?
new Whitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language) :
new ModifiedWhitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language);
}
private void EnsureWhitespaceTriviaInfo(int lineIndex, int indentationLevel)
{
Contract.ThrowIfFalse(lineIndex is >= 0 and < LineBreakCacheSize);
Contract.ThrowIfFalse(indentationLevel >= 0 && indentationLevel < _whitespaces.Length / _whitespaces.Rank);
// set up caches
if (_whitespaces[lineIndex, indentationLevel] == null)
{
var indentation = indentationLevel * Options.IndentationSize;
var triviaInfo = new Whitespace(Options, lineBreaks: lineIndex + 1, indentation: indentation, elastic: false, language: this.TreeInfo.Root.Language);
Interlocked.CompareExchange(ref _whitespaces[lineIndex, indentationLevel], triviaInfo, null);
}
}
public abstract TriviaData CreateLeadingTrivia(SyntaxToken token);
public abstract TriviaData CreateTrailingTrivia(SyntaxToken token);
public abstract TriviaData Create(SyntaxToken token1, SyntaxToken token2);
}
}
| 43.12037
| 165
| 0.622289
|
[
"MIT"
] |
AlexanderSemenyak/roslyn
|
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.cs
| 4,659
|
C#
|
using UnityEngine;
namespace SanAndreasUnity.Behaviours.Peds.States
{
public interface IPedState : Utilities.IState {
/// <summary> Called at the end of Update(). </summary>
void PostUpdateState ();
//void OnCollision(Collision info);
void OnButtonPressed(string buttonName);
void OnFireButtonPressed();
void OnAimButtonPressed();
void OnSubmitPressed ();
void OnJumpPressed ();
void OnCrouchButtonPressed ();
void OnNextWeaponButtonPressed();
void OnPreviousWeaponButtonPressed();
void OnFlyButtonPressed();
void OnFlyThroughButtonPressed();
/// <summary> Called when server sends a message that ped state has changed. </summary>
void OnSwitchedStateByServer(byte[] data);
/// <summary> Called when state is switched on server. The returned data will be available on client
/// when the state gets activated. </summary>
byte[] GetAdditionalNetworkData();
void OnChangedWeaponByServer(int newSlot);
void OnWeaponFiredFromServer(Weapon weapon, Vector3 firePos);
}
}
| 27.567568
| 103
| 0.74902
|
[
"MIT"
] |
alexandrus21a/SanAndreasUnity
|
Assets/Scripts/Behaviours/Ped/States/IPedState.cs
| 1,020
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Editor
{
/// <summary>
/// Custom property drawer for <see cref="Microsoft.MixedReality.Toolkit.PrefabAttribute"/> decorated <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> values rendered in the inspector.
/// </summary>
[CustomPropertyDrawer(typeof(PrefabAttribute))]
public class PrefabPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var prefabAttribute = (PrefabAttribute)attribute;
if (prefabAttribute != null &&
property.propertyType == SerializedPropertyType.ObjectReference &&
(property.objectReferenceValue is GameObject || property.objectReferenceValue == null))
{
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(position, property);
if (!EditorGUI.EndChangeCheck()) { return; }
if (property.objectReferenceValue == null) { return; }
if (PrefabUtility.GetPrefabAssetType(property.objectReferenceValue) == PrefabAssetType.NotAPrefab)
{
property.objectReferenceValue = null;
Debug.LogWarning("Assigned GameObject must be a prefab.");
}
}
else
{
EditorGUI.LabelField(position, label.text, "Use PrefabAttribute with GameObject fields only.");
}
}
}
}
| 42.682927
| 225
| 0.640571
|
[
"MIT"
] |
1ft-seabass/hololens2-work-sample-202101
|
Assets/MRTK/Core/Inspectors/PropertyDrawers/PrefabPropertyDrawer.cs
| 1,750
|
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 medialive-2017-10-14.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.MediaLive.Model
{
/// <summary>
/// Container for the parameters to the CreateInput operation.
/// Create an input
/// </summary>
public partial class CreateInputRequest : AmazonMediaLiveRequest
{
private List<InputDestinationRequest> _destinations = new List<InputDestinationRequest>();
private List<string> _inputSecurityGroups = new List<string>();
private List<MediaConnectFlowRequest> _mediaConnectFlows = new List<MediaConnectFlowRequest>();
private string _name;
private string _requestId;
private string _roleArn;
private List<InputSourceRequest> _sources = new List<InputSourceRequest>();
private Dictionary<string, string> _tags = new Dictionary<string, string>();
private InputType _type;
private InputVpcRequest _vpc;
/// <summary>
/// Gets and sets the property Destinations. Destination settings for PUSH type inputs.
/// </summary>
public List<InputDestinationRequest> Destinations
{
get { return this._destinations; }
set { this._destinations = value; }
}
// Check to see if Destinations property is set
internal bool IsSetDestinations()
{
return this._destinations != null && this._destinations.Count > 0;
}
/// <summary>
/// Gets and sets the property InputSecurityGroups. A list of security groups referenced
/// by IDs to attach to the input.
/// </summary>
public List<string> InputSecurityGroups
{
get { return this._inputSecurityGroups; }
set { this._inputSecurityGroups = value; }
}
// Check to see if InputSecurityGroups property is set
internal bool IsSetInputSecurityGroups()
{
return this._inputSecurityGroups != null && this._inputSecurityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property MediaConnectFlows. A list of the MediaConnect Flows that
/// you want to use in this input. You can specify as few as oneFlow and presently, as
/// many as two. The only requirement is when you have more than one is that each Flow
/// is in aseparate Availability Zone as this ensures your EML input is redundant to AZ
/// issues.
/// </summary>
public List<MediaConnectFlowRequest> MediaConnectFlows
{
get { return this._mediaConnectFlows; }
set { this._mediaConnectFlows = value; }
}
// Check to see if MediaConnectFlows property is set
internal bool IsSetMediaConnectFlows()
{
return this._mediaConnectFlows != null && this._mediaConnectFlows.Count > 0;
}
/// <summary>
/// Gets and sets the property Name. Name of the input.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property RequestId. Unique identifier of the request to ensure the
/// request is handledexactly once in case of retries.
/// </summary>
public string RequestId
{
get { return this._requestId; }
set { this._requestId = value; }
}
// Check to see if RequestId property is set
internal bool IsSetRequestId()
{
return this._requestId != null;
}
/// <summary>
/// Gets and sets the property RoleArn. The Amazon Resource Name (ARN) of the role this
/// input assumes during and after creation.
/// </summary>
public string RoleArn
{
get { return this._roleArn; }
set { this._roleArn = value; }
}
// Check to see if RoleArn property is set
internal bool IsSetRoleArn()
{
return this._roleArn != null;
}
/// <summary>
/// Gets and sets the property Sources. The source URLs for a PULL-type input. Every PULL
/// type input needsexactly two source URLs for redundancy.Only specify sources for PULL
/// type Inputs. Leave Destinations empty.
/// </summary>
public List<InputSourceRequest> Sources
{
get { return this._sources; }
set { this._sources = value; }
}
// Check to see if Sources property is set
internal bool IsSetSources()
{
return this._sources != null && this._sources.Count > 0;
}
/// <summary>
/// Gets and sets the property Tags. A collection of key-value pairs.
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property Type.
/// </summary>
public InputType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
/// <summary>
/// Gets and sets the property Vpc.
/// </summary>
public InputVpcRequest Vpc
{
get { return this._vpc; }
set { this._vpc = value; }
}
// Check to see if Vpc property is set
internal bool IsSetVpc()
{
return this._vpc != null;
}
}
}
| 33.043478
| 107
| 0.590789
|
[
"Apache-2.0"
] |
FoxBearBear/aws-sdk-net
|
sdk/src/Services/MediaLive/Generated/Model/CreateInputRequest.cs
| 6,840
|
C#
|
using UnityEngine;
using UnityEngine.Events;
namespace FrancoisSauce.Scripts.FSEvents.SO
{
/// <summary>
/// Implementation of <see cref="UnityEvent<int>"/> used in <see cref="FSIntEventSO"/>
/// </summary>
[System.Serializable]
public class FSIntEvent : UnityEvent<int>
{
}
/// <inheritdoc cref="FSOneArgumentEventSO{T}>"/>
[CreateAssetMenu(fileName = "FSIntEvent", menuName = "FSEvents/FSIntEvent", order = 1)]
public class FSIntEventSO : FSOneArgumentEventSO<int>
{
}
}
| 27.736842
| 91
| 0.664137
|
[
"MIT"
] |
aFranchon/FrancoisSauce
|
Assets/____FrancoisSauce/Scripts/___FSEvents/SO/FSIntEventSO.cs
| 529
|
C#
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type SharedInsightRequest.
/// </summary>
public partial class SharedInsightRequest : BaseRequest, ISharedInsightRequest
{
/// <summary>
/// Constructs a new SharedInsightRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public SharedInsightRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified SharedInsight using POST.
/// </summary>
/// <param name="sharedInsightToCreate">The SharedInsight to create.</param>
/// <returns>The created SharedInsight.</returns>
public System.Threading.Tasks.Task<SharedInsight> CreateAsync(SharedInsight sharedInsightToCreate)
{
return this.CreateAsync(sharedInsightToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified SharedInsight using POST.
/// </summary>
/// <param name="sharedInsightToCreate">The SharedInsight to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created SharedInsight.</returns>
public async System.Threading.Tasks.Task<SharedInsight> CreateAsync(SharedInsight sharedInsightToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<SharedInsight>(sharedInsightToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified SharedInsight.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified SharedInsight.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<SharedInsight>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified SharedInsight.
/// </summary>
/// <returns>The SharedInsight.</returns>
public System.Threading.Tasks.Task<SharedInsight> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified SharedInsight.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The SharedInsight.</returns>
public async System.Threading.Tasks.Task<SharedInsight> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<SharedInsight>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified SharedInsight using PATCH.
/// </summary>
/// <param name="sharedInsightToUpdate">The SharedInsight to update.</param>
/// <returns>The updated SharedInsight.</returns>
public System.Threading.Tasks.Task<SharedInsight> UpdateAsync(SharedInsight sharedInsightToUpdate)
{
return this.UpdateAsync(sharedInsightToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified SharedInsight using PATCH.
/// </summary>
/// <param name="sharedInsightToUpdate">The SharedInsight to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated SharedInsight.</returns>
public async System.Threading.Tasks.Task<SharedInsight> UpdateAsync(SharedInsight sharedInsightToUpdate, CancellationToken cancellationToken)
{
if (sharedInsightToUpdate.AdditionalData != null)
{
if (sharedInsightToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) ||
sharedInsightToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode))
{
throw new ClientException(
new Error
{
Code = GeneratedErrorConstants.Codes.NotAllowed,
Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, sharedInsightToUpdate.GetType().Name)
});
}
}
if (sharedInsightToUpdate.AdditionalData != null)
{
if (sharedInsightToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) ||
sharedInsightToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode))
{
throw new ClientException(
new Error
{
Code = GeneratedErrorConstants.Codes.NotAllowed,
Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, sharedInsightToUpdate.GetType().Name)
});
}
}
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<SharedInsight>(sharedInsightToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public ISharedInsightRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public ISharedInsightRequest Expand(Expression<Func<SharedInsight, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public ISharedInsightRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public ISharedInsightRequest Select(Expression<Func<SharedInsight, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="sharedInsightToInitialize">The <see cref="SharedInsight"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(SharedInsight sharedInsightToInitialize)
{
}
}
}
| 43.042194
| 153
| 0.613469
|
[
"MIT"
] |
OfficeGlobal/msgraph-beta-sdk-dotnet
|
src/Microsoft.Graph/Requests/Generated/SharedInsightRequest.cs
| 10,201
|
C#
|
using System;
using System.IO;
namespace GradeBook
{
public class DiskBook : Book
{
public DiskBook(string name) : base(name)
{
}
public override event GradeAddedDelegate GradeAdded;
public override void AddGrade(double grade)
{
using (var streamWriter = File.AppendText($"{Name}.txt"))
{
streamWriter.WriteLine(grade);
if (GradeAdded != null)
{
GradeAdded(this, new EventArgs());
}
// streamWriter.Dispose(); // Liberar o limpiar
}
}
public override Statistics GetStatistics()
{
var result = new Statistics();
using (var reader = File.OpenText($"{Name}.txt"))
{
var line = reader.ReadLine();
while (line != null)
{
var number = double.Parse(line);
result.Add(number);
line = reader.ReadLine();
}
}
return result;
}
}
}
| 25.266667
| 69
| 0.456464
|
[
"MIT"
] |
yrrodriguezb/NetCore-3.1.201
|
Fundamentals/1. OOP/DiskBook.cs
| 1,137
|
C#
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Kelary.Report")]
[assembly: AssemblyDescription("Kelary reporting WPF components")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kelary")]
[assembly: AssemblyProduct("Kelary Report")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c049f0c5-a5e5-4ec0-ad75-07bc9bcf3970")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.714286
| 84
| 0.748339
|
[
"MIT"
] |
vnau/Kelary.Report
|
Kelary.Report/Properties/AssemblyInfo.cs
| 1,358
|
C#
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityType.cs.tt
namespace Microsoft.Graph.ManagedTenants
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
/// <summary>
/// The type Managed Tenant.
/// </summary>
public partial class ManagedTenant : Microsoft.Graph.Entity
{
/// <summary>
/// Gets or sets aggregated policy compliances.
/// Aggregate view of device compliance policies across managed tenants.
/// </summary>
[JsonPropertyName("aggregatedPolicyCompliances")]
public IManagedTenantAggregatedPolicyCompliancesCollectionPage AggregatedPolicyCompliances { get; set; }
/// <summary>
/// Gets or sets aggregatedPolicyCompliancesNextLink.
/// </summary>
[JsonPropertyName("aggregatedPolicyCompliances@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string AggregatedPolicyCompliancesNextLink { get; set; }
/// <summary>
/// Gets or sets cloud pc connections.
/// The collection of cloud PC connections across managed tenants.
/// </summary>
[JsonPropertyName("cloudPcConnections")]
public IManagedTenantCloudPcConnectionsCollectionPage CloudPcConnections { get; set; }
/// <summary>
/// Gets or sets cloudPcConnectionsNextLink.
/// </summary>
[JsonPropertyName("cloudPcConnections@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string CloudPcConnectionsNextLink { get; set; }
/// <summary>
/// Gets or sets cloud pc devices.
/// The collection of cloud PC devices across managed tenants.
/// </summary>
[JsonPropertyName("cloudPcDevices")]
public IManagedTenantCloudPcDevicesCollectionPage CloudPcDevices { get; set; }
/// <summary>
/// Gets or sets cloudPcDevicesNextLink.
/// </summary>
[JsonPropertyName("cloudPcDevices@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string CloudPcDevicesNextLink { get; set; }
/// <summary>
/// Gets or sets cloud pcs overview.
/// Overview of cloud PC information across managed tenants.
/// </summary>
[JsonPropertyName("cloudPcsOverview")]
public IManagedTenantCloudPcsOverviewCollectionPage CloudPcsOverview { get; set; }
/// <summary>
/// Gets or sets cloudPcsOverviewNextLink.
/// </summary>
[JsonPropertyName("cloudPcsOverview@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string CloudPcsOverviewNextLink { get; set; }
/// <summary>
/// Gets or sets conditional access policy coverages.
/// Aggregate view of conditional access policy coverage across managed tenants.
/// </summary>
[JsonPropertyName("conditionalAccessPolicyCoverages")]
public IManagedTenantConditionalAccessPolicyCoveragesCollectionPage ConditionalAccessPolicyCoverages { get; set; }
/// <summary>
/// Gets or sets conditionalAccessPolicyCoveragesNextLink.
/// </summary>
[JsonPropertyName("conditionalAccessPolicyCoverages@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ConditionalAccessPolicyCoveragesNextLink { get; set; }
/// <summary>
/// Gets or sets credential user registrations summaries.
/// Summary information for user registration for multi-factor authentication and self service password reset across managed tenants.
/// </summary>
[JsonPropertyName("credentialUserRegistrationsSummaries")]
public IManagedTenantCredentialUserRegistrationsSummariesCollectionPage CredentialUserRegistrationsSummaries { get; set; }
/// <summary>
/// Gets or sets credentialUserRegistrationsSummariesNextLink.
/// </summary>
[JsonPropertyName("credentialUserRegistrationsSummaries@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string CredentialUserRegistrationsSummariesNextLink { get; set; }
/// <summary>
/// Gets or sets device compliance policy setting state summaries.
/// Summary information for device compliance policy setting states across managed tenants.
/// </summary>
[JsonPropertyName("deviceCompliancePolicySettingStateSummaries")]
public IManagedTenantDeviceCompliancePolicySettingStateSummariesCollectionPage DeviceCompliancePolicySettingStateSummaries { get; set; }
/// <summary>
/// Gets or sets deviceCompliancePolicySettingStateSummariesNextLink.
/// </summary>
[JsonPropertyName("deviceCompliancePolicySettingStateSummaries@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string DeviceCompliancePolicySettingStateSummariesNextLink { get; set; }
/// <summary>
/// Gets or sets managed device compliances.
/// The collection of compliance for managed devices across managed tenants.
/// </summary>
[JsonPropertyName("managedDeviceCompliances")]
public IManagedTenantManagedDeviceCompliancesCollectionPage ManagedDeviceCompliances { get; set; }
/// <summary>
/// Gets or sets managedDeviceCompliancesNextLink.
/// </summary>
[JsonPropertyName("managedDeviceCompliances@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagedDeviceCompliancesNextLink { get; set; }
/// <summary>
/// Gets or sets managed device compliance trends.
/// Trend insights for device compliance across managed tenants.
/// </summary>
[JsonPropertyName("managedDeviceComplianceTrends")]
public IManagedTenantManagedDeviceComplianceTrendsCollectionPage ManagedDeviceComplianceTrends { get; set; }
/// <summary>
/// Gets or sets managedDeviceComplianceTrendsNextLink.
/// </summary>
[JsonPropertyName("managedDeviceComplianceTrends@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagedDeviceComplianceTrendsNextLink { get; set; }
/// <summary>
/// Gets or sets management actions.
/// The collection of baseline management actions across managed tenants.
/// </summary>
[JsonPropertyName("managementActions")]
public IManagedTenantManagementActionsCollectionPage ManagementActions { get; set; }
/// <summary>
/// Gets or sets managementActionsNextLink.
/// </summary>
[JsonPropertyName("managementActions@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagementActionsNextLink { get; set; }
/// <summary>
/// Gets or sets management action tenant deployment statuses.
/// The tenant level status of management actions across managed tenants.
/// </summary>
[JsonPropertyName("managementActionTenantDeploymentStatuses")]
public IManagedTenantManagementActionTenantDeploymentStatusesCollectionPage ManagementActionTenantDeploymentStatuses { get; set; }
/// <summary>
/// Gets or sets managementActionTenantDeploymentStatusesNextLink.
/// </summary>
[JsonPropertyName("managementActionTenantDeploymentStatuses@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagementActionTenantDeploymentStatusesNextLink { get; set; }
/// <summary>
/// Gets or sets management intents.
/// The collection of baseline management intents across managed tenants.
/// </summary>
[JsonPropertyName("managementIntents")]
public IManagedTenantManagementIntentsCollectionPage ManagementIntents { get; set; }
/// <summary>
/// Gets or sets managementIntentsNextLink.
/// </summary>
[JsonPropertyName("managementIntents@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagementIntentsNextLink { get; set; }
/// <summary>
/// Gets or sets management template collections.
/// </summary>
[JsonPropertyName("managementTemplateCollections")]
public IManagedTenantManagementTemplateCollectionsCollectionPage ManagementTemplateCollections { get; set; }
/// <summary>
/// Gets or sets managementTemplateCollectionsNextLink.
/// </summary>
[JsonPropertyName("managementTemplateCollections@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagementTemplateCollectionsNextLink { get; set; }
/// <summary>
/// Gets or sets management templates.
/// The collection of baseline management templates across managed tenants.
/// </summary>
[JsonPropertyName("managementTemplates")]
public IManagedTenantManagementTemplatesCollectionPage ManagementTemplates { get; set; }
/// <summary>
/// Gets or sets managementTemplatesNextLink.
/// </summary>
[JsonPropertyName("managementTemplates@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagementTemplatesNextLink { get; set; }
/// <summary>
/// Gets or sets management template steps.
/// </summary>
[JsonPropertyName("managementTemplateSteps")]
public IManagedTenantManagementTemplateStepsCollectionPage ManagementTemplateSteps { get; set; }
/// <summary>
/// Gets or sets managementTemplateStepsNextLink.
/// </summary>
[JsonPropertyName("managementTemplateSteps@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagementTemplateStepsNextLink { get; set; }
/// <summary>
/// Gets or sets management template step versions.
/// </summary>
[JsonPropertyName("managementTemplateStepVersions")]
public IManagedTenantManagementTemplateStepVersionsCollectionPage ManagementTemplateStepVersions { get; set; }
/// <summary>
/// Gets or sets managementTemplateStepVersionsNextLink.
/// </summary>
[JsonPropertyName("managementTemplateStepVersions@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string ManagementTemplateStepVersionsNextLink { get; set; }
/// <summary>
/// Gets or sets tenant groups.
/// The collection of a logical grouping of managed tenants used by the multi-tenant management platform.
/// </summary>
[JsonPropertyName("tenantGroups")]
public IManagedTenantTenantGroupsCollectionPage TenantGroups { get; set; }
/// <summary>
/// Gets or sets tenantGroupsNextLink.
/// </summary>
[JsonPropertyName("tenantGroups@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string TenantGroupsNextLink { get; set; }
/// <summary>
/// Gets or sets tenants.
/// The collection of tenants associated with the managing entity.
/// </summary>
[JsonPropertyName("tenants")]
public IManagedTenantTenantsCollectionPage Tenants { get; set; }
/// <summary>
/// Gets or sets tenantsNextLink.
/// </summary>
[JsonPropertyName("tenants@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string TenantsNextLink { get; set; }
/// <summary>
/// Gets or sets tenants customized information.
/// The collection of tenant level customized information across managed tenants.
/// </summary>
[JsonPropertyName("tenantsCustomizedInformation")]
public IManagedTenantTenantsCustomizedInformationCollectionPage TenantsCustomizedInformation { get; set; }
/// <summary>
/// Gets or sets tenantsCustomizedInformationNextLink.
/// </summary>
[JsonPropertyName("tenantsCustomizedInformation@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string TenantsCustomizedInformationNextLink { get; set; }
/// <summary>
/// Gets or sets tenants detailed information.
/// The collection tenant level detailed information across managed tenants.
/// </summary>
[JsonPropertyName("tenantsDetailedInformation")]
public IManagedTenantTenantsDetailedInformationCollectionPage TenantsDetailedInformation { get; set; }
/// <summary>
/// Gets or sets tenantsDetailedInformationNextLink.
/// </summary>
[JsonPropertyName("tenantsDetailedInformation@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string TenantsDetailedInformationNextLink { get; set; }
/// <summary>
/// Gets or sets tenant tags.
/// The collection of tenant tags across managed tenants.
/// </summary>
[JsonPropertyName("tenantTags")]
public IManagedTenantTenantTagsCollectionPage TenantTags { get; set; }
/// <summary>
/// Gets or sets tenantTagsNextLink.
/// </summary>
[JsonPropertyName("tenantTags@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string TenantTagsNextLink { get; set; }
/// <summary>
/// Gets or sets windows device malware states.
/// The state of malware for Windows devices, registered with Microsoft Endpoint Manager, across managed tenants.
/// </summary>
[JsonPropertyName("windowsDeviceMalwareStates")]
public IManagedTenantWindowsDeviceMalwareStatesCollectionPage WindowsDeviceMalwareStates { get; set; }
/// <summary>
/// Gets or sets windowsDeviceMalwareStatesNextLink.
/// </summary>
[JsonPropertyName("windowsDeviceMalwareStates@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string WindowsDeviceMalwareStatesNextLink { get; set; }
/// <summary>
/// Gets or sets windows protection states.
/// The protection state for Windows devices, registered with Microsoft Endpoint Manager, across managed tenants.
/// </summary>
[JsonPropertyName("windowsProtectionStates")]
public IManagedTenantWindowsProtectionStatesCollectionPage WindowsProtectionStates { get; set; }
/// <summary>
/// Gets or sets windowsProtectionStatesNextLink.
/// </summary>
[JsonPropertyName("windowsProtectionStates@odata.nextLink")]
[JsonConverter(typeof(NextLinkConverter))]
public string WindowsProtectionStatesNextLink { get; set; }
}
}
| 44.663768
| 153
| 0.664287
|
[
"MIT"
] |
microsoftgraph/msgraph-beta-sdk-dotnet
|
src/Microsoft.Graph/Generated/managedtenants/model/ManagedTenant.cs
| 15,409
|
C#
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.cloudwf.Transform;
using Aliyun.Acs.cloudwf.Transform.V20170328;
namespace Aliyun.Acs.cloudwf.Model.V20170328
{
public class GetApgroupDetailedConfigRequest : RpcAcsRequest<GetApgroupDetailedConfigResponse>
{
public GetApgroupDetailedConfigRequest()
: base("cloudwf", "2017-03-28", "GetApgroupDetailedConfig", "cloudwf", "openAPI")
{
}
private long? id;
private string accessKeyId;
public long? Id
{
get
{
return id;
}
set
{
id = value;
DictionaryUtil.Add(QueryParameters, "Id", value.ToString());
}
}
public string AccessKeyId
{
get
{
return accessKeyId;
}
set
{
accessKeyId = value;
DictionaryUtil.Add(QueryParameters, "AccessKeyId", value);
}
}
public override GetApgroupDetailedConfigResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return GetApgroupDetailedConfigResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 27.616438
| 109
| 0.702381
|
[
"Apache-2.0"
] |
AxiosCros/aliyun-openapi-net-sdk
|
aliyun-net-sdk-cloudwf/Cloudwf/Model/V20170328/GetApgroupDetailedConfigRequest.cs
| 2,016
|
C#
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using CoreBase.Infra.Data.Context;
namespace CoreBase.Infra.Data.Migrations
{
[DbContext(typeof(CoreContext))]
[Migration("20170718135435_Initial Database")]
partial class InitialDatabase
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "1.1.2");
modelBuilder.Entity("CoreBase.Domain.Entities.Category", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd();
b.Property<bool>("Active");
b.Property<DateTime>("CreatedAt");
b.Property<string>("Description")
.IsRequired();
b.Property<string>("Name")
.IsRequired();
b.HasKey("ID");
b.ToTable("Categories");
});
modelBuilder.Entity("CoreBase.Domain.Entities.Product", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd();
b.Property<bool>("Active");
b.Property<int>("CategoryId");
b.Property<DateTime>("CreatedAt");
b.Property<string>("Description")
.IsRequired();
b.Property<string>("Name")
.IsRequired();
b.Property<decimal>("Price");
b.HasKey("ID");
b.HasIndex("CategoryId");
b.ToTable("Products");
});
modelBuilder.Entity("CoreBase.Domain.Entities.Product", b =>
{
b.HasOne("CoreBase.Domain.Entities.Category", "Category")
.WithMany("Products")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 30.802632
| 108
| 0.502349
|
[
"Apache-2.0"
] |
felipeolimpos/base-core-ddd-mvc-ef-pg-ioc-proj
|
CoreBase.Infra.Data/Migrations/20170718135435_Initial Database.Designer.cs
| 2,343
|
C#
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.DependencyResolution;
using System.Data.Entity.Internal;
using System.Data.Entity.ModelConfiguration.Utilities;
using System.Data.Entity.Utilities;
using System.Data.Entity.Validation;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that
/// it can be used to query from a database and group together changes that will then be written
/// back to the store as a unit.
/// DbContext is conceptually similar to ObjectContext.
/// </summary>
/// <remarks>
/// DbContext is usually used with a derived type that contains <see cref="DbSet{TEntity}" /> properties for
/// the root entities of the model. These sets are automatically initialized when the
/// instance of the derived class is created. This behavior can be modified by applying the
/// <see cref="SuppressDbSetInitializationAttribute" /> attribute to either the entire derived context
/// class, or to individual properties on the class.
/// The Entity Data Model backing the context can be specified in several ways. When using the Code First
/// approach, the <see cref="DbSet{TEntity}" /> properties on the derived context are used to build a model
/// by convention. The protected OnModelCreating method can be overridden to tweak this model. More
/// control over the model used for the Model First approach can be obtained by creating a <see cref="DbCompiledModel" />
/// explicitly from a <see cref="DbModelBuilder" /> and passing this model to one of the DbContext constructors.
/// When using the Database First or Model First approach the Entity Data Model can be created using the
/// Entity Designer (or manually through creation of an EDMX file) and then this model can be specified using
/// entity connection string or an <see cref="System.Data.Entity.Core.EntityClient.EntityConnection" /> object.
/// The connection to the database (including the name of the database) can be specified in several ways.
/// If the parameterless DbContext constructor is called from a derived context, then the name of the derived context
/// is used to find a connection string in the app.config or web.config file. If no connection string is found, then
/// the name is passed to the DefaultConnectionFactory registered on the <see cref="Entity.Database" /> class. The connection
/// factory then uses the context name as the database name in a default connection string. (This default connection
/// string points to .\SQLEXPRESS on the local machine unless a different DefaultConnectionFactory is registered.)
/// Instead of using the derived context name, the connection/database name can also be specified explicitly by
/// passing the name to one of the DbContext constructors that takes a string. The name can also be passed in
/// the form "name=myname", in which case the name must be found in the config file or an exception will be thrown.
/// Note that the connection found in the app.config or web.config file can be a normal database connection
/// string (not a special Entity Framework connection string) in which case the DbContext will use Code First.
/// However, if the connection found in the config file is a special Entity Framework connection string, then the
/// DbContext will use Database/Model First and the model specified in the connection string will be used.
/// An existing or explicitly created DbConnection can also be used instead of the database/connection name.
/// A <see cref="DbModelBuilderVersionAttribute" /> can be applied to a class derived from DbContext to set the
/// version of conventions used by the context when it creates a model. If no attribute is applied then the
/// latest version of conventions will be used.
/// </remarks>
public class DbContext : IDisposable, IObjectContextAdapter
{
#region Construction and fields
// Handles lazy creation of an underlying ObjectContext
private InternalContext _internalContext;
private Database _database;
/// <summary>
/// Constructs a new context instance using conventions to create the name of the database to
/// which a connection will be made. The by-convention name is the full name (namespace + class name)
/// of the derived context class.
/// See the class remarks for how this is used to create a connection.
/// </summary>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected DbContext()
{
InitializeLazyInternalContext(new LazyInternalConnection(this, GetType().DatabaseName()));
}
/// <summary>
/// Constructs a new context instance using conventions to create the name of the database to
/// which a connection will be made, and initializes it from the given model.
/// The by-convention name is the full name (namespace + class name) of the derived context class.
/// See the class remarks for how this is used to create a connection.
/// </summary>
/// <param name="model"> The model that will back this context. </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected DbContext(DbCompiledModel model)
{
Check.NotNull(model, "model");
InitializeLazyInternalContext(new LazyInternalConnection(this, GetType().DatabaseName()), model);
}
/// <summary>
/// Constructs a new context instance using the given string as the name or connection string for the
/// database to which a connection will be made.
/// See the class remarks for how this is used to create a connection.
/// </summary>
/// <param name="nameOrConnectionString"> Either the database name or a connection string. </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(string nameOrConnectionString)
{
Check.NotEmpty(nameOrConnectionString, "nameOrConnectionString");
InitializeLazyInternalContext(new LazyInternalConnection(this, nameOrConnectionString));
}
/// <summary>
/// Constructs a new context instance using the given string as the name or connection string for the
/// database to which a connection will be made, and initializes it from the given model.
/// See the class remarks for how this is used to create a connection.
/// </summary>
/// <param name="nameOrConnectionString"> Either the database name or a connection string. </param>
/// <param name="model"> The model that will back this context. </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(string nameOrConnectionString, DbCompiledModel model)
{
Check.NotEmpty(nameOrConnectionString, "nameOrConnectionString");
Check.NotNull(model, "model");
InitializeLazyInternalContext(new LazyInternalConnection(this, nameOrConnectionString), model);
}
/// <summary>
/// Constructs a new context instance using the existing connection to connect to a database.
/// The connection will not be disposed when the context is disposed if <paramref name="contextOwnsConnection" />
/// is <c>false</c>.
/// </summary>
/// <param name="existingConnection"> An existing connection to use for the new context. </param>
/// <param name="contextOwnsConnection">
/// If set to <c>true</c> the connection is disposed when the context is disposed, otherwise the caller must dispose the connection.
/// </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(DbConnection existingConnection, bool contextOwnsConnection)
{
Check.NotNull(existingConnection, "existingConnection");
InitializeLazyInternalContext(new EagerInternalConnection(this, existingConnection, contextOwnsConnection));
}
/// <summary>
/// Constructs a new context instance using the existing connection to connect to a database,
/// and initializes it from the given model.
/// The connection will not be disposed when the context is disposed if <paramref name="contextOwnsConnection" />
/// is <c>false</c>.
/// </summary>
/// <param name="existingConnection"> An existing connection to use for the new context. </param>
/// <param name="model"> The model that will back this context. </param>
/// <param name="contextOwnsConnection">
/// If set to <c>true</c> the connection is disposed when the context is disposed, otherwise the caller must dispose the connection.
/// </param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)
{
Check.NotNull(existingConnection, "existingConnection");
Check.NotNull(model, "model");
InitializeLazyInternalContext(new EagerInternalConnection(this, existingConnection, contextOwnsConnection), model);
}
/// <summary>
/// Constructs a new context instance around an existing ObjectContext.
/// </summary>
/// <param name="objectContext"> An existing ObjectContext to wrap with the new context. </param>
/// <param name="dbContextOwnsObjectContext">
/// If set to <c>true</c> the ObjectContext is disposed when the DbContext is disposed, otherwise the caller must dispose the connection.
/// </param>
public DbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
{
Check.NotNull(objectContext, "objectContext");
DbConfigurationManager.Instance.EnsureLoadedForContext(GetType());
_internalContext = new EagerInternalContext(this, objectContext, dbContextOwnsObjectContext);
DiscoverAndInitializeSets();
}
// <summary>
// Initializes the internal context, discovers and initializes sets, and initializes from a model if one is provided.
// </summary>
// <param name="internalConnection"> The internal connection object with which to initialize. </param>
// <param name="model"> An optional <see cref="DbCompiledModel" /> with which to initialize. </param>
internal virtual void InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model = null)
{
DbConfigurationManager.Instance.EnsureLoadedForContext(GetType());
_internalContext = new LazyInternalContext(
this, internalConnection, model
, DbConfiguration.DependencyResolver.GetService<Func<DbContext, IDbModelCacheKey>>()
, DbConfiguration.DependencyResolver.GetService<AttributeProvider>());
DiscoverAndInitializeSets();
}
// <summary>
// Discovers DbSets and initializes them.
// </summary>
private void DiscoverAndInitializeSets()
{
new DbSetDiscoveryService(this).InitializeSets();
}
#endregion
#region Model building
/// <summary>
/// This method is called when the model for a derived context has been initialized, but
/// before the model has been locked down and used to initialize the context. The default
/// implementation of this method does nothing, but it can be overridden in a derived class
/// such that the model can be further configured before it is locked down.
/// </summary>
/// <remarks>
/// Typically, this method is called only once when the first instance of a derived context
/// is created. The model for that context is then cached and is for all further instances of
/// the context in the app domain. This caching can be disabled by setting the ModelCaching
/// property on the given ModelBuilder, but note that this can seriously degrade performance.
/// More control over caching is provided through use of the DbModelBuilder and DbContextFactory
/// classes directly.
/// </remarks>
/// <param name="modelBuilder"> The builder that defines the model for the context being created. </param>
protected virtual void OnModelCreating(DbModelBuilder modelBuilder)
{
}
// <summary>
// Internal method used to make the call to the real OnModelCreating method.
// </summary>
// <param name="modelBuilder"> The model builder. </param>
internal void CallOnModelCreating(DbModelBuilder modelBuilder)
{
OnModelCreating(modelBuilder);
}
#endregion
#region Database management
/// <summary>
/// Creates a Database instance for this context that allows for creation/deletion/existence checks
/// for the underlying database.
/// </summary>
public Database Database
{
get
{
if (_database == null)
{
_database = new Database(InternalContext);
}
return _database;
}
}
#endregion
#region Context methods
/// <summary>
/// Returns a <see cref="DbSet{TEntity}"/> instance for access to entities of the given type in the context
/// and the underlying store.
/// </summary>
/// <remarks>
/// Note that Entity Framework requires that this method return the same instance each time that it is called
/// for a given context instance and entity type. Also, the non-generic <see cref="DbSet"/> returned by the
/// <see cref="Set(Type)"/> method must wrap the same underlying query and set of entities. These invariants must
/// be maintained if this method is overridden for anything other than creating test doubles for unit testing.
/// See the <see cref="DbSet{TEntity}"/> class for more details.
/// </remarks>
/// <typeparam name="TEntity"> The type entity for which a set should be returned. </typeparam>
/// <returns> A set for the given entity type. </returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Set")]
public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class
{
return (DbSet<TEntity>)InternalContext.Set<TEntity>();
}
/// <summary>
/// Returns a non-generic <see cref="DbSet"/> instance for access to entities of the given type in the context
/// and the underlying store.
/// </summary>
/// <param name="entityType"> The type of entity for which a set should be returned. </param>
/// <returns> A set for the given entity type. </returns>
/// <remarks>
/// Note that Entity Framework requires that this method return the same instance each time that it is called
/// for a given context instance and entity type. Also, the generic <see cref="DbSet{TEntity}"/> returned by the
/// <see cref="Set"/> method must wrap the same underlying query and set of entities. These invariants must
/// be maintained if this method is overridden for anything other than creating test doubles for unit testing.
/// See the <see cref="DbSet"/> class for more details.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Set")]
public virtual DbSet Set(Type entityType)
{
Check.NotNull(entityType, "entityType");
return (DbSet)InternalContext.Set(entityType);
}
/// <summary>
/// Saves all changes made in this context to the underlying database.
/// </summary>
/// <returns>
/// The number of state entries written to the underlying database. This can include
/// state entries for entities and/or relationships. Relationship state entries are created for
/// many-to-many relationships and relationships where there is no foreign key property
/// included in the entity class (often referred to as independent associations).
/// </returns>
/// <exception cref="DbUpdateException">An error occurred sending updates to the database.</exception>
/// <exception cref="DbUpdateConcurrencyException">
/// A database command did not affect the expected number of rows. This usually indicates an optimistic
/// concurrency violation; that is, a row has been changed in the database since it was queried.
/// </exception>
/// <exception cref="DbEntityValidationException">
/// The save was aborted because validation of entity property values failed.
/// </exception>
/// <exception cref="NotSupportedException">
/// An attempt was made to use unsupported behavior such as executing multiple asynchronous commands concurrently
/// on the same context instance.</exception>
/// <exception cref="ObjectDisposedException">The context or connection have been disposed.</exception>
/// <exception cref="InvalidOperationException">
/// Some error occurred attempting to process entities in the context either before or after sending commands
/// to the database.
/// </exception>
public virtual int SaveChanges()
{
return InternalContext.SaveChanges();
}
#if !NET40
/// <summary>
/// Asynchronously saves all changes made in this context to the underlying database.
/// </summary>
/// <remarks>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </remarks>
/// <returns>
/// A task that represents the asynchronous save operation.
/// The task result contains the number of state entries written to the underlying database. This can include
/// state entries for entities and/or relationships. Relationship state entries are created for
/// many-to-many relationships and relationships where there is no foreign key property
/// included in the entity class (often referred to as independent associations).
/// </returns>
/// <exception cref="DbUpdateException">An error occurred sending updates to the database.</exception>
/// <exception cref="DbUpdateConcurrencyException">
/// A database command did not affect the expected number of rows. This usually indicates an optimistic
/// concurrency violation; that is, a row has been changed in the database since it was queried.
/// </exception>
/// <exception cref="DbEntityValidationException">
/// The save was aborted because validation of entity property values failed.
/// </exception>
/// <exception cref="NotSupportedException">
/// An attempt was made to use unsupported behavior such as executing multiple asynchronous commands concurrently
/// on the same context instance.</exception>
/// <exception cref="ObjectDisposedException">The context or connection have been disposed.</exception>
/// <exception cref="InvalidOperationException">
/// Some error occurred attempting to process entities in the context either before or after sending commands
/// to the database.
/// </exception>
public virtual Task<int> SaveChangesAsync()
{
return SaveChangesAsync(CancellationToken.None);
}
/// <summary>
/// Asynchronously saves all changes made in this context to the underlying database.
/// </summary>
/// <remarks>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </remarks>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken" /> to observe while waiting for the task to complete.
/// </param>
/// <returns>
/// A task that represents the asynchronous save operation.
/// The task result contains the number of state entries written to the underlying database. This can include
/// state entries for entities and/or relationships. Relationship state entries are created for
/// many-to-many relationships and relationships where there is no foreign key property
/// included in the entity class (often referred to as independent associations).
/// </returns>
/// <exception cref="InvalidOperationException">Thrown if the context has been disposed.</exception>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "cancellationToken")]
public virtual Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
return InternalContext.SaveChangesAsync(cancellationToken);
}
#endif
/// <summary>
/// Returns the Entity Framework ObjectContext that is underlying this context.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the context has been disposed.</exception>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
ObjectContext IObjectContextAdapter.ObjectContext
{
get
{
// When dropping down to ObjectContext we force o-space loading for the types
// that we know about so that code can use the ObjectContext with o-space metadata
// without having to explicitly call LoadFromAssembly. For example Dynamic Data does
// this--see Dev11 142609.
InternalContext.ForceOSpaceLoadingForKnownEntityTypes();
return InternalContext.ObjectContext;
}
}
/// <summary>
/// Validates tracked entities and returns a Collection of <see cref="DbEntityValidationResult" /> containing validation results.
/// </summary>
/// <returns> Collection of validation results for invalid entities. The collection is never null and must not contain null values or results for valid entities. </returns>
/// <remarks>
/// 1. This method calls DetectChanges() to determine states of the tracked entities unless
/// DbContextConfiguration.AutoDetectChangesEnabled is set to false.
/// 2. By default only Added on Modified entities are validated. The user is able to change this behavior
/// by overriding ShouldValidateEntity method.
/// </remarks>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public IEnumerable<DbEntityValidationResult> GetValidationErrors()
{
var validationResults = new List<DbEntityValidationResult>();
//ChangeTracker.Entries() will call DetectChanges unless disabled by the user
foreach (var dbEntityEntry in ChangeTracker.Entries())
{
#pragma warning disable 612,618
if (dbEntityEntry.InternalEntry.EntityType != typeof(EdmMetadata)
&&
#pragma warning restore 612,618
ShouldValidateEntity(dbEntityEntry))
{
var validationResult = ValidateEntity(dbEntityEntry, new Dictionary<object, object>());
if (validationResult != null
&& !validationResult.IsValid)
{
validationResults.Add(validationResult);
}
}
}
return validationResults;
}
/// <summary>
/// Extension point allowing the user to override the default behavior of validating only
/// added and modified entities.
/// </summary>
/// <param name="entityEntry"> DbEntityEntry instance that is supposed to be validated. </param>
/// <returns> true to proceed with validation; false otherwise. </returns>
protected virtual bool ShouldValidateEntity(DbEntityEntry entityEntry)
{
Check.NotNull(entityEntry, "entityEntry");
return (entityEntry.State & (EntityState.Added | EntityState.Modified)) != 0;
}
/// <summary>
/// Extension point allowing the user to customize validation of an entity or filter out validation results.
/// Called by <see cref="GetValidationErrors" />.
/// </summary>
/// <param name="entityEntry"> DbEntityEntry instance to be validated. </param>
/// <param name="items">
/// User-defined dictionary containing additional info for custom validation. It will be passed to
/// <see
/// cref="System.ComponentModel.DataAnnotations.ValidationContext" />
/// and will be exposed as
/// <see
/// cref="System.ComponentModel.DataAnnotations.ValidationContext.Items" />
/// . This parameter is optional and can be null.
/// </param>
/// <returns> Entity validation result. Possibly null when overridden. </returns>
protected virtual DbEntityValidationResult ValidateEntity(
DbEntityEntry entityEntry, IDictionary<object, object> items)
{
Check.NotNull(entityEntry, "entityEntry");
return entityEntry.InternalEntry.GetValidationResult(items);
}
// <summary>
// Internal method that calls the protected ValidateEntity method.
// </summary>
// <param name="entityEntry"> DbEntityEntry instance to be validated. </param>
// <returns> Entity validation result. Possibly null when ValidateEntity is overridden. </returns>
internal virtual DbEntityValidationResult CallValidateEntity(DbEntityEntry entityEntry)
{
return ValidateEntity(entityEntry, new Dictionary<object, object>());
}
#endregion
#region Entity entries
/// <summary>
/// Gets a <see cref="DbEntityEntry{T}" /> object for the given entity providing access to
/// information about the entity and the ability to perform actions on the entity.
/// </summary>
/// <typeparam name="TEntity"> The type of the entity. </typeparam>
/// <param name="entity"> The entity. </param>
/// <returns> An entry for the entity. </returns>
public DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class
{
Check.NotNull(entity, "entity");
return new DbEntityEntry<TEntity>(new InternalEntityEntry(InternalContext, entity));
}
/// <summary>
/// Gets a <see cref="DbEntityEntry" /> object for the given entity providing access to
/// information about the entity and the ability to perform actions on the entity.
/// </summary>
/// <param name="entity"> The entity. </param>
/// <returns> An entry for the entity. </returns>
public DbEntityEntry Entry(object entity)
{
Check.NotNull(entity, "entity");
return new DbEntityEntry(new InternalEntityEntry(InternalContext, entity));
}
#endregion
#region ChangeTracker and Configuration
/// <summary>
/// Provides access to features of the context that deal with change tracking of entities.
/// </summary>
/// <value> An object used to access features that deal with change tracking. </value>
public DbChangeTracker ChangeTracker
{
get { return new DbChangeTracker(InternalContext); }
}
/// <summary>
/// Provides access to configuration options for the context.
/// </summary>
/// <value> An object used to access configuration options. </value>
public DbContextConfiguration Configuration
{
get { return new DbContextConfiguration(InternalContext); }
}
#endregion
#region Disposable
/// <summary>
/// Calls the protected Dispose method.
/// </summary>
public void Dispose()
{
Dispose(disposing: true);
// This class has no unmanaged resources but it is possible that somebody could add some in a subclass.
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the context. The underlying <see cref="ObjectContext" /> is also disposed if it was created
/// is by this context or ownership was passed to this context when this context was created.
/// The connection to the database (<see cref="DbConnection" /> object) is also disposed if it was created
/// is by this context or ownership was passed to this context when this context was created.
/// </summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
_internalContext.Dispose();
}
#endregion
#region InternalContext access
// <summary>
// Provides access to the underlying InternalContext for other parts of the internal design.
// </summary>
internal virtual InternalContext InternalContext
{
get { return _internalContext; }
}
#endregion
#region Hidden Object methods
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
{
return base.ToString();
}
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <inheritdoc />
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
[EditorBrowsable(EditorBrowsableState.Never)]
public new Type GetType()
{
return base.GetType();
}
#endregion
}
}
| 51.370429
| 180
| 0.659755
|
[
"Apache-2.0"
] |
dotnet-maestro-bot/EntityFramework6
|
src/EntityFramework/DbContext.cs
| 32,312
|
C#
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.FMS")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Firewall Management Service. This release is the initial release version for AWS Firewall Manager, a new AWS service that makes it easy for customers to centrally configure WAF rules across all their resources (ALBs and CloudFront distributions) and across accounts.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Firewall Management Service. This release is the initial release version for AWS Firewall Manager, a new AWS service that makes it easy for customers to centrally configure WAF rules across all their resources (ALBs and CloudFront distributions) and across accounts.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Firewall Management Service. This release is the initial release version for AWS Firewall Manager, a new AWS service that makes it easy for customers to centrally configure WAF rules across all their resources (ALBs and CloudFront distributions) and across accounts.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Firewall Management Service. This release is the initial release version for AWS Firewall Manager, a new AWS service that makes it easy for customers to centrally configure WAF rules across all their resources (ALBs and CloudFront distributions) and across accounts.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Firewall Management Service. This release is the initial release version for AWS Firewall Manager, a new AWS service that makes it easy for customers to centrally configure WAF rules across all their resources (ALBs and CloudFront distributions) and across accounts.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Firewall Management Service. This release is the initial release version for AWS Firewall Manager, a new AWS service that makes it easy for customers to centrally configure WAF rules across all their resources (ALBs and CloudFront distributions) and across accounts.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.101.54")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif
| 64.322034
| 357
| 0.786298
|
[
"Apache-2.0"
] |
costleya/aws-sdk-net
|
sdk/src/Services/FMS/Properties/AssemblyInfo.cs
| 3,795
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанных со сборкой.
[assembly: AssemblyTitle("SupportTools")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SupportTools")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, следует установить атрибут ComVisible в TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("278255e5-696d-4a22-97ce-8c3c12246393")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.675676
| 99
| 0.762404
|
[
"MIT"
] |
Trendyhall/Trendyhall
|
SupportTools/SupportTools/Properties/AssemblyInfo.cs
| 2,012
|
C#
|
using System.Text;
using System.Threading.Tasks;
using Firestorm.Endpoints.Formatting.Json;
using Firestorm.Host.Infrastructure;
using Newtonsoft.Json;
namespace Firestorm.Endpoints.Formatting
{
public class ContentNegotiator
{
private readonly IContentAccepts _accepts;
private readonly IContentWriter _writer;
private readonly JsonSerializerSettings _jsonSerializerSettings;
public ContentNegotiator(IContentAccepts accepts, IContentWriter writer, INamingConventionSwitcher namingConventionSwitcher)
{
_accepts = accepts;
_writer = writer;
_jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new NameSwitcherContractResolver(namingConventionSwitcher),
//Converters = { new RestItemDataJsonConverter(namingConventionSwitcher) }
};
}
public async Task SetResponseBodyAsync(object obj)
{
if (obj == null)
return;
_writer.SetMimeType("application/json; charset=utf-8");
string json = JsonConvert.SerializeObject(obj, _jsonSerializerSettings);
byte[] bytes = Encoding.UTF8.GetBytes(json);
_writer.SetLength(bytes.Length);
await _writer.WriteBytesAsync(bytes);
}
}
}
| 31.581395
| 132
| 0.667894
|
[
"MIT"
] |
connellw/Firestorm
|
src/Firestorm.Endpoints.Formatting/Content/ContentNegotiator.cs
| 1,360
|
C#
|
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Search.Spans
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexReaderContext = Lucene.Net.Index.IndexReaderContext;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Term = Lucene.Net.Index.Term;
[TestFixture]
public class TestNearSpansOrdered : LuceneTestCase
{
protected internal IndexSearcher searcher;
protected internal Directory directory;
protected internal IndexReader reader;
public const string FIELD = "field";
[TearDown]
public override void TearDown()
{
reader.Dispose();
directory.Dispose();
base.TearDown();
}
[SetUp]
public override void SetUp()
{
base.SetUp();
directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));
for (int i = 0; i < docFields.Length; i++)
{
Document doc = new Document();
doc.Add(NewTextField(FIELD, docFields[i], Field.Store.NO));
writer.AddDocument(doc);
}
reader = writer.GetReader();
writer.Dispose();
searcher = NewSearcher(reader);
}
protected internal string[] docFields = new string[] { "w1 w2 w3 w4 w5", "w1 w3 w2 w3 zz", "w1 xx w2 yy w3", "w1 w3 xx w2 yy w3 zz" };
protected internal virtual SpanNearQuery MakeQuery(string s1, string s2, string s3, int slop, bool inOrder)
{
return new SpanNearQuery(new SpanQuery[] { new SpanTermQuery(new Term(FIELD, s1)), new SpanTermQuery(new Term(FIELD, s2)), new SpanTermQuery(new Term(FIELD, s3)) }, slop, inOrder);
}
protected internal virtual SpanNearQuery MakeQuery()
{
return MakeQuery("w1", "w2", "w3", 1, true);
}
[Test]
public virtual void TestSpanNearQuery()
{
SpanNearQuery q = MakeQuery();
CheckHits.DoCheckHits(Random, q, FIELD, searcher, new int[] { 0, 1 });
}
public virtual string s(Spans span)
{
return s(span.Doc, span.Start, span.End);
}
public virtual string s(int doc, int start, int end)
{
return "s(" + doc + "," + start + "," + end + ")";
}
[Test]
public virtual void TestNearSpansNext()
{
SpanNearQuery q = MakeQuery();
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(0, 0, 3), s(span));
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(1, 0, 4), s(span));
Assert.AreEqual(false, span.MoveNext());
}
/// <summary>
/// test does not imply that skipTo(doc+1) should work exactly the
/// same as next -- it's only applicable in this case since we know doc
/// does not contain more than one span
/// </summary>
[Test]
public virtual void TestNearSpansSkipToLikeNext()
{
SpanNearQuery q = MakeQuery();
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.SkipTo(0));
Assert.AreEqual(s(0, 0, 3), s(span));
Assert.AreEqual(true, span.SkipTo(1));
Assert.AreEqual(s(1, 0, 4), s(span));
Assert.AreEqual(false, span.SkipTo(2));
}
[Test]
public virtual void TestNearSpansNextThenSkipTo()
{
SpanNearQuery q = MakeQuery();
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(0, 0, 3), s(span));
Assert.AreEqual(true, span.SkipTo(1));
Assert.AreEqual(s(1, 0, 4), s(span));
Assert.AreEqual(false, span.MoveNext());
}
[Test]
public virtual void TestNearSpansNextThenSkipPast()
{
SpanNearQuery q = MakeQuery();
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.MoveNext());
Assert.AreEqual(s(0, 0, 3), s(span));
Assert.AreEqual(false, span.SkipTo(2));
}
[Test]
public virtual void TestNearSpansSkipPast()
{
SpanNearQuery q = MakeQuery();
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(false, span.SkipTo(2));
}
[Test]
public virtual void TestNearSpansSkipTo0()
{
SpanNearQuery q = MakeQuery();
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.SkipTo(0));
Assert.AreEqual(s(0, 0, 3), s(span));
}
[Test]
public virtual void TestNearSpansSkipTo1()
{
SpanNearQuery q = MakeQuery();
Spans span = MultiSpansWrapper.Wrap(searcher.TopReaderContext, q);
Assert.AreEqual(true, span.SkipTo(1));
Assert.AreEqual(s(1, 0, 4), s(span));
}
/// <summary>
/// not a direct test of NearSpans, but a demonstration of how/when
/// this causes problems
/// </summary>
[Test]
public virtual void TestSpanNearScorerSkipTo1()
{
SpanNearQuery q = MakeQuery();
Weight w = searcher.CreateNormalizedWeight(q);
IndexReaderContext topReaderContext = searcher.TopReaderContext;
AtomicReaderContext leave = topReaderContext.Leaves[0];
Scorer s = w.GetScorer(leave, ((AtomicReader)leave.Reader).LiveDocs);
Assert.AreEqual(1, s.Advance(1));
}
/// <summary>
/// not a direct test of NearSpans, but a demonstration of how/when
/// this causes problems
/// </summary>
[Test]
public virtual void TestSpanNearScorerExplain()
{
SpanNearQuery q = MakeQuery();
Explanation e = searcher.Explain(q, 1);
Assert.IsTrue(0.0f < e.Value, "Scorer explanation value for doc#1 isn't positive: " + e.ToString());
}
}
}
| 38.254902
| 192
| 0.598155
|
[
"Apache-2.0"
] |
10088/lucenenet
|
src/Lucene.Net.Tests/Search/Spans/TestNearSpansOrdered.cs
| 7,806
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item : ScriptableObject
{
public string Name;
public string Description;
public Sprite Icon;
public virtual void Use()
{
Debug.Log(Name + " was used.");
}
}
| 17.6875
| 39
| 0.678445
|
[
"Apache-2.0"
] |
rambo5x/Senior-Project
|
SeniorProject3D/Assets/Scritable Objects/Items/Scripts/Item.cs
| 283
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harmony;
using UnityEngine;
namespace NoFixedTempMod
{
[HarmonyPatch(typeof(AlgaeDistilleryConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_AlgaeDistilleryConfig_ConfigureBuildingTemplate
{
private static void Postfix(AlgaeDistilleryConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[2]
{
//new ElementConverter.OutputElement(0.2f, SimHashes.Algae, 303.15f, true, 0f, 1f, false, 1f, 255, 0),
//new ElementConverter.OutputElement(0.400000036f, SimHashes.DirtyWater, 303.15f, true, 0f, 0.5f, false, 1f, 255, 0)
new ElementConverter.OutputElement(0.2f, SimHashes.Algae, 0f, true, 0f, 1f, true, 1f, 255, 0),
new ElementConverter.OutputElement(0.4f, SimHashes.DirtyWater, 0f, true, 0f, 0.5f, true, 1f, 255, 0)
};
}
}
/*
[HarmonyPatch(typeof(AlgaeHabitatConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_AlgaeHabitatConfig_ConfigureBuildingTemplate
{
private static void Postfix(AlgaeHabitatConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[1]
{
//new ElementConverter.OutputElement(0.0400000028f, SimHashes.Oxygen, 303.15f, false, 0f, 1f, false, 1f, 255, 0)
new ElementConverter.OutputElement(0.0400000028f, SimHashes.Oxygen, 0f, false, 0f, 1f, true, 1f, 255, 0)
};
ElementConverter elementConverter2 = go.AddComponent<ElementConverter>();
elementConverter2.outputElements = new ElementConverter.OutputElement[1]
{
//new ElementConverter.OutputElement(0.290333331f, SimHashes.DirtyWater, 303.15f, true, 0f, 1f, false, 1f, 255, 0)
new ElementConverter.OutputElement(0.290333331f, SimHashes.DirtyWater, 0f, true, 0f, 1f, true, 1f, 255, 0)
};
}
}
*/
[HarmonyPatch(typeof(CO2ScrubberConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_CO2ScrubberConfig_ConfigureBuildingTemplate
{
private static void Postfix(CO2ScrubberConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[1]
{
//new ElementConverter.OutputElement(1f, SimHashes.DirtyWater, 313.15f, true, 0f, 0.5f, false, 1f, 255, 0)
new ElementConverter.OutputElement(1f, SimHashes.DirtyWater, 0f, true, 0f, 0.5f, true, 1f, 255, 0)
};
}
}
[HarmonyPatch(typeof(CompostConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_CompostConfig_ConfigureBuildingTemplate
{
private static void Postfix(CompostConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[1]
{
//new ElementConverter.OutputElement(0.1f, SimHashes.Dirt, 348.15f, true, 0f, 0.5f, false, 1f, 255, 0)
new ElementConverter.OutputElement(0.1f, SimHashes.Dirt, 0f, true, 0f, 0.5f, true, 1f, 255, 0)
};
}
}
[HarmonyPatch(typeof(ElectrolyzerConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_ElectrolyzerConfig_ConfigureBuildingTemplate
{
private static void Postfix(ElectrolyzerConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[2]
{
//new ElementConverter.OutputElement(0.888f, SimHashes.Oxygen, 343.15f, false, 0f, 1f, false, 1f, 255, 0),
//new ElementConverter.OutputElement(0.111999989f, SimHashes.Hydrogen, 343.15f, false, 0f, 1f, false, 1f, 255, 0)
new ElementConverter.OutputElement(0.888f, SimHashes.Oxygen, 0f, false, 0f, 1f, true, 1f, 255, 0),
new ElementConverter.OutputElement(0.111999989f, SimHashes.Hydrogen, 0f, false, 0f, 1f, true, 1f, 255, 0)
};
}
}
[HarmonyPatch(typeof(FertilizerMakerConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_FertilizerMakerConfig_ConfigureBuildingTemplate
{
private static void Postfix(FertilizerMakerConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[1]
{
//new ElementConverter.OutputElement(0.12f, SimHashes.Fertilizer, 323.15f, true, 0f, 0.5f, false, 1f, 255, 0)
new ElementConverter.OutputElement(0.12f, SimHashes.Fertilizer, 0f, true, 0f, 0.5f, true, 1f, 255, 0)
};
}
}
[HarmonyPatch(typeof(MineralDeoxidizerConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_MineralDeoxidizerConfig_ConfigureBuildingTemplate
{
private static void Postfix(MineralDeoxidizerConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[1]
{
//new ElementConverter.OutputElement(0.5f, SimHashes.Oxygen, 303.15f, false, 0f, 1f, false, 1f, 255, 0)
new ElementConverter.OutputElement(0.5f, SimHashes.Oxygen, 0f, false, 0f, 1f, true, 1f, 255, 0)
};
}
}
[HarmonyPatch(typeof(OilRefineryConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_OilRefineryConfig_ConfigureBuildingTemplate
{
private static void Postfix(OilRefineryConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[2]
{
//new ElementConverter.OutputElement(5f, SimHashes.Petroleum, 348.15f, true, 0f, 1f, false, 1f, 255, 0),
//new ElementConverter.OutputElement(0.09f, SimHashes.Methane, 348.15f, false, 0f, 3f, false, 1f, 255, 0)
new ElementConverter.OutputElement(5f, SimHashes.Petroleum, 0f, true, 0f, 1f, true, 1f, 255, 0),
new ElementConverter.OutputElement(0.09f, SimHashes.Methane, 0f, false, 0f, 3f, true, 1f, 255, 0)
};
}
}
[HarmonyPatch(typeof(OilWellCapConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_OilWellCapConfig_ConfigureBuildingTemplate
{
private static void Postfix(OilWellCapConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[1]
{
//new ElementConverter.OutputElement(3.33333325f, SimHashes.CrudeOil, 363.15f, false, 2f, 1.5f, false, 0f, 255, 0)
new ElementConverter.OutputElement(3.33333325f, SimHashes.CrudeOil, 0f, false, 2f, 1.5f, true, 0f, 255, 0)
};
}
}
/*
[HarmonyPatch(typeof(PacuCleanerConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_PacuCleanerConfig_ConfigureBuildingTemplate
{
private static void Postfix(PacuCleanerConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[1]
{
new ElementConverter.OutputElement(PacuCleanerConfig.POLLUTED_WATER_CONVERTED_PER_CYCLE / 600f, SimHashes.Water, 0f, true, 0f, 0.5f, true, 1f, 255, 0)
};
}
}
*/
[HarmonyPatch(typeof(PolymerizerConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_PolymerizerConfig_ConfigureBuildingTemplate
{
private static void Postfix(PolymerizerConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[3]
{
//new ElementConverter.OutputElement(0.5f, SimHashes.Polypropylene, 348.15f, true, 0f, 0.5f, false, 1f, 255, 0),
//new ElementConverter.OutputElement(0.008333334f, SimHashes.Steam, 473.15f, true, 0f, 0.5f, false, 1f, 255, 0),
//new ElementConverter.OutputElement(0.008333334f, SimHashes.CarbonDioxide, 423.15f, true, 0f, 0.5f, false, 1f, 255, 0)
new ElementConverter.OutputElement(0.5f, SimHashes.Polypropylene, 0f, true, 0f, 0.5f, true, 1f, 255, 0),
new ElementConverter.OutputElement(0.008333334f, SimHashes.Steam, 0f, true, 0f, 0.5f, true, 1f, 255, 0),
new ElementConverter.OutputElement(0.008333334f, SimHashes.CarbonDioxide, 0f, true, 0f, 0.5f, true, 1f, 255, 0)
};
}
}
/*
[HarmonyPatch(typeof(ShowerConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_ShowerConfig_ConfigureBuildingTemplate
{
private static void Postfix(ShowerConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[1]
{
//new ElementConverter.OutputElement(1f, SimHashes.DirtyWater, 0f, true, 0f, 0.5f, true, 1f, 255, 0)
new ElementConverter.OutputElement(1f, SimHashes.DirtyWater, 0f, true, 0f, 0.5f, true, 1f, 255, 0)
};
}
}
*/
[HarmonyPatch(typeof(WaterPurifierConfig), "ConfigureBuildingTemplate")]
internal class NoFixedTemp_SWaterPurifierConfig_ConfigureBuildingTemplate
{
private static void Postfix(WaterPurifierConfig __instance, GameObject go, Tag prefab_tag)
{
ElementConverter elementConverter = go.AddOrGet<ElementConverter>();
elementConverter.outputElements = new ElementConverter.OutputElement[2]
{
//new ElementConverter.OutputElement(5f, SimHashes.Water, 313.15f, true, 0f, 0.5f, false, 0.75f, 255, 0),
//new ElementConverter.OutputElement(0.2f, SimHashes.ToxicSand, 313.15f, true, 0f, 0.5f, false, 0.25f, 255, 0)
new ElementConverter.OutputElement(5f, SimHashes.Water, 0f, true, 0f, 0.5f, true, 0.75f, 255, 0),
new ElementConverter.OutputElement(0.2f, SimHashes.ToxicSand, 0f, true, 0f, 0.5f, true, 0.25f, 255, 0)
};
}
}
}
| 44.547009
| 166
| 0.728703
|
[
"MIT"
] |
Blindfold-Games/ONI-Modloader-Mods
|
Source/NoFixedTempMod/NoFixedTempMod.cs
| 10,426
|
C#
|
/**
* Copyright 2017 The Nakama Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Nakama;
using UnityEngine;
namespace Framework
{
public class NakamaManager : Singleton<NakamaManager>
{
internal const string HostIp = "127.0.0.1";
internal const uint Port = 7350;
internal const bool UseSsl = false;
internal const string ServerKey = "defaultkey";
private const int MaxReconnectAttempts = 5;
private readonly Queue<Action> _dispatchQueue = new Queue<Action>();
private readonly INClient _client;
private readonly Action<INSession> _sessionHandler;
public static event EventHandler AfterConnected = (sender, evt) => { };
public static event EventHandler AfterDisconnected = (sender, evt) => { };
private static readonly Action<INError> ErrorHandler = err =>
{
if (err.Code == ErrorCode.GroupNameInuse)
{
// This is caused by the FakeDataLoader and is expected. We can ignore this safely in this case.
return;
}
Logger.LogErrorFormat("Error: code '{0}' with '{1}'.", err.Code, err.Message);
};
private INAuthenticateMessage _authenticateMessage;
// Flag to tell us whether the socket was closed intentially or not and whether to attempt reconnect.
private bool _doReconnect = true;
private uint _reconnectCount;
public INSession Session { get; private set; }
private NakamaManager()
{
_client = new NClient.Builder(ServerKey).Host(HostIp).Port(Port).SSL(UseSsl).Build();
_client.OnTopicMessage = message =>
{
var chatMessages = StateManager.Instance.ChatMessages;
foreach (var topic in chatMessages.Keys)
{
if (topic.Id.Equals(message.Topic.Id))
{
chatMessages[topic].Add(message.MessageId, message);
}
}
};
_sessionHandler = session =>
{
Logger.LogFormat("Session: '{0}'.", session.Token);
_client.Connect(session, done =>
{
Session = session;
_reconnectCount = 0;
// cache session for quick reconnects
_dispatchQueue.Enqueue(() =>
{
PlayerPrefs.SetString("nk.session", session.Token);
AfterConnected(this, EventArgs.Empty);
});
});
};
_client.OnDisconnect = evt =>
{
Logger.Log("Disconnected from server.");
if (_doReconnect && _reconnectCount < MaxReconnectAttempts)
{
_reconnectCount++;
_dispatchQueue.Enqueue(() => { Reconnect(); });
}
else
{
_dispatchQueue.Clear();
_dispatchQueue.Enqueue(() => { AfterDisconnected(this, EventArgs.Empty); });
}
};
_client.OnError = error => ErrorHandler(error);
}
private IEnumerator Reconnect()
{
// if it's the first time disconnected, then attempt to reconnect immediately
// every other time, wait 10,20,30,40,50 seconds each time
var reconnectTime = ((_reconnectCount - 1) + 10) * 60;
yield return new WaitForSeconds(reconnectTime);
_sessionHandler(Session);
}
// Restore serialised session token from PlayerPrefs
// If the token doesn't exist or is expired `null` is returned.
private static INSession RestoreSession()
{
var cachedSession = PlayerPrefs.GetString("nk.session");
if (string.IsNullOrEmpty(cachedSession))
{
Logger.Log("No Session in PlayerPrefs.");
return null;
}
var session = NSession.Restore(cachedSession);
if (!session.HasExpired(DateTime.UtcNow)) return session;
Logger.Log("Session expired.");
return null;
}
private void Update()
{
for (int i = 0, l = _dispatchQueue.Count; i < l; i++)
{
_dispatchQueue.Dequeue()();
}
}
private void OnApplicationQuit()
{
_doReconnect = false;
_client.Disconnect();
}
private void OnApplicationPause(bool isPaused)
{
if (isPaused)
{
_doReconnect = false;
_client.Disconnect();
return;
}
// let's re-authenticate (if neccessary) and reconnect to the server.
if (_authenticateMessage != null)
{
_doReconnect = true;
Connect(_authenticateMessage);
}
}
// This method connects the client to the server and
// if neccessary authenticates with the server
public void Connect(INAuthenticateMessage request)
{
// Check to see if we have a valid session token we can restore
var session = RestoreSession();
if (session != null)
{
// Session is valid, let's connect.
_sessionHandler(session);
return;
}
// Cache message for later use for reconnecting purposes in case the session had expired
_authenticateMessage = request;
// Let's login to authenticate and get a valid token
_client.Login(request, _sessionHandler, err =>
{
if (err.Code == ErrorCode.UserNotFound)
{
_client.Register(request, _sessionHandler, ErrorHandler);
}
else
{
ErrorHandler(err);
}
});
}
public void SelfFetch(NSelfFetchMessage message)
{
_client.Send(message, self => { StateManager.Instance.SelfInfo = self; }, ErrorHandler);
}
public void FriendAdd(NFriendAddMessage message, bool refreshList = true)
{
_client.Send(message, done =>
{
if (refreshList)
{
FriendsList(NFriendsListMessage.Default());
}
}, ErrorHandler);
}
public void FriendRemove(NFriendRemoveMessage message)
{
_client.Send(message, done => { FriendsList(NFriendsListMessage.Default()); }, ErrorHandler);
}
public void FriendsList(NFriendsListMessage message)
{
_client.Send(message, friends =>
{
StateManager.Instance.Friends.Clear();
StateManager.Instance.Friends.AddRange(friends.Results);
}, ErrorHandler);
}
public void GroupsList(NGroupsListMessage.Builder message, bool appendList = false, uint maxGroups = 100)
{
_client.Send(message.Build(), groups =>
{
if (!appendList)
{
StateManager.Instance.SearchedGroups.Clear();
}
foreach (var group in groups.Results)
{
// check to see if SearchedGroups has 'maxGroups' groups.
if (StateManager.Instance.SearchedGroups.Count >= maxGroups)
{
return;
}
StateManager.Instance.SearchedGroups.Add(group);
}
// Recursively fetch the next set of groups and append
if (groups.Cursor != null && groups.Cursor.Value != "")
{
message.Cursor(groups.Cursor);
GroupsList(message, true);
}
}, ErrorHandler);
}
public void GroupJoin(NGroupJoinMessage message, bool refreshList = true)
{
_client.Send(message, done =>
{
if (refreshList)
{
JoinedGroupsList(NGroupsSelfListMessage.Default());
}
}, ErrorHandler);
}
public void JoinedGroupsList(NGroupsSelfListMessage message)
{
_client.Send(message, groups =>
{
StateManager.Instance.JoinedGroups.Clear();
StateManager.Instance.JoinedGroups.AddRange(groups.Results);
}, ErrorHandler);
}
public void GroupCreate(NGroupCreateMessage message)
{
_client.Send(message, groups => { }, ErrorHandler);
}
public void TopicJoin(string userIdOrRoom, NTopicJoinMessage message)
{
_client.Send(message, topics =>
{
var topic = topics.Results[0];
StateManager.Instance.Topics.Add(userIdOrRoom, topic.Topic);
StateManager.Instance.ChatMessages.Add(topic.Topic, new Dictionary<string, INTopicMessage>());
}, ErrorHandler);
}
public void TopicMessageList(INTopicId topic, NTopicMessagesListMessage.Builder message,
bool appendList = false, uint maxMessages = 100)
{
_client.Send(message.Build(), messages =>
{
if (!appendList)
{
StateManager.Instance.ChatMessages[topic].Clear();
}
foreach (var chatMessage in messages.Results)
{
// check to see if ChatMessages has 'maxMessages' messages.
if (StateManager.Instance.ChatMessages[topic].Count >= maxMessages)
{
return;
}
StateManager.Instance.ChatMessages[topic].Add(chatMessage.MessageId, chatMessage);
}
// Recursively fetch the next set of groups and append
if (messages.Cursor != null && messages.Cursor.Value != "")
{
message.Cursor(messages.Cursor);
TopicMessageList(topic, message, true);
}
}, ErrorHandler);
}
public void TopicSendMessage(NTopicMessageSendMessage message)
{
_client.Send(message, acks => { }, ErrorHandler);
}
public void NotificationsList(NNotificationsListMessage.Builder message,
bool appendList = false, uint maxNotifications = 100)
{
_client.Send(message.Build(), notifications =>
{
if (!appendList)
{
StateManager.Instance.Notifications.Clear();
}
foreach (var notification in notifications.Results)
{
// check to see if ChatMessages has 'maxMessages' messages.
if (StateManager.Instance.Notifications.Count >= maxNotifications)
{
return;
}
StateManager.Instance.Notifications.Add(notification);
}
// Recursively fetch the next set of groups and append
if (notifications.Cursor != null && notifications.Cursor.Value != "")
{
message.Cursor(notifications.Cursor.Value);
NotificationsList(message, true);
}
}, ErrorHandler);
}
}
}
| 35.194915
| 113
| 0.526928
|
[
"Apache-2.0"
] |
GameInstitute/nakama-docs
|
docs/nakama/examples/unity/nakama-showreel/Assets/Framework/NakamaManager.cs
| 12,461
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_Runtime_CompilerServices_AsyncTaskMethodBuilder_1_Boolean_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>);
args = new Type[]{};
method = type.GetMethod("Create", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Create_0);
Dictionary<string, List<MethodInfo>> genericMethods = new Dictionary<string, List<MethodInfo>>();
List<MethodInfo> lst = null;
foreach(var m in type.GetMethods())
{
if(m.IsGenericMethodDefinition)
{
if (!genericMethods.TryGetValue(m.Name, out lst))
{
lst = new List<MethodInfo>();
genericMethods[m.Name] = lst;
}
lst.Add(m);
}
}
args = new Type[]{typeof(global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor)};
if (genericMethods.TryGetValue("Start", out lst))
{
foreach(var m in lst)
{
if(m.MatchGenericParameters(args, typeof(void), typeof(global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor).MakeByRefType()))
{
method = m.MakeGenericMethod(args);
app.RegisterCLRMethodRedirection(method, Start_1);
break;
}
}
}
args = new Type[]{};
method = type.GetMethod("get_Task", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_Task_2);
args = new Type[]{typeof(System.Runtime.CompilerServices.TaskAwaiter<System.Boolean>), typeof(global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor)};
if (genericMethods.TryGetValue("AwaitUnsafeOnCompleted", out lst))
{
foreach(var m in lst)
{
if(m.MatchGenericParameters(args, typeof(void), typeof(System.Runtime.CompilerServices.TaskAwaiter<System.Boolean>).MakeByRefType(), typeof(global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor).MakeByRefType()))
{
method = m.MakeGenericMethod(args);
app.RegisterCLRMethodRedirection(method, AwaitUnsafeOnCompleted_3);
break;
}
}
}
args = new Type[]{typeof(System.Exception)};
method = type.GetMethod("SetException", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, SetException_4);
args = new Type[]{typeof(System.Boolean)};
method = type.GetMethod("SetResult", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, SetResult_5);
app.RegisterCLRCreateDefaultInstance(type, () => new System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>());
}
static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean> instance_of_this_method)
{
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.Object:
{
__mStack[ptr_of_this_method->Value] = instance_of_this_method;
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
else
{
var t = __domain.GetType(___obj.GetType()) as CLRType;
t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var t = __domain.GetType(ptr_of_this_method->Value);
if(t is ILType)
{
((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
else
{
((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
break;
}
}
static StackObject* Create_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* __ret = ILIntepreter.Minus(__esp, 0);
var result_of_this_method = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>.Create();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* Start_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor @stateMachine = (global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor)typeof(global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack), (CLR.Utils.Extensions.TypeFlags)0);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
object instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)16);
((System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>)instance_of_this_method).Start<global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor>(ref @stateMachine);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);
object ___obj = @stateMachine;
if (___dst->ObjectType >= ObjectTypes.Object)
{
if (___obj is CrossBindingAdaptorType)
___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
__mStack[___dst->Value] = ___obj;
}
else
{
ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain);
}
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
var ___type = __domain.GetType(___obj.GetType()) as CLRType;
___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var ___type = __domain.GetType(ptr_of_this_method->Value);
if(___type is ILType)
{
((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine;
}
break;
}
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
__intp.Free(ptr_of_this_method);
return __ret;
}
static StackObject* get_Task_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)16);
var result_of_this_method = instance_of_this_method.Task;
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
object obj_result_of_this_method = result_of_this_method;
if(obj_result_of_this_method is CrossBindingAdaptorType)
{
return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance);
}
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* AwaitUnsafeOnCompleted_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 3);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor @stateMachine = (global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor)typeof(global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack), (CLR.Utils.Extensions.TypeFlags)0);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Runtime.CompilerServices.TaskAwaiter<System.Boolean> @awaiter = (System.Runtime.CompilerServices.TaskAwaiter<System.Boolean>)typeof(System.Runtime.CompilerServices.TaskAwaiter<System.Boolean>).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack), (CLR.Utils.Extensions.TypeFlags)16);
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)16);
instance_of_this_method.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<System.Boolean>, global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor>(ref @awaiter, ref @stateMachine);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);
object ___obj = @stateMachine;
if (___dst->ObjectType >= ObjectTypes.Object)
{
if (___obj is CrossBindingAdaptorType)
___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
__mStack[___dst->Value] = ___obj;
}
else
{
ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain);
}
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
var ___type = __domain.GetType(___obj.GetType()) as CLRType;
___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var ___type = __domain.GetType(ptr_of_this_method->Value);
if(___type is ILType)
{
((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as global::IAsyncStateMachineClassInheritanceAdaptor.IAsyncStateMachineAdaptor[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine;
}
break;
}
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);
object ___obj = @awaiter;
if (___dst->ObjectType >= ObjectTypes.Object)
{
if (___obj is CrossBindingAdaptorType)
___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
__mStack[___dst->Value] = ___obj;
}
else
{
ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain);
}
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter;
}
else
{
var ___type = __domain.GetType(___obj.GetType()) as CLRType;
___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var ___type = __domain.GetType(ptr_of_this_method->Value);
if(___type is ILType)
{
((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter;
}
else
{
((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.TaskAwaiter<System.Boolean>[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter;
}
break;
}
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
return __ret;
}
static StackObject* SetException_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Exception @exception = (System.Exception)typeof(System.Exception).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)0);
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)16);
instance_of_this_method.SetException(@exception);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
return __ret;
}
static StackObject* SetResult_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Boolean @result = ptr_of_this_method->Value == 1;
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Boolean>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)16);
instance_of_this_method.SetResult(@result);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
return __ret;
}
}
}
| 54.416471
| 373
| 0.579236
|
[
"MIT"
] |
Barryye/JEngine
|
UnityProject/Assets/Dependencies/ILRuntime/Generated/System_Runtime_CompilerServices_AsyncTaskMethodBuilder_1_Boo.cs
| 23,127
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.10
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace MixedRealityToolkit.Sharing {
public enum PairingResult {
Ok = 0,
CanceledByUser,
FailedToOpenIncomingConnection,
FailedToOpenOutgoingConnection,
PairingAlreadyInProgress,
ConnectionFailed,
NoAddressToConnectTo
}
}
| 26.541667
| 80
| 0.563579
|
[
"MIT"
] |
SteveKratos/Mirror
|
Viewer/API/PairingResult.cs
| 637
|
C#
|
using LibHac.Fat;
using LibHac.Fs;
using LibHac.Fs.Fsa;
namespace LibHac.FsSrv.FsCreator
{
public interface IFatFileSystemCreator
{
Result Create(out ReferenceCountedDisposable<IFileSystem> fileSystem,
ReferenceCountedDisposable<IStorage> baseStorage, FatAttribute attribute, int driveId,
Result invalidFatFormatResult, Result usableSpaceNotEnoughResult);
Result Format(ReferenceCountedDisposable<IStorage> partitionStorage, FatAttribute attribute,
FatFormatParam formatParam, int driveId, Result invalidFatFormatResult, Result usableSpaceNotEnoughResult);
}
}
| 40.125
| 120
| 0.753894
|
[
"BSD-3-Clause"
] |
Thealexbarney/LibHac
|
src/LibHac/FsSrv/FsCreator/IFatFileSystemCreator.cs
| 644
|
C#
|
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using UnityEngine;
using UnityScript.Lang;
public delegate void TargetUiChangeEventHandler();
public class Target : MonoBehaviour {
[SerializeField] private GameObject targetPrefab;
[SerializeField] public GameObject currentTarget;
[SerializeField] private GameObject targetFrame;
private RaycastHit2D[] hits;
/*private AutoAttack autoAttack;*/
public event TargetUiChangeEventHandler OnChangeUi;
private void NotifyUiChange()
{
if (OnChangeUi != null) OnChangeUi();
}
private void Awake()
{
InitializeComponents();
UpdateTargetUi();
}
private void InitializeComponents()
{
/*
autoAttack = GameObject.FindWithTag(Tags.Player).GetComponentInChildren<AutoAttack>();
*/
}
void Update()
{
DetectAndSetTargetOnClick();
//StartPlayerAutoAttackOn(Input.GetMouseButton(1));
}
/*private void StartPlayerAutoAttackOn(bool input)
{
if (!input && !autoAttack.IsAttacking) return;
if (IsTargetableUnderMouse())
{
InstantiateTarget();
UpdateTargetUi();
autoAttack.AutoAttackAtTarget();
}
else
{
RemoveTarget();
}
}*/
private void DetectAndSetTargetOnClick()
{
if (!Input.GetMouseButtonDown(0)) return;
if (IsTargetableUnderMouse())
{
InstantiateTarget();
UpdateTargetUi();
}
else
{
RemoveTarget();
}
}
public void RemoveTarget()
{
if (IsSomethingTargeted())
{
Destroy(GameObject.FindWithTag(Tags.Target).gameObject);
}
currentTarget = null;
UpdateTargetUi();
}
private bool IsTargetableUnderMouse()
{
hits = null;
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mousePos2D = new Vector2(mousePos.x, mousePos.y);
hits = Physics2D.RaycastAll(mousePos2D, Vector2.zero);
return hits.Length > 0;
}
private void InstantiateTarget()
{
foreach (var hit2D in hits)
{
if (hit2D.collider.CompareTag(Tags.Targetable))
{
var other = hit2D.collider.transform.root;
RemoveTarget();
Instantiate(targetPrefab, other.position, Quaternion.identity, other);
currentTarget = other.gameObject;
return;
}
RemoveTarget();
}
}
public bool IsTargetAttackable()
{
return IsSomethingTargeted() && currentTarget.CompareTag(Tags.Enemy);
}
public bool IsSomethingTargeted()
{
return currentTarget != null;
}
private void UpdateTargetUi()
{
targetFrame.SetActive(IsSomethingTargeted());
NotifyUiChange();
}
}
| 19.206107
| 88
| 0.721383
|
[
"MIT"
] |
JonathanRN/TopdownRPG
|
Assets/Scripts/Playmode/Characters/Target/Target.cs
| 2,518
|
C#
|
using FreeSql.Extensions.EntityUtil;
using FreeSql.Internal.Model;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace FreeSql.Internal.CommonProvider
{
public abstract class Select1Provider<T1> : Select0Provider<ISelect<T1>, T1>, ISelect<T1>
where T1 : class
{
public Select1Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere)
{
_whereGlobalFilter = _orm.GlobalFilter.GetFilters();
_whereCascadeExpression.AddRange(_whereGlobalFilter.Select(a => a.Where));
}
protected ISelect<T1> InternalFrom(LambdaExpression lambdaExp)
{
if (lambdaExp != null)
{
for (var a = 1; a < lambdaExp.Parameters.Count; a++)
{
var tb = _commonUtils.GetTableByEntity(lambdaExp.Parameters[a].Type);
if (tb == null) throw new ArgumentException($"{lambdaExp.Parameters[a].Name} 类型错误");
_tables.Add(new SelectTableInfo { Table = tb, Alias = lambdaExp.Parameters[a].Name, On = null, Type = SelectTableInfoType.From });
}
}
var exp = lambdaExp?.Body;
if (exp?.NodeType == ExpressionType.Call)
{
var expCall = exp as MethodCallExpression;
var stockCall = new Stack<MethodCallExpression>();
while (expCall != null)
{
stockCall.Push(expCall);
expCall = expCall.Object as MethodCallExpression;
}
while (stockCall.Any())
{
expCall = stockCall.Pop();
switch (expCall.Method.Name)
{
case "Where": this.InternalWhere(expCall.Arguments[0]); break;
case "WhereIf":
if ((bool)Expression.Lambda(expCall.Arguments[0]).Compile().DynamicInvoke())
this.InternalWhere(expCall.Arguments[1]);
break;
case "OrderBy":
if (expCall.Arguments.Count == 2 && expCall.Arguments[0].Type == typeof(bool))
{
var ifcond = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, expCall.Arguments[0], false, null);
if (ifcond == "1" || ifcond == "'t'")
this.InternalOrderBy(expCall.Arguments.LastOrDefault());
break;
}
this.InternalOrderBy(expCall.Arguments.LastOrDefault());
break;
case "OrderByDescending":
if (expCall.Arguments.Count == 2 && expCall.Arguments[0].Type == typeof(bool))
{
var ifcond = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, expCall.Arguments[0], false, null);
if (ifcond == "1" || ifcond == "'t'" || ifcond == "-1")//MsAccess -1
this.InternalOrderByDescending(expCall.Arguments.LastOrDefault());
break;
}
this.InternalOrderByDescending(expCall.Arguments.LastOrDefault());
break;
case "LeftJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.LeftJoin); break;
case "InnerJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.InnerJoin); break;
case "RightJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.RightJoin); break;
default: throw new NotImplementedException($"未实现 {expCall.Method.Name}");
}
}
}
return this;
}
public ISelect<T1> As(string alias)
{
var oldAs = _tables.First().Alias;
var newAs = string.IsNullOrEmpty(alias) ? "a" : alias;
if (oldAs != newAs)
{
_tables.First().Alias = newAs;
var wh = _where.ToString();
_where.Replace($" {oldAs}.", $" {newAs}.");
}
return this;
}
public double Avg<TMember>(Expression<Func<T1, TMember>> column)
{
if (column == null) return default(double);
_tables[0].Parameter = column.Parameters[0];
return this.InternalAvg(column?.Body);
}
public abstract ISelect<T1, T2> From<T2>(Expression<Func<ISelectFromExpression<T1>, T2, ISelectFromExpression<T1>>> exp) where T2 : class;
public abstract ISelect<T1, T2, T3> From<T2, T3>(Expression<Func<ISelectFromExpression<T1>, T2, T3, ISelectFromExpression<T1>>> exp) where T2 : class where T3 : class;
public abstract ISelect<T1, T2, T3, T4> From<T2, T3, T4>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, ISelectFromExpression<T1>>> exp) where T2 : class where T3 : class where T4 : class;
public abstract ISelect<T1, T2, T3, T4, T5> From<T2, T3, T4, T5>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, ISelectFromExpression<T1>>> exp) where T2 : class where T3 : class where T4 : class where T5 : class;
public abstract ISelect<T1, T2, T3, T4, T5, T6> From<T2, T3, T4, T5, T6>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, ISelectFromExpression<T1>>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class;
public abstract ISelect<T1, T2, T3, T4, T5, T6, T7> From<T2, T3, T4, T5, T6, T7>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, ISelectFromExpression<T1>>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class;
public abstract ISelect<T1, T2, T3, T4, T5, T6, T7, T8> From<T2, T3, T4, T5, T6, T7, T8>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression<T1>>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class;
public abstract ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9> From<T2, T3, T4, T5, T6, T7, T8, T9>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression<T1>>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class;
public abstract ISelect<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> From<T2, T3, T4, T5, T6, T7, T8, T9, T10>(Expression<Func<ISelectFromExpression<T1>, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression<T1>>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class;
public ISelectGrouping<TKey, T1> GroupBy<TKey>(Expression<Func<T1, TKey>> columns)
{
if (columns == null) return this.InternalGroupBy<TKey, T1>(columns);
_tables[0].Parameter = columns.Parameters[0];
return this.InternalGroupBy<TKey, T1>(columns);
}
public TMember Max<TMember>(Expression<Func<T1, TMember>> column)
{
if (column == null) return default(TMember);
_tables[0].Parameter = column.Parameters[0];
return this.InternalMax<TMember>(column.Body);
}
public TMember Min<TMember>(Expression<Func<T1, TMember>> column)
{
if (column == null) return default(TMember);
_tables[0].Parameter = column.Parameters[0];
return this.InternalMin<TMember>(column.Body);
}
public void OrderByReflection(LambdaExpression column, bool isDescending)
{
if (column == null) return;
_tables[0].Parameter = column.Parameters[0];
if (isDescending) this.InternalOrderByDescending(column.Body);
else this.InternalOrderBy(column.Body);
}
public ISelect<T1> OrderBy<TMember>(Expression<Func<T1, TMember>> column) => this.OrderBy(true, column);
public ISelect<T1> OrderBy<TMember>(bool condition, Expression<Func<T1, TMember>> column)
{
if (condition == false || column == null) return this;
_tables[0].Parameter = column.Parameters[0];
return this.InternalOrderBy(column.Body);
}
public ISelect<T1> OrderByDescending<TMember>(Expression<Func<T1, TMember>> column) => this.OrderByDescending(true, column);
public ISelect<T1> OrderByDescending<TMember>(bool condition, Expression<Func<T1, TMember>> column)
{
if (condition == false || column == null) return this;
_tables[0].Parameter = column.Parameters[0];
return this.InternalOrderByDescending(column.Body);
}
public ISelect<T1> OrderByIf<TMember>(bool condition, Expression<Func<T1, TMember>> column, bool descending = false) =>
descending ? this.OrderByDescending(condition, column) : this.OrderBy(condition, column);
public decimal Sum<TMember>(Expression<Func<T1, TMember>> column)
{
if (column == null) return default(decimal);
_tables[0].Parameter = column.Parameters[0];
return this.InternalSum(column.Body);
}
class IncludeManyNewInit
{
public TableInfo Table { get; }
public Dictionary<string, IncludeManyNewInit> Childs { get; } = new Dictionary<string, IncludeManyNewInit>();
public Expression CurrentExpression { get; }
public bool IsOutputPrimary { get; set; }
public IncludeManyNewInit(TableInfo table, Expression currentExpression)
{
this.Table = table;
this.CurrentExpression = currentExpression;
}
}
public List<TReturn> ToList<TReturn>(Expression<Func<T1, TReturn>> select)
{
if (select == null) return this.InternalToList<TReturn>(select?.Body);
_tables[0].Parameter = select.Parameters[0];
if (_includeToList?.Any() != true) return this.InternalToList<TReturn>(select.Body);
var findIncludeMany = new List<string>();
var map = new ReadAnonymousTypeInfo();
var field = new StringBuilder();
var index = 0;
_commonExpression.ReadAnonymousField(_tables, field, map, ref index, select.Body, this, null, _whereCascadeExpression, findIncludeMany, true);
var af = new ReadAnonymousTypeAfInfo(map, field.Length > 0 ? field.Remove(0, 2).ToString() : null);
if (findIncludeMany.Any() == false) return this.ToListMapReaderPrivate<TReturn>(af, null);
var parmExp = Expression.Parameter(_tables[0].Table.Type, _tables[0].Alias);
var incNewInit = new IncludeManyNewInit(_tables[0].Table, parmExp);
foreach (var inc in _includeInfo)
{
var curIncNewInit = incNewInit;
Expression curParmExp = parmExp;
for (var a = 0; a < inc.Value.Length - 1; a++)
{
curParmExp = Expression.MakeMemberAccess(parmExp, inc.Value[a].Member);
if (curIncNewInit.Childs.ContainsKey(inc.Value[a].Member.Name) == false)
curIncNewInit.Childs.Add(inc.Value[a].Member.Name, curIncNewInit = new IncludeManyNewInit(_orm.CodeFirst.GetTableByEntity(inc.Value[a].Type), curParmExp));
else
curIncNewInit = curIncNewInit.Childs[inc.Value[a].Member.Name];
}
curIncNewInit.IsOutputPrimary = true;
}
MemberInitExpression GetIncludeManyNewInitExpression(IncludeManyNewInit imni)
{
var bindings = new List<MemberBinding>();
if (imni.IsOutputPrimary) bindings.AddRange(imni.Table.Primarys.Select(a => Expression.Bind(imni.Table.Properties[a.CsName], Expression.MakeMemberAccess(imni.CurrentExpression, imni.Table.Properties[a.CsName]))));
if (imni.Childs.Any()) bindings.AddRange(imni.Childs.Select(a => Expression.Bind(imni.Table.Properties[a.Key], GetIncludeManyNewInitExpression(a.Value))));
return Expression.MemberInit(imni.Table.Type.InternalNewExpression(), bindings);
}
var otherNewInit = GetIncludeManyNewInitExpression(incNewInit); //获取 IncludeMany 包含的最简化字段
if (otherNewInit.Bindings.Any() == false) return this.ToListMapReaderPrivate<TReturn>(af, null);
var otherMap = new ReadAnonymousTypeInfo();
field.Clear();
_commonExpression.ReadAnonymousField(_tables, field, otherMap, ref index, otherNewInit, this, null, _whereCascadeExpression, null, true);
var otherRet = new List<object>();
var otherAf = new ReadAnonymousTypeOtherInfo(field.ToString(), otherMap, otherRet);
af.fillIncludeMany = new List<NativeTuple<string, IList, int>>();
var ret = this.ToListMapReaderPrivate<TReturn>(af, new[] { otherAf });
this.SetList(otherRet.Select(a => (T1)a).ToList()); //级联加载
foreach (var fim in af.fillIncludeMany)
{
var splitKeys = fim.Item1.Split('.');
var otherRetItem = otherRet[fim.Item3];
var otherRetItemType = _tables[0].Table.Type;
foreach(var splitKey in splitKeys)
{
otherRetItem = _orm.GetEntityValueWithPropertyName(otherRetItemType, otherRetItem, splitKey);
otherRetItemType = _orm.CodeFirst.GetTableByEntity(otherRetItemType).Properties[splitKey].PropertyType;
}
if (otherRetItem == null) continue;
var otherList = otherRetItem as IEnumerable;
foreach (var otherListItem in otherList) fim.Item2.Add(otherListItem);
}
return ret;
}
public List<TDto> ToList<TDto>() => ToList(GetToListDtoSelector<TDto>());
Expression<Func<T1, TDto>> GetToListDtoSelector<TDto>()
{
return Expression.Lambda<Func<T1, TDto>>(
typeof(TDto).InternalNewExpression(),
_tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"));
}
public void ToChunk<TReturn>(Expression<Func<T1, TReturn>> select, int size, Action<FetchCallbackArgs<List<TReturn>>> done)
{
if (select == null || done == null) return;
_tables[0].Parameter = select.Parameters[0];
this.InternalToChunk<TReturn>(select.Body, size, done);
}
public DataTable ToDataTable<TReturn>(Expression<Func<T1, TReturn>> select)
{
if (select == null) return this.InternalToDataTable(select?.Body);
_tables[0].Parameter = select.Parameters[0];
return this.InternalToDataTable(select?.Body);
}
public string ToSql<TReturn>(Expression<Func<T1, TReturn>> select, FieldAliasOptions fieldAlias = FieldAliasOptions.AsIndex)
{
if (select == null) return this.InternalToSql<TReturn>(select?.Body, fieldAlias);
_tables[0].Parameter = select.Parameters[0];
return this.InternalToSql<TReturn>(select?.Body, fieldAlias);
}
public TReturn ToAggregate<TReturn>(Expression<Func<ISelectGroupingAggregate<T1>, TReturn>> select)
{
if (select == null) return default(TReturn);
_tables[0].Parameter = select.Parameters[0];
return this.InternalToAggregate<TReturn>(select?.Body);
}
public ISelect<T1> Aggregate<TReturn>(Expression<Func<ISelectGroupingAggregate<T1>, TReturn>> select, out TReturn result)
{
result = ToAggregate(select);
return this;
}
public ISelect<T1> Where(Expression<Func<T1, bool>> exp) => WhereIf(true, exp);
public ISelect<T1> WhereIf(bool condition, Expression<Func<T1, bool>> exp)
{
if (condition == false || exp == null) return this;
_tables[0].Parameter = exp.Parameters[0];
return this.InternalWhere(exp?.Body);
}
public ISelect<T1> Where<T2>(Expression<Func<T1, T2, bool>> exp) where T2 : class
{
if (exp == null) return this;
_tables[0].Parameter = exp.Parameters[0];
return this.InternalWhere(exp?.Body);
}
public ISelect<T1> Where<T2>(Expression<Func<T2, bool>> exp) where T2 : class
{
if (exp == null) return this;
//_tables[0].Parameter = exp.Parameters[0];
return this.InternalWhere(exp?.Body);
}
public ISelect<T1> Where<T2, T3>(Expression<Func<T1, T2, T3, bool>> exp) where T2 : class where T3 : class
{
if (exp == null) return this;
_tables[0].Parameter = exp.Parameters[0];
return this.InternalWhere(exp?.Body);
}
public ISelect<T1> Where<T2, T3, T4>(Expression<Func<T1, T2, T3, T4, bool>> exp) where T2 : class where T3 : class where T4 : class
{
if (exp == null) return this;
_tables[0].Parameter = exp.Parameters[0];
return this.InternalWhere(exp?.Body);
}
public ISelect<T1> Where<T2, T3, T4, T5>(Expression<Func<T1, T2, T3, T4, T5, bool>> exp) where T2 : class where T3 : class where T4 : class where T5 : class
{
if (exp == null) return this;
_tables[0].Parameter = exp.Parameters[0];
return this.InternalWhere(exp?.Body);
}
public ISelect<T1> WhereDynamic(object dywhere, bool not = false) => not == false ?
this.Where(_commonUtils.WhereObject(_tables.First().Table, $"{_tables.First().Alias}.", dywhere)) :
this.Where($"not({_commonUtils.WhereObject(_tables.First().Table, $"{_tables.First().Alias}.", dywhere)})");
public ISelect<T1> WhereCascade(Expression<Func<T1, bool>> exp)
{
if (exp != null) _whereCascadeExpression.Add(exp);
return this;
}
public ISelect<T1> WithSql(string sql, object parms = null)
{
this.AsTable((type, old) =>
{
if (type == _tables[0].Table?.Type && string.IsNullOrEmpty(sql) == false) return $"( {sql} )";
return old;
});
if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms));
return this;
}
public bool Any(Expression<Func<T1, bool>> exp)
{
var oldwhere = _where.ToString();
var ret = this.Where(exp).Any();
_where.Clear().Append(oldwhere);
return ret;
}
public TReturn ToOne<TReturn>(Expression<Func<T1, TReturn>> select) => this.Limit(1).ToList(select).FirstOrDefault();
public TDto ToOne<TDto>() => this.Limit(1).ToList<TDto>().FirstOrDefault();
public TReturn First<TReturn>(Expression<Func<T1, TReturn>> select) => this.ToOne(select);
public TDto First<TDto>() => this.ToOne<TDto>();
public override List<T1> ToList(bool includeNestedMembers = false) => base.ToList(_isIncluded || includeNestedMembers);
bool _isIncluded = false;
public ISelect<T1> Include<TNavigate>(Expression<Func<T1, TNavigate>> navigateSelector) where TNavigate : class
{
var expBody = navigateSelector?.Body;
if (expBody == null) return this;
if (expBody.NodeType != ExpressionType.MemberAccess) throw new Exception("Include 参数类型错误,表达式类型应该为 MemberAccess");
if (typeof(IEnumerable).IsAssignableFrom(expBody.Type)) throw new Exception("Include 参数类型错误,集合属性请使用 IncludeMany");
var tb = _commonUtils.GetTableByEntity(expBody.Type);
if (tb == null) throw new Exception("Include 参数类型错误");
_isIncluded = true;
_tables[0].Parameter = navigateSelector.Parameters[0];
_commonExpression.ExpressionWhereLambda(_tables, Expression.MakeMemberAccess(expBody, tb.Properties[tb.ColumnsByCs.First().Value.CsName]), null, null, null);
return this;
}
static NativeTuple<ParameterExpression, List<MemberExpression>> GetExpressionStack(Expression exp)
{
Expression tmpExp = exp;
ParameterExpression param = null;
var members = new Stack<MemberExpression>();
var isbreak = false;
while (isbreak == false)
{
switch (tmpExp.NodeType)
{
case ExpressionType.MemberAccess:
var memExp = tmpExp as MemberExpression;
tmpExp = memExp.Expression;
members.Push(memExp);
continue;
case ExpressionType.Parameter:
param = tmpExp as ParameterExpression;
isbreak = true;
break;
default:
throw new Exception($"表达式错误,它不是连续的 MemberAccess 类型:{exp}");
}
}
if (param == null) throw new Exception($"表达式错误,它的顶级对象不是 ParameterExpression:{exp}");
return NativeTuple.Create(param, members.ToList());
}
static MethodInfo GetEntityValueWithPropertyNameMethod = typeof(EntityUtilExtensions).GetMethod("GetEntityValueWithPropertyName");
static ConcurrentDictionary<Type, ConcurrentDictionary<string, MethodInfo>> _dicTypeMethod = new ConcurrentDictionary<Type, ConcurrentDictionary<string, MethodInfo>>();
public ISelect<T1> IncludeMany<TNavigate>(Expression<Func<T1, IEnumerable<TNavigate>>> navigateSelector, Action<ISelect<TNavigate>> then = null) where TNavigate : class
{
var throwNavigateSelector = new Exception("IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess");
var expBody = navigateSelector?.Body;
if (expBody == null) return this;
if (expBody.NodeType == ExpressionType.Convert) expBody = (expBody as UnaryExpression)?.Operand; //- 兼容 Vb.Net 无法使用 IncludeMany 的问题;
MethodCallExpression whereExp = null;
int takeNumber = 0;
Expression<Func<TNavigate, TNavigate>> selectExp = null;
while (expBody.NodeType == ExpressionType.Call)
{
throwNavigateSelector = new Exception($"IncludeMany {nameof(navigateSelector)} 参数类型错误,正确格式: a.collections.Take(1).Where(c => c.aid == a.id).Select(a => new TNavigate {{ }})");
var callExp = (expBody as MethodCallExpression);
switch (callExp.Method.Name)
{
case "Where":
whereExp = callExp;
break;
case "Take":
takeNumber = int.Parse(_commonExpression.ExpressionLambdaToSql(callExp.Arguments[1], new CommonExpression.ExpTSC { }));
break;
case "Select":
selectExp = (callExp.Arguments[1] as Expression<Func<TNavigate, TNavigate>>);
if (selectExp?.Parameters.Count != 1) throw new Exception($"IncludeMany {nameof(navigateSelector)} 参数错误,Select 只可以使用一个参数的方法,正确格式: .Select(t => new TNavigate {{ }})");
break;
default: throw throwNavigateSelector;
}
expBody = callExp.Object ?? callExp.Arguments.FirstOrDefault();
}
if (expBody.NodeType != ExpressionType.MemberAccess) throw throwNavigateSelector;
var collMem = expBody as MemberExpression;
var ges = GetExpressionStack(collMem.Expression);
var membersParam = ges.Item1;
var members = ges.Item2;
var tb = _commonUtils.GetTableByEntity(collMem.Expression.Type);
if (tb == null) throw throwNavigateSelector;
var collMemElementType = (collMem.Type.IsGenericType ? collMem.Type.GetGenericArguments().FirstOrDefault() : collMem.Type.GetElementType());
if (typeof(TNavigate) != collMemElementType)
throw new Exception($"IncludeMany {nameof(navigateSelector)} 参数错误,Select lambda参数返回值必须和 {collMemElementType} 类型一致");
var tbNav = _commonUtils.GetTableByEntity(typeof(TNavigate));
if (tbNav == null) throw new Exception($"类型 {typeof(TNavigate).FullName} 错误,不能使用 IncludeMany");
if (collMem.Expression.NodeType != ExpressionType.Parameter)
_commonExpression.ExpressionWhereLambda(_tables, Expression.MakeMemberAccess(collMem.Expression, tb.Properties[tb.ColumnsByCs.First().Value.CsName]), null, null, null);
TableRef tbref = null;
var tbrefOneToManyColumns = new List<List<MemberExpression>>(); //临时 OneToMany 三个表关联,第三个表需要前两个表确定
if (whereExp == null)
{
tbref = tb.GetTableRef(collMem.Member.Name, true);
if (tbref == null) throw new Exception($"IncludeMany 类型 {tb.Type.DisplayCsharp()} 的属性 {collMem.Member.Name} 不是有效的导航属性,提示:IsIgnore = true 不会成为导航属性");
}
else
{
//处理临时关系映射
tbref = new TableRef
{
RefType = TableRefType.OneToMany,
Property = tb.Properties[collMem.Member.Name],
RefEntityType = tbNav.Type
};
foreach (var whereExpArg in whereExp.Arguments)
{
if (whereExpArg.NodeType != ExpressionType.Lambda) continue;
var whereExpArgLamb = whereExpArg as LambdaExpression;
Action<Expression> actWeiParse = null;
actWeiParse = expOrg =>
{
var binaryExp = expOrg as BinaryExpression;
if (binaryExp == null) throw throwNavigateSelector;
switch (binaryExp.NodeType)
{
case ExpressionType.AndAlso:
actWeiParse(binaryExp.Left);
actWeiParse(binaryExp.Right);
break;
case ExpressionType.Equal:
Expression leftExp = binaryExp.Left;
Expression rightExp = binaryExp.Right;
while (leftExp.NodeType == ExpressionType.Convert) leftExp = (leftExp as UnaryExpression)?.Operand;
while (rightExp.NodeType == ExpressionType.Convert) rightExp = (rightExp as UnaryExpression)?.Operand;
var leftP1MemberExp = leftExp as MemberExpression;
var rightP1MemberExp = rightExp as MemberExpression;
if (leftP1MemberExp == null || rightP1MemberExp == null) throw throwNavigateSelector;
if (leftP1MemberExp.Expression == whereExpArgLamb.Parameters[0])
{
var rightGes = GetExpressionStack(rightP1MemberExp.Expression);
var rightMembersParam = rightGes.Item1;
var rightMembers = rightGes.Item2;
if (rightMembersParam != membersParam) throw throwNavigateSelector;
var isCollMemEquals = rightMembers.Count == members.Count;
if (isCollMemEquals)
{
for (var l = 0; l < members.Count; l++)
if (members[l].Member != rightMembers[l].Member)
{
isCollMemEquals = false;
break;
}
}
if (isCollMemEquals)
{
tbref.Columns.Add(tb.ColumnsByCs[rightP1MemberExp.Member.Name]);
tbrefOneToManyColumns.Add(null);
}
else
{
var tmpTb = _commonUtils.GetTableByEntity(rightP1MemberExp.Expression.Type);
if (tmpTb == null) throw throwNavigateSelector;
tbref.Columns.Add(tmpTb.ColumnsByCs[rightP1MemberExp.Member.Name]);
tbrefOneToManyColumns.Add(rightMembers);
}
tbref.RefColumns.Add(tbNav.ColumnsByCs[leftP1MemberExp.Member.Name]);
return;
}
if (rightP1MemberExp.Expression == whereExpArgLamb.Parameters[0])
{
var leftGes = GetExpressionStack(leftP1MemberExp.Expression);
var leftMembersParam = leftGes.Item1;
var leftMembers = leftGes.Item2;
if (leftMembersParam != membersParam) throw throwNavigateSelector;
var isCollMemEquals = leftMembers.Count == members.Count;
if (isCollMemEquals)
{
for (var l = 0; l < members.Count; l++)
if (members[l].Member != leftMembers[l].Member)
{
isCollMemEquals = false;
break;
}
}
if (isCollMemEquals)
{
tbref.Columns.Add(tb.ColumnsByCs[leftP1MemberExp.Member.Name]);
tbrefOneToManyColumns.Add(null);
}
else
{
var tmpTb = _commonUtils.GetTableByEntity(leftP1MemberExp.Expression.Type);
if (tmpTb == null) throw throwNavigateSelector;
tbref.Columns.Add(tmpTb.ColumnsByCs[leftP1MemberExp.Member.Name]);
tbrefOneToManyColumns.Add(leftMembers);
}
tbref.RefColumns.Add(tbNav.ColumnsByCs[rightP1MemberExp.Member.Name]);
return;
}
throw throwNavigateSelector;
default: throw throwNavigateSelector;
}
};
actWeiParse(whereExpArgLamb.Body);
break;
}
if (tbref.Columns.Any() == false) throw throwNavigateSelector;
}
#if net40
Action<object, bool> includeToListSyncOrAsync = (listObj, isAsync) =>
{
isAsync = false;
#else
Func<object, bool, Task> includeToListSyncOrAsync = async (listObj, isAsync) =>
{
#endif
var list = listObj as List<T1>;
if (list == null) return;
if (list.Any() == false) return;
if (tbref.Columns.Any() == false) return;
var t1parm = Expression.Parameter(typeof(T1));
Expression membersExp = t1parm;
Expression membersExpNotNull = null;
foreach (var mem in members)
{
membersExp = Expression.MakeMemberAccess(membersExp, mem.Member);
var expNotNull = Expression.NotEqual(membersExp, Expression.Constant(null));
if (membersExpNotNull == null) membersExpNotNull = expNotNull;
else membersExpNotNull = Expression.AndAlso(membersExpNotNull, expNotNull);
}
members.Clear();
var listValueExp = Expression.Parameter(typeof(List<TNavigate>), "listValue");
var setListValue = membersExpNotNull == null ?
Expression.Lambda<Action<T1, List<TNavigate>>>(
Expression.Assign(
Expression.MakeMemberAccess(membersExp, collMem.Member),
Expression.TypeAs(listValueExp, collMem.Type)
), t1parm, listValueExp).Compile() :
Expression.Lambda<Action<T1, List<TNavigate>>>(
Expression.IfThen(
membersExpNotNull,
Expression.Assign(
Expression.MakeMemberAccess(membersExp, collMem.Member),
Expression.TypeAs(listValueExp, collMem.Type)
)
), t1parm, listValueExp).Compile();
var returnTarget = Expression.Label(typeof(object));
var propertyNameExp = Expression.Parameter(typeof(string), "propertyName");
var getListValue1 = membersExpNotNull == null ?
Expression.Lambda<Func<T1, string, object>>(
Expression.Block(
Expression.IfThenElse(
Expression.Equal(propertyNameExp, Expression.Constant("")), //propertyName == "" 返回自身
Expression.Return(returnTarget, membersExp),
Expression.Return(returnTarget, Expression.Call(null, GetEntityValueWithPropertyNameMethod, Expression.Constant(_orm), Expression.Constant(membersExp.Type), membersExp, propertyNameExp))
),
Expression.Label(returnTarget, Expression.Default(typeof(object)))
), t1parm, propertyNameExp).Compile() :
Expression.Lambda<Func<T1, string, object>>(
Expression.Block(
Expression.IfThen(
membersExpNotNull,
Expression.IfThenElse(
Expression.Equal(propertyNameExp, Expression.Constant("")),
Expression.Return(returnTarget, membersExp),
Expression.Return(returnTarget, Expression.Call(null, GetEntityValueWithPropertyNameMethod, Expression.Constant(_orm), Expression.Constant(membersExp.Type), membersExp, propertyNameExp))
)
),
Expression.Label(returnTarget, Expression.Default(typeof(object)))
), t1parm, propertyNameExp).Compile();
var getListValue2 = new List<Func<T1, string, object>>();
for (var j = 0; j < tbrefOneToManyColumns.Count; j++)
{
if (tbrefOneToManyColumns[j] == null)
{
getListValue2.Add(null);
continue;
}
Expression tbrefOneToManyColumnsMembers = t1parm;
Expression tbrefOneToManyColumnsMembersNotNull = null;
foreach (var mem in tbrefOneToManyColumns[j])
{
tbrefOneToManyColumnsMembers = Expression.MakeMemberAccess(tbrefOneToManyColumnsMembers, mem.Member);
var expNotNull = Expression.NotEqual(membersExp, Expression.Constant(null));
if (tbrefOneToManyColumnsMembersNotNull == null) tbrefOneToManyColumnsMembersNotNull = expNotNull;
else tbrefOneToManyColumnsMembersNotNull = Expression.AndAlso(tbrefOneToManyColumnsMembersNotNull, expNotNull);
}
tbrefOneToManyColumns[j].Clear();
getListValue2.Add(tbrefOneToManyColumnsMembersNotNull == null ?
Expression.Lambda<Func<T1, string, object>>(
Expression.Block(
Expression.Return(returnTarget, Expression.Call(null, GetEntityValueWithPropertyNameMethod, Expression.Constant(_orm), Expression.Constant(tbrefOneToManyColumnsMembers.Type), tbrefOneToManyColumnsMembers, propertyNameExp)),
Expression.Label(returnTarget, Expression.Default(typeof(object)))
), t1parm, propertyNameExp).Compile() :
Expression.Lambda<Func<T1, string, object>>(
Expression.Block(
Expression.IfThen(
tbrefOneToManyColumnsMembersNotNull,
Expression.Return(returnTarget, Expression.Call(null, GetEntityValueWithPropertyNameMethod, Expression.Constant(_orm), Expression.Constant(tbrefOneToManyColumnsMembers.Type), tbrefOneToManyColumnsMembers, propertyNameExp))
),
Expression.Label(returnTarget, Expression.Default(typeof(object)))
), t1parm, propertyNameExp).Compile());
}
tbrefOneToManyColumns.Clear();
Func<T1, string, int, object> getListValue = (item, propName, colIndex) =>
{
if (getListValue2.Any() && getListValue2[colIndex] != null) return getListValue2[colIndex](item, propName);
return getListValue1(item, propName);
};
foreach (var item in list)
setListValue(item, null);
Action<List<TNavigate>, TableInfo> fillOneToManyData = (subList, tbref2) =>
{
if (subList.Any() == false)
{
foreach (var item in list)
setListValue(item, new List<TNavigate>());
return;
}
Dictionary<string, List<Tuple<T1, List<TNavigate>>>> dicList = new Dictionary<string, List<Tuple<T1, List<TNavigate>>>>();
foreach (var item in list)
{
if (tbref.Columns.Count == 1)
{
var dicListKey = getListValue(item, tbref.Columns[0].CsName, 0)?.ToString();
if (dicListKey == null) continue;
var dicListVal = Tuple.Create(item, new List<TNavigate>());
if (dicList.TryGetValue(dicListKey, out var items) == false)
dicList.Add(dicListKey, items = new List<Tuple<T1, List<TNavigate>>>());
items.Add(dicListVal);
}
else
{
var sb = new StringBuilder();
for (var z = 0; z < tbref.Columns.Count; z++)
{
if (z > 0) sb.Append("*$*");
sb.Append(getListValue(item, tbref.Columns[z].CsName, z));
}
var dicListKey = sb.ToString();
var dicListVal = Tuple.Create(item, new List<TNavigate>());
if (dicList.TryGetValue(dicListKey, out var items) == false)
dicList.Add(dicListKey, items = new List<Tuple<T1, List<TNavigate>>>());
items.Add(dicListVal);
sb.Clear();
}
}
var parentNavs = new List<string>();
foreach (var navProp in tbref2.Properties)
{
if (tbref2.ColumnsByCs.ContainsKey(navProp.Key)) continue;
if (tbref2.ColumnsByCsIgnore.ContainsKey(navProp.Key)) continue;
var tr2ref = tbref2.GetTableRef(navProp.Key, false);
if (tr2ref == null) continue;
if (tr2ref.RefType != TableRefType.ManyToOne) continue;
if (tr2ref.RefEntityType != tb.Type) continue;
if (string.Join(",", tr2ref.Columns.Select(a => a.CsName).OrderBy(a => a)) != string.Join(",", tbref.RefColumns.Select(a => a.CsName).OrderBy(a => a))) continue; //- 修复 IncludeMany 只填充子属性中双向关系的 ManyToOne 对象值;防止把 ManyToOne 多个相同类型的导航属性值都填充了
parentNavs.Add(navProp.Key);
}
foreach (var nav in subList)
{
string key = null;
if (tbref.RefColumns.Count == 1)
{
key = _orm.GetEntityValueWithPropertyName(tbref.RefEntityType, nav, tbref.RefColumns[0].CsName)?.ToString() ?? "";
}
else
{
var sb = new StringBuilder();
for (var z = 0; z < tbref.RefColumns.Count; z++)
{
if (z > 0) sb.Append("*$*");
sb.Append(_orm.GetEntityValueWithPropertyName(tbref.RefEntityType, nav, tbref.RefColumns[z].CsName));
}
key = sb.ToString();
sb.Clear();
}
if (dicList.TryGetValue(key, out var t1items) == false) continue;
foreach (var t1item in t1items)
t1item.Item2.Add(nav);
//将子集合的,多对一,对象设置为当前对象
foreach (var parentNav in parentNavs)
foreach (var t1item in t1items)
_orm.SetEntityValueWithPropertyName(tbref.RefEntityType, nav, parentNav, getListValue1(t1item.Item1, "")); //propertyName == "" 返回自身
}
foreach (var t1items in dicList.Values)
foreach (var t1item in t1items)
setListValue(t1item.Item1, t1item.Item2);
dicList.Clear();
};
if (tbref.RefType == TableRefType.OneToMany && _includeManySubListOneToManyTempValue1 != null && _includeManySubListOneToManyTempValue1 is List<TNavigate>)
{
fillOneToManyData(_includeManySubListOneToManyTempValue1 as List<TNavigate>, _commonUtils.GetTableByEntity(tbref.RefEntityType));
return;
}
var subSelect = _orm.Select<TNavigate>()
.DisableGlobalFilter()
.WithConnection(_connection)
.WithTransaction(_transaction)
.TrackToList(_trackToList) as Select1Provider<TNavigate>;
if (_tableRules?.Any() == true)
foreach (var tr in _tableRules) subSelect.AsTable(tr);
if (_whereCascadeExpression.Any())
subSelect._whereCascadeExpression.AddRange(_whereCascadeExpression.ToArray());
//subSelect._aliasRule = _aliasRule; //把 SqlServer 查询锁传递下去
then?.Invoke(subSelect);
var subSelectT1Alias = subSelect._tables[0].Alias;
var oldWhere = subSelect._where.ToString();
if (oldWhere.StartsWith(" AND ")) oldWhere = oldWhere.Remove(0, 5);
if (selectExp != null)
{
var tmpinitExp = selectExp.Body as MemberInitExpression;
var newinitExpBindings = tmpinitExp.Bindings.ToList();
foreach (var tbrefCol in tbref.RefColumns)
{
if (newinitExpBindings.Any(a => a.Member.Name == tbrefCol.CsName)) continue;
var tmpMemberInfo = tbrefCol.Table.Properties[tbrefCol.CsName];
newinitExpBindings.Add(Expression.Bind(tmpMemberInfo, Expression.MakeMemberAccess(selectExp.Parameters[0], tmpMemberInfo)));
}
Expression newinitExp = Expression.MemberInit(tmpinitExp.NewExpression, newinitExpBindings.ToList());
var selectExpParam = subSelect._tables[0].Parameter ?? Expression.Parameter(typeof(TNavigate), subSelectT1Alias);
newinitExp = new NewExpressionVisitor(selectExpParam, selectExp.Parameters[0]).Replace(newinitExp);
selectExp = Expression.Lambda<Func<TNavigate, TNavigate>>(newinitExp, selectExpParam);
}
switch (tbref.RefType)
{
case TableRefType.OneToMany:
if (true)
{
var subList = new List<TNavigate>();
var tbref2 = _commonUtils.GetTableByEntity(tbref.RefEntityType);
Func<Dictionary<string, bool>> getWhereDic = () =>
{
var sbDic = new Dictionary<string, bool>();
for (var y = 0; y < list.Count; y++)
{
var sbWhereOne = new StringBuilder();
sbWhereOne.Append("(");
for (var z = 0; z < tbref.Columns.Count; z++)
{
if (z > 0) sbWhereOne.Append(" AND ");
sbWhereOne.Append(_commonUtils.FormatSql($"{subSelectT1Alias}.{_commonUtils.QuoteSqlName(tbref.RefColumns[z].Attribute.Name)}={{0}}", Utils.GetDataReaderValue(tbref.RefColumns[z].Attribute.MapType, getListValue(list[y], tbref.Columns[z].CsName, z))));
}
sbWhereOne.Append(")");
var whereOne = sbWhereOne.ToString();
sbWhereOne.Clear();
if (sbDic.ContainsKey(whereOne) == false) sbDic.Add(whereOne, true);
}
return sbDic;
};
if (takeNumber > 0)
{
Select0Provider<ISelect<TNavigate>, TNavigate>.GetAllFieldExpressionTreeInfo af = null;
ReadAnonymousTypeAfInfo mf = default;
if (selectExp == null) af = subSelect.GetAllFieldExpressionTreeLevelAll();
else mf = subSelect.GetExpressionField(selectExp);
var sbSql = new StringBuilder();
var sbDic = getWhereDic();
foreach (var sbd in sbDic)
{
subSelect._where.Clear();
subSelect.Where(sbd.Key).Where(oldWhere).Limit(takeNumber);
sbSql.Append("\r\nUNION ALL\r\nselect * from (").Append(subSelect.ToSql(selectExp == null ? af.Field : mf.field)).Append(") ftb");
}
sbSql.Remove(0, 13);
if (sbDic.Count == 1) sbSql.Remove(0, 15).Remove(sbSql.Length - 5, 5);
sbDic.Clear();
if (isAsync)
{
#if net40
#else
if (selectExp == null) subList = await subSelect.ToListAfPrivateAsync(sbSql.ToString(), af, null);
else subList = await subSelect.ToListMrPrivateAsync<TNavigate>(sbSql.ToString(), mf, null);
#endif
}
else
{
if (selectExp == null) subList = subSelect.ToListAfPrivate(sbSql.ToString(), af, null);
else subList = subSelect.ToListMrPrivate<TNavigate>(sbSql.ToString(), mf, null);
}
sbSql.Clear();
}
else
{
subSelect._where.Clear();
if (tbref.Columns.Count == 1)
{
var arrExp = Expression.NewArrayInit(tbref.RefColumns[0].CsType,
list.Select(a => getListValue(a, tbref.Columns[0].CsName, 0)).Distinct()
.Select(a => Expression.Constant(Utils.GetDataReaderValue(tbref.RefColumns[0].CsType, a), tbref.RefColumns[0].CsType)).ToArray());
var otmExpParm1 = Expression.Parameter(typeof(TNavigate), "a");
var containsMethod = _dicTypeMethod.GetOrAdd(tbref.RefColumns[0].CsType, et => new ConcurrentDictionary<string, MethodInfo>()).GetOrAdd("Contains", mn =>
typeof(Enumerable).GetMethods().Where(a => a.Name == mn).First()).MakeGenericMethod(tbref.RefColumns[0].CsType);
var refCol = Expression.MakeMemberAccess(otmExpParm1, tbref2.Properties[tbref.RefColumns[0].CsName]);
//if (refCol.Type.IsNullableType()) refCol = Expression.Property(refCol, CommonExpression._dicNullableValueProperty.GetOrAdd(refCol.Type, ct1 => ct1.GetProperty("Value")));
subSelect.Where(Expression.Lambda<Func<TNavigate, bool>>(
Expression.Call(null, containsMethod, arrExp, refCol), otmExpParm1));
}
else
{
var sbDic = getWhereDic();
var sbWhere = new StringBuilder();
foreach (var sbd in sbDic)
sbWhere.Append(" OR ").Append(sbd.Key);
subSelect.Where(sbWhere.Remove(0, 4).ToString());
sbWhere.Clear();
sbDic.Clear();
}
subSelect.Where(oldWhere);
if (isAsync)
{
#if net40
#else
if (selectExp == null) subList = await subSelect.ToListAsync(true);
else subList = await subSelect.ToListAsync<TNavigate>(selectExp);
#endif
}
else
{
if (selectExp == null) subList = subSelect.ToList(true);
else subList = subSelect.ToList<TNavigate>(selectExp);
}
}
fillOneToManyData(subList, tbref2);
}
break;
case TableRefType.ManyToMany:
if (true)
{
List<TNavigate> subList = null;
List<object> midList = new List<object>();
var tbref2 = _commonUtils.GetTableByEntity(tbref.RefEntityType);
var tbrefMid = _commonUtils.GetTableByEntity(tbref.RefMiddleEntityType);
var sbJoin = new StringBuilder().Append($"{_commonUtils.QuoteSqlName(tbrefMid.DbName)} midtb ON ");
for (var z = 0; z < tbref.RefColumns.Count; z++)
{
if (z > 0) sbJoin.Append(" AND ");
sbJoin.Append($"midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[tbref.Columns.Count + z].Attribute.Name)} = a.{_commonUtils.QuoteSqlName(tbref.RefColumns[z].Attribute.Name)}");
if (_whereCascadeExpression.Any())
{
var cascade = _commonExpression.GetWhereCascadeSql(new SelectTableInfo { Alias = "midtb", AliasInit = "midtb", Table = tbrefMid, Type = SelectTableInfoType.InnerJoin }, _whereCascadeExpression, true);
if (string.IsNullOrEmpty(cascade) == false)
sbJoin.Append(" AND (").Append(cascade).Append(")");
}
}
subSelect.InnerJoin(sbJoin.ToString());
sbJoin.Clear();
Select0Provider<ISelect<TNavigate>, TNavigate>.GetAllFieldExpressionTreeInfo af = null;
ReadAnonymousTypeAfInfo mf = default;
if (selectExp == null) af = subSelect.GetAllFieldExpressionTreeLevelAll();
else mf = subSelect.GetExpressionField(selectExp);
ReadAnonymousTypeAfInfo otherData = null;
var sbSql = new StringBuilder();
if (_selectExpression == null)
{
var field = new StringBuilder();
var read = new ReadAnonymousTypeInfo();
read.CsType = (tbrefMid.TypeLazy ?? tbrefMid.Type);
read.Consturctor = read.CsType.InternalGetTypeConstructor0OrFirst();
read.IsEntity = true;
read.Table = tbrefMid;
foreach (var col in tbrefMid.Columns.Values)
{
if (tbref.MiddleColumns.Where(a => a.CsName == col.CsName).Any() == false) continue;
var child = new ReadAnonymousTypeInfo
{
CsName = col.CsName,
CsType = col.CsType,
DbField = $"midtb.{_commonUtils.QuoteSqlName(col.Attribute.Name)}",
MapType = col.Attribute.MapType,
Property = tbrefMid.Properties[col.CsName]
};
read.Childs.Add(child);
field.Append(", ").Append(_commonUtils.QuoteReadColumn(child.CsType, child.MapType, child.DbField));
}
otherData = new ReadAnonymousTypeAfInfo(read, field.ToString());
}
Func<Dictionary<string, bool>> getWhereDic = () =>
{
var sbDic = new Dictionary<string, bool>();
for (var y = 0; y < list.Count; y++)
{
var sbWhereOne = new StringBuilder();
sbWhereOne.Append("(");
for (var z = 0; z < tbref.Columns.Count; z++)
{
if (z > 0) sbWhereOne.Append(" AND ");
sbWhereOne.Append(_commonUtils.FormatSql($" midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[z].Attribute.Name)}={{0}}", Utils.GetDataReaderValue(tbref.MiddleColumns[z].Attribute.MapType, getListValue1(list[y], tbref.Columns[z].CsName))));
}
sbWhereOne.Append(")");
var whereOne = sbWhereOne.ToString();
sbWhereOne.Clear();
if (sbDic.ContainsKey(whereOne) == false) sbDic.Add(whereOne, true);
}
return sbDic;
};
if (takeNumber > 0)
{
var sbDic = getWhereDic();
foreach (var sbd in sbDic)
{
subSelect._where.Clear();
subSelect.Where(sbd.Key).Where(oldWhere).Limit(takeNumber);
sbSql.Append("\r\nUNION ALL\r\nselect * from (").Append(subSelect.ToSql($"{(selectExp == null ? af.Field : mf.field)}{otherData?.field}")).Append(") ftb");
}
sbSql.Remove(0, 13);
if (sbDic.Count == 1) sbSql.Remove(0, 15).Remove(sbSql.Length - 5, 5);
sbDic.Clear();
}
else
{
subSelect._where.Clear();
if (tbref.Columns.Count == 1)
{
subSelect.Where(_commonUtils.FormatSql($"midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[0].Attribute.Name)} in {{0}}", list.Select(a => Utils.GetDataReaderValue(tbref.MiddleColumns[0].Attribute.MapType, getListValue1(a, tbref.Columns[0].CsName))).Distinct()));
}
else
{
var sbDic = getWhereDic();
var sbWhere = new StringBuilder();
foreach (var sbd in sbDic)
sbWhere.Append(" OR ").Append(sbd.Key);
subSelect.Where(sbWhere.Remove(0, 4).ToString());
sbWhere.Clear();
sbDic.Clear();
}
subSelect.Where(oldWhere);
sbSql.Append(subSelect.ToSql($"{(selectExp == null ? af.Field : mf.field)}{otherData?.field}"));
}
if (isAsync)
{
#if net40
#else
if (selectExp == null) subList = await subSelect.ToListAfPrivateAsync(sbSql.ToString(), af, otherData == null ? null : new[] { new ReadAnonymousTypeOtherInfo(otherData.field, otherData.map, midList) });
else subList = await subSelect.ToListMrPrivateAsync<TNavigate>(sbSql.ToString(), mf, otherData == null ? null : new[] { new ReadAnonymousTypeOtherInfo(otherData.field, otherData.map, midList) });
#endif
}
else
{
if (selectExp == null) subList = subSelect.ToListAfPrivate(sbSql.ToString(), af, otherData == null ? null : new[] { new ReadAnonymousTypeOtherInfo(otherData.field, otherData.map, midList) });
else subList = subSelect.ToListMrPrivate<TNavigate>(sbSql.ToString(), mf, otherData == null ? null : new[] { new ReadAnonymousTypeOtherInfo(otherData.field, otherData.map, midList) });
}
if (subList.Any() == false)
{
foreach (var item in list)
setListValue(item, new List<TNavigate>());
return;
}
Dictionary<string, List<Tuple<T1, List<TNavigate>>>> dicList = new Dictionary<string, List<Tuple<T1, List<TNavigate>>>>();
foreach (var item in list)
{
if (tbref.Columns.Count == 1)
{
var dicListKey = getListValue1(item, tbref.Columns[0].CsName)?.ToString();
if (dicListKey == null) continue;
var dicListVal = Tuple.Create(item, new List<TNavigate>());
if (dicList.TryGetValue(dicListKey, out var items) == false)
dicList.Add(dicListKey, items = new List<Tuple<T1, List<TNavigate>>>());
items.Add(dicListVal);
}
else
{
var sb = new StringBuilder();
for (var z = 0; z < tbref.Columns.Count; z++)
{
if (z > 0) sb.Append("*$*");
sb.Append(getListValue1(item, tbref.Columns[z].CsName));
}
var dicListKey = sb.ToString();
var dicListVal = Tuple.Create(item, new List<TNavigate>());
if (dicList.TryGetValue(dicListKey, out var items) == false)
dicList.Add(dicListKey, items = new List<Tuple<T1, List<TNavigate>>>());
items.Add(dicListVal);
sb.Clear();
}
}
for (var a = 0; a < subList.Count; a++)
{
string key = null;
if (tbref.Columns.Count == 1)
key = _orm.GetEntityValueWithPropertyName(tbref.RefMiddleEntityType, midList[a], tbref.MiddleColumns[0].CsName)?.ToString() ?? "";
else
{
var sb = new StringBuilder();
for (var z = 0; z < tbref.Columns.Count; z++)
{
if (z > 0) sb.Append("*$*");
sb.Append(_orm.GetEntityValueWithPropertyName(tbref.RefMiddleEntityType, midList[a], tbref.MiddleColumns[z].CsName));
}
key = sb.ToString();
sb.Clear();
}
if (dicList.TryGetValue(key, out var t1items) == false) continue;
foreach (var t1item in t1items)
t1item.Item2.Add(subList[a]);
}
foreach (var t1items in dicList.Values)
foreach (var t1item in t1items)
setListValue(t1item.Item1, t1item.Item2);
dicList.Clear();
}
break;
}
};
#if net40
_includeToList.Add(listObj => includeToListSyncOrAsync(listObj, false));
#else
_includeToList.Add(listObj =>
{
var task = includeToListSyncOrAsync(listObj, false);
if (task.Exception != null) throw task.Exception.InnerException ?? task.Exception;
});
_includeToListAsync.Add(listObj => includeToListSyncOrAsync(listObj, true));
#endif
var includeValue = new MemberExpression[members.Count + 1];
for (var a = 0; a < members.Count; a++) includeValue[a] = members[a];
includeValue[includeValue.Length - 1] = expBody as MemberExpression;
var includeKey = $"{string.Join(".", includeValue.Select(a => a.Member.Name))}";
if (_includeInfo.ContainsKey(includeKey) == false) _includeInfo.Add(includeKey, includeValue);
return this;
}
internal object _includeManySubListOneToManyTempValue1 = null;
internal void SetList(IEnumerable<T1> list)
{
foreach (var include in _includeToList) include?.Invoke(list);
_trackToList?.Invoke(list);
}
#if net40
#else
async internal Task SetListAsync(IEnumerable<T1> list)
{
foreach (var include in _includeToListAsync) await include?.Invoke(list);
_trackToList?.Invoke(list);
}
public Task<double> AvgAsync<TMember>(Expression<Func<T1, TMember>> column)
{
if (column == null) return Task.FromResult(default(double));
_tables[0].Parameter = column.Parameters[0];
return this.InternalAvgAsync(column?.Body);
}
public Task<TMember> MaxAsync<TMember>(Expression<Func<T1, TMember>> column)
{
if (column == null) return Task.FromResult(default(TMember));
_tables[0].Parameter = column.Parameters[0];
return this.InternalMaxAsync<TMember>(column?.Body);
}
public Task<TMember> MinAsync<TMember>(Expression<Func<T1, TMember>> column)
{
if (column == null) return Task.FromResult(default(TMember));
_tables[0].Parameter = column.Parameters[0];
return this.InternalMinAsync<TMember>(column?.Body);
}
public Task<decimal> SumAsync<TMember>(Expression<Func<T1, TMember>> column)
{
if (column == null) return Task.FromResult(default(decimal));
_tables[0].Parameter = column.Parameters[0];
return this.InternalSumAsync(column?.Body);
}
public Task<List<TReturn>> ToListAsync<TReturn>(Expression<Func<T1, TReturn>> select)
{
if (select == null) return this.InternalToListAsync<TReturn>(select?.Body);
_tables[0].Parameter = select.Parameters[0];
return this.InternalToListAsync<TReturn>(select?.Body);
}
public Task<List<TDto>> ToListAsync<TDto>() => ToListAsync(GetToListDtoSelector<TDto>());
public Task<DataTable> ToDataTableAsync<TReturn>(Expression<Func<T1, TReturn>> select)
{
if (select == null) return this.InternalToDataTableAsync(select?.Body);
_tables[0].Parameter = select.Parameters[0];
return this.InternalToDataTableAsync(select?.Body);
}
public Task<TReturn> ToAggregateAsync<TReturn>(Expression<Func<ISelectGroupingAggregate<T1>, TReturn>> select)
{
if (select == null) return Task.FromResult(default(TReturn));
_tables[0].Parameter = select.Parameters[0];
return this.InternalToAggregateAsync<TReturn>(select?.Body);
}
async public Task<bool> AnyAsync(Expression<Func<T1, bool>> exp)
{
var oldwhere = _where.ToString();
var ret = await this.Where(exp).AnyAsync();
_where.Clear().Append(oldwhere);
return ret;
}
async public Task<TReturn> ToOneAsync<TReturn>(Expression<Func<T1, TReturn>> select) => (await this.Limit(1).ToListAsync(select)).FirstOrDefault();
async public Task<TDto> ToOneAsync<TDto>() => (await this.Limit(1).ToListAsync<TDto>()).FirstOrDefault();
public Task<TReturn> FirstAsync<TReturn>(Expression<Func<T1, TReturn>> select) => this.ToOneAsync(select);
public Task<TDto> FirstAsync<TDto>() => this.ToOneAsync<TDto>();
public override Task<List<T1>> ToListAsync(bool includeNestedMembers = false) => base.ToListAsync(_isIncluded || includeNestedMembers);
#endif
}
}
| 59.009251
| 382
| 0.507739
|
[
"MIT"
] |
5118234/FreeSql
|
FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs
| 70,760
|
C#
|
// Copyright © 2017 Chromely Projects. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the LICENSE file.
namespace Chromely.Core;
public class ChromelyJsBindingHandler : IChromelyJsBindingHandler
{
/// <summary>
/// Initializes a new instance of the <see cref="ChromelyJsBindingHandler"/> class.
/// </summary>
public ChromelyJsBindingHandler()
{
Key = Guid.NewGuid().ToString();
ObjectName = Guid.NewGuid().ToString();
}
public ChromelyJsBindingHandler(string objectName)
{
Key = objectName;
ObjectName = objectName;
BoundObject = null;
BindingOptions = null;
}
public ChromelyJsBindingHandler(string objectName, object boundObject, object bindingOptions)
{
Key = objectName;
ObjectName = objectName;
BoundObject = boundObject;
BindingOptions = bindingOptions;
}
public string Key { get; }
public string ObjectName { get; set; }
public object? BoundObject { get; set; }
public object? BindingOptions { get; set; }
}
| 30.108108
| 97
| 0.666068
|
[
"MIT",
"BSD-3-Clause"
] |
ScriptBox99/Chromely
|
src_5.2/Chromely.Core/ChromelyJsBindingHandler.cs
| 1,117
|
C#
|
public class CommonItem : AbstractItem, IItem
{
public CommonItem(string name, int strengthBonus, int agilityBonus, int intelligenceBonus, int hitPointsBonus, int damageBonus)
: base(name, strengthBonus, agilityBonus, intelligenceBonus, hitPointsBonus, damageBonus)
{
}
}
| 39.875
| 136
| 0.69279
|
[
"MIT"
] |
BorislavBarov/OOP-Advanced-With-C-Sharp
|
ExamPreparation/HellExam16Aug2017/Hell/Entities/Items/CommonItem.cs
| 321
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit.HTMLEditor;
public partial class Admin_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//public void createUser()
Populate();
}
public void populateCheck()
{
var data = new MyModelContext();
var year = from y in data.tblYears
orderby y.YearName descending
select y;
}
public void Validator()
{
string casenr = txtCaseNr.Text;
//string laws = ddlLaws.SelectedValue;
string court = ddlCourt.SelectedValue;
string year = ddlYear.SelectedValue;
string ed1 = Editor1.Content;
string ed2 = Editor2.Content;
string head = txtHead.Text;
string prs = ddlPerson.SelectedValue;
//string file = FileUpload1.FileName;
if (string.IsNullOrEmpty(head))
{
txtHead.BackColor = Color.Tomato;
}
if (string.IsNullOrEmpty(casenr))
{
txtCaseNr.BackColor = Color.Tomato;
}
if (string.IsNullOrEmpty(court))
{
ddlCourt.BackColor = Color.Tomato;
}
if (string.IsNullOrEmpty(year))
{
ddlYear.BackColor = Color.Tomato;
}
if (string.IsNullOrEmpty(ed1))
{
Editor1.BackColor = Color.Tomato;
}
if (string.IsNullOrEmpty(ed2))
{
Editor2.BackColor = Color.Tomato;
}
if (string.IsNullOrEmpty(prs))
{
ddlPerson.BackColor = Color.Tomato;
}
//if (string.IsNullOrEmpty(file))
//{
// FileUpload1.BackColor = Color.Tomato;
//}
}
public void Populate()
{
if (!IsPostBack)
{
var data = new MyModelContext();
var year = from y in data.tblYears
orderby y.YearName descending
select y;
ddlYear.DataTextField = "YearName";
ddlYear.DataValueField = "YearId";
ddlYear.DataSource = year;
ddlYear.DataBind();
var person = from y in data.tblPersons
orderby y.PersonName ascending
select y;
ddlPerson.DataTextField = "PersonName";
ddlPerson.DataValueField = "PersonId";
ddlPerson.DataSource = person;
ddlPerson.DataBind();
var laws = from l in data.tblLaws
orderby l.LawName ascending
select l;
//ddlLaws.DataTextField = "LawName";
//ddlLaws.DataValueField = "LawId";
//ddlLaws.DataSource = laws;
//ddlLaws.DataBind();
var court = from c in data.tblCourts
orderby c.CourtName ascending
select c;
ddlCourt.DataTextField = "CourtName";
ddlCourt.DataValueField = "CourtId";
ddlCourt.DataSource = court;
ddlCourt.DataBind();
}
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
string nr = txtCaseNr.Text;
Validator();
var db = new MyModelContext();
var q = from x in db.tblDocuments
where x.DocNr.Equals(nr)
select x;
if (q.Any())
{
lblResult.Text = nr + " er longu skrásett í skipannini";
}
else
{
mData.CreateDocument(txtCaseNr.Text, Convert.ToInt32(ddlYear.SelectedValue), Editor1.Content,
Editor2.Content, Convert.ToInt32(ddlCourt.SelectedValue), txtHead.Text,
Convert.ToInt32(ddlPerson.SelectedValue));
txtHead.Text = "";
//ddlLaws.SelectedValue = "";
ddlCourt.SelectedValue = "";
ddlYear.SelectedValue = "";
ddlPerson.SelectedValue = "";
Editor1.Content = "";
Editor2.Content = "";
UnValidate();
lblResult.Text = txtCaseNr.Text + " er skrásett í skipannini";
lblResult.Text = txtCaseNr.Text + " er skrásett í skipannini";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
txtCaseNr.Text = "";
txtHead.Text = "";
//ddlLaws.SelectedValue = "";
ddlCourt.SelectedValue = "";
ddlYear.SelectedValue = "";
ddlPerson.SelectedValue = "";
Editor1.Content = "";
Editor2.Content = "";
lblResult.Text = "";
UnValidate();
}
public void UnValidate()
{
txtCaseNr.BackColor = ColorTranslator.FromHtml("#e4d100");
//ddlLaws.BackColor = ColorTranslator.FromHtml("#e4d100");
ddlCourt.BackColor = ColorTranslator.FromHtml("#e4d100");
ddlYear.BackColor = ColorTranslator.FromHtml("#e4d100");
ddlPerson.BackColor = ColorTranslator.FromHtml("#e4d100");
//FileUpload1.BackColor = ColorTranslator.FromHtml("#e4d100");
Editor1.BackColor = Color.White;
Editor2.BackColor = Color.White;
txtHead.BackColor = ColorTranslator.FromHtml("#e4d100");
}
private static Random random = new Random((int)DateTime.Now.Ticks);
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
}
// string name = txtName.Text;
// var db = new MyModelContext();
// tblPerson tp = new tblPerson();
// tp.PersonName = name;
// if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(name))
// {
// txtName.BackColor = Color.Tomato;
// lblMessage.Text = "Fejl";
// }
// else
// {
// txtName.BackColor = Color.White;
// db.tblPersons.InsertOnSubmit(tp);
// db.SubmitChanges();
// lblMessage.Text = name + " Succes!!";
// }
// }
// public void PopulatePerson()
// {
// var data = new MyModelContext();
// var person = from y in data.tblPersons
// orderby y.PersonName ascending
// select y;
// ddlDeletePerson.DataTextField = "PersonName";
// ddlDeletePerson.DataValueField = "PersonId";
// ddlDeletePerson.DataSource = person;
// ddlDeletePerson.DataBind();
// }
// protected void Unnamed1_Click(object sender, EventArgs e)
// {
// createUser();
// //if (FileUpload1.HasFile)
// //{
// // string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
// // if (fileExtension.ToLower() != ".pdf" && fileExtension.ToLower() != ".jpg")
// // {
// // lblText.Text = "1";
// // }
// // else
// // {
// // FileUpload1.SaveAs(Server.MapPath("~/File/" + FileUpload1.FileName));
// // lblText.Text = "2";
// // }
// //}
// }
//}
// }
| 27.371747
| 105
| 0.543528
|
[
"MIT"
] |
juuliusJuul/AppealWeb
|
KMS/Admin/Default.aspx.cs
| 7,371
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MovePlayer : MonoBehaviour
{
private Rigidbody2D _rb;
private Vector3 _playerPosition;
private Vector3 _playerRotation;
private float _shipThrust = 6f;
private float _rotationMultiplier = 150f;
private float _shipRadius;
private bool _slowMow;
[SerializeField] private GameObject asteroid;
[SerializeField] private GameObject explosion;
[SerializeField] private GameObject gameOver;
[SerializeField] private HUD hud;
private Shooter _shooter;
private Timer _timer;
private Timer _timer2;
private Timer _timer3;
// private TouchFollow _touchFollowScript;
// Start is called before the first frame update
void Start()
{
//RigidBody2D instantiation
_rb = gameObject.GetComponent<Rigidbody2D>();
//CircleCollider2D instantiation
var circleCollider2D = gameObject.GetComponent<CircleCollider2D>();
//collider radius
_shipRadius = circleCollider2D.radius;
// _touchFollowScript = GetComponent<TouchFollow>();
//reference to the shooter class
_shooter = GetComponent<Shooter>();
// hud = gameObject.GetComponent<HUD>();
_timer = gameObject.AddComponent<Timer>();
_timer.Duration = 0.5f;
_timer.Run();
_timer2 = gameObject.AddComponent<Timer>();
_timer3 = gameObject.AddComponent<Timer>();
}
private void FixedUpdate()
{
//Apply thrust to the ship
var zValue =(float) (transform.eulerAngles.z * Math.PI) / 180;
var angle = new Vector2(Mathf.Cos(zValue), Mathf.Sin(zValue));
var verticalScale = Input.GetAxis("Vertical");
if (verticalScale > 0)// || _touchFollowScript.UpArrowTriggered)
{
_rb.AddForce(angle * _shipThrust , ForceMode2D.Force);
}
var fireInput = Input.GetAxis("Fire1");
if (fireInput != 0f && _timer.Finished)
{
_timer.Duration = 1f;
_timer.Run();
_shooter.InstantiateBullet(angle , transform.position , transform.eulerAngles);
}
}
// Update is called once per frame
void Update()
{
//for slow motion effect
/*
if (Input.GetKeyDown(KeyCode.LeftAlt) && !_slowMow)
{
Time.timeScale = 0.4f;
_slowMow = true;
_timer2.Duration = 1f;
_timer2.Run();
}
if (_timer2.Finished && _slowMow)
{
print("finished");
Time.timeScale = 1f;
_timer3.Duration = 3f;
_timer3.Run();
}
if (_timer3.Finished && _slowMow)
{
print("timer 3");
_slowMow = false;
}
*/
var horizontalScale = Input.GetAxis("Horizontal");
float rotationSpeed = _rotationMultiplier * Time.deltaTime;
//change rotation based on User Input
if (horizontalScale > 0)// || _touchFollowScript.RightArrowTriggered)
{
_playerRotation = transform.eulerAngles;
_playerRotation.z -= rotationSpeed;
}
if (horizontalScale < 0)// || _touchFollowScript.LeftArrowTriggered)
{
_playerRotation = transform.eulerAngles;
_playerRotation.z += rotationSpeed;
}
transform.eulerAngles = _playerRotation;
//to wrap around the Edges
WrapToEdges();
}
private void OnCollisionStay2D(Collision2D other)
{
Instantiate(explosion, transform.position, Quaternion.identity);
Instantiate(gameOver);
AudioManager.Play(AudioClipName.PlayerDied);
hud.StopGameTimer = true;
Destroy(gameObject);
}
private void WrapToEdges()
{
var position = transform.position;
var ScreenError = 1f;
//simple 4 side wrapping conditions
if (position.x - _shipRadius < ScreenUtils.ScreenLeft - ScreenError)
{
position.x *= -1;
position.x -= ScreenError * Time.deltaTime;
}
else if (position.x + _shipRadius > ScreenUtils.ScreenRight + ScreenError)
{
position.x *= -1;
position.x += ScreenError * Time.deltaTime;
}
if (position.y + _shipRadius > ScreenUtils.ScreenTop + ScreenError)
{
position.y *= -1;
position.y += ScreenError * Time.deltaTime;
}
else if (position.y - _shipRadius < ScreenUtils.ScreenBottom - ScreenError)
{
position.y *= -1;
position.y -= ScreenError * Time.deltaTime;
}
transform.position = position;
}
}
| 30.42515
| 99
| 0.573116
|
[
"MIT"
] |
N12AM/Asteroid_2D
|
Assets/scripts/MovePlayer.cs
| 5,083
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SignalRHost")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("TheTrainline.com")]
[assembly: AssemblyProduct("SignalRHost")]
[assembly: AssemblyCopyright("Copyright © TheTrainline.com 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b5d127a5-1e6a-4c25-a4ca-cc32b06e2b0d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.5
| 85
| 0.734177
|
[
"MIT"
] |
LukeDefeo/HazardV2
|
SignalRHost/Properties/AssemblyInfo.cs
| 1,425
|
C#
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenGL;
using System;
using System.Buffers;
using System.Numerics;
using System.Runtime.InteropServices;
namespace OpenGLUnitTests
{
[TestClass]
public class GeometryTests
{
[TestMethod]
public void CalculateNormalsSingleTriangle()
{
Vector3[] vertices = new Vector3[]
{
new Vector3(0, 1, 0),
new Vector3(1, 0, 0),
new Vector3(0, 0, 0)
};
uint[] elements = new uint[] { 0, 1, 2 };
Vector3[] expectedNormals = new Vector3[]
{
new Vector3(0, 0, -1),
new Vector3(0, 0, -1),
new Vector3(0, 0, -1)
};
VerifyOverloads(vertices, elements, expectedNormals);
}
[TestMethod]
public void CalculateNormalsSingleTriangleReversed()
{
Vector3[] vertices = new Vector3[]
{
new Vector3(0, 1, 0),
new Vector3(1, 0, 0),
new Vector3(0, 0, 0)
};
uint[] elements = new uint[] { 2, 1, 0 };
Vector3[] expectedNormals = new Vector3[]
{
new Vector3(0, 0, 1),
new Vector3(0, 0, 1),
new Vector3(0, 0, 1)
};
VerifyOverloads(vertices, elements, expectedNormals);
}
[TestMethod]
public void CalculateNormalsMultipleTriangles()
{
// Pyramid shape
Vector3[] vertices = new Vector3[]
{
new Vector3( 0, 1, 0),
new Vector3( 0, 0, 1),
new Vector3( 1, 0, 0),
new Vector3( 0, 0, -1),
new Vector3(-1, 0, 0)
};
uint[] elements = new uint[]
{
0, 1, 2,
0, 2, 3,
0, 3, 4,
0, 4, 1
};
Vector3[] expectedNormals = new Vector3[]
{
new Vector3( 0, 1, 0).Normalize(),
new Vector3( 0, 1, 1).Normalize(),
new Vector3( 1, 1, 0).Normalize(),
new Vector3( 0, 1, -1).Normalize(),
new Vector3(-1, 1, 0).Normalize()
};
VerifyOverloads(vertices, elements, expectedNormals);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CalculateNormalWrongSizeNormalArray()
{
Geometry.CalculateNormals(new Vector3[3], new uint[3], new Vector3[2]);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CalculateNormalWrongSizeElementArray()
{
Geometry.CalculateNormals(new Vector3[3], new uint[4]);
}
private void VerifyOverloads(Vector3[] vertices, uint[] elements, Vector3[] expectedNormals)
{
{
int[] intElements = new int[elements.Length];
Span<int> casted = MemoryMarshal.Cast<uint, int>(elements);
casted.CopyTo(intElements);
Vector3[] actualNormals = Geometry.CalculateNormals(vertices, intElements);
CompareNormalArrays(expectedNormals, actualNormals);
}
{
Vector3[] actualNormals = Geometry.CalculateNormals(vertices, elements);
CompareNormalArrays(expectedNormals, actualNormals);
}
{
Vector3[] actualNormals = Geometry.CalculateNormals(vertices.AsSpan(), elements.AsSpan());
CompareNormalArrays(expectedNormals, actualNormals);
}
{
Vector3[] actualNormals = new Vector3[expectedNormals.Length];
Geometry.CalculateNormals(vertices, elements, actualNormals);
CompareNormalArrays(expectedNormals, actualNormals);
}
}
private void CompareNormalArrays(Vector3[] expected, Vector3[] actual)
{
Assert.AreEqual(expected.Length, actual.Length, $"{Environment.NewLine}Expected {expected.Length} normals but got {actual.Length} normals.");
for (int i = 0; i < expected.Length; i++)
{
CompareVectors(expected[i], actual[i]);
}
}
private void CompareVectors(Vector3 expected, Vector3 actual)
{
Assert.AreEqual(expected, actual, $"{Environment.NewLine}Expected: {expected}{Environment.NewLine}Actual: {actual}");
}
}
}
| 33.328571
| 153
| 0.515216
|
[
"MIT"
] |
giawa/opengl4csharp
|
OpenGLUnitTests/GeometryTests.cs
| 4,668
|
C#
|
using BlazorBoilerplate.Infrastructure.Server.Models;
using BlazorBoilerplate.Shared.Dto.Session;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlazorBoilerplate.Infrastructure.Server
{
public interface ISessionManager
{
Task<ApiResponse> GetSession(GetSessionRequestDto dataset);
Task<ApiResponse> GetSessions(GetSessionsRequestDto dataset);
}
}
| 26.882353
| 69
| 0.794311
|
[
"MIT"
] |
hochschule-darmstadt/MetaAutoML-Frontend
|
src/Shared/BlazorBoilerplate.Infrastructure/Server/ISessionManager.cs
| 459
|
C#
|
namespace Stelar
{
partial class Parov
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox5 = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.textBox4 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.infoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.calculateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.infoToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.infoToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.label5 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.clear = new System.Windows.Forms.Button();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.textBox3 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.listView1 = new System.Windows.Forms.ListView();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.Exitb = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.menuStrip1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// textBox5
//
this.textBox5.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(230)))), ((int)(((byte)(233)))));
this.textBox5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBox5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBox5.Location = new System.Drawing.Point(12, 398);
this.textBox5.Name = "textBox5";
this.textBox5.Size = new System.Drawing.Size(149, 26);
this.textBox5.TabIndex = 53;
//
// label4
//
this.label4.AutoSize = true;
this.label4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(73)))), ((int)(((byte)(94)))));
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.SystemColors.ButtonFace;
this.label4.Location = new System.Drawing.Point(8, 323);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(62, 20);
this.label4.TabIndex = 52;
this.label4.Text = "Income";
//
// textBox4
//
this.textBox4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(230)))), ((int)(((byte)(233)))));
this.textBox4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBox4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBox4.Location = new System.Drawing.Point(12, 346);
this.textBox4.Name = "textBox4";
this.textBox4.Size = new System.Drawing.Size(149, 26);
this.textBox4.TabIndex = 51;
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(73)))), ((int)(((byte)(94)))));
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.ButtonFace;
this.label1.Location = new System.Drawing.Point(12, 167);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(23, 20);
this.label1.TabIndex = 50;
this.label1.Text = "Id";
//
// menuStrip1
//
this.menuStrip1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(73)))), ((int)(((byte)(94)))));
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.infoToolStripMenuItem,
this.infoToolStripMenuItem1});
this.menuStrip1.Location = new System.Drawing.Point(0, 22);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.menuStrip1.Size = new System.Drawing.Size(800, 24);
this.menuStrip1.TabIndex = 42;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.saveToolStripMenuItem});
this.fileToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.openToolStripMenuItem.Text = "Open";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.saveToolStripMenuItem.Text = "Save";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// infoToolStripMenuItem
//
this.infoToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.calculateToolStripMenuItem});
this.infoToolStripMenuItem.ForeColor = System.Drawing.Color.White;
this.infoToolStripMenuItem.Name = "infoToolStripMenuItem";
this.infoToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.infoToolStripMenuItem.Text = "Stats";
//
// calculateToolStripMenuItem
//
this.calculateToolStripMenuItem.Name = "calculateToolStripMenuItem";
this.calculateToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.calculateToolStripMenuItem.Text = "Calculate";
this.calculateToolStripMenuItem.Click += new System.EventHandler(this.calculateToolStripMenuItem_Click);
//
// infoToolStripMenuItem1
//
this.infoToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.infoToolStripMenuItem2});
this.infoToolStripMenuItem1.ForeColor = System.Drawing.Color.White;
this.infoToolStripMenuItem1.Name = "infoToolStripMenuItem1";
this.infoToolStripMenuItem1.Size = new System.Drawing.Size(44, 20);
this.infoToolStripMenuItem1.Text = "Help";
//
// infoToolStripMenuItem2
//
this.infoToolStripMenuItem2.Name = "infoToolStripMenuItem2";
this.infoToolStripMenuItem2.Size = new System.Drawing.Size(180, 22);
this.infoToolStripMenuItem2.Text = "Info";
this.infoToolStripMenuItem2.Click += new System.EventHandler(this.infoToolStripMenuItem2_Click);
//
// columnHeader5
//
this.columnHeader5.Text = "Outcome";
this.columnHeader5.Width = 79;
//
// columnHeader4
//
this.columnHeader4.Text = "Income";
this.columnHeader4.Width = 66;
//
// columnHeader3
//
this.columnHeader3.Text = "LASTNAME";
this.columnHeader3.Width = 96;
//
// columnHeader2
//
this.columnHeader2.Text = "NAME";
this.columnHeader2.Width = 90;
//
// label5
//
this.label5.AutoSize = true;
this.label5.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(73)))), ((int)(((byte)(94)))));
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.ForeColor = System.Drawing.SystemColors.ButtonFace;
this.label5.Location = new System.Drawing.Point(8, 375);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(74, 20);
this.label5.TabIndex = 54;
this.label5.Text = "Outcome";
//
// button2
//
this.button2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(126)))), ((int)(((byte)(150)))));
this.button2.FlatAppearance.BorderSize = 0;
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.ForeColor = System.Drawing.Color.White;
this.button2.Location = new System.Drawing.Point(12, 89);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(149, 34);
this.button2.TabIndex = 49;
this.button2.Text = "Delete";
this.button2.UseVisualStyleBackColor = false;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(73)))), ((int)(((byte)(94)))));
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.SystemColors.ButtonFace;
this.label3.Location = new System.Drawing.Point(8, 271);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 20);
this.label3.TabIndex = 48;
this.label3.Text = "Lastname";
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(73)))), ((int)(((byte)(94)))));
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.SystemColors.ButtonFace;
this.label2.Location = new System.Drawing.Point(12, 219);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(51, 20);
this.label2.TabIndex = 47;
this.label2.Text = "Name";
//
// clear
//
this.clear.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(126)))), ((int)(((byte)(150)))));
this.clear.FlatAppearance.BorderSize = 0;
this.clear.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.clear.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.clear.ForeColor = System.Drawing.Color.White;
this.clear.Location = new System.Drawing.Point(12, 129);
this.clear.Name = "clear";
this.clear.Size = new System.Drawing.Size(149, 34);
this.clear.TabIndex = 46;
this.clear.Text = "Clear";
this.clear.UseVisualStyleBackColor = false;
this.clear.Click += new System.EventHandler(this.clear_Click);
//
// columnHeader1
//
this.columnHeader1.Text = "ID";
//
// textBox3
//
this.textBox3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(230)))), ((int)(((byte)(233)))));
this.textBox3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBox3.Location = new System.Drawing.Point(12, 294);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(149, 26);
this.textBox3.TabIndex = 45;
//
// textBox2
//
this.textBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(230)))), ((int)(((byte)(233)))));
this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBox2.Location = new System.Drawing.Point(12, 242);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(149, 26);
this.textBox2.TabIndex = 44;
//
// listView1
//
this.listView1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(73)))), ((int)(((byte)(94)))));
this.listView1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3,
this.columnHeader4,
this.columnHeader5});
this.listView1.Dock = System.Windows.Forms.DockStyle.Right;
this.listView1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.listView1.ForeColor = System.Drawing.Color.White;
this.listView1.HideSelection = false;
this.listView1.Location = new System.Drawing.Point(167, 46);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(633, 404);
this.listView1.TabIndex = 40;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.View = System.Windows.Forms.View.Details;
//
// textBox1
//
this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(230)))), ((int)(((byte)(233)))));
this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBox1.Location = new System.Drawing.Point(12, 190);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(149, 26);
this.textBox1.TabIndex = 43;
//
// button1
//
this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(102)))), ((int)(((byte)(126)))), ((int)(((byte)(150)))));
this.button1.FlatAppearance.BorderSize = 0;
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.ForeColor = System.Drawing.Color.White;
this.button1.Location = new System.Drawing.Point(12, 49);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(149, 34);
this.button1.TabIndex = 41;
this.button1.Text = "Add";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Exitb
//
this.Exitb.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(252)))), ((int)(((byte)(92)))), ((int)(((byte)(101)))));
this.Exitb.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Exitb.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(209)))), ((int)(((byte)(216)))), ((int)(((byte)(224)))));
this.Exitb.Location = new System.Drawing.Point(766, -1);
this.Exitb.Name = "Exitb";
this.Exitb.Size = new System.Drawing.Size(34, 26);
this.Exitb.TabIndex = 55;
this.Exitb.Text = "x";
this.Exitb.UseVisualStyleBackColor = false;
this.Exitb.Click += new System.EventHandler(this.Exitb_Click);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(44)))), ((int)(((byte)(62)))), ((int)(((byte)(80)))));
this.panel1.Controls.Add(this.Exitb);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(800, 22);
this.panel1.TabIndex = 56;
this.panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseMove);
//
// Parov
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(73)))), ((int)(((byte)(94)))));
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.listView1);
this.Controls.Add(this.textBox5);
this.Controls.Add(this.label4);
this.Controls.Add(this.textBox4);
this.Controls.Add(this.label1);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.label5);
this.Controls.Add(this.button2);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.clear);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "Parov";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Parov";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBox4;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem infoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem calculateToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem infoToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem infoToolStripMenuItem2;
private System.Windows.Forms.ColumnHeader columnHeader5;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button clear;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button Exitb;
private System.Windows.Forms.Panel panel1;
}
}
| 56.096698
| 172
| 0.605129
|
[
"Apache-2.0"
] |
MustaphaAlioglou/Stelar
|
Stelar/Stelar/Parov.Designer.cs
| 23,787
|
C#
|
using SocialCareCaseViewerApi.V1.Boundary.Requests;
using SocialCareCaseViewerApi.V1.Boundary.Response;
#nullable enable
namespace SocialCareCaseViewerApi.V1.UseCase.Interfaces
{
public interface IResidentUseCase
{
AddNewResidentResponse AddNewResident(AddNewResidentRequest request);
ResidentInformationList GetResidentsByQuery(ResidentQueryParam rqp, int cursor, int limit);
GetPersonResponse? GetResident(GetPersonRequest request);
void UpdateResident(UpdatePersonRequest request);
}
}
| 35.6
| 99
| 0.799625
|
[
"MIT"
] |
Duslerke/social-care-case-viewer-api
|
SocialCareCaseViewerApi/V1/UseCase/Interfaces/IResidentUseCase.cs
| 534
|
C#
|
using System;
using Android.App;
using Android.Runtime;
using Microsoft.Maui;
using Comet.Samples;
namespace Maui.Controls.Sample.SingleProject
{
[Application]
public class MainApplication : MauiApplication<MyApp>
{
public MainApplication(IntPtr handle, JniHandleOwnership ownership) : base(handle, ownership)
{
}
}
}
| 20.5625
| 95
| 0.778116
|
[
"MIT"
] |
ahmedattya95/Comet
|
sample/Comet.SingleProject.Sample/Android/MainApplication.cs
| 331
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input.Editor
{
[CustomPropertyDrawer(typeof(MixedRealityInputAction))]
public class InputActionPropertyDrawer : PropertyDrawer
{
private static MixedRealityInputActionsProfile profile = null;
private static GUIContent[] actionLabels = { new GUIContent("Missing Input Action Profile") };
private static int[] actionIds = { 0 };
public override void OnGUI(Rect rect, SerializedProperty property, GUIContent content)
{
if (!MixedRealityToolkit.IsInitialized || !MixedRealityToolkit.Instance.HasActiveProfile)
{
profile = null;
actionLabels = new[] { new GUIContent("Missing Mixed Reality Toolkit") };
actionIds = new[] { 0 };
}
else
{
if (profile == null ||
(MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled &&
profile.InputActions != null &&
profile.InputActions != MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionsProfile.InputActions))
{
profile = MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionsProfile;
if (profile != null)
{
actionLabels = profile.InputActions.Select(action => new GUIContent(action.Description)).Prepend(new GUIContent("None")).ToArray();
actionIds = profile.InputActions.Select(action => (int)action.Id).Prepend(0).ToArray();
}
else
{
actionLabels = new[] { new GUIContent("No input action profile found") };
actionIds = new[] { 0 };
}
}
if (!MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled)
{
profile = null;
actionLabels = new[] { new GUIContent("Input System Disabled") };
actionIds = new[] { 0 };
}
}
var label = EditorGUI.BeginProperty(rect, content, property);
var inputActionId = property.FindPropertyRelative("id");
if (profile == null || actionLabels == null || actionIds == null)
{
GUI.enabled = false;
EditorGUI.IntPopup(rect, label, inputActionId.intValue.ResetIfGreaterThan(0), actionLabels, actionIds);
GUI.enabled = true;
}
else
{
EditorGUI.BeginChangeCheck();
inputActionId.intValue = EditorGUI.IntPopup(rect, label, inputActionId.intValue.ResetIfGreaterThan(profile.InputActions.Length), actionLabels, actionIds);
if (EditorGUI.EndChangeCheck())
{
var description = property.FindPropertyRelative("description");
var axisConstraint = property.FindPropertyRelative("axisConstraint");
if (inputActionId.intValue > 0)
{
description.stringValue = profile.InputActions[inputActionId.intValue - 1].Description;
axisConstraint.intValue = (int)profile.InputActions[inputActionId.intValue - 1].AxisConstraint;
}
else
{
description.stringValue = "None";
axisConstraint.intValue = 0;
}
}
}
EditorGUI.EndProperty();
}
}
}
| 43.577778
| 170
| 0.555074
|
[
"MIT"
] |
1ft-seabass/hololens2-work-sample-202101
|
Assets/MRTK/Core/Inspectors/PropertyDrawers/InputActionPropertyDrawer.cs
| 3,924
|
C#
|
using Orckestra.Composer.ViewModels;
namespace Orckestra.Composer.MyAccount.ViewModels
{
public sealed class IsUserExistViewModel: BaseViewModel
{
public bool IsExist { get; set; }
}
}
| 20.7
| 59
| 0.724638
|
[
"MIT"
] |
InnaBoitsun/BetterRetailGroceryTest
|
src/Orckestra.Composer.MyAccount/ViewModels/IsUserExistViewModel.cs
| 209
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ValueAndReferenceType
{
/// <summary>
/// Class is reference type
/// </summary>
class PersonClass
{
public string GivenName { get; set; }
public string Surname { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}", this.GivenName, this.Surname);
}
}
}
/// <summary>
/// Struct is value type
/// </summary>
struct PersonStruct
{
public string GivenName { get; set; }
public string Surname { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}", this.GivenName, this.Surname);
}
}
}
}
| 17.414634
| 66
| 0.647059
|
[
"MIT"
] |
davidsonsousa/Back-To-Basics
|
ValueAndReferenceType/ValueAndReferenceType/Person.cs
| 716
|
C#
|
//*********************************************************************
//xCAD
//Copyright(C) 2020 Xarial Pty Limited
//Product URL: https://www.xcad.net
//License: https://xcad.xarial.com/license/
//*********************************************************************
using System.Collections.Generic;
using System.Linq;
namespace Xarial.XCad.Utils.Reflection
{
public static class EnumerableExtension
{
public static IEnumerable<T> ValueOrEmpty<T>(this IEnumerable<T> enumer)
{
if (enumer != null)
{
return enumer;
}
else
{
return Enumerable.Empty<T>();
}
}
}
}
| 26.185185
| 80
| 0.44413
|
[
"MIT"
] |
jonnypjohnston/Xarial-xcad
|
src/Toolkit/Reflection/EnumerableExtension.cs
| 709
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace TDFramework.Tool
{
public static class TDTools
{
/// <summary>
/// 获取距离下一天凌晨还有多少时间
/// </summary>
/// <returns></returns>
public static TimeSpan GetNextDayTimeSpan()
{
string dateDiff = null;
//获取当前时间
DateTime DateTime1 = DateTime.Now;
//第二天的0点00分00秒
DateTime DateTime2 = DateTime.Now.AddDays(1).Date;
//把2个时间转成TimeSpan,方便计算
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
//时间比较,得出差值
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + "秒";
return ts;
}
/// <summary>
/// 距离传入时间还有多长时间
/// </summary>
/// <param name="targetTime"></param>
/// <returns></returns>
public static TimeSpan GetTargetTimeSpan(DateTime targetTime)
{
string dateDiff = null;
//获取当前时间
DateTime DateTime1 = DateTime.Now;
//第二天的0点00分00秒
DateTime DateTime2 = targetTime;
//把2个时间转成TimeSpan,方便计算
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
//时间比较,得出差值
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + "秒";
return ts;
}
/// <summary>
/// 检测是不是同一天
/// </summary>
/// <param name="curTime"></param>
/// <returns></returns>
public static bool IsToday(DateTime curTime)
{
DateTime date = curTime;
DateTime dateToday = DateTime.Now;
//Debug.Log("isToday========" + dateToday + "date" + date + "ate.Year.ToString()=" + date.Year.ToString() + "date.Month.ToString()=" + date.Month.ToString() + "date.Date.ToString()=" + date.Day.ToString());
return date.Year.ToString() == dateToday.Year.ToString() && date.Month.ToString() == dateToday.Month.ToString() && date.Day.ToString() == dateToday.Day.ToString();
}
/// <summary>
/// 检测是不是同一天
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static bool IsToday(long timeStamp)
{
var today = DateTime.Now.ToString("yyyy/MM/dd");
var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
var dt = startTime.AddMilliseconds(timeStamp);
var day = dt.ToString("yyyy/MM/dd");
var todayArr = today.Split('/');
var dayArr = day.Split('/');
for (var i = 0; i < todayArr.Length; ++i)
{
if (todayArr[i] != dayArr[i])
{
return false;
}
}
return true;
}
/// <summary>
/// 获取贝塞尔曲线参数
/// </summary>
/// <param name="p0">起始点</param>
/// <param name="p1">偏移点1</param>
/// <param name="p2">偏移点2</param>
/// <param name="p3">结束点</param>
/// <param name="pointNum"></param>
/// 使用方式 transform.DOLocalPath(points, 0.7f, PathType.CatmullRom).SetEase(Ease.InQuad)
/// <returns>贝塞尔曲线</returns>
public static Vector3[] GetPointsFromBezier(Vector3 p0,Vector3 p1,Vector3 p2 ,Vector3 p3,int pointNum)
{
var points = new Vector3[pointNum +1];
var deltaT = 1f / pointNum;
var count = 0;
for (var t = 0f; t <= 1f; t = t + deltaT)
{
points[count] = p0 * (1 - t) * (1 - t) * (1 - t) + 3 * p1 * t * (1 - t) * (1 - t) + 3 * p2 * t * t * (1 - t) + p3 * t * t * t;
++count;
}
return points;
}
/// <summary>
/// 获取B物体转换到A物体上的坐标
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
/// <returns>转换坐标</returns>
public static Vector3 TransformBToTransformALocalPosition(Transform A , Transform B)
{
Vector3 v = B.transform.TransformPoint(Vector3.zero);
return A.transform.InverseTransformPoint(v);
}
/// <summary>
/// 两点之间的距离 x ,y 二维坐标
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns></returns>
public static double GetTwoPositionDistance(Vector2 p1, Vector2 p2)
{
return Math.Sqrt(Math.Abs(p1.x - p2.x) * Math.Abs(p1.x - p2.x) + Math.Abs(p1.y - p2.y) * Math.Abs(p1.y - p2.y));
}
/// <summary>
/// 获取两点角度
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns></returns>
public static float GetTwoPosintAngle(Vector2 p1, Vector2 p2)
{
double angleOfLine = Math.Atan2((p2.y - p1.y), (p2.x - p1.x)) * 180 / Math.PI;
return (float)angleOfLine;
}
/// <summary>
/// 保留小数点后指定位数
/// </summary>
/// <param name="value">操作数</param>
/// <param name="count">保留位数</param>
/// <returns></returns>
public static float FloatRetainN(float value, int count = 2)
{
int i =(int)(value * Math.Pow(10, count));
return (float) ((i*1.0f)/Math.Pow(10,count));
}
/// <summary>
/// 求方差函数
/// </summary>
/// <param name="values">数组</param>
/// <returns>方差</returns>
public static double CalculateStdDev(List<int> values)
{
var array = values.ToArray().Select(Convert.ToInt64);
double ret = 0;
if (values.Count() > 0)
{
// 计算平均数
double avg = values.Average();
// 计算个数值与平均数的差值的平方,然后求和
double sum = values.Sum(d => Math.Pow(d - avg, 2));
// 开方
ret = Math.Sqrt(sum / values.Count());
}
return ret;
}
}
}
| 32.629268
| 218
| 0.482135
|
[
"BSD-3-Clause"
] |
li1808464468/XLuaProject
|
Assets/TDFramework/Core/Tools/TDTools.cs
| 7,171
|
C#
|
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Web.Composing;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
namespace Umbraco.Web
{
/// <summary>
/// Extension methods for UrlHelper for use in templates
/// </summary>
public static class UrlHelperRenderExtensions
{
#region GetCropUrl
/// <summary>
/// Gets the ImageProcessor Url of a media item by the crop alias (using default media item property alias of "umbracoFile")
/// </summary>
/// <param name="urlHelper"></param>
/// <param name="mediaItem">
/// The IPublishedContent item.
/// </param>
/// <param name="cropAlias">
/// The crop alias e.g. thumbnail
/// </param>
/// <param name="htmlEncode">
/// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be
/// set to false if using the result of this method for CSS.
/// </param>
/// <returns></returns>
public static IHtmlString GetCropUrl(this UrlHelper urlHelper, IPublishedContent mediaItem, string cropAlias, bool htmlEncode = true)
{
var url = mediaItem.GetCropUrl(cropAlias: cropAlias, useCropDimensions: true);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
/// <summary>
/// Gets the ImageProcessor Url by the crop alias using the specified property containing the image cropper Json data on the IPublishedContent item.
/// </summary>
/// <param name="urlHelper"></param>
/// <param name="mediaItem">
/// The IPublishedContent item.
/// </param>
/// <param name="propertyAlias">
/// The property alias of the property containing the Json data e.g. umbracoFile
/// </param>
/// <param name="cropAlias">
/// The crop alias e.g. thumbnail
/// </param>
/// <param name="htmlEncode">
/// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be
/// set to false if using the result of this method for CSS.
/// </param>
/// <returns>
/// The ImageProcessor.Web Url.
/// </returns>
public static IHtmlString GetCropUrl(this UrlHelper urlHelper, IPublishedContent mediaItem, string propertyAlias, string cropAlias, bool htmlEncode = true)
{
var url = mediaItem.GetCropUrl(propertyAlias: propertyAlias, cropAlias: cropAlias, useCropDimensions: true);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
/// <summary>
/// Gets the ImageProcessor Url from the image path.
/// </summary>
/// <param name="mediaItem">
/// The IPublishedContent item.
/// </param>
/// <param name="width">
/// The width of the output image.
/// </param>
/// <param name="height">
/// The height of the output image.
/// </param>
/// <param name="propertyAlias">
/// Property alias of the property containing the Json data.
/// </param>
/// <param name="cropAlias">
/// The crop alias.
/// </param>
/// <param name="quality">
/// Quality percentage of the output image.
/// </param>
/// <param name="imageCropMode">
/// The image crop mode.
/// </param>
/// <param name="imageCropAnchor">
/// The image crop anchor.
/// </param>
/// <param name="preferFocalPoint">
/// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one
/// </param>
/// <param name="useCropDimensions">
/// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters
/// </param>
/// <param name="cacheBuster">
/// Add a serialised date of the last edit of the item to ensure client cache refresh when updated
/// </param>
/// <param name="furtherOptions">
/// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example:
/// <example>
/// <![CDATA[
/// furtherOptions: "&bgcolor=fff"
/// ]]>
/// </example>
/// </param>
/// <param name="ratioMode">
/// Use a dimension as a ratio
/// </param>
/// <param name="upScale">
/// If the image should be upscaled to requested dimensions
/// </param>
/// <param name="urlHelper"></param>
/// <param name="htmlEncode">
/// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be
/// set to false if using the result of this method for CSS.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static IHtmlString GetCropUrl(this UrlHelper urlHelper,
IPublishedContent mediaItem,
int? width = null,
int? height = null,
string propertyAlias = Umbraco.Core.Constants.Conventions.Media.File,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
bool cacheBuster = true,
string furtherOptions = null,
ImageCropRatioMode? ratioMode = null,
bool upScale = true,
bool htmlEncode = true)
{
var url = mediaItem.GetCropUrl(width, height, propertyAlias, cropAlias, quality, imageCropMode,
imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, ratioMode,
upScale);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
/// <summary>
/// Gets the ImageProcessor Url from the image path.
/// </summary>
/// <param name="imageUrl">
/// The image url.
/// </param>
/// <param name="width">
/// The width of the output image.
/// </param>
/// <param name="height">
/// The height of the output image.
/// </param>
/// <param name="imageCropperValue">
/// The Json data from the Umbraco Core Image Cropper property editor
/// </param>
/// <param name="cropAlias">
/// The crop alias.
/// </param>
/// <param name="quality">
/// Quality percentage of the output image.
/// </param>
/// <param name="imageCropMode">
/// The image crop mode.
/// </param>
/// <param name="imageCropAnchor">
/// The image crop anchor.
/// </param>
/// <param name="preferFocalPoint">
/// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one
/// </param>
/// <param name="useCropDimensions">
/// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters
/// </param>
/// <param name="cacheBusterValue">
/// Add a serialised date of the last edit of the item to ensure client cache refresh when updated
/// </param>
/// <param name="furtherOptions">
/// These are any query string parameters (formatted as query strings) that ImageProcessor supports. For example:
/// <example>
/// <![CDATA[
/// furtherOptions: "&bgcolor=fff"
/// ]]>
/// </example>
/// </param>
/// <param name="ratioMode">
/// Use a dimension as a ratio
/// </param>
/// <param name="upScale">
/// If the image should be upscaled to requested dimensions
/// </param>
/// <param name="urlHelper"></param>
/// <param name="htmlEncode">
/// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be
/// set to false if using the result of this method for CSS.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static IHtmlString GetCropUrl(this UrlHelper urlHelper,
string imageUrl,
int? width = null,
int? height = null,
string imageCropperValue = null,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
string cacheBusterValue = null,
string furtherOptions = null,
ImageCropRatioMode? ratioMode = null,
bool upScale = true,
bool htmlEncode = true)
{
var url = imageUrl.GetCropUrl(width, height, imageCropperValue, cropAlias, quality, imageCropMode,
imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode,
upScale);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
public static IHtmlString GetCropUrl(this UrlHelper urlHelper,
ImageCropperValue imageCropperValue,
int? width = null,
int? height = null,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
string cacheBusterValue = null,
string furtherOptions = null,
ImageCropRatioMode? ratioMode = null,
bool upScale = true,
bool htmlEncode = true)
{
var imageUrl = imageCropperValue.Src;
var url = imageUrl.GetCropUrl(imageCropperValue, width, height, cropAlias, quality, imageCropMode,
imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode,
upScale);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
#endregion
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, string controllerName)
{
return url.SurfaceAction(action, controllerName, null);
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, string controllerName, object additionalRouteVals)
{
return url.SurfaceAction(action, controllerName, "", additionalRouteVals);
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="area"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, string controllerName, string area, object additionalRouteVals)
{
if (string.IsNullOrEmpty(action)) throw new ArgumentNullOrEmptyException(nameof(action));
if (string.IsNullOrEmpty(controllerName)) throw new ArgumentNullOrEmptyException(nameof(controllerName));
var encryptedRoute = UmbracoHelper.CreateEncryptedRouteString(controllerName, action, area, additionalRouteVals);
var result = UmbracoContext.Current.OriginalRequestUrl.AbsolutePath.EnsureEndsWith('?') + "ufprt=" + encryptedRoute;
return result;
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="surfaceType"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, Type surfaceType)
{
return url.SurfaceAction(action, surfaceType, null);
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="surfaceType"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, Type surfaceType, object additionalRouteVals)
{
if (string.IsNullOrEmpty(action)) throw new ArgumentNullOrEmptyException(nameof(action));
if (surfaceType == null) throw new ArgumentNullException(nameof(surfaceType));
var area = "";
var surfaceController = Current.SurfaceControllerTypes.SingleOrDefault(x => x == surfaceType);
if (surfaceController == null)
throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName);
var metaData = PluginController.GetMetadata(surfaceController);
if (metaData.AreaName.IsNullOrWhiteSpace() == false)
{
//set the area to the plugin area
area = metaData.AreaName;
}
var encryptedRoute = UmbracoHelper.CreateEncryptedRouteString(metaData.ControllerName, action, area, additionalRouteVals);
var result = UmbracoContext.Current.OriginalRequestUrl.AbsolutePath.EnsureEndsWith('?') + "ufprt=" + encryptedRoute;
return result;
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="action"></param>
/// <returns></returns>
public static string SurfaceAction<T>(this UrlHelper url, string action)
where T : SurfaceController
{
return url.SurfaceAction(action, typeof (T));
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static string SurfaceAction<T>(this UrlHelper url, string action, object additionalRouteVals)
where T : SurfaceController
{
return url.SurfaceAction(action, typeof (T), additionalRouteVals);
}
/// <summary>
/// Generates a Absolute Media Item URL based on the current context
/// </summary>
/// <param name="urlHelper"></param>
/// <param name="mediaItem"></param>
/// <returns></returns>
public static string GetAbsoluteMediaUrl(this UrlHelper urlHelper, IPublishedContent mediaItem)
{
if (urlHelper == null) throw new ArgumentNullException("urlHelper");
if (mediaItem == null) throw new ArgumentNullException("mediaItem");
if (urlHelper.RequestContext.HttpContext.Request.Url != null)
{
var requestUrl = urlHelper.RequestContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority);
return string.Format("{0}{1}", requestUrl, mediaItem.Url);
}
return null;
}
}
}
| 44.442748
| 163
| 0.598534
|
[
"MIT"
] |
bharanijayasuri/umbraco8
|
src/Umbraco.Web/UrlHelperRenderExtensions.cs
| 17,468
|
C#
|
using System;
namespace Zenject
{
[NoReflectionBaking]
public class FactorySubContainerBinder<TParam1, TParam2, TParam3, TParam4, TContract>
: FactorySubContainerBinderWithParams<TContract>
{
public FactorySubContainerBinder(
DiContainer bindContainer, BindInfo bindInfo, FactoryBindInfo factoryBindInfo, object subIdentifier)
: base(bindContainer, bindInfo, factoryBindInfo, subIdentifier)
{
}
public ScopeConcreteIdArgConditionCopyNonLazyBinder ByMethod(
#if !NET_4_6 && !NET_STANDARD_2_0
ModestTree.Util.
#endif
Action<DiContainer, TParam1, TParam2, TParam3, TParam4> installerMethod)
{
var subcontainerBindInfo = new SubContainerCreatorBindInfo();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByMethod<TParam1, TParam2, TParam3, TParam4>(
container, subcontainerBindInfo, installerMethod), false);
return new ScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo);
}
#if !NOT_UNITY3D
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewGameObjectMethod(
#if !NET_4_6 && !NET_STANDARD_2_0
ModestTree.Util.
#endif
Action<DiContainer, TParam1, TParam2, TParam3, TParam4> installerMethod)
{
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByNewGameObjectMethod<TParam1, TParam2, TParam3, TParam4>(
container, gameObjectInfo, installerMethod), false);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod(
Func<InjectContext, UnityEngine.Object> prefabGetter,
#if !NET_4_6 && !NET_STANDARD_2_0
ModestTree.Util.
#endif
Action<DiContainer, TParam1, TParam2, TParam3, TParam4> installerMethod)
{
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByNewPrefabMethod<TParam1, TParam2, TParam3, TParam4>(
container,
new PrefabProviderCustom(prefabGetter),
gameObjectInfo, installerMethod), false);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod(
UnityEngine.Object prefab,
#if !NET_4_6 && !NET_STANDARD_2_0
ModestTree.Util.
#endif
Action<DiContainer, TParam1, TParam2, TParam3, TParam4> installerMethod)
{
BindingUtil.AssertIsValidPrefab(prefab);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByNewPrefabMethod<TParam1, TParam2, TParam3, TParam4>(
container,
new PrefabProvider(prefab),
gameObjectInfo, installerMethod), false);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceMethod(
string resourcePath,
#if !NET_4_6 && !NET_STANDARD_2_0
ModestTree.Util.
#endif
Action<DiContainer, TParam1, TParam2, TParam3, TParam4> installerMethod)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
var gameObjectInfo = new GameObjectCreationParameters();
ProviderFunc =
(container) => new SubContainerDependencyProvider(
ContractType, SubIdentifier,
new SubContainerCreatorByNewPrefabMethod<TParam1, TParam2, TParam3, TParam4>(
container,
new PrefabProviderResource(resourcePath),
gameObjectInfo, installerMethod), false);
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(BindInfo, gameObjectInfo);
}
#endif
}
}
| 41.034188
| 112
| 0.652572
|
[
"MIT"
] |
AEjlersen/Extenject
|
UnityProject/Assets/Plugins/Zenject/Source/Binding/Binders/Factory/FactoryFromBinder/SubContainerBinder/FactorySubContainerBinder4.cs
| 4,801
|
C#
|
/**
* *************************************************
* Copyright (c) 2019, Grindrod Bank Limited
* License MIT: https://opensource.org/licenses/MIT
* **************************************************
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using za.co.grindrodbank.a3s.Models;
using Microsoft.EntityFrameworkCore;
using NLog;
using za.co.grindrodbank.a3s.Extensions;
namespace za.co.grindrodbank.a3s.Repositories
{
public class PermissionRepository : PaginatedRepository<PermissionModel>, IPermissionRepository
{
private readonly A3SContext a3SContext;
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
public PermissionRepository(A3SContext a3SContex)
{
this.a3SContext = a3SContex;
}
public void InitSharedTransaction()
{
if (a3SContext.Database.CurrentTransaction == null)
a3SContext.Database.BeginTransaction();
}
public void CommitTransaction()
{
if (a3SContext.Database.CurrentTransaction != null)
a3SContext.Database.CurrentTransaction.Commit();
}
public void RollbackTransaction()
{
if (a3SContext.Database.CurrentTransaction != null)
a3SContext.Database.CurrentTransaction.Rollback();
}
public async Task<PermissionModel> CreateAsync(PermissionModel permission)
{
a3SContext.Permission.Add(permission);
await a3SContext.SaveChangesAsync();
return permission;
}
public async Task Delete(PermissionModel permission)
{
a3SContext.Permission.Remove(permission);
await a3SContext.SaveChangesAsync();
}
public async Task DeletePermissionsNotAssignedToApplicationFunctionsAsync()
{
List<PermissionModel> permissions = await a3SContext.Permission.Where(p => p.ApplicationFunctionPermissions.Count == 0).Include(p => p.FunctionPermissions).ToListAsync();
foreach(var permission in permissions)
{
logger.Debug($"Permission '{permission.Name}' is not assigned to any functions. Removing!");
a3SContext.Permission.Remove(permission);
}
await a3SContext.SaveChangesAsync();
}
public PermissionModel GetByName(string name, bool includeRelations = false)
{
IQueryable<PermissionModel> query = a3SContext.Permission.Where(p => p.Name == name);
query = includeRelations ? IncludeRelations(query) : query;
return query.FirstOrDefault();
}
public async Task<PermissionModel> GetByNameAsync(string name, bool includeRelations = false)
{
IQueryable<PermissionModel> query = a3SContext.Permission.Where(p => p.Name == name);
query = includeRelations ? IncludeRelations(query) : query;
return await query.FirstOrDefaultAsync();
}
public async Task<PermissionModel> UpdateAsync(PermissionModel permission)
{
a3SContext.Entry(permission).State = EntityState.Modified;
await a3SContext.SaveChangesAsync();
return permission;
}
public async Task<PermissionModel> GetByIdAsync(Guid permissionId)
{
return await a3SContext.Permission.FindAsync(permissionId);
}
public async Task<List<PermissionModel>> GetListAsync()
{
return await a3SContext.Permission.ToListAsync();
}
public async Task<PermissionModel> GetByIdWithApplicationAsync(Guid permissionId)
{
IQueryable<PermissionModel> query = a3SContext.Permission.Where(p => p.Id == permissionId);
query = IncludeRelations(query);
return await query.FirstOrDefaultAsync();
}
public async Task<PaginatedResult<PermissionModel>> GetPaginatedListAsync(int page, int pageSize, string filterName, List<KeyValuePair<string, string>> orderBy)
{
IQueryable<PermissionModel> query = a3SContext.Permission;
if (!string.IsNullOrWhiteSpace(filterName))
{
query = query.Where(p => p.Name == filterName);
}
foreach (var orderByComponent in orderBy)
{
switch (orderByComponent.Key)
{
case "name":
query = query.AppendOrderBy(a => a.Name, orderByComponent.Value == "asc" ? true : false);
break;
}
}
return await GetPaginatedListFromQueryAsync(query, page, pageSize);
}
private IQueryable<PermissionModel> IncludeRelations(IQueryable<PermissionModel> query)
{
return query.Include(p => p.ApplicationFunctionPermissions)
.ThenInclude(afp => afp.ApplicationFunction)
.ThenInclude(af => af.Application)
.Include(p => p.SubRealmPermissions)
.ThenInclude(psrp => psrp.SubRealm);
}
public async Task<List<PermissionModel>> GetListAsync(Guid userId)
{
return await a3SContext.Permission
.FromSqlRaw("select \"ParentRolePermission\".* " +
"FROM _a3s.application_user " +
"JOIN _a3s.user_role ON application_user.id = user_role.user_id " +
"JOIN _a3s.role ON role.id = user_role.role_id " +
"JOIN _a3s.role_function ON role.id = role_function.role_id " +
"JOIN _a3s.function ON role_function.function_id = function.id " +
"JOIN _a3s.function_permission ON function.id = function_permission.function_id " +
"JOIN _a3s.permission AS \"ParentRolePermission\" ON function_permission.permission_id = \"ParentRolePermission\".id " +
"WHERE application_user.id = {0} " +
"UNION " +
"select \"ChildRoleFunctionPermissions\".* " +
"FROM _a3s.application_user " +
"JOIN _a3s.user_role ON application_user.id = user_role.user_id " +
"JOIN _a3s.role AS \"ParentRole\" ON \"ParentRole\".id = user_role.role_id " +
"JOIN _a3s.role_role ON \"ParentRole\".id = role_role.parent_role_id " +
"JOIN _a3s.role AS \"ChildRole\" ON \"ChildRole\".id = role_role.child_role_id " +
"JOIN _a3s.role_function AS \"ChildRoleFunctionMap\" ON \"ChildRole\".id = \"ChildRoleFunctionMap\".role_id " +
"JOIN _a3s.function AS \"ChildRoleFunctions\" ON \"ChildRoleFunctionMap\".function_id = \"ChildRoleFunctions\".id " +
"JOIN _a3s.function_permission AS \"ChildRoleFunctionPermissionsMap\" ON \"ChildRoleFunctions\".id = \"ChildRoleFunctionPermissionsMap\".function_id " +
"JOIN _a3s.permission AS \"ChildRoleFunctionPermissions\" ON \"ChildRoleFunctionPermissionsMap\".permission_id = \"ChildRoleFunctionPermissions\".id " +
"WHERE application_user.id = {0}", userId.ToString())
.OrderBy(p => p.Name)
.ToListAsync();
}
}
}
| 43.371429
| 182
| 0.592095
|
[
"MIT"
] |
paulvancoller/A3S
|
src/za.co.grindrodbank.a3s/Repositories/PermissionRepository.cs
| 7,592
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gschwind.Lighthouse.Example.Models.Data {
/// <summary>
/// Untervorgang Betriebsdarlehen
/// </summary>
public record CompanyLoan : PlanData {
/// <summary>
/// Darlehensnominalbetrag
/// </summary>
public double LoanAmount {
get;
init;
}
/// <summary>
/// Restschuld
/// </summary>
public DateValue RemainingDebt {
get;
init;
} = new();
/// <summary>
/// Nominalbetrag oder Restschuld
/// </summary>
public LoanAmountType AmountType {
get;
init;
} = LoanAmountType.Amount;
/// <summary>
/// Name des Instituts
/// </summary>
public string Institute {
get;
init;
} = String.Empty;
/// <summary>
/// Kontonummer
/// </summary>
public string AccountNumber {
get;
init;
} = String.Empty;
/// <summary>
/// Zeitraum
/// </summary>
public TimePeriod TimePeriod {
get;
init;
} = new();
/// <summary>
/// Darlehenstyp
/// </summary>
public LoanType LoanType {
get;
init;
} = LoanType.Annuity;
/// <summary>
/// Start der Tilgung
/// </summary>
public DateTime RepaymentStart {
get;
init;
} = new(DateTime.Now.Year, DateTime.Now.Month, 1);
/// <summary>
/// Laufzeit des Darlehens automatisch berechnen
/// </summary>
public bool DurationAutomated {
get;
init;
} = true;
/// <summary>
/// Disagio
/// </summary>
public double Disagio {
get;
init;
}
/// <summary>
/// Annuität in EUR bei Annuitätendarlehen / Tilgung in EUR bei Tilgungsdarlehen
/// </summary>
public ICollection<DateValue> Repayments {
get;
init;
} = new List<DateValue>();
/// <summary>
/// Tilgungsintervall
/// </summary>
public Period RepaymentInterval {
get;
init;
} = Period.Monthly;
/// <summary>
/// Sondertilgungen
/// </summary>
public ICollection<DateValue> AdditionalRepayments {
get;
init;
} = new List<DateValue>();
/// <summary>
/// Zinssätze in %
/// </summary>
public ICollection<PercentValue> InterestRates {
get;
init;
} = new List<PercentValue>();
/// <summary>
/// Ende der Zinsbindung
/// </summary>
public DateTime EndOfFixedInterestRate {
get;
init;
} = DateTime.Now;
/// <summary>
/// Zinszuschüsse
/// </summary>
public ICollection<DateValue> InterestGrants {
get;
init;
} = new List<DateValue>();
/// <summary>
/// Teilauszahlungen der Darlehenssumme
/// </summary>
public ICollection<DateValue> LoanPayouts {
get;
init;
} = new List<DateValue>();
/// <summary>
/// Auszahlung zu Darlehensbeginn
/// </summary>
public bool PayoutAutomated {
get;
init;
} = true;
/// <summary>
/// Bereitstellungszins in %
/// </summary>
public double CommitmentInterestRate {
get;
init;
}
/// <summary>
/// Anzahl bereitsellungsfreie Monate
/// </summary>
public int FreeCommitmentMonths {
get;
init;
}
}
}
| 22.725714
| 88
| 0.45914
|
[
"Apache-2.0"
] |
GschwindSoftware/lighthouse-examples-net
|
Models/Data/CompanyLoan.cs
| 3,981
|
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;
using System;
using System.Linq;
using HoloToolkit.Unity;
namespace HoloToolkit.Unity.SharingWithUNET
{
/// <summary>
/// Controls a scrollable list of sessions.
/// </summary>
public class ScrollingSessionListUIController : SingleInstance<ScrollingSessionListUIController>
{
/// <summary>
/// Object which controls finding sessions so we know what to put on our buttons.
/// </summary>
private NetworkDiscoveryWithAnchors networkDiscovery;
/// <summary>
/// Current list of sessions.
/// TODO: Currently these don't clean up if a session goes away...
/// </summary>
private Dictionary<string, NetworkDiscoveryWithAnchors.SessionInfo> sessionList;
/// <summary>
/// Keeps track of the current index that is the 'top' of the UI list
/// to enable scolling.
/// </summary>
private int SessionIndex = 0;
/// <summary>
/// List of session controls that will have the session info on them.
/// </summary>
public SessionListButton[] SessionControls;
/// <summary>
/// Keeps track of the session the user has currently selected.
/// </summary>
public NetworkDiscoveryWithAnchors.SessionInfo SelectedSession { get; private set; }
private void Start()
{
// On the immersive device the UI is best placed a little closer than on a HoloLens
if (UnityEngine.XR.WSA.HolographicSettings.IsDisplayOpaque == true)
{
gameObject.GetComponent<SimpleTagalong>().TagalongDistance = 1;
}
// Register for events when sessions are found / joined.
networkDiscovery = NetworkDiscoveryWithAnchors.Instance;
networkDiscovery.SessionListChanged += NetworkDiscovery_SessionListChanged;
networkDiscovery.ConnectionStatusChanged += NetworkDiscovery_ConnectionStatusChanged;
ScrollSessions(0);
}
/// <summary>
/// When we are connected we want to disable the UI
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">the event data</param>
private void NetworkDiscovery_ConnectionStatusChanged(object sender, EventArgs e)
{
gameObject.SetActive(networkDiscovery.running && !networkDiscovery.isServer);
// sets the UI to be active when not connected and disabled when connected.
//SetChildren(networkDiscovery.running && !networkDiscovery.isServer);
}
/// <summary>
/// Called when a session is discovered
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">the event data</param>
private void NetworkDiscovery_SessionListChanged(object sender, EventArgs e)
{
sessionList = networkDiscovery.remoteSessions;
SessionIndex = Mathf.Min(SessionIndex, sessionList.Count);
// this will force a recalculation of the buttons.
ScrollSessions(0);
}
/// <summary>
/// Sometimes it is useful to disable rendering
/// </summary>
/// <param name="Enabled"></param>
void SetChildren(bool Enabled)
{
foreach (Renderer mr in GetComponentsInChildren<Renderer>())
{
mr.enabled = Enabled;
}
foreach (BoxCollider bc in GetComponentsInChildren<BoxCollider>())
{
bc.enabled = Enabled;
}
}
/// <summary>
/// Updates which session is the 'top' session in the list, and sets the
/// session buttons accordinglingly
/// </summary>
/// <param name="Direction">are we scrolling up, down, or not scrolling</param>
public void ScrollSessions(int Direction)
{
int sessionCount = sessionList == null ? 0 : sessionList.Count;
// Update the session index
SessionIndex = Mathf.Clamp(SessionIndex + Direction, 0, Mathf.Max(0, sessionCount - SessionControls.Length));
// Update all of the controls
for (int index = 0; index < SessionControls.Length; index++)
{
if (SessionIndex + index < sessionCount)
{
SessionControls[index].gameObject.SetActive(true);
NetworkDiscoveryWithAnchors.SessionInfo sessionInfo = sessionList.Values.ElementAt(SessionIndex + index);
SessionControls[index].SetSessionInfo(sessionInfo);
}
else
{
SessionControls[index].gameObject.SetActive(false);
}
}
}
/// <summary>
/// Sets the selected session
/// </summary>
/// <param name="sessionInfo">The session to set as selected</param>
public void SetSelectedSession(NetworkDiscoveryWithAnchors.SessionInfo sessionInfo)
{
SelectedSession = sessionInfo;
// Recalculating the session list so we can update the text colors.
ScrollSessions(0);
}
/// <summary>
/// Joins the selected session if there is a selected session.
/// </summary>
public void JoinSelectedSession()
{
if (SelectedSession != null && networkDiscovery.running)
{
networkDiscovery.JoinSession(SelectedSession);
}
}
}
}
| 38.806667
| 125
| 0.599725
|
[
"MIT"
] |
JulienPlouvier/Hololens_BouncingBall
|
Bouncing Ball/Assets/DesignLabs_Unity/Assets/HoloToolkit/SharingWithUNET/UI/Scripts/ScrollingSessionListUIController.cs
| 5,823
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenMetaverse.TestClient.Commands
{
class SearchEventsCommand : Command
{
System.Threading.AutoResetEvent waitQuery = new System.Threading.AutoResetEvent(false);
int resultCount;
public SearchEventsCommand(TestClient testClient)
{
Name = "searchevents";
Description = "Searches Events list. Usage: searchevents [search text]";
Category = CommandCategory.Search;
}
public override string Execute(string[] args, UUID fromAgentID)
{
// process command line arguments
if (args.Length < 1)
return "Usage: searchevents [search text]";
string searchText = string.Empty;
for (int i = 0; i < args.Length; i++)
searchText += args[i] + " ";
searchText = searchText.TrimEnd();
waitQuery.Reset();
Client.Directory.DirEventsReply += Directory_DirEvents;
// send the request to the directory manager
Client.Directory.StartEventsSearch(searchText, 0);
string result;
if (waitQuery.WaitOne(20000, false) && Client.Network.Connected)
{
result = "Your query '" + searchText + "' matched " + resultCount + " Events. ";
}
else
{
result = "Timeout waiting for simulator to respond.";
}
Client.Directory.DirEventsReply -= Directory_DirEvents;
return result;
}
void Directory_DirEvents(object sender, DirEventsReplyEventArgs e)
{
if (e.MatchedEvents[0].ID == 0 && e.MatchedEvents.Count == 1)
{
Console.WriteLine("No Results matched your search string");
}
else
{
foreach (DirectoryManager.EventsSearchData ev in e.MatchedEvents)
{
Console.WriteLine("Event ID: {0} Event Name: {1} Event Date: {2}", ev.ID, ev.Name, ev.Date);
}
}
resultCount = e.MatchedEvents.Count;
waitQuery.Set();
}
}
}
| 33.231884
| 112
| 0.541212
|
[
"BSD-3-Clause"
] |
Ana-Green/halcyon-1
|
ThirdParty/libopenmetaverse/Programs/examples/TestClient/Commands/Directory/SearchEventsCommand.cs
| 2,293
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using USBModem;
using MachineControl;
namespace Robo
{
public partial class frmSplash : Form
{
private static __temporary temp=new __temporary();
public frmSplash()
{
InitializeComponent();
}
private class __temporary
{
public bool value { get; set; }
public string strValue { get; set; }
public bool exit { get; set; }
public bool lblAct { get; set; }
public string actString { get; set; }
}
private void frmSplash_Load(object sender, EventArgs e)
{
temp.value = false;
temp.strValue = "Loading ...";
this.Text = Properties.Resources.appTitle;
lblTitle.Text = Properties.Resources.appTitle;
lblVersion.Text = "Version: " + Properties.Resources.appVersion;
temp.actString = "Product not activated";
Thread thr = new Thread(new ParameterizedThreadStart(thread));
thr.Start((object)temp);
}
void showActivation()
{
if (this.InvokeRequired)
{
Action a = () => triggerDialog();
Invoke(a);
}
else
{
triggerDialog();
}
}
void triggerDialog()
{
new RegisterRobo().ShowDialog(this);
}
private void thread(object arg)
{
try
{
__temporary bl = (__temporary)arg;
bl.strValue = "Loading MIND library ...";
try
{
SqlConnection conn = new SqlConnection(Program.connString);
conn.Open();
conn.Close();
}
catch (Exception)
{
bl.strValue = "MIND Library failed.";
Thread.Sleep(2000);
}
if (bl.strValue == "MIND Library failed.")
{
bl.exit = true;
return;
}
bl.strValue = "Checking activation ...";
Program.actRetString = UserSetting.Activation;
if (Program.actRetString.Length<=0)
{
//new RegisterRobo().ShowDialog();
showActivation();
if (Program.actRetString.Length<=0)
{
bl.strValue = "Activation failed.";
bl.lblAct = true;
bl.actString = "Product not activated";
Thread.Sleep(2000);
bl.exit = true;
return;
}
}
else if(Program.actRetString.Length<=0)
{
bl.strValue = "Activation failed.";
bl.lblAct = true;
bl.actString = "Product not activated";
Thread.Sleep(2000);
bl.exit = true;
return;
}
bl.lblAct = true;
bl.actString = Program.actRetString;
bl.strValue = "Loading USBModem library ...";
Thread.Sleep(500);
try
{
USBModem.Port p1 = new Port();
}
catch (Exception)
{
bl.strValue = "USBModem Library failed.";
Thread.Sleep(2000);
bl.exit = true;
return;
}
bl.strValue = "Loading MachineControl library ...";
Thread.Sleep(500);
try
{
Machine mac = new Machine();
}
catch (Exception)
{
bl.strValue = "MachineControl Library failed.";
Thread.Sleep(2000);
bl.exit = true;
return;
}
bl.value = true;
}
catch (StackOverflowException ex)
{
MessageBox.Show("Robo unable to connect with its mind, please try restart robo or reinstall robo program."+Environment.NewLine+"Error message: "+ex.Message,"Mind connectivity",MessageBoxButtons.OK,MessageBoxIcon.Error);
Program.splashError = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
lblActivation.Visible = temp.lblAct;
lblActivation.Text = temp.actString;
label1.Text = temp.strValue;
if (temp.exit)
Application.Exit();
else if (temp.value)
Close();
}
}
}
| 32.468354
| 235
| 0.450097
|
[
"MIT"
] |
mohansharma-me/roboapp
|
C#/Robo/Robo/frmSplash.cs
| 5,132
|
C#
|
namespace Markdig.Adf.Nodes
{
public interface IInlineNode : INode
{
}
}
| 12.285714
| 40
| 0.639535
|
[
"MIT"
] |
Thorarin/Markdig.Adf
|
Markdig.Adf/Nodes/IInlineNode.cs
| 88
|
C#
|
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.451)
// Version 5.451.0.0 www.ComponentFactory.com
// *****************************************************************************
using System.ComponentModel;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Storage for KryptonContextMenuItem state values.
/// </summary>
public class PaletteContextMenuItemState : Storage
{
#region Instance Fields
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the PaletteContextMenuItemState class.
/// </summary>
/// <param name="redirect">Redirector for inheriting values.</param>
public PaletteContextMenuItemState(PaletteContextMenuRedirect redirect)
: this(redirect.ItemHighlight, redirect.ItemImage,
redirect.ItemShortcutTextRedirect, redirect.ItemSplit,
redirect.ItemTextStandardRedirect, redirect.ItemTextAlternateRedirect)
{
}
/// <summary>
/// Initialize a new instance of the PaletteContextMenuItemState class.
/// </summary>
/// <param name="redirect">Redirector for inheriting values.</param>
public PaletteContextMenuItemState(PaletteContextMenuItemStateRedirect redirect)
: this(redirect.ItemHighlight, redirect.ItemImage,
redirect.ItemShortcutText, redirect.ItemSplit,
redirect.ItemTextStandard, redirect.ItemTextAlternate)
{
}
/// <summary>
/// Initialize a new instance of the PaletteContextMenuItemState class.
/// </summary>
/// <param name="redirectItemHighlight">Redirector for ItemHighlight.</param>
/// <param name="redirectItemImage">Redirector for ItemImage.</param>
/// <param name="redirectItemShortcutText">Redirector for ItemShortcutText.</param>
/// <param name="redirectItemSplit">Redirector for ItemSplit.</param>
/// <param name="redirectItemTextAlternate">Redirector for ItemTextStandard.</param>
/// <param name="redirectItemTextStandard">Redirector for ItemTextAlternate.</param>
public PaletteContextMenuItemState(PaletteDoubleMetricRedirect redirectItemHighlight,
PaletteTripleJustImageRedirect redirectItemImage,
PaletteContentInheritRedirect redirectItemShortcutText,
PaletteDoubleRedirect redirectItemSplit,
PaletteContentInheritRedirect redirectItemTextStandard,
PaletteContentInheritRedirect redirectItemTextAlternate)
{
ItemHighlight = new PaletteDoubleMetric(redirectItemHighlight);
ItemImage = new PaletteTripleJustImage(redirectItemImage);
ItemShortcutText = new PaletteContentJustShortText(redirectItemShortcutText);
ItemSplit = new PaletteDouble(redirectItemSplit);
ItemTextStandard = new PaletteContentJustText(redirectItemTextStandard);
ItemTextAlternate = new PaletteContentJustText(redirectItemTextAlternate);
}
#endregion
#region IsDefault
/// <summary>
/// Gets a value indicating if all values are default.
/// </summary>
[Browsable(false)]
public override bool IsDefault => (ItemHighlight.IsDefault &&
ItemImage.IsDefault &&
ItemShortcutText.IsDefault &&
ItemSplit.IsDefault &&
ItemTextStandard.IsDefault &&
ItemTextAlternate.IsDefault);
#endregion
#region PopulateFromBase
/// <summary>
/// Populate values from the base palette.
/// </summary>
/// <param name="common">Reference to common settings.</param>
/// <param name="state">State to inherit.</param>
public void PopulateFromBase(KryptonPaletteCommon common,
PaletteState state)
{
common.StateCommon.BackStyle = PaletteBackStyle.ContextMenuItemHighlight;
common.StateCommon.BorderStyle = PaletteBorderStyle.ContextMenuItemHighlight;
ItemHighlight.PopulateFromBase(state);
common.StateCommon.BackStyle = PaletteBackStyle.ContextMenuItemImage;
common.StateCommon.BorderStyle = PaletteBorderStyle.ContextMenuItemImage;
common.StateCommon.ContentStyle = PaletteContentStyle.ContextMenuItemImage;
ItemImage.PopulateFromBase(state);
common.StateCommon.ContentStyle = PaletteContentStyle.ContextMenuItemShortcutText;
ItemShortcutText.PopulateFromBase(state);
common.StateCommon.BackStyle = PaletteBackStyle.ContextMenuSeparator;
common.StateCommon.BorderStyle = PaletteBorderStyle.ContextMenuSeparator;
ItemSplit.PopulateFromBase(state);
common.StateCommon.ContentStyle = PaletteContentStyle.ContextMenuItemTextStandard;
ItemTextStandard.PopulateFromBase(state);
common.StateCommon.ContentStyle = PaletteContentStyle.ContextMenuItemTextAlternate;
ItemTextAlternate.PopulateFromBase(state);
}
#endregion
#region ItemHighlight
/// <summary>
/// Gets access to the item highlight appearance entries.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining item highlight appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteDoubleMetric ItemHighlight { get; }
private bool ShouldSerializeItemHighlight()
{
return !ItemHighlight.IsDefault;
}
#endregion
#region ItemImage
/// <summary>
/// Gets access to the item image appearance entries.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining item image appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteTripleJustImage ItemImage { get; }
private bool ShouldSerializeItemImage()
{
return !ItemImage.IsDefault;
}
#endregion
#region ItemShortcutText
/// <summary>
/// Gets access to the item shortcut text appearance entries.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining item shortcut text appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteContentJustShortText ItemShortcutText { get; }
private bool ShouldSerializeItemShortcutText()
{
return !ItemShortcutText.IsDefault;
}
#endregion
#region ItemSplit
/// <summary>
/// Gets access to the item split appearance entries.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining item split appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteDouble ItemSplit { get; }
private bool ShouldSerializeItemSplit()
{
return !ItemSplit.IsDefault;
}
#endregion
#region ItemTextAlternate
/// <summary>
/// Gets access to the alternate item text appearance entries.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining alternate item text appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteContentJustText ItemTextAlternate { get; }
private bool ShouldSerializeItemTextAlternate()
{
return !ItemTextAlternate.IsDefault;
}
#endregion
#region ItemTextStandard
/// <summary>
/// Gets access to the standard item text appearance entries.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining standard item text appearance.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public PaletteContentJustText ItemTextStandard { get; }
private bool ShouldSerializeItemTextStandard()
{
return !ItemTextStandard.IsDefault;
}
#endregion
}
}
| 44.306604
| 157
| 0.632918
|
[
"BSD-3-Clause"
] |
Krypton-Suite-Legacy/Krypton-NET-5.451
|
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Controls/PaletteContextMenuItemState.cs
| 9,396
|
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 ds-2015-04-16.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.DirectoryService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DirectoryService.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DirectoryLimits Object
/// </summary>
public class DirectoryLimitsUnmarshaller : IUnmarshaller<DirectoryLimits, XmlUnmarshallerContext>, IUnmarshaller<DirectoryLimits, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
DirectoryLimits IUnmarshaller<DirectoryLimits, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public DirectoryLimits Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
DirectoryLimits unmarshalledObject = new DirectoryLimits();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("CloudOnlyDirectoriesCurrentCount", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.CloudOnlyDirectoriesCurrentCount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CloudOnlyDirectoriesLimit", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.CloudOnlyDirectoriesLimit = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CloudOnlyDirectoriesLimitReached", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.CloudOnlyDirectoriesLimitReached = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ConnectedDirectoriesCurrentCount", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.ConnectedDirectoriesCurrentCount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ConnectedDirectoriesLimit", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.ConnectedDirectoriesLimit = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ConnectedDirectoriesLimitReached", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.ConnectedDirectoriesLimitReached = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static DirectoryLimitsUnmarshaller _instance = new DirectoryLimitsUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static DirectoryLimitsUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 39.204918
| 158
| 0.62074
|
[
"Apache-2.0"
] |
jasoncwik/aws-sdk-net
|
sdk/src/Services/DirectoryService/Generated/Model/Internal/MarshallTransformations/DirectoryLimitsUnmarshaller.cs
| 4,783
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PhotographyAddicted.Web.Areas.Identity.Data;
namespace PhotographyAddicted.Web.Areas.Identity.Pages.Account.Manage
{
public class DownloadPersonalDataModel : PageModel
{
private readonly UserManager<PhotographyAddictedUser> _userManager;
private readonly ILogger<DownloadPersonalDataModel> _logger;
public DownloadPersonalDataModel(
UserManager<PhotographyAddictedUser> userManager,
ILogger<DownloadPersonalDataModel> logger)
{
_userManager = userManager;
_logger = logger;
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
_logger.LogInformation("User with ID '{UserId}' asked for their personal data.", _userManager.GetUserId(User));
// Only include personal data for download
var personalData = new Dictionary<string, string>();
var personalDataProps = typeof(PhotographyAddictedUser).GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
foreach (var p in personalDataProps)
{
personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null");
}
Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json");
return new FileContentResult(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(personalData)), "text/json");
}
}
}
| 38.153846
| 123
| 0.667843
|
[
"MIT"
] |
severin87/PhotographyAddict
|
source/Web/PhotographyAddicted.Web/Areas/Identity/Pages/Account/Manage/DownloadPersonalData.cshtml.cs
| 1,986
|
C#
|
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
namespace BuildIt.Bot.Client.DirectLinkApi.Interfaces
{
/// <summary>
///
/// </summary>
public partial interface ITokens
{
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<string>> GenerateTokenForNewConversationWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='conversationId'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<string>> RenewTokenWithOperationResponseAsync(string conversationId, CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| 36.137931
| 187
| 0.69084
|
[
"MIT"
] |
builttoroam/BuildIt
|
src/BuildIt.Bot/BuildIt.Bot.Client/DirectLinkApi/Interfaces/ITokens.cs
| 1,050
|
C#
|
using FluentMigrator.Builders.Create.Table;
using Nop.Plugin.Misc.Sms77.Domain;
namespace Nop.Plugin.Misc.Sms77.Data {
/// <summary>Represents a voice entity builder</summary>
public partial class VoiceRecordBuilder : AbstractMessageRecordBuilder<VoiceRecord> {
#region Methods
/// <inheritdoc />
public override void MapEntity(CreateTableExpressionBuilder table) {
table
.WithColumn(nameof(VoiceRecord.Code)).AsInt16().Nullable()
.WithColumn(nameof(VoiceRecord.Cost)).AsDouble().Nullable()
.WithColumn(nameof(VoiceRecord.Sms77Id)).AsInt32().Nullable()
;
base.MapEntity(table);
}
#endregion
}
}
| 33.545455
| 89
| 0.640921
|
[
"MIT"
] |
sms77io/nopCommerce
|
Nop.Plugin.Misc.Sms77/Data/VoiceRecordBuilder.cs
| 738
|
C#
|
using Microsoft.EntityFrameworkCore;
namespace ProjectBank.Infrastructure;
public interface IProjectBankContext : IDisposable
{
DbSet<Project> Projects { get; }
DbSet<User> Users { get; }
DbSet<Tag> Tags { get; }
int SaveChanges();
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
| 29.909091
| 78
| 0.744681
|
[
"MIT"
] |
JacobMoller/BDSAProject
|
ProjectBank/Infrastructure/IProjectBankContext.cs
| 329
|
C#
|
using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Threading;
using System.Linq;
using AjaxControlToolkit;
using RO.Facade3;
using RO.Common3;
using RO.Common3.Data;
using RO.WebRules;
namespace RO.Common3.Data
{
public class AdmScreenCri73 : DataSet
{
public AdmScreenCri73()
{
this.Tables.Add(MakeColumns(new DataTable("AdmScreenCri")));
this.Tables.Add(MakeDtlColumns(new DataTable("AdmScreenCriDef")));
this.Tables.Add(MakeDtlColumns(new DataTable("AdmScreenCriAdd")));
this.Tables.Add(MakeDtlColumns(new DataTable("AdmScreenCriUpd")));
this.Tables.Add(MakeDtlColumns(new DataTable("AdmScreenCriDel")));
this.DataSetName = "AdmScreenCri73";
this.Namespace = "http://Rintagi.com/DataSet/AdmScreenCri73";
}
private DataTable MakeColumns(DataTable dt)
{
DataColumnCollection columns = dt.Columns;
columns.Add("ScreenCriId104", typeof(string));
columns.Add("ScreenId104", typeof(string));
columns.Add("LabelCss104", typeof(string));
columns.Add("ContentCss104", typeof(string));
columns.Add("ColumnId104", typeof(string));
columns.Add("OperatorId104", typeof(string));
columns.Add("DisplayModeId104", typeof(string));
columns.Add("TabIndex104", typeof(string));
columns.Add("RequiredValid104", typeof(string));
columns.Add("ColumnJustify104", typeof(string));
columns.Add("ColumnSize104", typeof(string));
columns.Add("RowSize104", typeof(string));
columns.Add("DdlKeyColumnId104", typeof(string));
columns.Add("DdlRefColumnId104", typeof(string));
columns.Add("DdlSrtColumnId104", typeof(string));
columns.Add("DdlFtrColumnId104", typeof(string));
return dt;
}
private DataTable MakeDtlColumns(DataTable dt)
{
DataColumnCollection columns = dt.Columns;
columns.Add("ScreenCriId104", typeof(string));
columns.Add("ScreenCriHlpId105", typeof(string));
columns.Add("CultureId105", typeof(string));
columns.Add("ColumnHeader105", typeof(string));
return dt;
}
}
}
namespace RO.Web
{
public partial class AdmScreenCriModule : RO.Web.ModuleBase
{
private const string KEY_lastAddedRow = "Cache:lastAddedRow3_73";
private const string KEY_lastSortOrd = "Cache:lastSortOrd3_73";
private const string KEY_lastSortImg = "Cache:lastSortImg3_73";
private const string KEY_lastSortCol = "Cache:lastSortCol3_73";
private const string KEY_lastSortExp = "Cache:lastSortExp3_73";
private const string KEY_lastSortUrl = "Cache:lastSortUrl3_73";
private const string KEY_lastSortTog = "Cache:lastSortTog3_73";
private const string KEY_lastImpPwdOvride = "Cache:lastImpPwdOvride3_73";
private const string KEY_cntImpPwdOvride = "Cache:cntImpPwdOvride3_73";
private const string KEY_currPageIndex = "Cache:currPageIndex3_73";
private const string KEY_bHiImpVisible = "Cache:bHiImpVisible3_73";
private const string KEY_bShImpVisible = "Cache:bShImpVisible3_73";
private const string KEY_dtAdmScreenCriGrid = "Cache:dtAdmScreenCriGrid";
private const string KEY_scrImport = "Cache:scrImport3_73";
private const string KEY_dtScreenHlp = "Cache:dtScreenHlp3_73";
private const string KEY_dtClientRule = "Cache:dtClientRule3_73";
private const string KEY_dtAuthCol = "Cache:dtAuthCol3_73";
private const string KEY_dtAuthRow = "Cache:dtAuthRow3_73";
private const string KEY_dtLabel = "Cache:dtLabel3_73";
private const string KEY_dtCriHlp = "Cache:dtCriHlp3_73";
private const string KEY_dtScrCri = "Cache:dtScrCri3_73";
private const string KEY_dsScrCriVal = "Cache:dsScrCriVal3_73";
private const string KEY_dtScreenId104 = "Cache:dtScreenId104";
private const string KEY_dtColumnId104 = "Cache:dtColumnId104";
private const string KEY_dtOperatorId104 = "Cache:dtOperatorId104";
private const string KEY_dtDisplayModeId104 = "Cache:dtDisplayModeId104";
private const string KEY_dtColumnJustify104 = "Cache:dtColumnJustify104";
private const string KEY_dtDdlKeyColumnId104 = "Cache:dtDdlKeyColumnId104";
private const string KEY_dtDdlRefColumnId104 = "Cache:dtDdlRefColumnId104";
private const string KEY_dtDdlSrtColumnId104 = "Cache:dtDdlSrtColumnId104";
private const string KEY_dtDdlFtrColumnId104 = "Cache:dtDdlFtrColumnId104";
private const string KEY_dtCultureId105 = "Cache:dtCultureId105";
private const string KEY_dtSystems = "Cache:dtSystems3_73";
private const string KEY_sysConnectionString = "Cache:sysConnectionString3_73";
private const string KEY_dtAdmScreenCri73List = "Cache:dtAdmScreenCri73List";
private const string KEY_bNewVisible = "Cache:bNewVisible3_73";
private const string KEY_bNewSaveVisible = "Cache:bNewSaveVisible3_73";
private const string KEY_bCopyVisible = "Cache:bCopyVisible3_73";
private const string KEY_bCopySaveVisible = "Cache:bCopySaveVisible3_73";
private const string KEY_bDeleteVisible = "Cache:bDeleteVisible3_73";
private const string KEY_bUndoAllVisible = "Cache:bUndoAllVisible3_73";
private const string KEY_bUpdateVisible = "Cache:bUpdateVisible3_73";
private const string KEY_bClCriVisible = "Cache:bClCriVisible3_73";
private byte LcSystemId;
private string LcSysConnString;
private string LcAppConnString;
private string LcAppDb;
private string LcDesDb;
private string LcAppPw;
protected System.Collections.Generic.Dictionary<string, DataRow> LcAuth;
// *** Custom Function/Procedure Web Rule starts here *** //
public AdmScreenCriModule()
{
this.Init += new System.EventHandler(Page_Init);
}
protected void Page_Load(object sender, System.EventArgs e)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(base.LUser.Culture);
string lang2 = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
string lang = "en,zh".IndexOf(lang2) < 0 ? lang2 : Thread.CurrentThread.CurrentCulture.Name;
try { ScriptManager.RegisterStartupScript(this, this.GetType(), "datepicker_i18n", File.ReadAllText(Request.MapPath("~/scripts/i18n/jquery.ui.datepicker-" + lang + ".js")), true); } catch { };
if (!IsPostBack) { Session.Remove(KEY_dtScrCri); }
int ii = 0; DataView dvCri = GetScrCriteria(); SetCriHolder(ii, dvCri);
bConfirm.Value = "Y";
// To get around ajax not displaying ErrMsg and InfoMsg; Set them to Y to show immediately:
bErrNow.Value = "N"; bInfoNow.Value = "N"; bExpNow.Value = "N";
CtrlToFocus.Value = string.Empty;
EnableValidators(false);
if (!IsPostBack)
{
DataTable dtMenuAccess = (new MenuSystem()).GetMenu(base.LUser.CultureId, 3, base.LImpr, LcSysConnString, LcAppPw,73, null, null);
if (dtMenuAccess.Rows.Count == 0 && !IsCronInvoked())
{
string message = (new AdminSystem()).GetLabel(base.LUser.CultureId, "cSystem", "AccessDeny", null, null, null);
throw new Exception(message);
}
cFind.Attributes.Add("OnKeyDown", "return EnterKeyCtrl(event,'" + cFindButton.ClientID + "')");
cPgSize.Attributes.Add("OnKeyDown", "return EnterKeyCtrl(event,'" + cPgSizeButton.ClientID + "')");
Session[KEY_lastImpPwdOvride] = 0; Session[KEY_cntImpPwdOvride] = 0; Session[KEY_currPageIndex] = 0;
Session.Remove(KEY_dtAdmScreenCriGrid);
Session.Remove(KEY_lastSortCol);
Session.Remove(KEY_lastSortExp);
Session.Remove(KEY_lastSortImg);
Session.Remove(KEY_lastSortUrl);
Session.Remove(KEY_dtAdmScreenCri73List);
Session.Remove(KEY_dtSystems);
Session.Remove(KEY_sysConnectionString);
Session.Remove(KEY_dtScreenHlp);
Session.Remove(KEY_dtClientRule);
Session.Remove(KEY_dtAuthCol);
Session.Remove(KEY_dtAuthRow);
Session.Remove(KEY_dtLabel);
Session.Remove(KEY_dtCriHlp);
Session.Remove(KEY_dtScreenId104);
Session.Remove(KEY_dtColumnId104);
Session.Remove(KEY_dtOperatorId104);
Session.Remove(KEY_dtDisplayModeId104);
Session.Remove(KEY_dtColumnJustify104);
Session.Remove(KEY_dtDdlKeyColumnId104);
Session.Remove(KEY_dtDdlRefColumnId104);
Session.Remove(KEY_dtDdlSrtColumnId104);
Session.Remove(KEY_dtDdlFtrColumnId104);
Session.Remove(KEY_dtCultureId105);
SetButtonHlp();
GetSystems();
SetColumnAuthority();
GetGlobalFilter();
GetScreenFilter();
GetPageInfo();
GetCriteria(dvCri);
DataTable dtHlp = GetScreenHlp();
cHelpMsg.HelpTitle = dtHlp.Rows[0]["ScreenTitle"].ToString(); cHelpMsg.HelpMsg = dtHlp.Rows[0]["DefaultHlpMsg"].ToString();
cFootLabel.Text = dtHlp.Rows[0]["FootNote"].ToString();
if (cFootLabel.Text == string.Empty) { cFootLabel.Visible = false; }
cTitleLabel.Text = dtHlp.Rows[0]["ScreenTitle"].ToString();
DataTable dt = GetScreenTab();
cTab36.InnerText = dt.Rows[0]["TabFolderName"].ToString();
cTab108.InnerText = dt.Rows[1]["TabFolderName"].ToString();
SetClientRule(null,false);
IgnoreConfirm(); InitPreserve();
try
{
(new AdminSystem()).LogUsage(base.LUser.UsrId, string.Empty, dtHlp.Rows[0]["ScreenTitle"].ToString(), 73, 0, 0, string.Empty, LcSysConnString, LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
// *** Criteria Trigger (before) Web Rule starts here *** //
PopAdmScreenCri73List(sender, e, true, null);
if (cAuditButton.Attributes["OnClick"] == null || cAuditButton.Attributes["OnClick"].IndexOf("AdmScrAudit.aspx") < 0) { cAuditButton.Attributes["OnClick"] += "SearchLink('AdmScrAudit.aspx?cri0=73&typ=N&sys=3','','',''); return false;"; }
// *** Page Load (End of) Web Rule starts here *** //
cBrowse.Attributes.Add("OnChange", "__doPostBack('" + cBrowseButton.ClientID.Replace("_", "$") + "','')");
DataTable dtLabel = (new AdminSystem()).GetLabels(base.LUser.CultureId, "cGrid", null, null, null);
if (dtLabel != null)
{
cGridFtrLabel.Text = dtLabel.Rows[0][1].ToString();
cGridFndLabel.Text = dtLabel.Rows[1][1].ToString();
cImpPwdLabel.Text = dtLabel.Rows[2][1].ToString();
cImportPwd.ToolTip = dtLabel.Rows[3][1].ToString();
cGridWksLabel.Text = dtLabel.Rows[4][1].ToString();
cGridStrLabel.Text = dtLabel.Rows[5][1].ToString();
cStartRow.ToolTip = dtLabel.Rows[6][1].ToString();
}
}
else
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if (dt != null)
{
string sr = ViewState["_SortColumn"] as string;
if (sr != null) { dt.DefaultView.Sort = sr.ToString(); }
string rf = ViewState["_RowFilter"] as string;
if (rf != null) { dt.DefaultView.RowFilter = rf.ToString(); }
}
}
if (IsPostBack && !ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack) {SetClientRule(null,false);};
if (!IsPostBack) // Test for Viewstate being lost.
{
bViewState.Text = "Y";
string xx = Session["Idle:" + Request.Url.PathAndQuery] as string;
if (xx == "Y")
{
Session.Remove("Idle:" + Request.Url.PathAndQuery);
bInfoNow.Value = "Y"; PreMsgPopup("Page has been idled past preset limit and no longer valid, please be notified that it has been reloaded.");
}
}
else if (string.IsNullOrEmpty(bViewState.Text)) // Viewstate is lost.
{
Session["Idle:" + Request.Url.PathAndQuery] = "Y"; Response.Redirect(Request.Url.PathAndQuery);
}
if (!string.IsNullOrEmpty(cCurrentTab.Value))
{
HtmlControl wcTab = this.FindControl(cCurrentTab.Value.Substring(1)) as HtmlControl;
wcTab.Style["display"] = "block";
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "ScreenLabel", this.ClientID + "={" + string.Join(",", (from dr in GetLabel().AsEnumerable() select string.Format("{0}: {{msg:'{1}',hint:'{2}'}}", "c" + dr.Field<string>("ColumnName") + (dr.Field<int?>("TableId").ToString()), (dr.Field<string>("ErrMessage") ?? string.Empty).Replace("'", "\\'").Replace("\r", "\\r").Replace("\n", "\\n"), (dr.Field<string>("TbHint") ?? string.Empty).Replace("'", "\\'").Replace("\r", "\\r").Replace("\n", "\\n"))).ToArray()) + "};", true);
}
protected void Page_Init(object sender, EventArgs e)
{
// *** Page Init (Front of) Web Rule starts here *** //
InitializeComponent();
// *** Page Init (End of) Web Rule starts here *** //
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
CheckAuthentication(true);
if (LcSysConnString == null)
{
SetSystem(3);
try
{
DataTable dt;
dt = (new AdminSystem()).GetAuthRow(73,base.LImpr.RowAuthoritys,LcSysConnString,LcAppPw);
Session[KEY_dtAuthRow] = dt;
DataRow dr = dt.Rows[0];
if (!((dr["AllowUpd"].ToString() == "N" || dr["ViewOnly"].ToString() == "G") && dr["AllowAdd"].ToString() == "N") && (Request.QueryString["enb"] == null || Request.QueryString["enb"] != "N"))
{
cAdmScreenCriGrid.PreRender += new EventHandler(cAdmScreenCriGrid_OnPreRender);
}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
}
#endregion
private void SetSystem(byte SystemId)
{
LcSystemId = SystemId;
LcSysConnString = base.SysConnectStr(SystemId);
LcAppConnString = base.AppConnectStr(SystemId);
LcDesDb = base.DesDb(SystemId);
LcAppDb = base.AppDb(SystemId);
LcAppPw = base.AppPwd(SystemId);
try
{
base.CPrj = new CurrPrj(((new RobotSystem()).GetEntityList()).Rows[0]);
DataRow row = base.SystemsList.Rows.Find(SystemId);
base.CSrc = new CurrSrc(true, row);
base.CTar = new CurrTar(true, row);
if ((Config.DeployType == "DEV" || row["dbAppDatabase"].ToString() == base.CPrj.EntityCode + "View") && !(base.CPrj.EntityCode != "RO" && row["SysProgram"].ToString() == "Y") && (new AdminSystem()).IsRegenNeeded(string.Empty,73,0,0,LcSysConnString,LcAppPw))
{
(new GenScreensSystem()).CreateProgram(73, "Screen Criteria", row["dbAppDatabase"].ToString(), base.CPrj, base.CSrc, base.CTar, LcAppConnString, LcAppPw);
Response.Redirect(Request.RawUrl);
}
}
catch (Exception e) { bErrNow.Value = "Y"; PreMsgPopup(e.Message); }
}
private void EnableValidators(bool bEnable)
{
foreach (System.Web.UI.WebControls.WebControl va in Page.Validators)
{
if (bEnable) {va.Enabled = true;} else {va.Enabled = false;}
}
}
private void CheckAuthentication(bool pageLoad)
{
if (IsCronInvoked()) AnonymousLogin();
else CheckAuthentication(pageLoad, true);
}
private void SetButtonHlp()
{
try
{
DataTable dt;
dt = (new AdminSystem()).GetButtonHlp(73,0,0,base.LUser.CultureId,LcSysConnString,LcAppPw);
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
if (dr["ButtonTypeName"].ToString() == "ClearCri") { cClearCriButton.CssClass = "ButtonImg ClearCriButtonImg"; Session[KEY_bClCriVisible] = base.GetBool(dr["ButtonVisible"].ToString()); cClearCriButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "Save") { cSaveButton.CssClass = "ButtonImg SaveButtonImg"; cSaveButton.Text = dr["ButtonName"].ToString(); cSaveButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cSaveButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bUpdateVisible] = cSaveButton.Visible; }
else if (dr["ButtonTypeName"].ToString() == "ExpTxt") { cExpTxtButton.CssClass = "ButtonImg ExpTxtButtonImg"; cExpTxtButton.Text = dr["ButtonName"].ToString(); cExpTxtButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cExpTxtButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "ExpRtf") { cExpRtfButton.CssClass = "ButtonImg ExpRtfButtonImg"; cExpRtfButton.Text = dr["ButtonName"].ToString(); cExpRtfButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cExpRtfButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "UndoAll") { cUndoAllButton.CssClass = "ButtonImg UndoAllButtonImg"; cUndoAllButton.Text = dr["ButtonName"].ToString(); cUndoAllButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cUndoAllButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bUndoAllVisible] = cUndoAllButton.Visible; }
else if (dr["ButtonTypeName"].ToString() == "More") { cMoreButton.CssClass = "ButtonImg MoreButtonImg"; cMoreButton.Text = dr["ButtonName"].ToString(); cMoreButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cMoreButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "SaveClose") { cSaveCloseButton.CssClass = "ButtonImg SaveCloseButtonImg"; cSaveCloseButton.Text = dr["ButtonName"].ToString(); cSaveCloseButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cSaveCloseButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "Edit") { cEditButton.CssClass = "ButtonImg EditButtonImg"; cEditButton.Text = dr["ButtonName"].ToString(); cEditButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cEditButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "Preview") { cPreviewButton.CssClass = "ButtonImg PreviewButtonImg"; cPreviewButton.Text = dr["ButtonName"].ToString(); cPreviewButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cPreviewButton.ToolTip = dr["ButtonToolTip"].ToString(); }
if (dr["ButtonTypeName"].ToString() == "Audit") { cAuditButton.CssClass = "ButtonImg AuditButtonImg"; cAuditButton.Text = dr["ButtonName"].ToString(); cAuditButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cAuditButton.ToolTip = dr["ButtonToolTip"].ToString(); }
if (dr["ButtonTypeName"].ToString() == "Clear") { cClearButton.CssClass = "ButtonImg ClearButtonImg"; cClearButton.Text = dr["ButtonName"].ToString(); cClearButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cClearButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "New") { cNewButton.CssClass = "ButtonImg NewButtonImg"; cNewButton.Text = dr["ButtonName"].ToString(); cNewButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cNewButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bNewVisible] = cNewButton.Visible; }
else if (dr["ButtonTypeName"].ToString() == "NewSave") { cNewSaveButton.CssClass = "ButtonImg NewSaveButtonImg"; cNewSaveButton.Text = dr["ButtonName"].ToString(); cNewSaveButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cNewSaveButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bNewSaveVisible] = cNewSaveButton.Visible; }
else if (dr["ButtonTypeName"].ToString() == "Copy") { cCopyButton.CssClass = "ButtonImg CopyButtonImg"; cCopyButton.Text = dr["ButtonName"].ToString(); cCopyButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cCopyButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bCopyVisible] = cCopyButton.Visible;}
else if (dr["ButtonTypeName"].ToString() == "CopySave") { cCopySaveButton.CssClass = "ButtonImg CopySaveButtonImg"; cCopySaveButton.Text = dr["ButtonName"].ToString(); cCopySaveButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cCopySaveButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bCopySaveVisible] = cCopySaveButton.Visible;}
else if (dr["ButtonTypeName"].ToString() == "Delete") { cDeleteButton.CssClass = "ButtonImg DeleteButtonImg"; cDeleteButton.Text = dr["ButtonName"].ToString(); cDeleteButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cDeleteButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bDeleteVisible] = cDeleteButton.Visible;}
if (dr["ButtonTypeName"].ToString() == "InsRow") { cInsRowButton.CssClass = "ButtonImg InsRowButtonImg"; cInsRowButton.Text = "ADD"; cInsRowButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cInsRowButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "PgSize") { cPgSizeButton.CssClass = "ButtonImg PgSizeButtonImg"; cPgSizeButton.Text = string.Empty; cPgSizeButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cPgSizeButton.ToolTip = dr["ButtonToolTip"].ToString(); cPgSize.Visible = base.GetBool(dr["ButtonVisible"].ToString()); }
else if (dr["ButtonTypeName"].ToString() == "First") { cFirstButton.CssClass = "ButtonImg FirstButtonImg"; cFirstButton.Text = string.Empty; cFirstButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cFirstButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "Prev") { cPrevButton.CssClass = "ButtonImg PrevButtonImg"; cPrevButton.Text = string.Empty; cPrevButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cPrevButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "Next") { cNextButton.CssClass = "ButtonImg NextButtonImg"; cNextButton.Text = string.Empty; cNextButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cNextButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "Last") { cLastButton.CssClass = "ButtonImg LastButtonImg"; cLastButton.Text = string.Empty; cLastButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cLastButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "Find") { cFindButton.CssClass = "ButtonImg FindButtonImg"; cFindButton.Text = string.Empty; cFindButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cFindButton.ToolTip = dr["ButtonToolTip"].ToString(); cFind.Visible = base.GetBool(dr["ButtonVisible"].ToString()); }
else if (dr["ButtonTypeName"].ToString() == "Import") { cImportButton.CssClass = "ButtonImg ImportButtonImg"; cImportButton.Text = string.Empty; cImportButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cImportButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "Continue") { cContinueButton.CssClass = "ButtonImg ContinueButtonImg"; cContinueButton.Text = string.Empty; cContinueButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cContinueButton.ToolTip = dr["ButtonToolTip"].ToString(); }
else if (dr["ButtonTypeName"].ToString() == "HideImp") { cHideImpButton.CssClass = "ButtonImg HideImpButtonImg"; cHideImpButton.Text = string.Empty; cHideImpButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cHideImpButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bHiImpVisible] = base.GetBool(dr["ButtonVisible"].ToString()); cHideImpButton.Visible = false; }
else if (dr["ButtonTypeName"].ToString() == "ShowImp") { cShowImpButton.CssClass = "ButtonImg ShowImpButtonImg"; cShowImpButton.Text = string.Empty; cShowImpButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cShowImpButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bShImpVisible] = cShowImpButton.Visible; }
}
}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
private DataTable GetClientRule()
{
DataTable dtRul = (DataTable)Session[KEY_dtClientRule];
if (dtRul == null)
{
CheckAuthentication(false);
try
{
dtRul = (new AdminSystem()).GetClientRule(73,0,base.LUser.CultureId,LcSysConnString,LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
Session[KEY_dtClientRule] = dtRul;
}
return dtRul;
}
private void SetClientRule(ListViewDataItem ee, bool isEditItem)
{
DataView dvRul = new DataView(GetClientRule());
if (ee != null) {dvRul.RowFilter = "MasterTable = 'N'";} else {dvRul.RowFilter = "MasterTable <> 'N'";}
if (dvRul.Count > 0)
{
WebControl cc = null;
string srp = string.Empty;
string sn = string.Empty;
string st = string.Empty;
string sg = string.Empty;
int ii = 0;
int jj = 0;
Regex missing = new Regex("@[0-9]+@");
string lang2 = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
string lang = "en,zh".IndexOf(lang2) < 0 ? lang2 : Thread.CurrentThread.CurrentCulture.Name;
foreach (DataRowView drv in dvRul)
{
if (ee == null || drv["ScriptEvent"].ToString().Substring(0,2).ToLower() != "on" || (cAdmScreenCriGrid.EditIndex > -1 && GetDataItemIndex(cAdmScreenCriGrid.EditIndex) == ee.DataItemIndex))
{
srp = drv["ScriptName"].ToString();
srp = srp.Replace("@cLang@", "\'" + lang + "\'");
if (drv["ParamName"].ToString() != string.Empty)
{
StringBuilder sbName = new StringBuilder();
StringBuilder sbType = new StringBuilder();
StringBuilder sbInGrid = new StringBuilder();
sbName.Append(drv["ParamName"].ToString().Trim());
sbType.Append(drv["ParamType"].ToString().Trim());
sbInGrid.Append(drv["ParamInGrid"].ToString().Trim());
ii = 0;
while (sbName.Length > 0)
{
sn = Utils.PopFirstWord(sbName,(char)44); st = Utils.PopFirstWord(sbType,(char)44);sg = Utils.PopFirstWord(sbInGrid,(char)44);
if (ee != null && sg == "Y")
{
if (st.ToLower() == "combobox" && isEditItem) {srp = srp.Replace("@" + ii.ToString() + "@","'"+((RoboCoder.WebControls.ComboBox)ee.FindControl(sn)).KeyID+"'");} else {srp = srp.Replace("@" + ii.ToString() + "@","'"+((WebControl)ee.FindControl(sn + (!isEditItem ? "l" : ""))).ClientID+"'");}
}
else
{
if (st.ToLower() == "combobox") {srp = srp.Replace("@" + ii.ToString() + "@","'"+((RoboCoder.WebControls.ComboBox)this.FindControl(sn)).KeyID+"'");} else {srp = srp.Replace("@" + ii.ToString() + "@","'"+((WebControl)this.FindControl(sn)).ClientID+"'");}
}
ii = ii + 1;
}
}
if (drv["ScriptEvent"].ToString() == "js")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), drv["ColName"].ToString() + "_" + drv["ScriptName"].ToString() + jj.ToString(),"<script>"+ drv["ClientRuleProg"].ToString() + srp + "</script>", false);
}
else if (drv["ScriptEvent"].ToString() == "css")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), drv["ColName"].ToString() + "_" + drv["ScriptName"].ToString() + jj.ToString(),"<style>"+ drv["ClientRuleProg"].ToString() + "</style>", false);
}
else if (drv["ScriptEvent"].ToString() == "css_link")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), drv["ColName"].ToString() + "_" + drv["ScriptName"].ToString() + jj.ToString(),"<link rel='stylesheet' type='text/css' href='"+ drv["ClientRuleProg"].ToString() + "' />", false);
}
else if (drv["ScriptEvent"].ToString() == "js_link")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), drv["ColName"].ToString() + "_" + drv["ScriptName"].ToString() + jj.ToString(),"<script type='text/javascript' src='"+ drv["ClientRuleProg"].ToString() + "'></script>", false);
}
else
{
srp = missing.Replace(srp, "''");
string scriptEvent = drv["ScriptEvent"].ToString().TrimStart(new char[]{'_'});
if (ee != null) {cc = ee.FindControl(drv["ColName"].ToString()) as WebControl;} else {cc = this.FindControl(drv["ColName"].ToString()) as WebControl;}
if (cc != null && (cc.Attributes[scriptEvent] == null || cc.Attributes[scriptEvent].IndexOf(srp) < 0)) {cc.Attributes[scriptEvent] += srp;}
if (ee != null && drv["ScriptEvent"].ToString().Substring(0,2).ToLower() != "on")
{
cc = ee.FindControl(drv["ColName"].ToString() + "l") as WebControl;
if (cc != null && (cc.Attributes[scriptEvent] == null || cc.Attributes[scriptEvent].IndexOf(srp) < 0)) {cc.Attributes[scriptEvent] += srp;}
}
}
}
jj = jj + 1;
}
}
}
private DataTable GetScreenCriHlp()
{
DataTable dtCriHlp = (DataTable)Session[KEY_dtCriHlp];
if (dtCriHlp == null)
{
CheckAuthentication(false);
try
{
dtCriHlp = (new AdminSystem()).GetScreenCriHlp(73,base.LUser.CultureId,LcSysConnString,LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
Session[KEY_dtCriHlp] = dtCriHlp;
}
return dtCriHlp;
}
private DataTable GetScreenHlp()
{
DataTable dtHlp = (DataTable)Session[KEY_dtScreenHlp];
if (dtHlp == null)
{
CheckAuthentication(false);
try
{
dtHlp = (new AdminSystem()).GetScreenHlp(73,base.LUser.CultureId,LcSysConnString,LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
Session[KEY_dtScreenHlp] = dtHlp;
}
return dtHlp;
}
private void GetGlobalFilter()
{
try
{
DataTable dt;
dt = (new AdminSystem()).GetGlobalFilter(base.LUser.UsrId,73,base.LUser.CultureId,LcSysConnString,LcAppPw);
if (dt != null && dt.Rows.Count > 0)
{
cGlobalFilter.Text = dt.Rows[0]["FilterDesc"].ToString();
cGlobalFilter.Visible = true;
}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
private void GetScreenFilter()
{
try
{
DataTable dt = (new AdminSystem()).GetScreenFilter(73,base.LUser.CultureId,LcSysConnString,LcAppPw);
if (dt != null)
{
cFilterId.DataSource = dt;
cFilterId.DataBind();
if (cFilterId.Items.Count > 0)
{
if (Request.QueryString["ftr"] != null) {cFilterId.Items.FindByValue(Request.QueryString["ftr"]).Selected = true;} else {cFilterId.Items[0].Selected = true;}
cFilterLabel.Text = (new AdminSystem()).GetLabel(base.LUser.CultureId, "QFilter", "QFilter", null, null, null);
cFilter.Visible = true;
}
}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
private void GetSystems()
{
Session[KEY_sysConnectionString] = LcSysConnString;
DataTable dtSystems = base.SystemsList;
if (dtSystems != null)
{
Session[KEY_dtSystems] = dtSystems;
cSystemId.DataSource = dtSystems;
cSystemId.DataBind();
if (cSystemId.Items.Count > 1)
{
if (Request.QueryString["sys"] != null) {cSystemId.Items.FindByValue(Request.QueryString["sys"]).Selected = true;}
else
{
try { cSystemId.Items.FindByValue(base.LCurr.DbId.ToString()).Selected = true; }
catch {cSystemId.Items[0].Selected = true;}
}
base.LCurr.DbId = byte.Parse(cSystemId.SelectedValue);
Session[KEY_sysConnectionString] = Config.GetConnStr(dtSystems.Rows[cSystemId.SelectedIndex]["dbAppProvider"].ToString(), dtSystems.Rows[cSystemId.SelectedIndex]["ServerName"].ToString(), dtSystems.Rows[cSystemId.SelectedIndex]["dbDesDatabase"].ToString(), "", dtSystems.Rows[cSystemId.SelectedIndex]["dbAppUserId"].ToString());
cSystemLabel.Text = (new AdminSystem()).GetLabel(base.LUser.CultureId, "cSystem", "Label", null, null, null);
cSystem.Visible = true;
}
}
}
protected string ColumnWatermark(int idx)
{
return GetLabel().Rows[idx]["tbHint"].ToString();
}
protected string ColumnHeaderText(int idx)
{
return (GetLabel().Rows[idx]["RequiredValid"].ToString() == "Y" ? Config.MandatoryChar : string.Empty) + GetLabel().Rows[idx]["ColumnHeader"].ToString();
}
protected string ColumnToolTip(int idx)
{
return GetLabel().Rows[idx]["ToolTip"].ToString();
}
protected bool GridColumnVisible(int idx)
{
return GetAuthCol().Rows[idx]["ColVisible"].ToString()=="Y";
}
protected bool GridColumnEnable(int idx)
{
return GetAuthCol().Rows[idx]["ColReadOnly"].ToString()=="N";
}
private DataTable GetLabel()
{
DataTable dt = (DataTable)Session[KEY_dtLabel];
if (dt == null)
{
try
{
dt = (new AdminSystem()).GetScreenLabel(73,base.LUser.CultureId,base.LImpr,base.LCurr,LcSysConnString,LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
Session[KEY_dtLabel] = dt;
}
return dt;
}
private DataTable GetAuthCol()
{
DataTable dt = (DataTable)Session[KEY_dtAuthCol];
if (dt == null)
{
try
{
dt = (new AdminSystem()).GetAuthCol(73,base.LImpr,base.LCurr,LcSysConnString,LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
Session[KEY_dtAuthCol] = dt;
}
return dt;
}
protected DataTable GetAuthRow()
{
DataTable dt = (DataTable)Session[KEY_dtAuthRow];
if (dt == null)
{
try
{
dt = (new AdminSystem()).GetAuthRow(73,base.LImpr.RowAuthoritys,LcSysConnString,LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
Session[KEY_dtAuthRow] = dt;
}
return dt;
}
private void getReport(string eExport)
{
try
{
StringBuilder sb = new StringBuilder();
CheckAuthentication(false);
DataView dv = null;
int filterId = 0; if (Utils.IsInt(cFilterId.SelectedValue)) { filterId = int.Parse(cFilterId.SelectedValue); }
try
{
try {dv = new DataView((new AdminSystem()).GetExp(73,"GetExpAdmScreenCri73","Y",(string)Session[KEY_sysConnectionString],LcAppPw,filterId,GetScrCriteria(),base.LImpr,base.LCurr,UpdCriteria(false)));}
catch {dv = new DataView((new AdminSystem()).GetExp(73,"GetExpAdmScreenCri73","N",(string)Session[KEY_sysConnectionString],LcAppPw,filterId,GetScrCriteria(),base.LImpr,base.LCurr,UpdCriteria(false)));}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (eExport == "TXT")
{
DataTable dtAu;
dtAu = (new AdminSystem()).GetAuthExp(73,base.LUser.CultureId,base.LImpr,base.LCurr,LcSysConnString,LcAppPw);
if (dtAu != null)
{
if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[0]["ColumnHeader"].ToString() + (char)9);}
if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[1]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[1]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[2]["ColumnHeader"].ToString() + (char)9);}
if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[3]["ColumnHeader"].ToString() + (char)9);}
if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[4]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[4]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[5]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[5]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[6]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[6]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[7]["ColumnHeader"].ToString() + (char)9);}
if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[8]["ColumnHeader"].ToString() + (char)9);}
if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[9]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[9]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[10]["ColumnHeader"].ToString() + (char)9);}
if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[11]["ColumnHeader"].ToString() + (char)9);}
if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[12]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[12]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[13]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[13]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[14]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[14]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[15]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[15]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[16]["ColumnHeader"].ToString() + (char)9);}
if (dtAu.Rows[17]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[17]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[17]["ColumnHeader"].ToString() + " Text" + (char)9);}
if (dtAu.Rows[18]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[18]["ColumnHeader"].ToString() + (char)9);}
sb.Append(Environment.NewLine);
}
foreach (DataRowView drv in dv)
{
if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["ScreenCriId104"].ToString(),base.LUser.Culture) + (char)9);}
if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {sb.Append(drv["ScreenId104"].ToString() + (char)9 + drv["ScreenId104Text"].ToString() + (char)9);}
if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["LabelCss104"].ToString().Replace("\"","\"\"") + "\"" + (char)9);}
if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["ContentCss104"].ToString().Replace("\"","\"\"") + "\"" + (char)9);}
if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {sb.Append(drv["ColumnId104"].ToString() + (char)9 + drv["ColumnId104Text"].ToString() + (char)9);}
if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {sb.Append(drv["OperatorId104"].ToString() + (char)9 + drv["OperatorId104Text"].ToString() + (char)9);}
if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {sb.Append(drv["DisplayModeId104"].ToString() + (char)9 + drv["DisplayModeId104Text"].ToString() + (char)9);}
if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["TabIndex104"].ToString(),base.LUser.Culture) + (char)9);}
if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["RequiredValid104"].ToString().Replace("\"","\"\"") + "\"" + (char)9);}
if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["ColumnJustify104"].ToString().Replace("\"","\"\"") + "\"" + (char)9 + "\"" + drv["ColumnJustify104Text"].ToString().Replace("\"","\"\"") + "\"" + (char)9);}
if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["ColumnSize104"].ToString(),base.LUser.Culture) + (char)9);}
if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["RowSize104"].ToString(),base.LUser.Culture) + (char)9);}
if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {sb.Append(drv["DdlKeyColumnId104"].ToString() + (char)9 + drv["DdlKeyColumnId104Text"].ToString() + (char)9);}
if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {sb.Append(drv["DdlRefColumnId104"].ToString() + (char)9 + drv["DdlRefColumnId104Text"].ToString() + (char)9);}
if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {sb.Append(drv["DdlSrtColumnId104"].ToString() + (char)9 + drv["DdlSrtColumnId104Text"].ToString() + (char)9);}
if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {sb.Append(drv["DdlFtrColumnId104"].ToString() + (char)9 + drv["DdlFtrColumnId104Text"].ToString() + (char)9);}
if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["ScreenCriHlpId105"].ToString(),base.LUser.Culture) + (char)9);}
if (dtAu.Rows[17]["ColExport"].ToString() == "Y") {sb.Append(drv["CultureId105"].ToString() + (char)9 + drv["CultureId105Text"].ToString() + (char)9);}
if (dtAu.Rows[18]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["ColumnHeader105"].ToString().Replace("\"","\"\"") + "\"" + (char)9);}
sb.Append(Environment.NewLine);
}
bExpNow.Value = "Y"; Session["ExportFnm"] = "AdmScreenCri.xls"; Session["ExportStr"] = sb.Replace("\r\n","\n");
}
else if (eExport == "RTF")
{
sb.Append(@"{\rtf1\ansi\ansicpg1252\uc1\deff0\stshfdbch0\stshfloch0\stshfhich0\stshfbi0\deflang1033\deflangfe1033{\fonttbl{\f0\froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f37\fswiss\fcharset0\fprq2{\*\panose 020b0604030504040204}Verdana;}
{\f182\froman\fcharset238\fprq2 Times New Roman CE;}{\f183\froman\fcharset204\fprq2 Times New Roman Cyr;}{\f185\froman\fcharset161\fprq2 Times New Roman Greek;}{\f186\froman\fcharset162\fprq2 Times New Roman Tur;}
{\f187\froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f188\froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f189\froman\fcharset186\fprq2 Times New Roman Baltic;}{\f190\froman\fcharset163\fprq2 Times New Roman (Vietnamese);}
{\f552\fswiss\fcharset238\fprq2 Verdana CE;}{\f553\fswiss\fcharset204\fprq2 Verdana Cyr;}{\f555\fswiss\fcharset161\fprq2 Verdana Greek;}{\f556\fswiss\fcharset162\fprq2 Verdana Tur;}{\f559\fswiss\fcharset186\fprq2 Verdana Baltic;}
{\f560\fswiss\fcharset163\fprq2 Verdana (Vietnamese);}}{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;
\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;}{\stylesheet{
\ql \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \fs24\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 \snext0 Normal;}{\*\cs10 \additive \ssemihidden Default Paragraph Font;}{\*
\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tscellwidthfts0\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv
\ql \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \fs20\lang1024\langfe1024\cgrid\langnp1024\langfenp1024 \snext11 \ssemihidden Normal Table;}}{\*\latentstyles\lsdstimax156\lsdlockeddef0}{\*\rsidtbl \rsid1574081\rsid2952683
\rsid4674135\rsid4855636\rsid6620441\rsid6645578\rsid7160396\rsid7497391\rsid8133092\rsid8259185\rsid8528326\rsid8936003\rsid9058410\rsid10305085\rsid10505691\rsid13726773\rsid14047122\rsid14576392\rsid15756354\rsid16472473\rsid16525787}{\*\generator Micr
osoft Word 11.0.6359;}{\info{\title [[ScreenTitle]]}{\author }{\operator }{\creatim\yr2004\mo12\dy21\hr12\min7}{\revtim\yr2004\mo12\dy21\hr16\min16}{\version7}{\edmins5}{\nofpages1}{\nofwords6}{\nofchars38}
{\*\company robocoder corporation}{\nofcharsws43}{\vern24703}}\margl1440\margr1440 \widowctrl\ftnbj\aenddoc\noxlattoyen\expshrtn\noultrlspc\dntblnsbdb\nospaceforul\hyphcaps0\formshade\horzdoc\dgmargin\dghspace180\dgvspace180\dghorigin1440\dgvorigin1440
\dghshow1\dgvshow1\jexpand\viewkind1\viewscale100\pgbrdrhead\pgbrdrfoot\splytwnine\ftnlytwnine\htmautsp\nolnhtadjtbl\useltbaln\alntblind\lytcalctblwd\lyttblrtgr\lnbrkrule\nobrkwrptbl\snaptogridincell\allowfieldendsel\wrppunct
\asianbrkrule\rsidroot4855636\newtblstyruls\nogrowautofit \fet0\sectd \linex0\endnhere\sectlinegrid360\sectdefaultcl\sectrsid7497391\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang
{\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang
{\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}\pard\plain
\qc \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid4855636 \fs24\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 {\b\fs32\insrsid4855636\charrsid6645578 [[TitleLabel]]}{\b\fs32\insrsid16472473\charrsid6645578
\par }{\insrsid4855636
\par }{\b\i\fs18\insrsid4855636\charrsid8936003 [[GlobalFilter]]
\par }\pard \ql \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid8259185 {\insrsid7497391
\par }\pard \qc \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid4855636 {\f37\fs16\insrsid4855636\charrsid1574081 [[Grid]]
\par }\pard \ql \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 {\insrsid4855636
\par }}");
sb.Replace("[[TitleLabel]]", cTitleLabel.Text);
sb.Replace("[[GlobalFilter]]", cGlobalFilter.Text);
sb.Replace("[[Grid]]", GetRtfGrid(dv));
bExpNow.Value = "Y"; Session["ExportFnm"] = "AdmScreenCri.rtf"; Session["ExportStr"] = sb;
}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
private string GetRtfGrid(DataView dv)
{
StringBuilder sb = new StringBuilder("");
try
{
int iColCnt = 0;
DataTable dtAu;
dtAu = (new AdminSystem()).GetAuthExp(73,base.LUser.CultureId,base.LImpr,base.LCurr,LcSysConnString,LcAppPw);
if (dtAu != null)
{
if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[17]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
if (dtAu.Rows[18]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;}
//Create Header
sb.Append(@"\trowd \irow0\irowband0\lastrow \ts15\trgaph108\trleft-108\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 \trbrdrh\brdrs\brdrw10 \trbrdrv\brdrs\brdrw10 ");
sb.Append(@"\trftsWidth1\trftsWidthB3\trautofit1\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblrsid2981395\tbllkhdrrows\tbllklastrow\tbllkhdrcols\tbllklastcol ");
sb.Append("\r\n");
sb.Append(GenCellx(iColCnt));
sb.Append(@"\pard \ql \li0\ri0\widctlpar\intbl\aspalpha\aspnum\adjustright\rin0\lin0 \lang1033\langfe1033\cgrid\langnp1033\langfenp1033 ");
sb.Append("\r\n");
sb.Append(@"\b");
sb.Append(@"{");
if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[0]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[1]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[2]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[3]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[4]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[5]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[6]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[7]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[8]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[9]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[10]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[11]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[12]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[13]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[14]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[15]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[16]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[17]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[17]["ColumnHeader"].ToString() + @"\cell ");}
if (dtAu.Rows[18]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[18]["ColumnHeader"].ToString() + @"\cell ");}
sb.Append(@"}");
sb.Append(@"\b0");
sb.Append("\r\n");
sb.Append(@"\pard \ql \li0\ri0\widctlpar\intbl\aspalpha\aspnum\adjustright\rin0\lin0 {");
sb.Append(@"\insrsid2981395 \trowd \irow0\irowband0\lastrow \ts15\trgaph108\trleft-108\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 \trbrdrh\brdrs\brdrw10 \trbrdrv\brdrs\brdrw10 ");
sb.Append(@"\trftsWidth1\trftsWidthB3\trautofit1\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblrsid2981395\tbllkhdrrows\tbllklastrow\tbllkhdrcols\tbllklastcol ");
sb.Append("\r\n");
sb.Append(GenCellx(iColCnt));
sb.Append("\r\n");
sb.Append(@"\row }");
sb.Append("\r\n");
}
//Create Data Rows
foreach (DataRowView drv in dv)
{
sb.Append(@"\trowd \irow0\irowband0\lastrow \ts15\trgaph108\trleft-108\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 \trbrdrh\brdrs\brdrw10 \trbrdrv\brdrs\brdrw10 ");
sb.Append(@"\trftsWidth1\trftsWidthB3\trautofit1\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblrsid2981395\tbllkhdrrows\tbllklastrow\tbllkhdrcols\tbllklastcol ");
sb.Append("\r\n");
sb.Append(GenCellx(iColCnt));
sb.Append(@"\pard \ql \li0\ri0\widctlpar\intbl\aspalpha\aspnum\adjustright\rin0\lin0 \lang1033\langfe1033\cgrid\langnp1033\langfenp1033 ");
sb.Append("\r\n");
sb.Append(@"{");
if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["ScreenCriId104"].ToString(),base.LUser.Culture) + @"\cell ");}
if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {sb.Append(drv["ScreenId104Text"].ToString() + @"\cell ");}
if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {sb.Append(drv["LabelCss104"].ToString().Replace("\r\n",@"\par ") + @"\cell ");}
if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {sb.Append(drv["ContentCss104"].ToString().Replace("\r\n",@"\par ") + @"\cell ");}
if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {sb.Append(drv["ColumnId104Text"].ToString() + @"\cell ");}
if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {sb.Append(drv["OperatorId104Text"].ToString() + @"\cell ");}
if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {sb.Append(drv["DisplayModeId104Text"].ToString() + @"\cell ");}
if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["TabIndex104"].ToString(),base.LUser.Culture) + @"\cell ");}
if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {sb.Append(drv["RequiredValid104"].ToString().Replace("\r\n",@"\par ") + @"\cell ");}
if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {sb.Append(drv["ColumnJustify104Text"].ToString().Replace("\r\n",@"\par ") + @"\cell ");}
if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["ColumnSize104"].ToString(),base.LUser.Culture) + @"\cell ");}
if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["RowSize104"].ToString(),base.LUser.Culture) + @"\cell ");}
if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {sb.Append(drv["DdlKeyColumnId104Text"].ToString() + @"\cell ");}
if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {sb.Append(drv["DdlRefColumnId104Text"].ToString() + @"\cell ");}
if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {sb.Append(drv["DdlSrtColumnId104Text"].ToString() + @"\cell ");}
if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {sb.Append(drv["DdlFtrColumnId104Text"].ToString() + @"\cell ");}
if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["ScreenCriHlpId105"].ToString(),base.LUser.Culture) + @"\cell ");}
if (dtAu.Rows[17]["ColExport"].ToString() == "Y") {sb.Append(drv["CultureId105Text"].ToString() + @"\cell ");}
if (dtAu.Rows[18]["ColExport"].ToString() == "Y") {sb.Append(drv["ColumnHeader105"].ToString().Replace("\r\n",@"\par ") + @"\cell ");}
sb.Append(@"}");
sb.Append("\r\n");
sb.Append(@"\pard \ql \li0\ri0\widctlpar\intbl\aspalpha\aspnum\adjustright\rin0\lin0 {");
sb.Append(@"\insrsid2981395 \trowd \irow0\irowband0\lastrow \ts15\trgaph108\trleft-108\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 \trbrdrh\brdrs\brdrw10 \trbrdrv\brdrs\brdrw10 ");
sb.Append(@"\trftsWidth1\trftsWidthB3\trautofit1\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblrsid2981395\tbllkhdrrows\tbllklastrow\tbllkhdrcols\tbllklastcol ");
sb.Append("\r\n");
sb.Append(GenCellx(iColCnt));
sb.Append("\r\n");
sb.Append(@"\row }");
sb.Append("\r\n");
}
sb.Append(@"\pard \par }");
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
return sb.ToString();
}
private StringBuilder GenCellx(int CellCnt)
{
StringBuilder sb = new StringBuilder("");
string strRowPre = @"\clvertalt\clbrdrt\brdrs\brdrw10 \clbrdrl\brdrs\brdrw10 \clbrdrb\brdrs\brdrw10 \clbrdrr\brdrs\brdrw10 \cltxlrtb\clftsWidth3\clwWidth4428\clshdrawnil ";
for (int cnt=0; cnt<CellCnt; cnt++) {sb.Append(strRowPre + @"\cellx" + cnt.ToString() + " ");}
return sb;
}
public void cExpTxtButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
getReport("TXT");
// *** System Button Click (After) Web Rule starts here *** //
}
public void cExpRtfButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
getReport("RTF");
// *** System Button Click (after) Web Rule starts here *** //
}
private void GetPageInfo()
{
try
{
DataTable dt;
dt = (new AdminSystem()).GetLastPageInfo(73, base.LUser.UsrId, LcSysConnString, LcAppPw);
cPgSize.Text = dt.Rows[0]["LastPageInfo"].ToString();
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
public void cClearCriButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
System.Web.UI.WebControls.Calendar cCalendar;
ListBox cListBox;
RoboCoder.WebControls.ComboBox cComboBox;
DropDownList cDropDownList;
RadioButtonList cRadioButtonList;
CheckBox cCheckBox;
TextBox cTextBox;
DataView dvCri = GetScrCriteria();
foreach (DataRowView drv in dvCri)
{
if (drv["DisplayName"].ToString() == "ComboBox") // Reset to page 1 by reassigning the datasource:
{
cComboBox = (RoboCoder.WebControls.ComboBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cComboBox != null && cComboBox.Items.Count > 0) { cComboBox.DataSource = cComboBox.DataSource; cComboBox.SelectByValue(cComboBox.Items[0].Value, string.Empty, true); }
}
else if (drv["DisplayName"].ToString() == "DropDownList")
{
cDropDownList = (DropDownList)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cDropDownList != null && cDropDownList.Items.Count > 0) { cDropDownList.SelectedIndex = 0; }
}
else if (drv["DisplayName"].ToString() == "ListBox")
{
cListBox = (ListBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cListBox != null && cListBox.Items.Count > 0) { cListBox.SelectedIndex = 0; }
}
else if (drv["DisplayName"].ToString() == "RadioButtonList")
{
cRadioButtonList = (RadioButtonList)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cRadioButtonList != null && cRadioButtonList.Items.Count > 0) { cRadioButtonList.SelectedIndex = 0; }
}
else if (drv["DisplayName"].ToString() == "Calendar")
{
cCalendar = (System.Web.UI.WebControls.Calendar)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cCalendar != null)
{
if (drv["RequiredValid"].ToString() == "N") { cCalendar.SelectedDates.Clear(); } else { cCalendar.SelectedDate = System.DateTime.Today; }
}
}
else if (drv["DisplayName"].ToString() == "CheckBox")
{
cCheckBox = (CheckBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cCheckBox != null) { cCheckBox.Checked = false; }
}
else
{
cTextBox = (TextBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cTextBox != null)
{
if (drv["RequiredValid"].ToString() == "N") { cTextBox.Text = string.Empty; } else if (drv["DisplayMode"].ToString().IndexOf("Date") >= 0) { cTextBox.Text = System.DateTime.Today.ToString(); } else { cTextBox.Text = "0"; }
}
}
}
cCriButton_Click(sender, e);
if (cFilterId.Items.Count > 0) { cFilterId.SelectedIndex = 0; }
// *** System Button Click (after) Web Rule starts here *** //
}
private void GetCriteria(DataView dvCri)
{
try
{
DataTable dt;
dt = (new AdminSystem()).GetLastCriteria(int.Parse(dvCri.Count.ToString()) + 1, 73, 0, base.LUser.UsrId, LcSysConnString, LcAppPw);
cCriPanel.Visible = true; // Enable cCriteria.Visible to be set:
if (dt.Rows.Count <= 0) { cCriteria.Visible = false; }
if (!string.IsNullOrEmpty(Request.QueryString["key"]) && bUseCri.Value == string.Empty)
{
cCriPanel.Visible = false; cClearCriButton.Visible = false;
}
else
{
cCriPanel.Visible = (cCriteria.Visible && cCriteria.Controls.Count > 2) || cFilter.Visible;
if ((bool)Session[KEY_bClCriVisible]) {cClearCriButton.Visible = cCriteria.Visible && cCriteria.Controls.Count > 2;} else {cClearCriButton.Visible = false;}
}
if (!IsPostBack)
{
int jj = 0; // Zero-based to be consistent with SQL reporting.
foreach (DataRowView drv in dvCri)
{
if (Request.QueryString["Cri" + jj.ToString()] != null)
{
dt.Rows[jj+1]["LastCriteria"] = Request.QueryString["Cri" + jj.ToString()].ToString();
}
jj = jj + 1;
}
}
SetCriteria(dt, dvCri);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
private void GetSelectedItems(ListBox cObj, string selectedItems)
{
string selectedItem;
bool finish;
if (selectedItems == string.Empty)
{
try {cObj.SelectedIndex = 0;} catch {}
}
else
{
finish = false;
while (!finish)
{
selectedItem = GetSelectedItem(ref selectedItems);
if (selectedItem == string.Empty) { finish = true; }
else
{
try { cObj.Items.FindByValue(selectedItem).Selected = true; }
catch { finish = true; try {cObj.SelectedIndex = 0;} catch {} }
}
}
}
}
private string GetSelectedItem(ref string selectedItems)
{
string selectedItem;
int sIndex = selectedItems.IndexOf("'");
int eIndex = selectedItems.IndexOf("'",sIndex + 1);
if (sIndex >= 0 && eIndex >= 0)
{
selectedItem = selectedItems.Substring(sIndex + 1, eIndex - sIndex - 1);
}
else
{
selectedItem = string.Empty;
}
selectedItems = selectedItems.Substring(eIndex + 1, selectedItems.Length - eIndex - 1);
return selectedItem;
}
protected void cCriButton_Click(object sender, System.EventArgs e)
{
// *** Criteria Trigger (before) Web Rule starts here *** //
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if (cAdmScreenCriGrid.EditIndex < 0 || (dt != null && UpdateGridRow(sender, new CommandEventArgs("Save", ""))))
{
if (IsPostBack && cCriteria.Visible) ReBindCriteria(GetScrCriteria());
UpdCriteria(true);
cAdmScreenCri73List.ClearSearch(); Session.Remove(KEY_dtAdmScreenCri73List);
PopAdmScreenCri73List(sender, e, false, null);
}
}
private void SetCriteria(DataTable dt, DataView dvCri)
{
Label cLabel;
System.Web.UI.WebControls.Calendar cCalendar;
ListBox cListBox;
RoboCoder.WebControls.ComboBox cComboBox;
DropDownList cDropDownList;
RadioButtonList cRadioButtonList;
CheckBox cCheckBox;
TextBox cTextBox;
DataTable dtCriHlp = GetScreenCriHlp();
int ii = 1;
try
{
foreach (DataRowView drv in dvCri)
{
cLabel = (Label)cCriteria.FindControl("x" + drv["ColumnName"].ToString() + "Label");
if (drv["DisplayName"].ToString() == "ComboBox")
{
cComboBox = (RoboCoder.WebControls.ComboBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
string val = null; try {val=dt.Rows[ii]["LastCriteria"].ToString();} catch {};
base.SetCriBehavior(cComboBox, null, cLabel, dtCriHlp.Rows[ii-1]);
(new AdminSystem()).MkGetScreenIn("73", drv["ScreenCriId"].ToString(), "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), LcAppDb, LcDesDb, drv["MultiDesignDb"].ToString(), LcSysConnString, LcAppPw);
DataView dv = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, drv["DisplayMode"].ToString() != "AutoListBox", val, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw));
FilterCriteriaDdl(cCriteria, dv, drv);
cComboBox.DataSource = dv;
try { cComboBox.SelectByValue(dt.Rows[ii]["LastCriteria"], string.Empty, false); } catch { try { cComboBox.SelectedIndex = 0; } catch { } }
}
else if (drv["DisplayName"].ToString() == "DropDownList")
{
cDropDownList = (DropDownList)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
base.SetCriBehavior(cDropDownList, null, cLabel, dtCriHlp.Rows[ii-1]);
(new AdminSystem()).MkGetScreenIn("73", drv["ScreenCriId"].ToString(), "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), LcAppDb, LcDesDb, drv["MultiDesignDb"].ToString(), LcSysConnString, LcAppPw);
DataView dv = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw));
FilterCriteriaDdl(cCriteria, dv, drv);
cDropDownList.DataSource = dv;
cDropDownList.DataBind();
try { cDropDownList.Items.FindByValue(dt.Rows[ii]["LastCriteria"].ToString()).Selected = true; } catch { try { cDropDownList.SelectedIndex = 0; } catch { } }
}
else if (drv["DisplayName"].ToString() == "ListBox")
{
cListBox = (ListBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
string val = null; try {val=dt.Rows[ii]["LastCriteria"].ToString();} catch {};
base.SetCriBehavior(cListBox, null, cLabel, dtCriHlp.Rows[ii-1]);
(new AdminSystem()).MkGetScreenIn("73", drv["ScreenCriId"].ToString(), "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), LcAppDb, LcDesDb, drv["MultiDesignDb"].ToString(), LcSysConnString, LcAppPw);
DataView dv = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, drv["DisplayMode"].ToString() != "AutoListBox", val, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw));
FilterCriteriaDdl(cCriteria, dv, drv);
cListBox.DataSource = dv;
cListBox.DataBind();
GetSelectedItems(cListBox, dt.Rows[ii]["LastCriteria"].ToString());
}
else if (drv["DisplayName"].ToString() == "RadioButtonList")
{
cRadioButtonList = (RadioButtonList)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
base.SetCriBehavior(cRadioButtonList, null, cLabel, dtCriHlp.Rows[ii-1]);
(new AdminSystem()).MkGetScreenIn("73", drv["ScreenCriId"].ToString(), "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), LcAppDb, LcDesDb, drv["MultiDesignDb"].ToString(), LcSysConnString, LcAppPw);
DataView dv = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw));
FilterCriteriaDdl(cCriteria, dv, drv);
cRadioButtonList.DataSource = dv;
cRadioButtonList.DataBind();
try { cRadioButtonList.Items.FindByValue(dt.Rows[ii]["LastCriteria"].ToString()).Selected = true; } catch { try { cRadioButtonList.SelectedIndex = 0; } catch { } }
}
else if (drv["DisplayName"].ToString() == "Calendar")
{
cCalendar = (System.Web.UI.WebControls.Calendar)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
base.SetCriBehavior(cCalendar, null, cLabel, dtCriHlp.Rows[ii-1]);
if (dt.Rows[ii]["LastCriteria"].ToString() == string.Empty)
{
cCalendar.SelectedDates.Clear();
}
else
{
cCalendar.SelectedDate = DateTime.Parse(dt.Rows[ii]["LastCriteria"].ToString()); cCalendar.VisibleDate = cCalendar.SelectedDate;
}
}
else if (drv["DisplayName"].ToString() == "CheckBox")
{
cCheckBox = (CheckBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
base.SetCriBehavior(cCheckBox, null, cLabel, dtCriHlp.Rows[ii-1]);
if (dt.Rows[ii]["LastCriteria"].ToString() != string.Empty) { cCheckBox.Checked = base.GetBool(dt.Rows[ii]["LastCriteria"].ToString()); }
}
else
{
cTextBox = (TextBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
base.SetCriBehavior(cTextBox, null, cLabel, dtCriHlp.Rows[ii-1]);
cTextBox.Text = dt.Rows[ii]["LastCriteria"].ToString();
}
ii = ii + 1;
}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
private void ReBindCriteria(DataView dvCri)
{
ListBox cListBox;
RoboCoder.WebControls.ComboBox cComboBox;
DropDownList cDropDownList;
RadioButtonList cRadioButtonList;
try
{
foreach (DataRowView drv in dvCri)
{
if (string.IsNullOrEmpty(drv["DdlFtrColumnId"].ToString()) && drv["DisplayMode"].ToString() != "AutoListBox" ) continue;
if (drv["DisplayName"].ToString() == "ComboBox")
{
cComboBox = (RoboCoder.WebControls.ComboBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
string val = cComboBox.SelectedValue;
DataView dv = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, drv["DisplayMode"].ToString() != "AutoListBox", val, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw));
FilterCriteriaDdl(cCriteria, dv, drv);
cComboBox.DataSource = dv;
try { cComboBox.SelectByValue(val, string.Empty, false); } catch { try { cComboBox.SelectedIndex = 0; } catch { } }
}
else if (drv["DisplayName"].ToString() == "DropDownList")
{
cDropDownList = (DropDownList)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
string val = cDropDownList.SelectedValue;
DataView dv = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw));
FilterCriteriaDdl(cCriteria, dv, drv);
cDropDownList.DataSource = dv;
cDropDownList.DataBind();
try { cDropDownList.Items.FindByValue(val).Selected = true; } catch { try { cDropDownList.SelectedIndex = 0; } catch { } }
}
else if (drv["DisplayName"].ToString() == "ListBox")
{
cListBox = (ListBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
TextBox cTextBox = (TextBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString() + "Hidden");
string selectedValues = string.Join(",", cListBox.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => "'" + x.Value + "'").ToArray());
if (drv["DisplayMode"].ToString() == "AutoListBox" && cTextBox != null) selectedValues = cTextBox.Text ;
DataView dv = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, drv["DisplayMode"].ToString() != "AutoListBox", selectedValues, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw));
FilterCriteriaDdl(cCriteria, dv, drv);
cListBox.DataSource = dv;
cListBox.DataBind();
GetSelectedItems(cListBox, selectedValues);
}
else if (drv["DisplayName"].ToString() == "RadioButtonList")
{
cRadioButtonList = (RadioButtonList)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
string val = cRadioButtonList.SelectedValue;
DataView dv = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw));
FilterCriteriaDdl(cCriteria, dv, drv);
cRadioButtonList.DataSource = dv;
cRadioButtonList.DataBind();
try { cRadioButtonList.Items.FindByValue(val).Selected = true; } catch { try { cRadioButtonList.SelectedIndex = 0; } catch { } }
}
}
}
catch { }
}
private DataView GetScrCriteria()
{
DataTable dtScrCri = (DataTable)Session[KEY_dtScrCri];
if (dtScrCri == null)
{
try
{
dtScrCri = (new AdminSystem()).GetScrCriteria("73", LcSysConnString, LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
Session[KEY_dtScrCri] = dtScrCri;
}
return dtScrCri.DefaultView;
}
private void MakeScrGrpLab(DataRowView drv)
{
Literal cLiteral = new Literal();
string sLabelCss = drv["LabelCss"].ToString();
if (sLabelCss != string.Empty)
{
if (sLabelCss.StartsWith(".")) {cLiteral.Text = "<div class=\"" + sLabelCss.Substring(1) + "\">";} else {cLiteral.Text = "<div class=\"r-labelL\" style=\"" + sLabelCss + "\">";}
}
else {cLiteral.Text = "<div class=\"r-labelL\">";}
cCriteria.Controls.Add(cLiteral);
Label cLabel = new Label(); cLabel.ID = "x" + drv["ColumnName"].ToString() + "Label"; cLabel.CssClass = "inp-lbl"; cCriteria.Controls.Add(cLabel);
cLiteral = new Literal(); cLiteral.Text = "</div>"; cCriteria.Controls.Add(cLiteral);
}
private void MakeScrGrpInp(DataRowView drv)
{
System.Web.UI.WebControls.Calendar cCalendar;
ListBox cListBox;
RoboCoder.WebControls.ComboBox cComboBox;
DropDownList cDropDownList;
RadioButtonList cRadioButtonList;
CheckBox cCheckBox;
TextBox cTextBox;
Literal cLiteral = new Literal();
string sContentCss = drv["ContentCss"].ToString();
if (sContentCss != string.Empty)
{
if (sContentCss.StartsWith(".")) {cLiteral.Text = "<div class=\"" + sContentCss.Substring(1) + "\">";} else {cLiteral.Text = "<div class=\"r-content\" style=\"" + sContentCss + "\">";}
}
else {cLiteral.Text = "<div class=\"r-content\">";}
cCriteria.Controls.Add(cLiteral);
if (drv["DisplayName"].ToString() == "ComboBox")
{
cComboBox = new RoboCoder.WebControls.ComboBox(); cComboBox.ID = "x" + drv["ColumnName"].ToString(); cComboBox.CssClass = "inp-ddl"; cComboBox.SelectedIndexChanged += new EventHandler(cCriButton_Click);
cComboBox.DataValueField = drv["DdlKeyColumnName"].ToString(); cComboBox.DataTextField = drv["DdlRefColumnName"].ToString(); cComboBox.AutoPostBack = true;
if (drv["DisplayMode"].ToString() == "AutoComplete")
{
WebControl wcFtr = (WebControl)cCriteria.FindControl("x" + drv["DdlFtrColumnName"].ToString());
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetScreenIn";
context["addnew"] = "Y";
context["sp"] = "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString();
context["requiredValid"] = drv["RequiredValid"].ToString();
context["mKey"] = drv["DdlKeyColumnName"].ToString();
context["mVal"] = drv["DdlRefColumnName"].ToString();
context["mTip"] = drv["DdlRefColumnName"].ToString();
context["mImg"] = drv["DdlRefColumnName"].ToString();
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = drv["MultiDesignDb"].ToString() == "N" ? string.Empty : KEY_sysConnectionString;
context["refColCID"] = wcFtr != null ? wcFtr.ClientID : null;
context["refCol"] = wcFtr != null ? drv["DdlFtrColumnName"].ToString() : null;
context["refColDataType"] = wcFtr != null ? drv["DdlFtrDataType"].ToString() : null;
cComboBox.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests";
cComboBox.DataContext = context;
cComboBox.Mode = "A";
}
cCriteria.Controls.Add(cComboBox);
}
else if (drv["DisplayName"].ToString() == "DropDownList")
{
cDropDownList = new DropDownList(); cDropDownList.ID = "x" + drv["ColumnName"].ToString(); cDropDownList.CssClass = "inp-ddl"; cDropDownList.SelectedIndexChanged += new EventHandler(cCriButton_Click);
cDropDownList.DataValueField = drv["DdlKeyColumnName"].ToString(); cDropDownList.DataTextField = drv["DdlRefColumnName"].ToString(); cDropDownList.AutoPostBack = true;
cCriteria.Controls.Add(cDropDownList);
}
else if (drv["DisplayName"].ToString() == "ListBox")
{
cListBox = new ListBox(); cListBox.ID = "x" + drv["ColumnName"].ToString(); cListBox.SelectionMode = ListSelectionMode.Multiple; cListBox.CssClass = "inp-pic"; cListBox.SelectedIndexChanged += new EventHandler(cCriButton_Click);
cListBox.DataValueField = drv["DdlKeyColumnName"].ToString(); cListBox.DataTextField = drv["DdlRefColumnName"].ToString(); cListBox.AutoPostBack = true;
if (drv["RowSize"].ToString() != string.Empty) {cListBox.Rows = int.Parse(drv["RowSize"].ToString()); cListBox.Height = int.Parse(drv["RowSize"].ToString()) * 16 + 7; }
cCriteria.Controls.Add(cListBox);
if (drv["DisplayMode"].ToString() == "AutoListBox")
{
WebControl wcFtr = (WebControl)cCriteria.FindControl("x" + drv["DdlFtrColumnName"].ToString());
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetScreenIn";
context["addnew"] = "Y";
context["sp"] = "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString();
context["requiredValid"] = drv["RequiredValid"].ToString();
context["mKey"] = drv["DdlKeyColumnName"].ToString();
context["mVal"] = drv["DdlRefColumnName"].ToString();
context["mTip"] = drv["DdlRefColumnName"].ToString();
context["mImg"] = drv["DdlRefColumnName"].ToString();
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = drv["MultiDesignDb"].ToString() == "N" ? string.Empty : KEY_sysConnectionString;
context["refColCID"] = wcFtr != null ? wcFtr.ClientID : null;
context["refCol"] = wcFtr != null ? drv["DdlFtrColumnName"].ToString() : null;
context["refColDataType"] = wcFtr != null ? drv["DdlFtrDataType"].ToString() : null;
Session["AdmScreenCri73" + cListBox.ID] = context;
cListBox.Attributes["ac_context"] = "AdmScreenCri73" + cListBox.ID;
cListBox.Attributes["ac_url"] = "AutoComplete.aspx/DdlSuggestsEx";
cListBox.Attributes["refColCID"] = wcFtr != null ? wcFtr.ClientID : null;
cListBox.Attributes["searchable"] = "";
TextBox tb = new TextBox(); tb.ID = "x" + drv["ColumnName"].ToString() + "Hidden";tb.Attributes["style"] = "display:none;";
cCriteria.Controls.Add(tb);
}
}
else if (drv["DisplayName"].ToString() == "RadioButtonList")
{
cRadioButtonList = new RadioButtonList(); cRadioButtonList.ID = "x" + drv["ColumnName"].ToString(); cRadioButtonList.CssClass = "inp-rad"; cRadioButtonList.SelectedIndexChanged += new EventHandler(cCriButton_Click);
cRadioButtonList.DataValueField = drv["DdlKeyColumnName"].ToString(); cRadioButtonList.DataTextField = drv["DdlRefColumnName"].ToString(); cRadioButtonList.AutoPostBack = true; cRadioButtonList.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;
cRadioButtonList.Attributes["OnClick"] = "this.focus();";
cLiteral = new Literal(); cLiteral.Text = "<div>"; cCriteria.Controls.Add(cLiteral);
cCriteria.Controls.Add(cRadioButtonList);
cLiteral = new Literal(); cLiteral.Text = "</div>"; cCriteria.Controls.Add(cLiteral);
}
else if (drv["DisplayName"].ToString() == "Calendar")
{
cCalendar = new System.Web.UI.WebControls.Calendar(); cCalendar.ID = "x" + drv["ColumnName"].ToString(); cCalendar.CssClass = "inp-txt calendar"; cCalendar.SelectionChanged += new EventHandler(cCriButton_Click); cCriteria.Controls.Add(cCalendar);
}
else if (drv["DisplayName"].ToString() == "CheckBox")
{
cCheckBox = new CheckBox(); cCheckBox.ID = "x" + drv["ColumnName"].ToString(); cCheckBox.CssClass = "inp-chk"; cCheckBox.AutoPostBack = true; cCheckBox.CheckedChanged += new EventHandler(cCriButton_Click); cCriteria.Controls.Add(cCheckBox);
cCheckBox.Attributes["OnClick"] = "this.focus();";
}
else
{
cTextBox = new TextBox(); cTextBox.ID = "x" + drv["ColumnName"].ToString(); cTextBox.CssClass = "inp-txt"; cTextBox.AutoPostBack = true; cTextBox.TextChanged += new EventHandler(cCriButton_Click);
if (drv["DisplayMode"].ToString() == "MultiLine") { cTextBox.TextMode = TextBoxMode.MultiLine; }
else if (drv["DisplayMode"].ToString() == "Password") { cTextBox.TextMode = TextBoxMode.Password; }
if (drv["ColumnJustify"].ToString() == "L") { cTextBox.Style.Value = "text-align:left;"; }
else if (drv["ColumnJustify"].ToString() == "R") { cTextBox.Style.Value = "text-align:right;"; }
else { cTextBox.Style.Value = "text-align:center;"; }
cCriteria.Controls.Add(cTextBox);
}
cLiteral = new Literal(); cLiteral.Text = "</div>"; cCriteria.Controls.Add(cLiteral);
}
private void SetCriHolder(int ii, DataView dvCri)
{
Literal cLiteral;
if (dvCri.Count > 0)
{
foreach (DataRowView drv in dvCri)
{
cLiteral = new Literal(); cLiteral.Text = "<div class=\"r-criteria\">"; cCriteria.Controls.Add(cLiteral);
MakeScrGrpLab(drv);
MakeScrGrpInp(drv);
cLiteral = new Literal(); cLiteral.Text = "</div>"; cCriteria.Controls.Add(cLiteral);
}
}
}
private DataTable MakeColumns(DataTable dt)
{
DataColumnCollection columns = dt.Columns;
DataView dvCri = GetScrCriteria();
foreach (DataRowView drv in dvCri)
{
if (drv["DataTypeSysName"].ToString() == "DateTime") { columns.Add(drv["ColumnName"].ToString(), typeof(DateTime)); }
else if (drv["DataTypeSysName"].ToString() == "Byte") { columns.Add(drv["ColumnName"].ToString(), typeof(Byte)); }
else if (drv["DataTypeSysName"].ToString() == "Int16") { columns.Add(drv["ColumnName"].ToString(), typeof(Int16)); }
else if (drv["DataTypeSysName"].ToString() == "Int32") { columns.Add(drv["ColumnName"].ToString(), typeof(Int32)); }
else if (drv["DataTypeSysName"].ToString() == "Int64") { columns.Add(drv["ColumnName"].ToString(), typeof(Int64)); }
else if (drv["DataTypeSysName"].ToString() == "Single") { columns.Add(drv["ColumnName"].ToString(), typeof(Single)); }
else if (drv["DataTypeSysName"].ToString() == "Double") { columns.Add(drv["ColumnName"].ToString(), typeof(Double)); }
else if (drv["DataTypeSysName"].ToString() == "Byte[]") { columns.Add(drv["ColumnName"].ToString(), typeof(Byte[])); }
else if (drv["DataTypeSysName"].ToString() == "Object") { columns.Add(drv["ColumnName"].ToString(), typeof(Object)); }
else { columns.Add(drv["ColumnName"].ToString(), typeof(String)); }
}
return dt;
}
private DataSet UpdCriteria(bool bUpdate)
{
System.Web.UI.WebControls.Calendar cCalendar;
ListBox cListBox;
RoboCoder.WebControls.ComboBox cComboBox;
DropDownList cDropDownList;
RadioButtonList cRadioButtonList;
CheckBox cCheckBox;
TextBox cTextBox;
DataSet ds = new DataSet();
ds.Tables.Add(MakeColumns(new DataTable("DtScreenIn")));
DataRow dr = ds.Tables["DtScreenIn"].NewRow();
DataView dvCri = GetScrCriteria();
foreach (DataRowView drv in dvCri)
{
if (drv["DisplayName"].ToString() == "ListBox")
{
cListBox = (ListBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cListBox != null)
{
int CriCnt = (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw);
int TotalChoiceCnt = new DataView((new AdminSystem()).GetScreenIn("73", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), CriCnt, drv["RequiredValid"].ToString(), 0, string.Empty, true, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)).Count;
string selectedValues = string.Join(",", cListBox.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => "'" + x.Value + "'").ToArray());
bool noneSelected = string.IsNullOrEmpty(selectedValues) || selectedValues == "''";
dr[drv["ColumnName"].ToString()] = "(";
if (noneSelected && CriCnt+1 > TotalChoiceCnt) dr[drv["ColumnName"].ToString()] = dr[drv["ColumnName"].ToString()].ToString() + "'-1'";
foreach (ListItem li in cListBox.Items)
{
if (li.Selected)
{
if (dr[drv["ColumnName"].ToString()].ToString() != "(")
{
dr[drv["ColumnName"].ToString()] = dr[drv["ColumnName"].ToString()].ToString() + ",";
}
dr[drv["ColumnName"].ToString()] = dr[drv["ColumnName"].ToString()].ToString() + "'" + li.Value + "'";
}
}
}
if (IsPostBack && drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cListBox.SelectedValue))
{
bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again.");
}
if (dr[drv["ColumnName"].ToString()].ToString() == "(''" || dr[drv["ColumnName"].ToString()].ToString() == "(") { dr[drv["ColumnName"].ToString()] = string.Empty; } else { dr[drv["ColumnName"].ToString()] = dr[drv["ColumnName"].ToString()].ToString() + ")"; }
}
else if (drv["DisplayName"].ToString() == "Calendar")
{
cCalendar = (System.Web.UI.WebControls.Calendar)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cCalendar != null && cCalendar.SelectedDate > DateTime.Parse("0001-01-01")) { dr[drv["ColumnName"].ToString()] = cCalendar.SelectedDate; }
}
else if (drv["DisplayName"].ToString() == "ComboBox")
{
cComboBox = (RoboCoder.WebControls.ComboBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (IsPostBack && drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cComboBox.SelectedValue))
{
bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again.");
}
if (cComboBox != null && cComboBox.SelectedIndex >= 0 && cComboBox.SelectedValue != string.Empty) { dr[drv["ColumnName"].ToString()] = cComboBox.SelectedValue; }
}
else if (drv["DisplayName"].ToString() == "DropDownList")
{
cDropDownList = (DropDownList)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (IsPostBack && drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cDropDownList.SelectedValue))
{
bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again.");
}
if (cDropDownList != null && cDropDownList.SelectedIndex >= 0 && cDropDownList.SelectedValue != string.Empty) { dr[drv["ColumnName"].ToString()] = cDropDownList.SelectedValue; }
}
else if (drv["DisplayName"].ToString() == "RadioButtonList")
{
cRadioButtonList = (RadioButtonList)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (IsPostBack && drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cRadioButtonList.SelectedValue))
{
bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again.");
}
if (cRadioButtonList != null && cRadioButtonList.SelectedIndex >= 0 && cRadioButtonList.SelectedValue != string.Empty) { dr[drv["ColumnName"].ToString()] = cRadioButtonList.SelectedValue; }
}
else if (drv["DisplayName"].ToString() == "CheckBox")
{
cCheckBox = (CheckBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (cCheckBox != null) { dr[drv["ColumnName"].ToString()] = base.SetBool(cCheckBox.Checked); }
}
else
{
cTextBox = (TextBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString());
if (drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cTextBox.Text))
{
if (IsPostBack) { bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again.");}
cTextBox.Text = drv["DisplayMode"].ToString().Contains("Date") ? DateTime.Today.Date.ToShortDateString() : "?";
}
if (cTextBox != null && cTextBox.Text != string.Empty) { dr[drv["ColumnName"].ToString()] = (",DateUTC,DateTimeUTC,ShortDateTimeUTC,LongDateTimeUTC,".IndexOf("," + drv["DisplayMode"].ToString() + ",") >= 0) ? SetDateTimeUTC(cTextBox.Text,!bUpdate) : (drv["DisplayName"].ToString().Contains("Date") ? (DateTime.Parse(cTextBox.Text,System.Threading.Thread.CurrentThread.CurrentCulture).ToString()): cTextBox.Text); }
}
}
ds.Tables["DtScreenIn"].Rows.Add(dr);
if (bUpdate)
{
try
{
(new AdminSystem()).UpdScrCriteria("73", "AdmScreenCri73", dvCri, base.LUser.UsrId, cCriteria.Visible, ds, LcAppConnString, LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
Session[KEY_dsScrCriVal] = ds;
return ds;
}
private DataTable GetScreenTab()
{
CheckAuthentication(false);
DataTable dtScreenTab = null;
try
{
dtScreenTab = (new AdminSystem()).GetScreenTab(73,base.LUser.CultureId,LcSysConnString,LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
return dtScreenTab;
}
protected void cbScreenId104(object sender, System.EventArgs e)
{
SetScreenId104((RoboCoder.WebControls.ComboBox)sender,string.Empty);
}
private void SetScreenId104(RoboCoder.WebControls.ComboBox ddl, string keyId)
{
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetDdlScreenId3S1179";
context["addnew"] = "Y";
context["mKey"] = "ScreenId104";
context["mVal"] = "ScreenId104Text";
context["mTip"] = "ScreenId104Text";
context["mImg"] = "ScreenId104Text";
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = KEY_sysConnectionString;
ddl.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests";
ddl.DataContext = context;
if (ddl != null)
{
DataView dv = null;
if (keyId == string.Empty && ddl.SearchText.StartsWith("**")) {keyId = ddl.SearchText.Substring(2);}
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlScreenId3S1179",true,false,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
context["pMKeyColID"] = cAdmScreenCri73List.ClientID;
context["pMKeyCol"] = "ScreenCriId";
string ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
dv.RowFilter = ss;
}
ddl.DataSource = dv; Session[KEY_dtScreenId104] = dv.Table;
try { ddl.SelectByValue(keyId,string.Empty,true); } catch { try { ddl.SelectedIndex = 0; } catch { } }
}
}
}
protected void cbColumnId104(object sender, System.EventArgs e)
{
SetColumnId104((RoboCoder.WebControls.ComboBox)sender,string.Empty);
}
private void SetColumnId104(RoboCoder.WebControls.ComboBox ddl, string keyId)
{
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetDdlColumnId3S1181";
context["addnew"] = "Y";
context["mKey"] = "ColumnId104";
context["mVal"] = "ColumnId104Text";
context["mTip"] = "ColumnId104Text";
context["mImg"] = "ColumnId104Text";
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = KEY_sysConnectionString;
ddl.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests";
ddl.DataContext = context;
if (ddl != null)
{
DataView dv = null;
if (keyId == string.Empty && ddl.SearchText.StartsWith("**")) {keyId = ddl.SearchText.Substring(2);}
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlColumnId3S1181",true,false,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
context["pMKeyColID"] = cAdmScreenCri73List.ClientID;
context["pMKeyCol"] = "ScreenCriId";
string ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
dv.RowFilter = ss;
}
ddl.DataSource = dv; Session[KEY_dtColumnId104] = dv.Table;
try { ddl.SelectByValue(keyId,string.Empty,true); } catch { try { ddl.SelectedIndex = 0; } catch { } }
}
}
}
private void SetOperatorId104(DropDownList ddl, string keyId)
{
DataTable dt = (DataTable)Session[KEY_dtOperatorId104];
DataView dv = dt != null ? dt.DefaultView : null;
if (ddl != null)
{
string ss = string.Empty;
ListItem li = null;
bool bFirst = false;
bool bAll = false; if (ddl.Enabled && ddl.Visible) {bAll = true;}
if (dv == null)
{
bFirst = true;
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlOperatorId3S3305",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
}
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
}
if (!string.IsNullOrEmpty(keyId) && !ddl.Enabled) { ss = ss + (string.IsNullOrEmpty(ss) ? string.Empty : " AND ") + "OperatorId104 is not NULL"; }
dv.RowFilter = ss;
ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
else if (!bFirst)
{
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlOperatorId3S3305",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
}
if (dv.Count <= 1 && keyId != string.Empty) // In case invalid value casued by copy action.
{
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlOperatorId3S3305",true,true,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
}
Session[KEY_dtOperatorId104] = dv.Table;
}
}
}
private void SetDisplayModeId104(DropDownList ddl, string keyId)
{
DataTable dt = (DataTable)Session[KEY_dtDisplayModeId104];
DataView dv = dt != null ? dt.DefaultView : null;
if (ddl != null)
{
string ss = string.Empty;
ListItem li = null;
bool bFirst = false;
bool bAll = false; if (ddl.Enabled && ddl.Visible) {bAll = true;}
if (dv == null)
{
bFirst = true;
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlDisplayModeId3S1183",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
}
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
}
if (!string.IsNullOrEmpty(keyId) && !ddl.Enabled) { ss = ss + (string.IsNullOrEmpty(ss) ? string.Empty : " AND ") + "DisplayModeId104 is not NULL"; }
dv.RowFilter = ss;
ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
else if (!bFirst)
{
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlDisplayModeId3S1183",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
}
if (dv.Count <= 1 && keyId != string.Empty) // In case invalid value casued by copy action.
{
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlDisplayModeId3S1183",true,true,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
}
Session[KEY_dtDisplayModeId104] = dv.Table;
}
}
}
private void SetColumnJustify104(DropDownList ddl, string keyId)
{
DataTable dt = (DataTable)Session[KEY_dtColumnJustify104];
DataView dv = dt != null ? dt.DefaultView : null;
if (ddl != null)
{
string ss = string.Empty;
ListItem li = null;
bool bFirst = false;
bool bAll = false; if (ddl.Enabled && ddl.Visible) {bAll = true;}
if (dv == null)
{
bFirst = true;
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlColumnJustify3S1425",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
}
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
}
if (!string.IsNullOrEmpty(keyId) && !ddl.Enabled) { ss = ss + (string.IsNullOrEmpty(ss) ? string.Empty : " AND ") + "ColumnJustify104 is not NULL"; }
dv.RowFilter = ss;
ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
else if (!bFirst)
{
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlColumnJustify3S1425",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
}
if (dv.Count <= 1 && keyId != string.Empty) // In case invalid value casued by copy action.
{
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlColumnJustify3S1425",true,true,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind();
li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;}
}
Session[KEY_dtColumnJustify104] = dv.Table;
}
}
}
protected void cbDdlKeyColumnId104(object sender, System.EventArgs e)
{
SetDdlKeyColumnId104((RoboCoder.WebControls.ComboBox)sender,string.Empty);
}
private void SetDdlKeyColumnId104(RoboCoder.WebControls.ComboBox ddl, string keyId)
{
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetDdlDdlKeyColumnId3S1185";
context["addnew"] = "Y";
context["mKey"] = "DdlKeyColumnId104";
context["mVal"] = "DdlKeyColumnId104Text";
context["mTip"] = "DdlKeyColumnId104Text";
context["mImg"] = "DdlKeyColumnId104Text";
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = KEY_sysConnectionString;
ddl.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests";
ddl.DataContext = context;
if (ddl != null)
{
DataView dv = null;
if (keyId == string.Empty && ddl.SearchText.StartsWith("**")) {keyId = ddl.SearchText.Substring(2);}
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlDdlKeyColumnId3S1185",true,false,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
context["pMKeyColID"] = cAdmScreenCri73List.ClientID;
context["pMKeyCol"] = "ScreenCriId";
string ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
dv.RowFilter = ss;
}
ddl.DataSource = dv; Session[KEY_dtDdlKeyColumnId104] = dv.Table;
try { ddl.SelectByValue(keyId,string.Empty,true); } catch { try { ddl.SelectedIndex = 0; } catch { } }
}
}
}
protected void cbDdlRefColumnId104(object sender, System.EventArgs e)
{
SetDdlRefColumnId104((RoboCoder.WebControls.ComboBox)sender,string.Empty);
}
private void SetDdlRefColumnId104(RoboCoder.WebControls.ComboBox ddl, string keyId)
{
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetDdlDdlRefColumnId3S1186";
context["addnew"] = "Y";
context["mKey"] = "DdlRefColumnId104";
context["mVal"] = "DdlRefColumnId104Text";
context["mTip"] = "DdlRefColumnId104Text";
context["mImg"] = "DdlRefColumnId104Text";
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = KEY_sysConnectionString;
ddl.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests";
ddl.DataContext = context;
if (ddl != null)
{
DataView dv = null;
if (keyId == string.Empty && ddl.SearchText.StartsWith("**")) {keyId = ddl.SearchText.Substring(2);}
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlDdlRefColumnId3S1186",true,false,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
context["pMKeyColID"] = cAdmScreenCri73List.ClientID;
context["pMKeyCol"] = "ScreenCriId";
string ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
dv.RowFilter = ss;
}
ddl.DataSource = dv; Session[KEY_dtDdlRefColumnId104] = dv.Table;
try { ddl.SelectByValue(keyId,string.Empty,true); } catch { try { ddl.SelectedIndex = 0; } catch { } }
}
}
}
protected void cbDdlSrtColumnId104(object sender, System.EventArgs e)
{
SetDdlSrtColumnId104((RoboCoder.WebControls.ComboBox)sender,string.Empty);
}
private void SetDdlSrtColumnId104(RoboCoder.WebControls.ComboBox ddl, string keyId)
{
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetDdlDdlSrtColumnId3S1278";
context["addnew"] = "Y";
context["mKey"] = "DdlSrtColumnId104";
context["mVal"] = "DdlSrtColumnId104Text";
context["mTip"] = "DdlSrtColumnId104Text";
context["mImg"] = "DdlSrtColumnId104Text";
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = KEY_sysConnectionString;
ddl.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests";
ddl.DataContext = context;
if (ddl != null)
{
DataView dv = null;
if (keyId == string.Empty && ddl.SearchText.StartsWith("**")) {keyId = ddl.SearchText.Substring(2);}
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlDdlSrtColumnId3S1278",true,false,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
context["pMKeyColID"] = cAdmScreenCri73List.ClientID;
context["pMKeyCol"] = "ScreenCriId";
string ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
dv.RowFilter = ss;
}
ddl.DataSource = dv; Session[KEY_dtDdlSrtColumnId104] = dv.Table;
try { ddl.SelectByValue(keyId,string.Empty,true); } catch { try { ddl.SelectedIndex = 0; } catch { } }
}
}
}
protected void cbDdlFtrColumnId104(object sender, System.EventArgs e)
{
SetDdlFtrColumnId104((RoboCoder.WebControls.ComboBox)sender,string.Empty,cScreenId104.SelectedValue);
}
private void SetDdlFtrColumnId104(RoboCoder.WebControls.ComboBox ddl, string keyId, string filtr)
{
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetDdlDdlFtrColumnId3S3365";
context["addnew"] = "Y";
context["mKey"] = "DdlFtrColumnId104";
context["mVal"] = "DdlFtrColumnId104Text";
context["mTip"] = "DdlFtrColumnId104Text";
context["mImg"] = "DdlFtrColumnId104Text";
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = KEY_sysConnectionString;
context["refColCID"] = cScreenId104.ClientID;
context["refCol"] = "ScreenId";
context["refColDataType"] = "Int";
ddl.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests";
ddl.DataContext = context;
if (ddl != null)
{
DataView dv = null;
if (keyId == string.Empty && ddl.SearchText.StartsWith("**")) {keyId = ddl.SearchText.Substring(2);}
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlDdlFtrColumnId3S3365",true,false,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
context["pMKeyColID"] = cAdmScreenCri73List.ClientID;
context["pMKeyCol"] = "ScreenCriId";
string ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
dv.RowFilter = ss;
}
ddl.DataSource = dv; Session[KEY_dtDdlFtrColumnId104] = dv.Table;
try { ddl.SelectByValue(keyId,filtr != string.Empty ? "(ScreenId is null OR ScreenId = " + filtr + ")" : string.Empty,true); } catch { try { ddl.SelectedIndex = 0; } catch { } }
}
}
}
protected void cbCultureId105(object sender, System.EventArgs e)
{
SetCultureId105((RoboCoder.WebControls.ComboBox)sender,string.Empty,cAdmScreenCriGrid.EditItem);
}
private void SetCultureId105(RoboCoder.WebControls.ComboBox ddl, string keyId, ListViewItem li)
{
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetDdlCultureId3S1191";
context["addnew"] = "Y";
context["mKey"] = "CultureId105";
context["mVal"] = "CultureId105Text";
context["mTip"] = "CultureId105Text";
context["mImg"] = "CultureId105Text";
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = KEY_sysConnectionString;
ddl.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests";
ddl.DataContext = context;
if (ddl != null)
{
DataView dv = null;
if (keyId == string.Empty && ddl.SearchText.StartsWith("**")) {keyId = ddl.SearchText.Substring(2);}
try
{
dv = new DataView((new AdminSystem()).GetDdl(73,"GetDdlCultureId3S1191",true,false,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr));
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (dv != null)
{
if (dv.Table.Columns.Contains("ScreenCriId"))
{
context["pMKeyColID"] = cAdmScreenCri73List.ClientID;
context["pMKeyCol"] = "ScreenCriId";
string ss = "(ScreenCriId is null";
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ScreenCriId = " + cAdmScreenCri73List.SelectedValue + ")";}
dv.RowFilter = ss;
}
ddl.DataSource = dv; Session[KEY_dtCultureId105] = dv.Table;
try { ddl.SelectByValue(keyId,string.Empty,true); } catch { try { ddl.SelectedIndex = 0; } catch { } }
}
}
}
private DataView GetAdmScreenCri73List()
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCri73List];
if (dt == null)
{
CheckAuthentication(false);
int filterId = 0;
string key = string.Empty;
if (!string.IsNullOrEmpty(Request.QueryString["key"]) && bUseCri.Value == string.Empty) { key = Request.QueryString["key"].ToString(); }
else if (Utils.IsInt(cFilterId.SelectedValue)) { filterId = int.Parse(cFilterId.SelectedValue); }
try
{
try {dt = (new AdminSystem()).GetLis(73,"GetLisAdmScreenCri73",true,"Y",0,(string)Session[KEY_sysConnectionString],LcAppPw,filterId,key,string.Empty,GetScrCriteria(),base.LImpr,base.LCurr,UpdCriteria(false));}
catch {dt = (new AdminSystem()).GetLis(73,"GetLisAdmScreenCri73",true,"N",0,(string)Session[KEY_sysConnectionString],LcAppPw,filterId,key,string.Empty,GetScrCriteria(),base.LImpr,base.LCurr,UpdCriteria(false));}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return new DataView(); }
dt = SetFunctionality(dt);
}
return (new DataView(dt,"","",System.Data.DataViewRowState.CurrentRows));
}
private void PopAdmScreenCri73List(object sender, System.EventArgs e, bool bPageLoad, object ID)
{
DataView dv = GetAdmScreenCri73List();
System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>();
context["method"] = "GetLisAdmScreenCri73";
context["mKey"] = "ScreenCriId104";
context["mVal"] = "ScreenCriId104Text";
context["mTip"] = "ScreenCriId104Text";
context["mImg"] = "ScreenCriId104Text";
context["ssd"] = Request.QueryString["ssd"];
context["scr"] = "73";
context["csy"] = "3";
context["filter"] = Utils.IsInt(cFilterId.SelectedValue) && cFilter.Visible ? cFilterId.SelectedValue : "0";
context["isSys"] = "N";
context["conn"] = KEY_sysConnectionString;
cAdmScreenCri73List.AutoCompleteUrl = "AutoComplete.aspx/LisSuggests";
cAdmScreenCri73List.DataContext = context;
if (dv.Table == null) return;
cAdmScreenCri73List.DataSource = dv;
cAdmScreenCri73List.Visible = true;
if (cAdmScreenCri73List.Items.Count <= 0) {cAdmScreenCri73List.Visible = false; cAdmScreenCri73List_SelectedIndexChanged(sender,e);}
else
{
if (bPageLoad && !string.IsNullOrEmpty(Request.QueryString["key"]) && bUseCri.Value == string.Empty)
{
try {cAdmScreenCri73List.SelectByValue(Request.QueryString["key"],string.Empty,true);} catch {cAdmScreenCri73List.Items[0].Selected = true; cAdmScreenCri73List_SelectedIndexChanged(sender, e);}
cScreenSearch.Visible = false; cSystem.Visible = false; cEditButton.Visible = true; cSaveCloseButton.Visible = cSaveButton.Visible;
}
else
{
if (ID != null) {if (!cAdmScreenCri73List.SelectByValue(ID,string.Empty,true)) {ID = null;}}
if (ID == null)
{
cAdmScreenCri73List_SelectedIndexChanged(sender, e);
}
}
}
}
private void SetColumnAuthority()
{
DataTable dtAuth = GetAuthCol();
DataTable dtLabel = GetLabel();
cTabFolder.CssClass = "TabFolder rmvSpace";
foreach (DataRow dr in dtAuth.Rows) {if (dr["MasterTable"].ToString() == "Y" && dr["ColVisible"].ToString() == "Y") {cTabFolder.CssClass = "TabFolder"; break;}}
if (dtAuth != null && dtLabel != null)
{
base.SetFoldBehavior(cScreenCriId104, dtAuth.Rows[0], cScreenCriId104P1, cScreenCriId104Label, cScreenCriId104P2, null, dtLabel.Rows[0], null, null, null);
base.SetFoldBehavior(cScreenId104, dtAuth.Rows[1], cScreenId104P1, cScreenId104Label, cScreenId104P2, null, dtLabel.Rows[1], cRFVScreenId104, null, null);
SetScreenId104(cScreenId104,string.Empty);
base.SetFoldBehavior(cLabelCss104, dtAuth.Rows[2], cLabelCss104P1, cLabelCss104Label, cLabelCss104P2, null, dtLabel.Rows[2], null, null, null);
base.SetFoldBehavior(cContentCss104, dtAuth.Rows[3], cContentCss104P1, cContentCss104Label, cContentCss104P2, null, dtLabel.Rows[3], null, null, null);
base.SetFoldBehavior(cColumnId104, dtAuth.Rows[4], cColumnId104P1, cColumnId104Label, cColumnId104P2, null, dtLabel.Rows[4], cRFVColumnId104, null, null);
SetColumnId104(cColumnId104,string.Empty);
base.SetFoldBehavior(cOperatorId104, dtAuth.Rows[5], cOperatorId104P1, cOperatorId104Label, cOperatorId104P2, null, dtLabel.Rows[5], cRFVOperatorId104, null, null);
base.SetFoldBehavior(cDisplayModeId104, dtAuth.Rows[6], cDisplayModeId104P1, cDisplayModeId104Label, cDisplayModeId104P2, null, dtLabel.Rows[6], cRFVDisplayModeId104, null, null);
base.SetFoldBehavior(cTabIndex104, dtAuth.Rows[7], cTabIndex104P1, cTabIndex104Label, cTabIndex104P2, null, dtLabel.Rows[7], cRFVTabIndex104, null, null);
base.SetFoldBehavior(cRequiredValid104, dtAuth.Rows[8], cRequiredValid104P1, cRequiredValid104Label, cRequiredValid104P2, null, dtLabel.Rows[8], null, null, null);
base.SetFoldBehavior(cColumnJustify104, dtAuth.Rows[9], cColumnJustify104P1, cColumnJustify104Label, cColumnJustify104P2, null, dtLabel.Rows[9], cRFVColumnJustify104, null, null);
base.SetFoldBehavior(cColumnSize104, dtAuth.Rows[10], cColumnSize104P1, cColumnSize104Label, cColumnSize104P2, null, dtLabel.Rows[10], null, null, null);
base.SetFoldBehavior(cRowSize104, dtAuth.Rows[11], cRowSize104P1, cRowSize104Label, cRowSize104P2, null, dtLabel.Rows[11], null, null, null);
base.SetFoldBehavior(cDdlKeyColumnId104, dtAuth.Rows[12], cDdlKeyColumnId104P1, cDdlKeyColumnId104Label, cDdlKeyColumnId104P2, null, dtLabel.Rows[12], null, null, null);
SetDdlKeyColumnId104(cDdlKeyColumnId104,string.Empty);
base.SetFoldBehavior(cDdlRefColumnId104, dtAuth.Rows[13], cDdlRefColumnId104P1, cDdlRefColumnId104Label, cDdlRefColumnId104P2, null, dtLabel.Rows[13], null, null, null);
SetDdlRefColumnId104(cDdlRefColumnId104,string.Empty);
base.SetFoldBehavior(cDdlSrtColumnId104, dtAuth.Rows[14], cDdlSrtColumnId104P1, cDdlSrtColumnId104Label, cDdlSrtColumnId104P2, null, dtLabel.Rows[14], null, null, null);
SetDdlSrtColumnId104(cDdlSrtColumnId104,string.Empty);
base.SetFoldBehavior(cDdlFtrColumnId104, dtAuth.Rows[15], cDdlFtrColumnId104P1, cDdlFtrColumnId104Label, cDdlFtrColumnId104P2, null, dtLabel.Rows[15], null, null, null);
SetDdlFtrColumnId104(cDdlFtrColumnId104,string.Empty,string.Empty);
}
if ((cScreenId104.Attributes["OnChange"] == null || cScreenId104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cScreenId104.Visible && cScreenId104.Enabled) {cScreenId104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if ((cLabelCss104.Attributes["OnChange"] == null || cLabelCss104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cLabelCss104.Visible && !cLabelCss104.ReadOnly) {cLabelCss104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cContentCss104.Attributes["OnChange"] == null || cContentCss104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cContentCss104.Visible && !cContentCss104.ReadOnly) {cContentCss104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cColumnId104.Attributes["OnChange"] == null || cColumnId104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cColumnId104.Visible && cColumnId104.Enabled) {cColumnId104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cOperatorId104.Attributes["OnChange"] == null || cOperatorId104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cOperatorId104.Visible && cOperatorId104.Enabled) {cOperatorId104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cDisplayModeId104.Attributes["OnChange"] == null || cDisplayModeId104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cDisplayModeId104.Visible && cDisplayModeId104.Enabled) {cDisplayModeId104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cTabIndex104.Attributes["OnChange"] == null || cTabIndex104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cTabIndex104.Visible && !cTabIndex104.ReadOnly) {cTabIndex104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cRequiredValid104.Attributes["OnClick"] == null || cRequiredValid104.Attributes["OnClick"].IndexOf("ChkPgDirty") < 0) && cRequiredValid104.Visible && cRequiredValid104.Enabled) {cRequiredValid104.Attributes["OnClick"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty(); this.focus();";}
if ((cColumnJustify104.Attributes["OnChange"] == null || cColumnJustify104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cColumnJustify104.Visible && cColumnJustify104.Enabled) {cColumnJustify104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cColumnSize104.Attributes["OnChange"] == null || cColumnSize104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cColumnSize104.Visible && !cColumnSize104.ReadOnly) {cColumnSize104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cRowSize104.Attributes["OnChange"] == null || cRowSize104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cRowSize104.Visible && !cRowSize104.ReadOnly) {cRowSize104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cDdlKeyColumnId104.Attributes["OnChange"] == null || cDdlKeyColumnId104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cDdlKeyColumnId104.Visible && cDdlKeyColumnId104.Enabled) {cDdlKeyColumnId104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cDdlRefColumnId104.Attributes["OnChange"] == null || cDdlRefColumnId104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cDdlRefColumnId104.Visible && cDdlRefColumnId104.Enabled) {cDdlRefColumnId104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cDdlSrtColumnId104.Attributes["OnChange"] == null || cDdlSrtColumnId104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cDdlSrtColumnId104.Visible && cDdlSrtColumnId104.Enabled) {cDdlSrtColumnId104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
if ((cDdlFtrColumnId104.Attributes["OnChange"] == null || cDdlFtrColumnId104.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cDdlFtrColumnId104.Visible && cDdlFtrColumnId104.Enabled) {cDdlFtrColumnId104.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
}
private DataTable SetFunctionality(DataTable dt)
{
DataTable dtAuthRow = GetAuthRow();
if (dtAuthRow != null)
{
DataRow dr = dtAuthRow.Rows[0];
if (dr["AllowDel"].ToString() == "N" || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N"))
{
if ((bool)Session[KEY_bDeleteVisible]) {cDeleteButton.Visible = false; Session[KEY_bDeleteVisible] = false;}
}
else if ((bool)Session[KEY_bDeleteVisible]) {cDeleteButton.Visible = true; cDeleteButton.Enabled = true;}
if ((dr["AllowUpd"].ToString() == "N" && dr["AllowAdd"].ToString() == "N") || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N"))
{
cUndoAllButton.Visible = false; cSaveButton.Visible = false; cSaveCloseButton.Visible = false;
cShowImpButton.Visible = false;
}
else
{
cShowImpButton.Visible = dr["ViewOnly"].ToString() != "G";
if ((bool)Session[KEY_bUndoAllVisible]) {cUndoAllButton.Visible = true; cUndoAllButton.Enabled = true;}
if ((bool)Session[KEY_bUpdateVisible]) {cSaveButton.Visible = true; cSaveButton.Enabled = true;}
}
if ((dr["AllowAdd"].ToString() == "N" && dr["AllowUpd"].ToString() == "N") || dr["ViewOnly"].ToString() == "G" || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N")) { cInsRowButton.Visible = false; }
if (dr["AllowAdd"].ToString() == "N" || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N"))
{
cNewButton.Visible = false; cNewSaveButton.Visible = false; cCopyButton.Visible = false; cCopySaveButton.Visible = false;
if (dt != null && dt.Rows.Count > 0) {dt.Rows[0].Delete();}
}
else
{
if ((bool)Session[KEY_bNewVisible]) {cNewButton.Visible = true; cNewButton.Enabled = true;} else {cNewButton.Visible = false;}
if ((bool)Session[KEY_bNewSaveVisible]) {cNewSaveButton.Visible = true; cNewSaveButton.Enabled = true;} else {cNewSaveButton.Visible = false;}
if ((bool)Session[KEY_bCopyVisible]) {cCopyButton.Visible = true; cCopyButton.Enabled = true;} else {cCopyButton.Visible = false;}
if ((bool)Session[KEY_bCopySaveVisible]) {cCopySaveButton.Visible = true; cCopySaveButton.Enabled = true;} else {cCopySaveButton.Visible = false;}
}
}
return dt;
}
protected void cFilterId_SelectedIndexChanged(object sender, System.EventArgs e)
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if (cAdmScreenCriGrid.EditIndex < 0 || (dt != null && UpdateGridRow(sender, new CommandEventArgs("Save", ""))))
{
cNewButton_Click(sender, new EventArgs());
}
}
protected void cSystemId_SelectedIndexChanged(object sender, System.EventArgs e)
{
base.LCurr.DbId = byte.Parse(cSystemId.SelectedValue);
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if (cAdmScreenCriGrid.EditIndex < 0 || (dt != null && UpdateGridRow(sender, new CommandEventArgs("Save", ""))))
{
DataTable dtSystems = (DataTable)Session[KEY_dtSystems];
Session[KEY_sysConnectionString] = Config.GetConnStr(dtSystems.Rows[cSystemId.SelectedIndex]["dbAppProvider"].ToString(), dtSystems.Rows[cSystemId.SelectedIndex]["ServerName"].ToString(), dtSystems.Rows[cSystemId.SelectedIndex]["dbDesDatabase"].ToString(), "", dtSystems.Rows[cSystemId.SelectedIndex]["dbAppUserId"].ToString());
Session.Remove(KEY_dtScreenId104);
Session.Remove(KEY_dtColumnId104);
Session.Remove(KEY_dtOperatorId104);
Session.Remove(KEY_dtDisplayModeId104);
Session.Remove(KEY_dtColumnJustify104);
Session.Remove(KEY_dtDdlKeyColumnId104);
Session.Remove(KEY_dtDdlRefColumnId104);
Session.Remove(KEY_dtDdlSrtColumnId104);
Session.Remove(KEY_dtDdlFtrColumnId104);
Session.Remove(KEY_dtCultureId105);
GetCriteria(GetScrCriteria());
cFilterId_SelectedIndexChanged(sender, e);
}
}
private void ClearMaster(object sender, System.EventArgs e)
{
DataTable dt = GetAuthCol();
if (dt.Rows[1]["ColVisible"].ToString() == "Y" && dt.Rows[1]["ColReadOnly"].ToString() != "Y") {cScreenId104.ClearSearch();}
if (dt.Rows[2]["ColVisible"].ToString() == "Y" && dt.Rows[2]["ColReadOnly"].ToString() != "Y") {cLabelCss104.Text = string.Empty;}
if (dt.Rows[3]["ColVisible"].ToString() == "Y" && dt.Rows[3]["ColReadOnly"].ToString() != "Y") {cContentCss104.Text = string.Empty;}
if (dt.Rows[4]["ColVisible"].ToString() == "Y" && dt.Rows[4]["ColReadOnly"].ToString() != "Y") {cColumnId104.ClearSearch();}
if (dt.Rows[5]["ColVisible"].ToString() == "Y" && dt.Rows[5]["ColReadOnly"].ToString() != "Y") {SetOperatorId104(cOperatorId104,"1");}
if (dt.Rows[6]["ColVisible"].ToString() == "Y" && dt.Rows[6]["ColReadOnly"].ToString() != "Y") {SetDisplayModeId104(cDisplayModeId104,string.Empty);}
if (dt.Rows[7]["ColVisible"].ToString() == "Y" && dt.Rows[7]["ColReadOnly"].ToString() != "Y") {cTabIndex104.Text = string.Empty;}
if (dt.Rows[8]["ColVisible"].ToString() == "Y" && dt.Rows[8]["ColReadOnly"].ToString() != "Y") {cRequiredValid104.Checked = base.GetBool("N");}
if (dt.Rows[9]["ColVisible"].ToString() == "Y" && dt.Rows[9]["ColReadOnly"].ToString() != "Y") {SetColumnJustify104(cColumnJustify104,"L");}
if (dt.Rows[10]["ColVisible"].ToString() == "Y" && dt.Rows[10]["ColReadOnly"].ToString() != "Y") {cColumnSize104.Text = string.Empty;}
if (dt.Rows[11]["ColVisible"].ToString() == "Y" && dt.Rows[11]["ColReadOnly"].ToString() != "Y") {cRowSize104.Text = string.Empty;}
if (dt.Rows[12]["ColVisible"].ToString() == "Y" && dt.Rows[12]["ColReadOnly"].ToString() != "Y") {cDdlKeyColumnId104.ClearSearch();}
if (dt.Rows[13]["ColVisible"].ToString() == "Y" && dt.Rows[13]["ColReadOnly"].ToString() != "Y") {cDdlRefColumnId104.ClearSearch();}
if (dt.Rows[14]["ColVisible"].ToString() == "Y" && dt.Rows[14]["ColReadOnly"].ToString() != "Y") {cDdlSrtColumnId104.ClearSearch();}
if (dt.Rows[15]["ColVisible"].ToString() == "Y" && dt.Rows[15]["ColReadOnly"].ToString() != "Y") {cDdlFtrColumnId104.ClearSearch();}
// *** Default Value (Folder) Web Rule starts here *** //
}
private void InitMaster(object sender, System.EventArgs e)
{
cScreenCriId104.Text = string.Empty;
cScreenId104.ClearSearch();
cLabelCss104.Text = string.Empty;
cContentCss104.Text = string.Empty;
cColumnId104.ClearSearch();
SetOperatorId104(cOperatorId104,"1");
SetDisplayModeId104(cDisplayModeId104,string.Empty);
cTabIndex104.Text = string.Empty;
cRequiredValid104.Checked = base.GetBool("N");
SetColumnJustify104(cColumnJustify104,"L");
cColumnSize104.Text = string.Empty;
cRowSize104.Text = string.Empty;
cDdlKeyColumnId104.ClearSearch();
cDdlRefColumnId104.ClearSearch();
cDdlSrtColumnId104.ClearSearch();
cDdlFtrColumnId104.ClearSearch();
// *** Default Value (Folder) Web Rule starts here *** //
}
protected void cAdmScreenCri73List_TextChanged(object sender, System.EventArgs e)
{
ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)sender).FocusID);
}
protected void cAdmScreenCri73List_DDFindClick(object sender, System.EventArgs e)
{
ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)sender).FocusID);
}
protected void cAdmScreenCri73List_SelectedIndexChanged(object sender, System.EventArgs e)
{
InitMaster(sender, e); // Do this first to enable defaults for non-database columns.
DataTable dt = null;
try
{
dt = (new AdminSystem()).GetMstById("GetAdmScreenCri73ById",cAdmScreenCri73List.SelectedValue,(string)Session[KEY_sysConnectionString],LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (dt != null)
{
CheckAuthentication(false);
if (dt.Rows.Count > 0)
{
cAdmScreenCri73List.SetDdVisible();
DataRow dr = dt.Rows[0];
try {cScreenCriId104.Text = RO.Common3.Utils.fmNumeric("0",dr["ScreenCriId104"].ToString(),base.LUser.Culture);} catch {cScreenCriId104.Text = string.Empty;}
SetScreenId104(cScreenId104,dr["ScreenId104"].ToString()); cScreenId104_SelectedIndexChanged(cScreenId104, new EventArgs());
try {cLabelCss104.Text = dr["LabelCss104"].ToString();} catch {cLabelCss104.Text = string.Empty;}
try {cContentCss104.Text = dr["ContentCss104"].ToString();} catch {cContentCss104.Text = string.Empty;}
SetColumnId104(cColumnId104,dr["ColumnId104"].ToString());
SetOperatorId104(cOperatorId104,dr["OperatorId104"].ToString()); if (cOperatorId104.SelectedIndex <= 0 && !(cOperatorId104.Enabled && cOperatorId104.Visible)) { SetOperatorId104(cOperatorId104,"1"); }
SetDisplayModeId104(cDisplayModeId104,dr["DisplayModeId104"].ToString());
try {cTabIndex104.Text = RO.Common3.Utils.fmNumeric("0",dr["TabIndex104"].ToString(),base.LUser.Culture);} catch {cTabIndex104.Text = string.Empty;}
try {cRequiredValid104.Checked = base.GetBool(dr["RequiredValid104"].ToString());} catch {cRequiredValid104.Checked = false;}
SetColumnJustify104(cColumnJustify104,dr["ColumnJustify104"].ToString()); if (cColumnJustify104.SelectedIndex <= 0 && !(cColumnJustify104.Enabled && cColumnJustify104.Visible)) { SetColumnJustify104(cColumnJustify104,"L"); }
try {cColumnSize104.Text = RO.Common3.Utils.fmNumeric("0",dr["ColumnSize104"].ToString(),base.LUser.Culture);} catch {cColumnSize104.Text = string.Empty;}
try {cRowSize104.Text = RO.Common3.Utils.fmNumeric("0",dr["RowSize104"].ToString(),base.LUser.Culture);} catch {cRowSize104.Text = string.Empty;}
SetDdlKeyColumnId104(cDdlKeyColumnId104,dr["DdlKeyColumnId104"].ToString());
SetDdlRefColumnId104(cDdlRefColumnId104,dr["DdlRefColumnId104"].ToString());
SetDdlSrtColumnId104(cDdlSrtColumnId104,dr["DdlSrtColumnId104"].ToString());
SetDdlFtrColumnId104(cDdlFtrColumnId104,dr["DdlFtrColumnId104"].ToString(),cScreenId104.SelectedValue);
}
}
cButPanel.DataBind(); if (!cSaveButton.Visible) { cInsRowButton.Visible = false; }
DataTable dtAdmScreenCriGrid = null;
int filterId = 0; if (Utils.IsInt(cFilterId.SelectedValue)) { filterId = int.Parse(cFilterId.SelectedValue); }
try
{
dtAdmScreenCriGrid = (new AdminSystem()).GetDtlById(73,"GetAdmScreenCri73DtlById",cAdmScreenCri73List.SelectedValue,(string)Session[KEY_sysConnectionString],LcAppPw,filterId,base.LImpr,base.LCurr);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (!dtAdmScreenCriGrid.Columns.Contains("_NewRow")) { dtAdmScreenCriGrid.Columns.Add("_NewRow"); }
Session[KEY_dtAdmScreenCriGrid] = dtAdmScreenCriGrid;
cAdmScreenCriGrid.EditIndex = -1;
cAdmScreenCriGridDataPager.PageSize = Int16.Parse(cPgSize.Text); GotoPage(0);
if (Session[KEY_lastSortCol] != null)
{
cAdmScreenCriGrid_OnSorting(sender, new ListViewSortEventArgs((string)Session[KEY_lastSortExp], SortDirection.Ascending));
}
else if (dtAdmScreenCriGrid.Rows.Count <= 0 || (!((GetAuthRow().Rows[0]["AllowUpd"].ToString() == "N" || GetAuthRow().Rows[0]["ViewOnly"].ToString() == "G") && GetAuthRow().Rows[0]["AllowAdd"].ToString() == "N") && !(Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N") && dtAdmScreenCriGrid.Rows.Count == 1))
{
cAdmScreenCriGrid_DataBind(dtAdmScreenCriGrid.DefaultView);
}
cFindButton_Click(sender, e);
cNaviPanel.Visible = true; cImportPwdPanel.Visible = false; Session.Remove(KEY_scrImport);
ScriptManager.GetCurrent(Parent.Page).SetFocus(cAdmScreenCri73List.FocusID);
ShowDirty(false); PanelTop.Update();
// *** List Selection (End of) Web Rule starts here *** //
}
protected void cScreenId104_TextChanged(object sender, System.EventArgs e)
{
ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)sender).FocusID);
}
protected void cScreenId104_DDFindClick(object sender, System.EventArgs e)
{
ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)sender).FocusID);
}
protected void cScreenId104_SelectedIndexChanged(object sender, System.EventArgs e)
{
// *** On Change/ On Click Web Rule starts here *** //
EnableValidators(true); // Do not remove; Need to reenable after postback, especially in the grid.
TextBox pwd = null;
if (cScreenId104.Items.Count > 0 && cScreenId104.DataSource != null)
{
DataView dv = (DataView) cScreenId104.DataSource; dv.RowFilter = string.Empty;
DataRowView dr = cScreenId104.DataSetIndex >= 0 && cScreenId104.DataSetIndex < dv.Count ? dv[cScreenId104.DataSetIndex] : dv[0];
if (cDdlFtrColumnId104.Mode!="A") cDdlFtrColumnId104.ClearSearch(); else SetDdlFtrColumnId104(cDdlFtrColumnId104,cDdlFtrColumnId104.SelectedValue,cScreenId104.SelectedValue);
if (pwd != null) {ScriptManager.GetCurrent(Parent.Page).SetFocus(pwd.ClientID);} else {ScriptManager.GetCurrent(Parent.Page).SetFocus(SenderFocusId(sender));}
}
}
public void cFindButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
DataView dv = dt != null ? dt.DefaultView : null;
if (dv != null)
{
WebControl cc = sender as WebControl;
if ((cc != null && cc.ID.Equals("cAdmScreenCri73List")) || cAdmScreenCriGrid.EditIndex < 0 || UpdateGridRow(cAdmScreenCriGrid, new CommandEventArgs("Save", "")))
{
string rf = string.Empty;
if (cFind.Text != string.Empty) { rf = "(" + base.GetExpression(cFind.Text.Trim(), GetAuthCol(), 16, cFindFilter.SelectedValue) + ")"; }
if (rf != string.Empty) { rf = "((" + rf + " or _NewRow = 'Y' ))"; }
dv.RowFilter = rf;
ViewState["_RowFilter"] = rf;
GotoPage(0); cAdmScreenCriGrid_DataBind(dv);
if (GetCurrPageIndex() != (int)Session[KEY_currPageIndex] && (int)Session[KEY_currPageIndex] < GetTotalPages()) { GotoPage((int)Session[KEY_currPageIndex]); cAdmScreenCriGrid_DataBind(dv);}
try {ScriptManager.GetCurrent(Parent.Page).SetFocus(((TextBox)sender).ClientID);} catch {}
}
}
grdCount.InnerText = "(" + RO.Common3.Utils.fmNumeric("0",dv.Count.ToString(),base.LUser.Culture) + " found)";
// *** System Button Click (after) Web Rule starts here *** //
}
public void cFirstButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
GotoPage(0);
// *** System Button Click (after) Web Rule starts here *** //
}
public void cLastButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
GotoPage(GetTotalPages() - 1);
// *** System Button Click (after) Web Rule starts here *** //
}
public void cNextButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
GotoPage(GetCurrPageIndex() + 1);
// *** System Button Click (after) Web Rule starts here *** //
}
public void cPrevButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
GotoPage(GetCurrPageIndex() - 1);
// *** System Button Click (after) Web Rule starts here *** //
}
public void cInsRowButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if (dt != null && (ValidPage()) && UpdateGridRow(sender, new CommandEventArgs("Save", "")))
{
DataRow dr = dt.NewRow();
int? sortorder = null;
dr["CultureId105"] = 1;
if (dt.Columns.Contains("_SortOrder"))
{
try
{
sortorder = 1;
} catch {};
}
dt.Rows.InsertAt(dr, 0);
dt.Rows[0]["_NewRow"] = "Y";
if (sortorder.HasValue) dr["_SortOrder"] = sortorder;
Session[KEY_lastAddedRow] = 0; Session[KEY_dtAdmScreenCriGrid] = dt; Session[KEY_currPageIndex] = 0; GotoPage(0);
cAdmScreenCriGrid_DataBind(dt.DefaultView);
cAdmScreenCriGrid_OnItemEditing(cAdmScreenCriGrid, new ListViewEditEventArgs(0));
// *** Default Value (Grid) Web Rule starts here *** //
}
// *** System Button Click (after) Web Rule starts here *** //
}
public void cPgSizeButton_Click(object sender, System.EventArgs e)
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if (cAdmScreenCriGrid.EditIndex < 0 || (dt != null && UpdateGridRow(sender, new CommandEventArgs("Save", ""))))
{
try {if (int.Parse(cPgSize.Text) < 1 || int.Parse(cPgSize.Text) > 200) {cPgSize.Text = "2";}} catch {cPgSize.Text = "2";}
cAdmScreenCriGridDataPager.PageSize = int.Parse(cPgSize.Text); GotoPage(0);
if (dt.Rows.Count <= 0 || (!((GetAuthRow().Rows[0]["AllowUpd"].ToString() == "N" || GetAuthRow().Rows[0]["ViewOnly"].ToString() == "G") && GetAuthRow().Rows[0]["AllowAdd"].ToString() == "N") && !(Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N") && dt.Rows.Count == 1)) {cAdmScreenCriGrid_DataBind(dt.DefaultView);} else {cFindButton_Click(sender, e);}
try
{
(new AdminSystem()).UpdLastPageInfo(73, base.LUser.UsrId, cPgSize.Text, LcSysConnString, LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); }
}
}
public void cGoto_TextChanged(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
try {GotoPage(Convert.ToInt32(cGoto.Text) - 1);} catch {} finally {cGoto.Text = (GetCurrPageIndex() + 1).ToString();}
// *** System Button Click (after) Web Rule starts here *** //
}
public void cHideImpButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
cImport.Visible = false; cHideImpButton.Visible = false; cShowImpButton.Visible = (bool)Session[KEY_bShImpVisible];
cNaviPanel.Visible = true; cImportPwdPanel.Visible = false;
if ((cShowImpButton.Attributes["OnClick"] == null || cShowImpButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) && cShowImpButton.Visible) {cShowImpButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
// *** System Button Click (after) Web Rule starts here *** //
}
public void cShowImpButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
cImport.Visible = true; cShowImpButton.Visible = false; cHideImpButton.Visible = (bool)Session[KEY_bHiImpVisible];
cNaviPanel.Visible = false; cImportPwdPanel.Visible = false;
if ((cImportButton.Attributes["OnClick"] == null || cImportButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) && cImportButton.Visible) {cImportButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if ((cHideImpButton.Attributes["OnClick"] == null || cHideImpButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) && cHideImpButton.Visible) {cHideImpButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cSchemaImage.Visible)
{
try
{
Session["ImportSchema"] = (new AdminSystem()).GetSchemaScrImp(73,base.LUser.CultureId,LcSysConnString,LcAppPw);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
if (cSchemaImage.Attributes["OnClick"] == null || cSchemaImage.Attributes["OnClick"].IndexOf("ImportSchema.aspx") < 0) {cSchemaImage.Attributes["OnClick"] += "SearchLink('ImportSchema.aspx?scm=S&key=73&csy=3','','',''); return false;";}
}
// *** System Button Click (after) Web Rule starts here *** //
}
private void ScrImportDdl(DataView dvd, DataRowView drv, bool bComboBox, string PKey, string CKey, string CNam, int MaxLen, string MatchCd, bool bAllowNulls)
{
if (dvd != null)
{
if (dvd.Table.Columns.Contains(PKey))
{
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue))
{
dvd.RowFilter = "(" + PKey + " is null)";
}
else
{
dvd.RowFilter = "(" + PKey + " is null OR " + PKey + " = " + cAdmScreenCri73List.SelectedValue + ")";
}
}
bool bFound = false; bool bUnique = true;
if (!string.IsNullOrEmpty(drv[CKey].ToString().Trim())) // Always do this first.
{
foreach (DataRowView drvd in dvd)
{
if (drvd[0].ToString().Trim() == drv[CKey].ToString().Trim()) {drv[CNam] = drvd[1].ToString(); bFound = true; break;}
}
}
if (!string.IsNullOrEmpty(drv[CNam].ToString().Trim()))
{
if (drv[CNam].ToString().Length > MaxLen) { drv[CNam] = drv[CNam].ToString().Substring(0,MaxLen); }
string cnam = drv[CNam].ToString(); object ckey = drv[CKey]; // Saved for reverse later.
if (!bFound && "2,3,4".IndexOf(MatchCd) >= 0) // Exact match.
{
foreach (DataRowView drvd in dvd)
{
if (drvd[1].ToString().Trim().ToLower() == cnam.Trim().ToLower())
{
drv[CKey] = drvd[0].ToString();
if (bComboBox) {drv[CNam] = drvd[1].ToString();}
if (!bFound) {bFound = true;}
else { bUnique = false; drv[CNam] = cnam; drv[CKey] = ckey; break; }
}
else if (bFound) break;
}
}
if (!bFound && "3,4".IndexOf(MatchCd) >= 0) // StartsWith.
{
foreach (DataRowView drvd in dvd)
{
if (drvd[1].ToString().Trim().ToLower().StartsWith(cnam.Trim().ToLower()))
{
drv[CKey] = drvd[0].ToString();
if (bComboBox) {drv[CNam] = drvd[1].ToString();}
if (!bFound) {bFound = true;}
else { bUnique = false; drv[CNam] = cnam; drv[CKey] = ckey; break; }
}
else if (bFound) break;
}
}
if (!bFound && "4".IndexOf(MatchCd) >= 0) // Wild search.
{
foreach (DataRowView drvd in dvd)
{
if (drvd[1].ToString().Trim().ToLower().IndexOf(cnam.Trim().ToLower()) >= 0)
{
drv[CKey] = drvd[0].ToString();
if (bComboBox) {drv[CNam] = drvd[1].ToString();}
if (!bFound) {bFound = true;}
else { bUnique = false; drv[CNam] = cnam; drv[CKey] = ckey; break; }
}
else if (bFound) break;
}
}
if (!(bFound && bUnique) && MatchCd != "1") {drv[CNam] = "Invalid>" + drv[CNam].ToString(); bErrNow.Value = "Y"; PreMsgPopup("Import has invalid data, please check for \"Invalid>\", rectify and try again.");}
}
}
}
protected void ScrImport(bool bClear)
{
int iRow;
cNaviPanel.Visible = true; cImportPwdPanel.Visible = false;
DataTable dti = (DataTable)Session[KEY_scrImport];
DataTable dtAdmScreenCriGrid = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if (dti != null && dtAdmScreenCriGrid != null)
{
if (bClear)
{
dtAdmScreenCriGrid.Rows.Clear();
}
cFind.Text = string.Empty;
int iExist = dtAdmScreenCriGrid.Rows.Count;
// Validate dropdown, combobox, etc.
int jj = 0;
foreach (DataRowView drv in dti.DefaultView)
{
if ((drv.Row.RowState == System.Data.DataRowState.Added || drv.Row.RowState == System.Data.DataRowState.Detached) && jj >= iExist)
{
DataTable dtd;
dtd = jj==iExist ? null : (DataTable)Session[KEY_dtCultureId105];
if (dtd == null)
{
try
{
dtd = (new AdminSystem()).GetDdl(73,"GetDdlCultureId3S1191",true,true,0,string.Empty,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr);
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
Session[KEY_dtCultureId105] = dtd;
}
ScrImportDdl(dtd.DefaultView, drv, true, "ScreenCriId", "CultureId105", "CultureId105Text", 50, "2", false);
}
jj = jj + 1;
}
iRow = dti.DefaultView.Count - iExist;
if (!dti.Columns.Contains("_NewRow")) { dti.Columns.Add("_NewRow"); }
Session[KEY_dtAdmScreenCriGrid] = dti;
cAdmScreenCriGrid_DataBind(dti.DefaultView);
string msg = iRow.ToString() + " rows from selected source imported successfully. " + Session[KEY_cntImpPwdOvride].ToString() + " rows validated by Password Override. Please press Save button to save to database.";
if (Session["CtrlAcctList"] != null)
{
System.Collections.Hashtable ht = (System.Collections.Hashtable) Session["CtrlAcctList"];
string ss = string.Empty;
System.Collections.IDictionaryEnumerator de = ht.GetEnumerator();
while ( de.MoveNext() )
{
ss = ss + de.Key + " (" + de.Value.ToString() + "), ";
}
msg = msg + " List of Password Override items: " + ss.Remove(ss.Length - 2, 2) + ".";
}
Session.Remove(KEY_scrImport); Session.Remove("CtrlAcctList");
cImportPwd.Text = string.Empty;
ShowDirty(true);
Session[KEY_lastImpPwdOvride] = 0; Session[KEY_cntImpPwdOvride] = 0;
bInfoNow.Value = "Y"; PreMsgPopup(msg);
}
}
public void cContinueButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (before) Web Rule starts here *** //
ScrImport(false);
// *** System Button Click (after) Web Rule starts here *** //
}
protected void cBrowseButton_Click(object sender, EventArgs e)
{
if (cBrowse.HasFile && cBrowse.PostedFile.FileName != string.Empty)
{
string fileAndPath = cBrowse.PostedFile.FileName;
string fNameO = string.Empty;
try {
foreach (var c in Path.GetInvalidPathChars()) { fileAndPath = fileAndPath.Replace(c, '_'); }
fNameO = Path.GetFileName(fileAndPath);
}
catch (Exception err) {
bErrNow.Value = "Y"; PreMsgPopup("Invalid characters in file and/or path \"" + fileAndPath + "\": " + err.Message);
return;
}
try {
string fName;
if (fNameO.LastIndexOf(".") >= 0)
{
fName = fNameO.Insert(fNameO.LastIndexOf("."), "_" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString());
}
else
{
fName = fNameO + "_" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
}
fName = fName.Replace(":","").Replace("..","");
if (!Directory.Exists(Config.PathTmpImport)) { Directory.CreateDirectory(Config.PathTmpImport); }
cBrowse.PostedFile.SaveAs(Config.PathTmpImport + fName);
cWorkSheet.DataSource = (new XLSImport()).GetSheetNames(Config.PathTmpImport + fName); cWorkSheet.DataBind();
cFNameO.Text = fNameO; cFName.Text = fName;
}
catch (Exception err) {bErrNow.Value = "Y"; PreMsgPopup("Unable to retrieve sheet names from \"" + fNameO + "\": " + err.Message); }
}
}
public void cImportButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
if (cFNameO.Text != string.Empty && cWorkSheet.Items.Count > 0 && cWorkSheet.SelectedItem.Text != string.Empty && cStartRow.Text != string.Empty)
{
DataTable dtAdmScreenCriGrid = (DataTable)Session[KEY_dtAdmScreenCriGrid];
try
{
if (cAdmScreenCriGrid.EditIndex < 0 || UpdateGridRow(cAdmScreenCriGrid, new CommandEventArgs("Save", "")))
{
Session[KEY_scrImport] = ImportFile(dtAdmScreenCriGrid.Copy(),cFNameO.Text,cWorkSheet.SelectedItem.Text,cStartRow.Text,Config.PathTmpImport + cFName.Text);
}
cHideImpButton_Click(sender,new EventArgs());
}
catch (Exception err) {bErrNow.Value = "Y"; PreMsgPopup("Error in spreadsheet \"" + cFNameO.Text + "\":<br>" + err.Message); return; }
finally {cWorkSheet.Items.Clear();}
ScrImport(false);
}
else
{
bInfoNow.Value = "Y"; PreMsgPopup("Please select a spreadsheet, then a worksheet, indicate the starting row and try again.");
}
// *** System Button Click (After) Web Rule starts here *** //
}
private DataTable ImportFile(DataTable dt, string fileName, string workSheet, string startRow, string fileFullName)
{
try
{
DataTable dtImp = RO.Common3.XmlUtils.XmlToDataSet((new XLSImport()).ImportFile(fileName,workSheet,startRow,fileFullName)).Tables[0];
DataRowCollection rows = dtImp.Rows;
DataColumnCollection cols = dt.Columns;
Func<string, string, bool> isDateCol = (cl, c) => ("," + cl + ",").IndexOf("," + c + ",") >= 0;
Func<string, string, bool> isDateUTCCol = (cl, c) => ("," + cl + ",").IndexOf("," + c + ",") >= 0;
string ss;
int iStart = int.Parse(startRow) - 1;
int idv = dt.Rows.Count;
int idel = 0;
System.Collections.Generic.List<string> ErrLst = new System.Collections.Generic.List<string>();
bool bHasErr = false;
for ( int iRow = iStart; iRow < rows.Count; iRow++ )
{
if (rows[iRow][1].ToString() == string.Empty && rows[iRow][2].ToString() == string.Empty) {idel = idel + 1;}
else
{
dt.Rows.Add(dt.NewRow());
if (rows[iRow][1].ToString() == string.Empty && rows[iRow][2].ToString() == string.Empty) { rows[iRow][1] = 1;}
for ( int iCol = 0; iCol < cols.Count; iCol++ )
{
try { ss = rows[iRow][iCol].ToString().Trim(); } catch { ss = string.Empty; }
try {
if (!string.IsNullOrEmpty(ss)) {
dt.Rows[iRow - iStart - idel + idv][iCol] = isDateCol("", iCol.ToString()) ? base.ToIntDateTime(ss, isDateUTCCol("", iCol.ToString()), true) : ss;
}
}
catch (Exception ex) {
if (ss.EndsWith("%")) {
try { dt.Rows[iRow - iStart - idel + idv][iCol] = ss.Left(ss.Length - 1); } catch { }
}
else {
bHasErr = true;
ErrLst.Add("Row " + (iRow + 1).ToString() + " Col " + Utils.Num2ExcelCol(iCol + 1) + ": " + Server.HtmlEncode(ex.Message));
}
}
}
}
}
if (bHasErr) { throw new Exception(string.Join("<br>", ErrLst)); }
}
catch(Exception e) { throw (e); }
return dt;
}
private void GotoPage(int pageNo)
{
if (pageNo >= 0 && pageNo < GetTotalPages())
{
if (cAdmScreenCriGrid.EditIndex < 0 || UpdateGridRow(cAdmScreenCriGrid, new CommandEventArgs("Save", "")))
{
try { cAdmScreenCriGridDataPager.SetPageProperties(cAdmScreenCriGridDataPager.PageSize * pageNo, cAdmScreenCriGridDataPager.MaximumRows, false); cAdmScreenCriGrid_DataBind(null); }
catch
{
try { cAdmScreenCriGridDataPager.SetPageProperties(0, cAdmScreenCriGridDataPager.MaximumRows, false); cAdmScreenCriGrid_DataBind(null); } catch {}
}
}
}
}
protected void cAdmScreenCriGrid_OnItemCommand(object sender, ListViewCommandEventArgs e)
{
}
private void cAdmScreenCriGrid_DataBind(DataView dvAdmScreenCriGrid)
{
if (dvAdmScreenCriGrid == null)
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
dvAdmScreenCriGrid = dt != null ? dt.DefaultView : null;
}
if (dvAdmScreenCriGrid != null)
{
LcAuth = GetAuthCol().AsEnumerable().ToDictionary<DataRow,string>(dr=>dr["ColName"].ToString());
cAdmScreenCriGrid.DataSource = dvAdmScreenCriGrid;
cAdmScreenCriGrid.DataBind();
int totalPages = GetTotalPages(); if (totalPages <= 0) { totalPages = 1; }
cPageNoLabel.Text = " of " + totalPages.ToString(); cGoto.Text = (GetCurrPageIndex() + 1).ToString();
}
if (cFindFilter.Items.Count <= 0)
{
DataTable dtAuth = GetAuthCol();
DataTable dtLabel = GetLabel();
int ii = 0;
ListItem li = new ListItem();
li.Value = string.Empty; li.Text = "All";
cFindFilter.Items.Add(li);
foreach (DataRow dr in dtLabel.Rows)
{
if (ii >= 16 && !string.IsNullOrEmpty(dr["ColumnHeader"].ToString()) && !string.IsNullOrEmpty(dr["TableId"].ToString()) && dtAuth.Rows[ii]["ColVisible"].ToString() == "Y")
{
li = new ListItem();
li.Value = ii.ToString(); li.Text = dr["ColumnHeader"].ToString().Replace("*", string.Empty);
cFindFilter.Items.Add(li);
}
ii = ii + 1;
}
}
}
protected void cAdmScreenCriGrid_OnSorting(object sender, ListViewSortEventArgs e)
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
DataView dv = dt != null ? dt.DefaultView : null;
if (dv != null)
{
if (cAdmScreenCriGrid.EditIndex < 0 || UpdateGridRow(cAdmScreenCriGrid, new CommandEventArgs("Save", "")))
{
string ftr = string.Empty;
if (!dv.Table.Columns.Contains("_SortOrder")) { dv.Table.Columns.Add("_SortOrder"); }
if (dv.RowFilter != string.Empty) { ftr = dv.RowFilter; dv.RowFilter = string.Empty; }
if (Session[KEY_lastSortUrl] == null) // First time.
{
dv.Sort = "_SortOrder DESC, " + e.SortExpression; Session[KEY_lastSortUrl] = "~/images/ArrowUp.png"; Session[KEY_lastSortTog] = "N";
}
else if ((string)Session[KEY_lastSortTog] == "Y")
{
if (((string)Session[KEY_lastSortUrl]).IndexOf("ArrowDn") >= 0)
{
dv.Sort = "_SortOrder DESC, " + e.SortExpression; Session[KEY_lastSortUrl] = "~/images/ArrowUp.png";
}
else
{
dv.Sort = "_SortOrder DESC, " + e.SortExpression + " DESC"; Session[KEY_lastSortUrl] = "~/images/ArrowDn.png";
}
Session[KEY_lastSortTog] = "N";
}
else if (((string)Session[KEY_lastSortUrl]).IndexOf("ArrowDn") >= 0) { dv.Sort = "_SortOrder DESC, " + e.SortExpression + " DESC"; } else { dv.Sort = "_SortOrder DESC, " + e.SortExpression; }
ViewState["_SortColumn"] = dv.Sort;
if (ftr != string.Empty) { dv.RowFilter = ftr; }
Session[KEY_dtAdmScreenCriGrid] = dt;
cAdmScreenCriGrid_DataBind(dv);
}
}
}
protected void cAdmScreenCriGrid_OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
cAdmScreenCriGridDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
DataView dv = dt != null ? dt.DefaultView : null;
cAdmScreenCriGrid_DataBind(dv); cAdmScreenCriGrid.EditIndex = -1;
}
private void GridChkPgDirty(ListViewItem lvi)
{
WebControl cc = null;
cc = ((WebControl)lvi.FindControl("cCultureId105"));
if ((cc.Attributes["OnChange"] == null || cc.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cc.Visible && cc.Enabled) {cc.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
cc = ((WebControl)lvi.FindControl("cColumnHeader105"));
if ((cc.Attributes["OnChange"] == null || cc.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cc.Visible && cc.Enabled) {cc.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";}
}
protected void cAdmScreenCriGrid_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
// *** GridItemDataBound (before) Web Rule End *** //
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
bool isEditItem = false;
DataView dvAdmScreenCriGrid = dt != null ? dt.DefaultView : null;
if (cAdmScreenCriGrid.EditIndex > -1 && GetDataItemIndex(cAdmScreenCriGrid.EditIndex) == e.Item.DataItemIndex)
{
isEditItem = true;
base.SetGridEnabled(e.Item, GetAuthCol(), GetLabel(), 16);
if (dvAdmScreenCriGrid[e.Item.DataItemIndex]["CultureId105"].ToString() != string.Empty) {SetCultureId105((RoboCoder.WebControls.ComboBox)e.Item.FindControl("cCultureId105"),dvAdmScreenCriGrid[e.Item.DataItemIndex]["CultureId105"].ToString(), e.Item);} else {SetCultureId105((RoboCoder.WebControls.ComboBox)e.Item.FindControl("cCultureId105"),"1", e.Item);}
GridChkPgDirty(e.Item);
}
SetClientRule((ListViewDataItem) e.Item,isEditItem);
DataTable dtAuthRow = GetAuthRow();
if (dtAuthRow != null)
{
DataRow dr = dtAuthRow.Rows[0];
Control cc = null;
if (!CanAct('S') || dr["ViewOnly"].ToString() == "G" || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N"))
{
cc = e.Item.FindControl("cAdmScreenCriGridDelete"); if (cc != null) { cc.Visible = false; }
cc = e.Item.FindControl("cAdmScreenCriGridEdit"); if (cc != null) { cc.Visible = false; }
}
else
{
HtmlTableRow tr = e.Item.FindControl("cAdmScreenCriGridRow") as HtmlTableRow;
LinkButton lb = e.Item.FindControl("cAdmScreenCriGridEdit") as LinkButton;
if (tr != null && lb != null) { SetDefaultCtrl(tr, lb, string.Empty); }
}
}
if (cAdmScreenCriGrid.EditIndex > -1 && GetDataItemIndex(cAdmScreenCriGrid.EditIndex) == e.Item.DataItemIndex)
{
}
// *** GridItemDataBound (after) Web Rule End *** //
}
protected void cScreenCriHlpId105hl_Click(object sender, System.EventArgs e)
{
if (Session[KEY_lastSortCol] == null || (string)Session[KEY_lastSortCol] != "0") { Session.Remove(KEY_lastSortUrl); }
Session[KEY_lastSortTog] = "Y"; Session[KEY_lastSortCol] = "0"; Session[KEY_lastSortExp] = "ScreenCriHlpId105";Session[KEY_lastSortImg] = "cScreenCriHlpId105hi";
cAdmScreenCriGrid_OnSorting(sender, new ListViewSortEventArgs("ScreenCriHlpId105", SortDirection.Ascending));
}
protected void cCultureId105hl_Click(object sender, System.EventArgs e)
{
if (Session[KEY_lastSortCol] == null || (string)Session[KEY_lastSortCol] != "1") { Session.Remove(KEY_lastSortUrl); }
Session[KEY_lastSortTog] = "Y"; Session[KEY_lastSortCol] = "1"; Session[KEY_lastSortExp] = "CultureId105Text";Session[KEY_lastSortImg] = "cCultureId105hi";
cAdmScreenCriGrid_OnSorting(sender, new ListViewSortEventArgs("CultureId105Text", SortDirection.Ascending));
}
protected void cColumnHeader105hl_Click(object sender, System.EventArgs e)
{
if (Session[KEY_lastSortCol] == null || (string)Session[KEY_lastSortCol] != "2") { Session.Remove(KEY_lastSortUrl); }
Session[KEY_lastSortTog] = "Y"; Session[KEY_lastSortCol] = "2"; Session[KEY_lastSortExp] = "ColumnHeader105";Session[KEY_lastSortImg] = "cColumnHeader105hi";
cAdmScreenCriGrid_OnSorting(sender, new ListViewSortEventArgs("ColumnHeader105", SortDirection.Ascending));
}
protected void cAdmScreenCriGrid_OnItemEditing(object sender, ListViewEditEventArgs e)
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if ((ValidPage()) && UpdateGridRow(sender, new CommandEventArgs("Save", "")) && dt != null && dt.DefaultView.Count > GetDataItemIndex(e.NewEditIndex))
{
cAdmScreenCriGrid.EditIndex = e.NewEditIndex;
cAdmScreenCriGrid_DataBind(null);
Control wc = null;
string idx = Page.Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(idx))
{
Control ctrlToFocus = cAdmScreenCriGrid.EditItem.FindControl("c" + idx);
if (((WebControl)ctrlToFocus).Enabled) { wc = ctrlToFocus; }
}
if (wc == null) { wc = FindEditableControl(cAdmScreenCriGrid.EditItem); }
if (wc != null)
{
if (wc is RoboCoder.WebControls.ComboBox)
{
if (isMobile.Text != "isMobile") ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)wc).FocusID);
}
else if (wc is CheckBox && ("c" + idx) == wc.ID)
{
((CheckBox)wc).Checked = !((CheckBox)wc).Checked; ShowDirty(true);
}
else
{
if (isMobile.Text != "isMobile") ScriptManager.GetCurrent(Parent.Page).SetFocus(wc.ClientID);
}
}
MkMobileLabel(cAdmScreenCriGrid.EditItem);
}
else { e.Cancel = true; }
}
private void MkMobileLabel(ListViewItem lvi)
{
Label ml = null;
ml = lvi.FindControl("cScreenCriHlpId105ml") as Label;
if (ml != null) { ml.Text = ColumnHeaderText(16); }
ml = lvi.FindControl("cCultureId105ml") as Label;
if (ml != null) { ml.Text = ColumnHeaderText(17); }
ml = lvi.FindControl("cColumnHeader105ml") as Label;
if (ml != null) { ml.Text = ColumnHeaderText(18); }
}
protected void GridFill(ListViewItem lvi, DataTable dt, DataRow dr, bool bInsert)
{
RoboCoder.WebControls.ComboBox cbb = null;
cbb = (RoboCoder.WebControls.ComboBox)lvi.FindControl("cCultureId105");
if (cbb != null)
{
if (cbb.SelectedValue != string.Empty)
{
dr["CultureId105"] = cbb.SelectedValue;
dr["CultureId105Text"] = cbb.SelectedText;
}
else
{
dr["CultureId105"] = System.DBNull.Value;
dr["CultureId105Text"] = System.DBNull.Value;
}
}
TextBox tb = null;
tb = (TextBox)lvi.FindControl("cColumnHeader105");
if (tb != null)
{
if (tb.Text != string.Empty) {dr["ColumnHeader105"] = tb.Text;} else {dr["ColumnHeader105"] = System.DBNull.Value;}
}
if (bInsert) { dt.Rows.InsertAt(dr, 0); }
Session[KEY_dtAdmScreenCriGrid] = dt;
cAdmScreenCriGrid.EditIndex = -1;
cAdmScreenCriGrid_DataBind(dt.DefaultView);
}
protected void cAdmScreenCriGrid_OnItemUpdating(object sender, ListViewUpdateEventArgs e)
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
if (dt != null && dt.Rows.Count > 0)
{
DataRow dr = dt.DefaultView[GetDataItemIndex(e.ItemIndex)].Row;
GridFill(cAdmScreenCriGrid.EditItem, dt, dr, false);
dr["_NewRow"] = "N";
if (dt.Columns.Contains("_SortOrder")) dr["_SortOrder"] = null;
}
}
protected void cAdmScreenCriGrid_OnItemCanceling(object sender, ListViewCancelEventArgs e)
{
PanelTop.Update();
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
DataView dv = dt != null ? dt.DefaultView : null;
if (dv != null && dv[GetDataItemIndex(e.ItemIndex)]["_NewRow"].ToString() == "Y")
{
cAdmScreenCriGrid_OnItemDeleting(sender, new ListViewDeleteEventArgs(e.ItemIndex));
}
if (dt.Columns.Contains("_SortOrder")) dt.DefaultView[GetDataItemIndex(e.ItemIndex)].Row["_SortOrder"] = null;
cAdmScreenCriGrid.EditIndex = -1; cAdmScreenCriGrid_DataBind(null);
}
protected void cDeleteAllButton_Click(object sender, System.EventArgs e)
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
DataView dv = dt != null ? dt.DefaultView : null;
if (dv != null && (cAdmScreenCriGrid.EditIndex < 0 || UpdateGridRow(sender, new CommandEventArgs("Save", ""))))
{
GotoPage(0);
while (dv.Count > 0) {dv.Delete(0);}
Session[KEY_dtAdmScreenCriGrid] = dt;
cAdmScreenCriGrid.EditIndex = -1; cAdmScreenCriGrid_DataBind(dv);
}
}
protected void cAdmScreenCriGrid_OnItemDeleting(object sender, ListViewDeleteEventArgs e)
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
DataView dv = dt != null ? dt.DefaultView : null;
DataRow dr = dv != null ? dv[GetDataItemIndex(e.ItemIndex)].Row : null;
if (dv != null && (cAdmScreenCriGrid.EditIndex == e.ItemIndex || UpdateGridRow(sender, new CommandEventArgs("Save",""))))
{
// *** Delete Grid Row (before) Web Rule End *** //
dr.Delete();
Session[KEY_dtAdmScreenCriGrid] = dt;
cAdmScreenCriGrid.EditIndex = -1; cAdmScreenCriGrid_DataBind(dv);
}
}
public void cNewSaveButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
try {
string msg = SaveDb(sender, new EventArgs());
cNewButton_Click(sender, new EventArgs());
if (msg != string.Empty && Config.PromptMsg) { bInfoNow.Value = "Y"; PreMsgPopup(msg); }
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
// *** System Button Click (After) Web Rule starts here *** //
}
public void cNewButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
cAdmScreenCri73List.ClearSearch(); Session.Remove(KEY_dtAdmScreenCri73List);
PopAdmScreenCri73List(sender, e, false, null);
// *** System Button Click (After) Web Rule starts here *** //
}
public void cClearButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
ClearMaster(sender, e);
cDeleteAllButton_Click(sender, new EventArgs());
// *** System Button Click (After) Web Rule starts here *** //
}
public void cCopyButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
cScreenCriId104.Text = string.Empty;
cAdmScreenCri73List.ClearSearch(); Session.Remove(KEY_dtAdmScreenCri73List);
ShowDirty(true);
// *** System Button Click (After) Web Rule starts here *** //
}
public void cCopySaveButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
try {
string msg = SaveDb(sender, new EventArgs());
cCopyButton_Click(sender, new EventArgs());
if (msg != string.Empty && Config.PromptMsg) { bInfoNow.Value = "Y"; PreMsgPopup(msg); }
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
// *** System Button Click (After) Web Rule starts here *** //
}
public void cUndoAllButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
if (cScreenCriId104.Text == string.Empty) { cClearButton_Click(sender, new EventArgs()); ShowDirty(false); PanelTop.Update();}
else { PopAdmScreenCri73List(sender, e, false, cScreenCriId104.Text); }
// *** System Button Click (After) Web Rule starts here *** //
}
public void cPreviewButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
// *** System Button Click (After) Web Rule starts here *** //
}
public void cEditButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
cScreenSearch.Visible = true;
cSystem.Visible = true;
bUseCri.Value = "Y"; GetCriteria(GetScrCriteria());
Session.Remove(KEY_dtAdmScreenCri73List); PopAdmScreenCri73List(sender, e, false, null);
cEditButton.Visible = false;
// *** System Button Click (After) Web Rule starts here *** //
}
public void cSaveCloseButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
try {
string msg = SaveDb(sender, new EventArgs());
if (msg != string.Empty)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "closeDlg", @"<script type='text/javascript'>window.parent.closeParentDlg();</script>", false);
}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
// *** System Button Click (After) Web Rule starts here *** //
}
private string SaveDb(object sender, System.EventArgs e)
{
string rtn = string.Empty;
// *** System Button Click (Before) Web Rule starts here *** //
string pid = string.Empty;
if (ValidPage() && (cAdmScreenCriGrid.EditIndex < 0 || UpdateGridRow(cAdmScreenCriGrid, new CommandEventArgs("Save", ""))))
{
DataTable dt = (DataTable)Session[KEY_dtAdmScreenCriGrid];
DataView dv = dt != null ? dt.DefaultView : null;
string ftr = string.Empty;
if (dv.RowFilter != string.Empty) { ftr = dv.RowFilter; dv.RowFilter = string.Empty; }
AdmScreenCri73 ds = PrepAdmScreenCriData(dv,cScreenCriId104.Text == string.Empty);
if (ftr != string.Empty) {dv.RowFilter = ftr;}
if (string.IsNullOrEmpty(cAdmScreenCri73List.SelectedValue)) // Add
{
if (ds != null)
{
pid = (new AdminSystem()).AddData(73,false,base.LUser,base.LImpr,base.LCurr,ds,(string)Session[KEY_sysConnectionString],LcAppPw,base.CPrj,base.CSrc);
}
if (!string.IsNullOrEmpty(pid))
{
cAdmScreenCri73List.ClearSearch(); Session.Remove(KEY_dtAdmScreenCri73List);
ShowDirty(false); bUseCri.Value = "Y"; PopAdmScreenCri73List(sender, e, false, pid);
rtn = GetScreenHlp().Rows[0]["AddMsg"].ToString();
}
}
else {
bool bValid7 = false;
if (ds != null && (new AdminSystem()).UpdData(73,false,base.LUser,base.LImpr,base.LCurr,ds,(string)Session[KEY_sysConnectionString],LcAppPw,base.CPrj,base.CSrc)) {bValid7 = true;}
if (bValid7)
{
cAdmScreenCri73List.ClearSearch(); Session.Remove(KEY_dtAdmScreenCri73List);
Session[KEY_currPageIndex] = GetCurrPageIndex();
ShowDirty(false); PopAdmScreenCri73List(sender, e, false, ds.Tables["AdmScreenCri"].Rows[0]["ScreenCriId104"]);
rtn = GetScreenHlp().Rows[0]["UpdMsg"].ToString();
}
}
}
// *** System Button Click (After) Web Rule starts here *** //
return rtn;
}
public void cSaveButton_Click(object sender, System.EventArgs e)
{
try {
string msg = SaveDb(sender, e);
if (msg != string.Empty && Config.PromptMsg) { bInfoNow.Value = "Y"; PreMsgPopup(msg); }
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
}
public void cDeleteButton_Click(object sender, System.EventArgs e)
{
// *** System Button Click (Before) Web Rule starts here *** //
if (cScreenCriId104.Text != string.Empty)
{
AdmScreenCri73 ds = PrepAdmScreenCriData(null,false);
try
{
if (ds != null && (new AdminSystem()).DelData(73,false,base.LUser,base.LImpr,base.LCurr,ds,(string)Session[KEY_sysConnectionString],LcAppPw,base.CPrj,base.CSrc))
{
cAdmScreenCri73List.ClearSearch(); Session.Remove(KEY_dtAdmScreenCri73List);
ShowDirty(false); PopAdmScreenCri73List(sender, e, false, null);
if (Config.PromptMsg) {bInfoNow.Value = "Y"; PreMsgPopup(GetScreenHlp().Rows[0]["DelMsg"].ToString());}
}
}
catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; }
}
// *** System Button Click (After) Web Rule starts here *** //
}
private AdmScreenCri73 PrepAdmScreenCriData(DataView dv, bool bAdd)
{
AdmScreenCri73 ds = new AdmScreenCri73();
DataRow dr = ds.Tables["AdmScreenCri"].NewRow();
DataRow drType = ds.Tables["AdmScreenCri"].NewRow();
DataRow drDisp = ds.Tables["AdmScreenCri"].NewRow();
if (bAdd) { dr["ScreenCriId104"] = string.Empty; } else { dr["ScreenCriId104"] = cScreenCriId104.Text; }
drType["ScreenCriId104"] = "Numeric"; drDisp["ScreenCriId104"] = "TextBox";
try {dr["ScreenId104"] = cScreenId104.SelectedValue;} catch {}
drType["ScreenId104"] = "Numeric"; drDisp["ScreenId104"] = "AutoComplete";
try {dr["LabelCss104"] = cLabelCss104.Text.Trim();} catch {}
drType["LabelCss104"] = "VarChar"; drDisp["LabelCss104"] = "TextBox";
try {dr["ContentCss104"] = cContentCss104.Text.Trim();} catch {}
drType["ContentCss104"] = "VarChar"; drDisp["ContentCss104"] = "TextBox";
try {dr["ColumnId104"] = cColumnId104.SelectedValue;} catch {}
drType["ColumnId104"] = "Numeric"; drDisp["ColumnId104"] = "AutoComplete";
try {dr["OperatorId104"] = cOperatorId104.SelectedValue;} catch {}
drType["OperatorId104"] = "Numeric"; drDisp["OperatorId104"] = "DropDownList";
try {dr["DisplayModeId104"] = cDisplayModeId104.SelectedValue;} catch {}
drType["DisplayModeId104"] = "Numeric"; drDisp["DisplayModeId104"] = "DropDownList";
try {dr["TabIndex104"] = cTabIndex104.Text.Trim();} catch {}
drType["TabIndex104"] = "Numeric"; drDisp["TabIndex104"] = "TextBox";
try {dr["RequiredValid104"] = base.SetBool(cRequiredValid104.Checked);} catch {}
drType["RequiredValid104"] = "Char"; drDisp["RequiredValid104"] = "CheckBox";
try {dr["ColumnJustify104"] = cColumnJustify104.SelectedValue;} catch {}
drType["ColumnJustify104"] = "Char"; drDisp["ColumnJustify104"] = "DropDownList";
try {dr["ColumnSize104"] = cColumnSize104.Text.Trim();} catch {}
drType["ColumnSize104"] = "Numeric"; drDisp["ColumnSize104"] = "TextBox";
try {dr["RowSize104"] = cRowSize104.Text.Trim();} catch {}
drType["RowSize104"] = "Numeric"; drDisp["RowSize104"] = "TextBox";
try {dr["DdlKeyColumnId104"] = cDdlKeyColumnId104.SelectedValue;} catch {}
drType["DdlKeyColumnId104"] = "Numeric"; drDisp["DdlKeyColumnId104"] = "AutoComplete";
try {dr["DdlRefColumnId104"] = cDdlRefColumnId104.SelectedValue;} catch {}
drType["DdlRefColumnId104"] = "Numeric"; drDisp["DdlRefColumnId104"] = "AutoComplete";
try {dr["DdlSrtColumnId104"] = cDdlSrtColumnId104.SelectedValue;} catch {}
drType["DdlSrtColumnId104"] = "Numeric"; drDisp["DdlSrtColumnId104"] = "AutoComplete";
try {dr["DdlFtrColumnId104"] = cDdlFtrColumnId104.SelectedValue;} catch {}
drType["DdlFtrColumnId104"] = "Numeric"; drDisp["DdlFtrColumnId104"] = "AutoComplete";
if (dv != null)
{
ds.Tables["AdmScreenCriDef"].Rows.Add(MakeTypRow(ds.Tables["AdmScreenCriDef"].NewRow()));
ds.Tables["AdmScreenCriDef"].Rows.Add(MakeDisRow(ds.Tables["AdmScreenCriDef"].NewRow()));
if (bAdd)
{
foreach (DataRowView drv in dv)
{
ds.Tables["AdmScreenCriAdd"].Rows.Add(MakeColRow(ds.Tables["AdmScreenCriAdd"].NewRow(), drv, true));
}
}
else
{
dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
foreach (DataRowView drv in dv)
{
ds.Tables["AdmScreenCriUpd"].Rows.Add(MakeColRow(ds.Tables["AdmScreenCriUpd"].NewRow(), drv, false));
}
dv.RowStateFilter = DataViewRowState.Added;
foreach (DataRowView drv in dv)
{
ds.Tables["AdmScreenCriAdd"].Rows.Add(MakeColRow(ds.Tables["AdmScreenCriAdd"].NewRow(), drv, true));
}
dv.RowStateFilter = DataViewRowState.Deleted;
foreach (DataRowView drv in dv)
{
ds.Tables["AdmScreenCriDel"].Rows.Add(MakeColRow(ds.Tables["AdmScreenCriDel"].NewRow(), drv, false));
}
dv.RowStateFilter = DataViewRowState.CurrentRows;
}
}
ds.Tables["AdmScreenCri"].Rows.Add(dr); ds.Tables["AdmScreenCri"].Rows.Add(drType); ds.Tables["AdmScreenCri"].Rows.Add(drDisp);
return ds;
}
public bool CanAct(char typ) { return CanAct(typ, GetAuthRow(), cAdmScreenCri73List.SelectedValue.ToString()); }
private bool ValidPage()
{
EnableValidators(true);
Page.Validate();
if (!Page.IsValid) { PanelTop.Update(); return false; }
DataTable dt = null;
dt = (DataTable)Session[KEY_dtScreenId104];
if (dt != null && dt.Rows.Count <= 0)
{
bErrNow.Value = "Y"; PreMsgPopup("Value is expected for 'ScreenId', please investigate."); return false;
}
dt = (DataTable)Session[KEY_dtColumnId104];
if (dt != null && dt.Rows.Count <= 0)
{
bErrNow.Value = "Y"; PreMsgPopup("Value is expected for 'ColumnId', please investigate."); return false;
}
dt = (DataTable)Session[KEY_dtOperatorId104];
if (dt != null && dt.Rows.Count <= 0)
{
bErrNow.Value = "Y"; PreMsgPopup("Value is expected for 'OperatorId', please investigate."); return false;
}
dt = (DataTable)Session[KEY_dtDisplayModeId104];
if (dt != null && dt.Rows.Count <= 0)
{
bErrNow.Value = "Y"; PreMsgPopup("Value is expected for 'DisplayModeId', please investigate."); return false;
}
dt = (DataTable)Session[KEY_dtColumnJustify104];
if (dt != null && dt.Rows.Count <= 0)
{
bErrNow.Value = "Y"; PreMsgPopup("Value is expected for 'ColumnJustify', please investigate."); return false;
}
dt = (DataTable)Session[KEY_dtCultureId105];
if (dt != null && dt.Rows.Count <= 0)
{
bErrNow.Value = "Y"; PreMsgPopup("Value is expected for 'CultureId', please investigate."); return false;
}
return true;
}
private DataRow MakeTypRow(DataRow dr)
{
dr["ScreenCriId104"] = System.Data.OleDb.OleDbType.Numeric.ToString();
dr["ScreenCriHlpId105"] = System.Data.OleDb.OleDbType.Numeric.ToString();
dr["CultureId105"] = System.Data.OleDb.OleDbType.Numeric.ToString();
dr["ColumnHeader105"] = System.Data.OleDb.OleDbType.VarWChar.ToString();
return dr;
}
private DataRow MakeDisRow(DataRow dr)
{
dr["ScreenCriId104"] = "TextBox";
dr["ScreenCriHlpId105"] = "TextBox";
dr["CultureId105"] = "AutoComplete";
dr["ColumnHeader105"] = "TextBox";
return dr;
}
private DataRow MakeColRow(DataRow dr, DataRowView drv, bool bAdd)
{
dr["ScreenCriId104"] = cScreenCriId104.Text;
DataTable dtAuth = GetAuthCol();
if (dtAuth != null)
{
dr["ScreenCriHlpId105"] = drv["ScreenCriHlpId105"].ToString().Trim();
dr["CultureId105"] = drv["CultureId105"];
dr["ColumnHeader105"] = drv["ColumnHeader105"].ToString().Trim();
if (bAdd && dtAuth.Rows[18]["ColReadOnly"].ToString() == "Y" && dr["ColumnHeader105"].ToString() == string.Empty) {dr["ColumnHeader105"] = System.DBNull.Value;}
}
return dr;
}
private bool UpdateGridRow(object sender, CommandEventArgs e)
{
if (cAdmScreenCriGrid.EditIndex > -1)
{
TextBox pwd = null; cAdmScreenCriGrid_OnItemUpdating(sender, new ListViewUpdateEventArgs(cAdmScreenCriGrid.EditIndex));
}
return true;
}
protected void cAdmScreenCriGrid_OnPreRender(object sender, System.EventArgs e)
{
System.Web.UI.WebControls.Image hi = null;
hi = (System.Web.UI.WebControls.Image)cAdmScreenCriGrid.FindControl("cScreenCriHlpId105hi"); if (hi != null) { hi.Visible = false; }
hi = (System.Web.UI.WebControls.Image)cAdmScreenCriGrid.FindControl("cCultureId105hi"); if (hi != null) { hi.Visible = false; }
hi = (System.Web.UI.WebControls.Image)cAdmScreenCriGrid.FindControl("cColumnHeader105hi"); if (hi != null) { hi.Visible = false; }
if (Session[KEY_lastSortImg] != null)
{
hi = (System.Web.UI.WebControls.Image)cAdmScreenCriGrid.FindControl((string)Session[KEY_lastSortImg]);
if (hi != null) { hi.ImageUrl = Utils.AddTilde((string)Session[KEY_lastSortUrl]); hi.Visible = true; }
}
IgnoreHeaderConfirm((LinkButton)cAdmScreenCriGrid.FindControl("cScreenCriHlpId105hl"));
IgnoreHeaderConfirm((LinkButton)cAdmScreenCriGrid.FindControl("cCultureId105hl"));
IgnoreHeaderConfirm((LinkButton)cAdmScreenCriGrid.FindControl("cColumnHeader105hl"));
}
private string GetButtonId(ListViewItem lvi)
{
string ButtonID = String.Empty;
Control c = lvi.FindControl("cAdmScreenCriGridEdit");
if (c != null) { ButtonID = c.UniqueID; }
return ButtonID;
}
private void SetDefaultCtrl(HtmlTableRow tr, LinkButton lb, string ctrlId)
{
tr.Attributes.Add("onclick", "document.getElementById('" + bConfirm.ClientID + "').value='N'; fFocusedEdit('" + lb.UniqueID + "','" + ctrlId + "',event);");
}
private int GetCurrPageIndex()
{
return cAdmScreenCriGridDataPager.StartRowIndex / cAdmScreenCriGridDataPager.PageSize;
}
private int GetTotalPages()
{
return (int)Math.Ceiling((double)cAdmScreenCriGridDataPager.TotalRowCount / cAdmScreenCriGridDataPager.PageSize);
}
private int GetDataItemIndex(int editIndex)
{
return cAdmScreenCriGridDataPager.StartRowIndex + editIndex;
}
protected void cAdmScreenCriGrid_OnLayoutCreated(object sender, EventArgs e)
{
// Header:
LinkButton lb = null;
lb = cAdmScreenCriGrid.FindControl("cScreenCriHlpId105hl") as LinkButton;
if (lb != null) { lb.Text = ColumnHeaderText(16); lb.ToolTip = ColumnToolTip(16); lb.Parent.Visible = GridColumnVisible(16); }
lb = cAdmScreenCriGrid.FindControl("cCultureId105hl") as LinkButton;
if (lb != null) { lb.Text = ColumnHeaderText(17); lb.ToolTip = ColumnToolTip(17); lb.Parent.Visible = GridColumnVisible(17); }
lb = cAdmScreenCriGrid.FindControl("cColumnHeader105hl") as LinkButton;
if (lb != null) { lb.Text = ColumnHeaderText(18); lb.ToolTip = ColumnToolTip(18); lb.Parent.Visible = GridColumnVisible(18); }
// Hide DeleteAll:
DataTable dtAuthRow = GetAuthRow();
if (dtAuthRow != null)
{
DataRow dr = dtAuthRow.Rows[0];
if ((dr["AllowUpd"].ToString() == "N" && dr["AllowAdd"].ToString() == "N") || dr["ViewOnly"].ToString() == "G" || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N"))
{
lb = cAdmScreenCriGrid.FindControl("cDeleteAllButton") as LinkButton; if (lb != null) { lb.Visible = false; }
}
}
// footer:
Label gc = null;
gc = cAdmScreenCriGrid.FindControl("cScreenCriHlpId105fl") as Label;
if (gc != null) { gc.Parent.Visible = GridColumnVisible(16); }
gc = cAdmScreenCriGrid.FindControl("cCultureId105fl") as Label;
if (gc != null) { gc.Parent.Visible = GridColumnVisible(17); }
gc = cAdmScreenCriGrid.FindControl("cColumnHeader105fl") as Label;
if (gc != null) { gc.Parent.Visible = GridColumnVisible(18); }
}
protected void cbPostBack(object sender, System.EventArgs e)
{
}
protected void IgnoreHeaderConfirm(LinkButton lb)
{
if (lb != null && (lb.Attributes["OnClick"] == null || lb.Attributes["OnClick"].IndexOf("_bConfirm") < 0) && lb.Visible) { lb.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';"; }
}
protected void IgnoreConfirm()
{
if (cExpTxtButton.Attributes["OnClick"] == null || cExpTxtButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cExpTxtButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cExpRtfButton.Attributes["OnClick"] == null || cExpRtfButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cExpRtfButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cUndoAllButton.Attributes["OnClick"] == null || cUndoAllButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cUndoAllButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cSaveCloseButton.Attributes["OnClick"] == null || cSaveCloseButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cSaveCloseButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cSaveButton.Attributes["OnClick"] == null || cSaveButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cSaveButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cInsRowButton.Attributes["OnClick"] == null || cInsRowButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cInsRowButton.Attributes["onclick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cBrowse.Attributes["OnClick"] == null || cBrowse.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cBrowse.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cPgSizeButton.Attributes["OnClick"] == null || cPgSizeButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cPgSizeButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cFirstButton.Attributes["OnClick"] == null || cFirstButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cFirstButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cPrevButton.Attributes["OnClick"] == null || cPrevButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cPrevButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cNextButton.Attributes["OnClick"] == null || cNextButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cNextButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cLastButton.Attributes["OnClick"] == null || cLastButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cLastButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cFindButton.Attributes["OnClick"] == null || cFindButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cFindButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cHideImpButton.Attributes["OnClick"] == null || cHideImpButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cHideImpButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cShowImpButton.Attributes["OnClick"] == null || cShowImpButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cShowImpButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cNewSaveButton.Attributes["OnClick"] == null || cNewSaveButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cNewSaveButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cCopySaveButton.Attributes["OnClick"] == null || cCopySaveButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cCopySaveButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";}
if (cDeleteButton.Attributes["OnClick"] == null || cDeleteButton.Attributes["OnClick"].IndexOf("return confirm") < 0) {cDeleteButton.Attributes["OnClick"] += "return confirm('Delete this record for sure?');";}
if (cClearButton.Attributes["OnClick"] == null || cClearButton.Attributes["OnClick"].IndexOf("return confirm") < 0) {cClearButton.Attributes["OnClick"] += "return confirm('Clear this record for sure and assume initial defaulted values except non-editable fields? You may click the New button if you wish to create a new record instead.');";}
}
protected void InitPreserve()
{
cSystemId.Attributes["onchange"] = "javascript:return CanPostBack(true,this);";cSystemId.Attributes["NeedConfirm"] = "Y";
cFilterId.Attributes["onchange"] = "javascript:return CanPostBack(true,this);";cFilterId.Attributes["NeedConfirm"] = "Y";
}
protected void ShowDirty(bool bShow)
{
if (bShow) {bPgDirty.Value = "Y";} else {bPgDirty.Value = "N";}
}
private void PreMsgPopup(string msg) { PreMsgPopup(msg,cAdmScreenCri73List,null); }
private void PreMsgPopup(string msg, RoboCoder.WebControls.ComboBox cb, WebControl wc)
{
if (string.IsNullOrEmpty(msg)) return;
int MsgPos = msg.IndexOf("RO.SystemFramewk.ApplicationAssert");
string iconUrl = "images/warning.gif";
string focusOnCloseId = cb != null ? cb.FocusID : (wc != null ? wc.ClientID : string.Empty);
string msgContent = ReformatErrMsg(msg);
if (MsgPos >= 0 && LUser.TechnicalUsr != "Y") { msgContent = ReformatErrMsg(msg.Substring(0, MsgPos - 3)); }
if (bErrNow.Value == "Y") { iconUrl = "images/error.gif"; bErrNow.Value = "N"; }
else if (bInfoNow.Value == "Y") { iconUrl = "images/info.gif"; bInfoNow.Value = "N"; }
string script =
@"<script type='text/javascript' lang='javascript'>
PopDialog('" + iconUrl + "','" + msgContent.Replace(@"\", @"\\").Replace("'", @"\'") + "','" + focusOnCloseId + @"');
</script>";
ScriptManager.RegisterStartupScript(cMsgContent, typeof(Label), "Popup", script, false);
}
private Control FindEditableControl(Control root)
{
Control found = null;
if (IsEditableControl(root)) { found = root; return found; }
foreach (Control c in root.Controls)
{
found = FindEditableControl(c); if (found != null) return found;
}
return null;
}
}
}
| 56.156323
| 634
| 0.672684
|
[
"Apache-2.0"
] |
fintrux-team/Low-Code-Development-Platform
|
Web/modules/AdmScreenCriModule.ascx.cs
| 191,830
|
C#
|
using QuoteShared;
namespace QuoteClient.Akka.Messages
{
public class RfqReceived
{
public RfqReceived(RFQ rfq)
{
RFQ = rfq;
}
public RFQ RFQ { get; }
}
}
| 14.266667
| 35
| 0.53271
|
[
"MIT"
] |
goblinfactory/10-alternatives-to-akka
|
QuoteClient.Akka/Messages/RfqReceived.cs
| 216
|
C#
|
using System;
using System.Threading.Tasks;
using AElf.Kernel;
using AElf.Kernel.Blockchain.Application;
using AElf.Kernel.SmartContract.Application;
using AElf.OS;
using AElf.Types;
using BenchmarkDotNet.Attributes;
using Google.Protobuf.WellKnownTypes;
namespace AElf.Benchmark
{
[MarkdownExporterAttribute.GitHub]
public class Fibonacci16Tests : BenchmarkTestBase
{
private IBlockchainService _blockchainService;
private ITransactionReadOnlyExecutionService _transactionReadOnlyExecutionService;
private OSTestHelper _osTestHelper;
private Transaction _transaction;
private Block _block;
private Address _contractAddress;
private Chain _chain;
private TransactionTrace _transactionTrace;
private const ulong _fibonacci16Result =987;
[GlobalSetup]
public async Task GlobalSetup()
{
_blockchainService = GetRequiredService<IBlockchainService>();
_transactionReadOnlyExecutionService = GetRequiredService<ITransactionReadOnlyExecutionService>();
_osTestHelper = GetRequiredService<OSTestHelper>();
_contractAddress = await _osTestHelper.DeployContract<PerformanceTestContract.PerformanceTestContract>();
_chain = await _blockchainService.GetChainAsync();
}
[IterationSetup]
public async Task IterationSetup()
{
_transaction = _osTestHelper.GenerateTransaction(SampleAddress.AddressList[0], _contractAddress,
nameof(PerformanceTestContract.PerformanceTestContract.Fibonacci), new UInt64Value
{
Value = 16
});
}
[Benchmark]
public async Task Fibonacci16()
{
_transactionTrace = await _transactionReadOnlyExecutionService.ExecuteAsync(new ChainContext
{
BlockHash = _chain.BestChainHash,
BlockHeight = _chain.BestChainHeight
},
_transaction,
TimestampHelper.GetUtcNow());
}
[IterationCleanup]
public async Task IterationCleanup()
{
var calResult = UInt64Value.Parser.ParseFrom(_transactionTrace.ReturnValue).Value;
if (calResult != _fibonacci16Result)
{
throw new Exception("execute fail");
}
}
}
}
| 34.464789
| 117
| 0.653862
|
[
"MIT"
] |
IamWenboZhang/AElf
|
bench/AElf.Benchmark/Fibonacci16Tests.cs
| 2,447
|
C#
|
#if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
using System;
using System.Runtime.InteropServices;
public class AkMIDIPost : IDisposable {
private IntPtr swigCPtr;
protected bool swigCMemOwn;
internal AkMIDIPost(IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
internal static IntPtr getCPtr(AkMIDIPost obj) {
return (obj == null) ? IntPtr.Zero : obj.swigCPtr;
}
~AkMIDIPost() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
AkSoundEnginePINVOKE.CSharp_delete_AkMIDIPost(swigCPtr);
}
swigCPtr = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
}
public uint uOffset {
set {
AkSoundEnginePINVOKE.CSharp_AkMIDIPost_uOffset_set(swigCPtr, value);
}
get {
uint ret = AkSoundEnginePINVOKE.CSharp_AkMIDIPost_uOffset_get(swigCPtr);
return ret;
}
}
public AkMIDIPost() : this(AkSoundEnginePINVOKE.CSharp_new_AkMIDIPost(), true) {
}
}
#endif // #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
| 28.393443
| 161
| 0.619515
|
[
"MIT"
] |
JackM36/Chickie-Mayhem
|
Assets/Wwise/Deployment/API/Generated/Common/AkMIDIPost.cs
| 1,732
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AdaptiveExpressions.Properties;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Adaptive.Recognizers;
using Microsoft.Bot.Builder.TraceExtensions;
using Microsoft.BotFramework.Orchestrator;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Bot.Builder.AI.Orchestrator
{
/// <summary>
/// Class that represents an adaptive Orchestrator recognizer.
/// </summary>
public class OrchestratorRecognizer : AdaptiveRecognizer
{
/// <summary>
/// The Kind name for this recognizer.
/// </summary>
[JsonProperty("$kind")]
public const string Kind = "Microsoft.OrchestratorRecognizer";
/// <summary>
/// Property key in RecognizerResult that holds the full recognition result from Orchestrator core.
/// </summary>
public const string ResultProperty = "result";
/// <summary>
/// Property key used when storing extracted entities in a custom event within telemetry.
/// </summary>
public const string EntitiesProperty = "entityResult";
private const float UnknownIntentFilterScore = 0.4F;
private static ConcurrentDictionary<string, OrchestratorDictionaryEntry> orchestratorMap = new ConcurrentDictionary<string, OrchestratorDictionaryEntry>();
private OrchestratorDictionaryEntry _orchestrator = null;
private ILabelResolver _resolver = null;
private bool _isResolverMockup = false;
/// <summary>
/// Initializes a new instance of the <see cref="OrchestratorRecognizer"/> class.
/// </summary>
/// <param name="callerLine">Caller line.</param>
/// <param name="callerPath">Caller path.</param>
[JsonConstructor]
public OrchestratorRecognizer([CallerFilePath] string callerPath = "", [CallerLineNumber] int callerLine = 0)
: base(callerPath, callerLine)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OrchestratorRecognizer"/> class.
/// </summary>
/// <param name="modelFolder">Specifies the base model folder.</param>
/// <param name="snapshotFile">Specifies full path to the snapshot file.</param>
/// <param name="resolverExternal">External label resolver object.</param>
public OrchestratorRecognizer(string modelFolder, string snapshotFile, ILabelResolver resolverExternal = null)
{
InitializeModel(modelFolder, snapshotFile, resolverExternal);
}
/// <summary>
/// Gets or sets the folder path to Orchestrator base model to use.
/// </summary>
/// <value>
/// Model path.
/// </value>
[JsonProperty("modelFolder")]
public StringExpression ModelFolder { get; set; } = "=settings.orchestrator.modelFolder";
/// <summary>
/// Gets or sets the full path to Orchestrator snapshot file to use.
/// </summary>
/// <value>
/// Snapshot path.
/// </value>
[JsonProperty("snapshotFile")]
public StringExpression SnapshotFile { get; set; } = "=settings.orchestrator.snapshotFile";
/// <summary>
/// Gets or sets an external entity recognizer.
/// </summary>
/// <remarks>This recognizer is run before calling Orchestrator and the entities are merged with Orchestrator results.</remarks>
/// <value>Recognizer.</value>
[JsonProperty("externalEntityRecognizer")]
public Recognizer ExternalEntityRecognizer { get; set; }
/// <summary>
/// Gets or sets the disambiguation score threshold.
/// </summary>
/// <value>
/// Recognizer returns ChooseIntent (disambiguation) if other intents are classified within this threshold of the top scoring intent.
/// </value>
[JsonProperty("disambiguationScoreThreshold")]
public NumberExpression DisambiguationScoreThreshold { get; set; } = 0.05F;
/// <summary>
/// Gets or sets detect ambiguous intents.
/// </summary>
/// <value>
/// When true, recognizer will look for ambiguous intents - those within specified threshold to top scoring intent.
/// </value>
[JsonProperty("detectAmbiguousIntents")]
public BoolExpression DetectAmbiguousIntents { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether to enable or disable entity-extraction logic.
/// NOTE: SHOULD consider removing this flag in the next major SDK release (V5).
/// </summary>
/// <value>
/// The flag for enabling or disabling entity-extraction function.
/// </value>
public bool ScoreEntities { get; set; } = true;
/// <summary>
/// Return recognition results.
/// </summary>
/// <param name="dc">Context object containing information for a single turn of conversation with a user.</param>
/// <param name="activity">The incoming activity received from the user. The Text property value is used as the query text for QnA Maker.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
/// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
/// <returns>A <see cref="RecognizerResult"/> containing the QnA Maker result.</returns>
public override async Task<RecognizerResult> RecognizeAsync(DialogContext dc, Schema.Activity activity, CancellationToken cancellationToken, Dictionary<string, string> telemetryProperties = null, Dictionary<string, double> telemetryMetrics = null)
{
if (_resolver == null)
{
string modelFolder = ModelFolder.GetValue(dc.State);
string snapshotFile = SnapshotFile.GetValue(dc.State);
InitializeModel(modelFolder, snapshotFile, null);
}
var text = activity.Text ?? string.Empty;
var detectAmbiguity = DetectAmbiguousIntents.GetValue(dc.State);
var recognizerResult = new RecognizerResult()
{
Text = text,
Intents = new Dictionary<string, IntentScore>(),
};
if (string.IsNullOrWhiteSpace(text))
{
// nothing to recognize, return empty recognizerResult
return recognizerResult;
}
// Score with orchestrator
var results = _resolver.Score(text)?.ToList();
if ((results != null) && results.Any())
{
// Add full recognition result as a 'result' property
recognizerResult.Properties.Add(ResultProperty, results);
var topScore = results[0].Score;
// if top scoring intent is less than threshold, return None
if (topScore < UnknownIntentFilterScore)
{
((List<Result>)recognizerResult.Properties[ResultProperty]).Insert(0, new Result() { Score = 1.0, Label = new Label() { Name = "None", Type = LabelType.Intent } });
// add all scores
foreach (var result in results)
{
recognizerResult.Intents.Add(result.Label.Name, new IntentScore()
{
Score = result.Score
});
}
}
else
{
// add top score
foreach (var result in results)
{
recognizerResult.Intents.Add(result.Label.Name, new IntentScore()
{
Score = result.Score
});
}
// Disambiguate if configured
if (detectAmbiguity)
{
var thresholdScore = DisambiguationScoreThreshold.GetValue(dc.State);
var classifyingScore = Math.Round(topScore, 2) - Math.Round(thresholdScore, 2);
var ambiguousResults = results.Where(item => item.Score >= classifyingScore).ToList();
if (ambiguousResults.Count > 1)
{
// create a RecognizerResult for each ambiguous result.
var recognizerResults = ambiguousResults.Select(result => new RecognizerResult()
{
Text = text,
AlteredText = result.ClosestText,
Entities = recognizerResult.Entities,
Properties = recognizerResult.Properties,
Intents = new Dictionary<string, IntentScore>()
{
{ result.Label.Name, new IntentScore() { Score = result.Score } }
},
});
// replace RecognizerResult with ChooseIntent => Ambiguous recognizerResults as candidates.
recognizerResult = CreateChooseIntentResult(recognizerResults.ToDictionary(result => Guid.NewGuid().ToString(), result => result));
}
}
}
}
else
{
// Return 'None' if no intent matched.
recognizerResult.Intents.Add(NoneIntent, new IntentScore() { Score = 1.0 });
}
if (ExternalEntityRecognizer != null)
{
// Run external recognition
var externalResults = await ExternalEntityRecognizer.RecognizeAsync(dc, activity, cancellationToken, telemetryProperties, telemetryMetrics).ConfigureAwait(false);
recognizerResult.Entities = externalResults.Entities;
}
TryScoreEntities(text, recognizerResult);
// Add full recognition result as a 'result' property
await dc.Context.TraceActivityAsync($"{nameof(OrchestratorRecognizer)}Result", JObject.FromObject(recognizerResult), nameof(OrchestratorRecognizer), "Orchestrator Recognition", cancellationToken).ConfigureAwait(false);
TrackRecognizerResult(dc, $"{nameof(OrchestratorRecognizer)}Result", FillRecognizerResultTelemetryProperties(recognizerResult, telemetryProperties, dc), telemetryMetrics);
return recognizerResult;
}
/// <summary>
/// Uses the RecognizerResult to create a list of properties to be included when tracking the result in telemetry.
/// </summary>
/// <param name="recognizerResult">Recognizer Result.</param>
/// <param name="telemetryProperties">A list of properties to append or override the properties created using the RecognizerResult.</param>
/// <param name="dialogContext">Dialog Context.</param>
/// <returns>A dictionary that can be included when calling the TrackEvent method on the TelemetryClient.</returns>
protected override Dictionary<string, string> FillRecognizerResultTelemetryProperties(RecognizerResult recognizerResult, Dictionary<string, string> telemetryProperties, DialogContext dialogContext = null)
{
if (dialogContext == null)
{
throw new ArgumentNullException(nameof(dialogContext), "DialogContext needed for state in AdaptiveRecognizer.FillRecognizerResultTelemetryProperties method.");
}
var orderedIntents = recognizerResult.Intents.Any() ? recognizerResult.Intents.OrderByDescending(key => key.Value.Score) : null;
var properties = new Dictionary<string, string>
{
{ "TopIntent", recognizerResult.Intents.Any() ? orderedIntents.First().Key : null },
{ "TopIntentScore", recognizerResult.Intents.Any() ? orderedIntents.First().Value?.Score?.ToString("N1", CultureInfo.InvariantCulture) : null },
{ "NextIntent", recognizerResult.Intents.Count > 1 ? orderedIntents.ElementAtOrDefault(1).Key : null },
{ "NextIntentScore", recognizerResult.Intents.Count > 1 ? orderedIntents.ElementAtOrDefault(1).Value?.Score?.ToString("N1", CultureInfo.InvariantCulture) : null },
{ "Intents", recognizerResult.Intents.Any() ? JsonConvert.SerializeObject(recognizerResult.Intents) : null },
{ "Entities", recognizerResult.Entities?.ToString() },
{ "AdditionalProperties", recognizerResult.Properties.Any() ? JsonConvert.SerializeObject(recognizerResult.Properties) : null },
};
var (logPersonalInfo, error) = LogPersonalInformation.TryGetValue(dialogContext.State);
if (logPersonalInfo && !string.IsNullOrEmpty(recognizerResult.Text))
{
properties.Add("Text", recognizerResult.Text);
properties.Add("AlteredText", recognizerResult.AlteredText);
}
// Additional Properties can override "stock" properties.
if (telemetryProperties != null)
{
return telemetryProperties.Concat(properties)
.GroupBy(kv => kv.Key)
.ToDictionary(g => g.Key, g => g.First().Value);
}
return properties;
}
private static JToken EntityResultToJObject(string text, Result result)
{
Span span = result.Label.Span;
return new JObject(
new JProperty("type", result.Label.Name),
new JProperty("score", result.Score),
new JProperty("text", text.Substring((int)span.Offset, (int)span.Length)),
new JProperty("start", (int)span.Offset),
new JProperty("end", (int)(span.Offset + span.Length)));
}
private static JToken EntityResultToInstanceJObject(string text, Result result)
{
Span span = result.Label.Span;
dynamic instance = new JObject();
instance.startIndex = (int)span.Offset;
instance.endIndex = (int)(span.Offset + span.Length);
instance.score = result.Score;
instance.text = text.Substring((int)span.Offset, (int)span.Length);
instance.type = result.Label.Name;
return instance;
}
private void TryScoreEntities(string text, RecognizerResult recognizerResult)
{
// It's impossible to extract entities without a _resolver object.
if (_resolver == null)
{
return;
}
// Entity extraction can be controlled by the ScoreEntities flag.
// NOTE: SHOULD consider removing this flag in the next major SDK release (V5).
if (!this.ScoreEntities)
{
return;
}
// The following check is necessary to ensure that the _resolver object
// is capable of entity exttraction. However, this check can also block
// a mock-up _resolver.
if (!_isResolverMockup)
{
if ((_orchestrator == null) || (!_orchestrator.IsEntityExtractionCapable))
{
return;
}
}
// As this method is TryScoreEntities, so it's best effort only, there should
// not be any exception thrown out of this method.
try
{
var results = _resolver.Score(text, LabelType.Entity);
if ((results != null) && results.Any())
{
recognizerResult.Properties.Add(EntitiesProperty, results);
if (recognizerResult.Entities == null)
{
recognizerResult.Entities = new JObject();
}
var entitiesResult = recognizerResult.Entities;
foreach (var result in results)
{
// add value
JToken values;
if (!entitiesResult.TryGetValue(result.Label.Name, StringComparison.OrdinalIgnoreCase, out values))
{
values = new JArray();
entitiesResult[result.Label.Name] = values;
}
// values came from an external entity recognizer, which may not make it a JArray.
if (values.Type != JTokenType.Array)
{
values = new JArray();
}
((JArray)values).Add(EntityResultToJObject(text, result));
// get/create $instance
JToken instanceRoot;
if (!recognizerResult.Entities.TryGetValue("$instance", StringComparison.OrdinalIgnoreCase, out instanceRoot))
{
instanceRoot = new JObject();
recognizerResult.Entities["$instance"] = instanceRoot;
}
// instanceRoot came from an external entity recognizer, which may not make it a JObject.
if (instanceRoot.Type != JTokenType.Object)
{
instanceRoot = new JObject();
}
// add instanceData
JToken instanceData;
if (!((JObject)instanceRoot).TryGetValue(result.Label.Name, StringComparison.OrdinalIgnoreCase, out instanceData))
{
instanceData = new JArray();
instanceRoot[result.Label.Name] = instanceData;
}
// instanceData came from an external entity recognizer, which may not make it a JArray.
if (instanceData.Type != JTokenType.Array)
{
instanceData = new JArray();
}
((JArray)instanceData).Add(EntityResultToInstanceJObject(text, result));
}
}
}
catch (ApplicationException)
{
return; // ---- This is a "Try" function, i.e., best effort only, no exception.
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
private void InitializeModel(string modelFolder, string snapshotFile, ILabelResolver resolverExternal = null)
{
if (resolverExternal != null)
{
_resolver = resolverExternal;
_isResolverMockup = true;
return;
}
{
if (string.IsNullOrWhiteSpace(modelFolder))
{
throw new ArgumentNullException(nameof(modelFolder));
}
if (string.IsNullOrWhiteSpace(snapshotFile))
{
throw new ArgumentNullException(nameof(snapshotFile));
}
}
var fullModelFolder = Path.GetFullPath(PathUtils.NormalizePath(modelFolder));
_orchestrator = orchestratorMap.GetOrAdd(fullModelFolder, path =>
{
// Create Orchestrator
string entityModelFolder = null;
bool isEntityExtractionCapable = false;
try
{
entityModelFolder = Path.Combine(path, "entity");
isEntityExtractionCapable = Directory.Exists(entityModelFolder);
return new OrchestratorDictionaryEntry()
{
Orchestrator = isEntityExtractionCapable ?
new BotFramework.Orchestrator.Orchestrator(path, entityModelFolder) :
new BotFramework.Orchestrator.Orchestrator(path),
IsEntityExtractionCapable = isEntityExtractionCapable
};
}
catch (Exception ex)
{
throw new InvalidOperationException(
isEntityExtractionCapable ? $"Failed to find or load Model with path {path}, entity model path {entityModelFolder}" : $"Failed to find or load Model with path {path}",
ex);
}
});
var fullSnapShotFile = Path.GetFullPath(PathUtils.NormalizePath(snapshotFile));
// Load the snapshot
byte[] snapShotByteArray = File.ReadAllBytes(fullSnapShotFile);
// Create label resolver
_resolver = this._orchestrator.Orchestrator.CreateLabelResolver(snapShotByteArray);
}
/// <summary>
/// OrchestratorDictionaryEntry is used for the static orchestratorMap object.
/// </summary>
private class OrchestratorDictionaryEntry
{
/// <summary>
/// Gets or sets the Orchestrator object.
/// </summary>
/// <value>
/// The Orchestrator object.
/// </value>
public BotFramework.Orchestrator.Orchestrator Orchestrator
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the Orchestrator object is capable of entity extraction.
/// </summary>
/// <value>
/// The IsEntityExtractionCapable flag.
/// </value>
public bool IsEntityExtractionCapable
{
get;
set;
}
}
}
}
| 45.456914
| 255
| 0.565798
|
[
"MIT"
] |
KenniVelez/botbuilder-dotnet
|
libraries/Microsoft.Bot.Builder.AI.Orchestrator/OrchestratorRecognizer.cs
| 22,685
|
C#
|
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// 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;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace ICSharpCode.Core.Presentation
{
/// <summary>
/// A tool bar button that opens a drop down menu.
/// </summary>
sealed class ToolBarDropDownButton : DropDownButton, IStatusUpdate
{
readonly Codon codon;
readonly object caller;
readonly IEnumerable<ICondition> conditions;
public ToolBarDropDownButton(Codon codon, object caller, IList subMenu, IEnumerable<ICondition> conditions)
{
ToolTipService.SetShowOnDisabled(this, true);
this.codon = codon;
this.caller = caller;
this.conditions = conditions;
this.Content = ToolBarService.CreateToolBarItemContent(codon);
if (codon.Properties.Contains("name")) {
this.Name = codon.Properties["name"];
}
this.DropDownMenu = MenuService.CreateContextMenu(subMenu);
UpdateText();
}
public void UpdateText()
{
if (codon.Properties.Contains("tooltip")) {
this.ToolTip = StringParser.Parse(codon.Properties["tooltip"]);
}
}
public void UpdateStatus()
{
if (Condition.GetFailedAction(conditions, caller) == ConditionFailedAction.Exclude)
this.Visibility = Visibility.Collapsed;
else
this.Visibility = Visibility.Visible;
}
}
}
| 35.823529
| 109
| 0.748358
|
[
"MIT"
] |
TetradogOther/SharpDevelop
|
src/Main/ICSharpCode.Core.Presentation/ToolBar/ToolBarDropDownButton.cs
| 2,438
|
C#
|
using System;
namespace _09.LeftAndRightSum
{
class Program
{
static void Main(string[] args)
{
int numN = int.Parse(Console.ReadLine());
int leftSum = 0;
int rightSum = 0;
for (int i = 0; i < numN; i++)
{
int leftNum = int.Parse(Console.ReadLine());
leftSum += leftNum;
}
for (int i = 0; i < numN; i++)
{
int rightNum = int.Parse(Console.ReadLine());
rightSum += rightNum;
}
if (leftSum == rightSum)
{
Console.WriteLine("Yes, sum = " + leftSum);
}
else
{
Console.WriteLine("No, diff = " + Math.Abs(leftSum - rightSum));
}
}
}
}
| 22.525
| 81
| 0.384018
|
[
"MIT"
] |
ivanstamboliyski/Programming-Basics-With-CSharp-Course
|
05.01 - Loops Part1 - Lab/09. Left And Right Sum/Program.cs
| 903
|
C#
|
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Zell.UiPathAutomation.Orchestrator
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for QueueProcessingRecords.
/// </summary>
public static partial class QueueProcessingRecordsExtensions
{
/// <summary>
/// Returns the computed processing status for a given queue in the last
/// specified days.
/// </summary>
/// <remarks>
/// Client Credentials Flow required permissions: Queues or Queues.Read.
///
/// Required permissions: Queues.View and Transactions.View.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='daysNo'>
/// The number of days to go back from the present moment when calculating the
/// report. If it is 0 the report will be computed for the last hour.
/// </param>
/// <param name='queueDefinitionId'>
/// The Id of the queue for which the report is computed.
/// </param>
/// <param name='expand'>
/// Indicates the related entities to be represented inline. The maximum depth
/// is 2.
/// </param>
/// <param name='filter'>
/// Restricts the set of items returned. The maximum number of expressions is
/// 100.
/// </param>
/// <param name='select'>
/// Limits the properties returned in the result.
/// </param>
/// <param name='orderby'>
/// Specifies the order in which items are returned. The maximum number of
/// expressions is 5.
/// </param>
/// <param name='count'>
/// Indicates whether the total count of items within a collection are returned
/// in the result.
/// </param>
/// <param name='xUIPATHOrganizationUnitId'>
/// Folder/OrganizationUnit Id
/// </param>
public static ODataValueOfIEnumerableOfQueueProcessingRecordDto RetrieveLastDaysProcessingRecordsByDaysnoAndQueuedefinitionid(this IQueueProcessingRecords operations, int daysNo, long queueDefinitionId, string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), bool? count = default(bool?), long? xUIPATHOrganizationUnitId = default(long?))
{
return operations.RetrieveLastDaysProcessingRecordsByDaysnoAndQueuedefinitionidAsync(daysNo, queueDefinitionId, expand, filter, select, orderby, count, xUIPATHOrganizationUnitId).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the computed processing status for a given queue in the last
/// specified days.
/// </summary>
/// <remarks>
/// Client Credentials Flow required permissions: Queues or Queues.Read.
///
/// Required permissions: Queues.View and Transactions.View.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='daysNo'>
/// The number of days to go back from the present moment when calculating the
/// report. If it is 0 the report will be computed for the last hour.
/// </param>
/// <param name='queueDefinitionId'>
/// The Id of the queue for which the report is computed.
/// </param>
/// <param name='expand'>
/// Indicates the related entities to be represented inline. The maximum depth
/// is 2.
/// </param>
/// <param name='filter'>
/// Restricts the set of items returned. The maximum number of expressions is
/// 100.
/// </param>
/// <param name='select'>
/// Limits the properties returned in the result.
/// </param>
/// <param name='orderby'>
/// Specifies the order in which items are returned. The maximum number of
/// expressions is 5.
/// </param>
/// <param name='count'>
/// Indicates whether the total count of items within a collection are returned
/// in the result.
/// </param>
/// <param name='xUIPATHOrganizationUnitId'>
/// Folder/OrganizationUnit Id
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ODataValueOfIEnumerableOfQueueProcessingRecordDto> RetrieveLastDaysProcessingRecordsByDaysnoAndQueuedefinitionidAsync(this IQueueProcessingRecords operations, int daysNo, long queueDefinitionId, string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), bool? count = default(bool?), long? xUIPATHOrganizationUnitId = default(long?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RetrieveLastDaysProcessingRecordsByDaysnoAndQueuedefinitionidWithHttpMessagesAsync(daysNo, queueDefinitionId, expand, filter, select, orderby, count, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns the processing status for all queues. Allows odata query options.
/// </summary>
/// <remarks>
/// Client Credentials Flow required permissions: Queues or Queues.Read.
///
/// Required permissions: Queues.View.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='expand'>
/// Indicates the related entities to be represented inline. The maximum depth
/// is 2.
/// </param>
/// <param name='filter'>
/// Restricts the set of items returned. The maximum number of expressions is
/// 100.
/// </param>
/// <param name='select'>
/// Limits the properties returned in the result.
/// </param>
/// <param name='orderby'>
/// Specifies the order in which items are returned. The maximum number of
/// expressions is 5.
/// </param>
/// <param name='top'>
/// Limits the number of items returned from a collection. The maximum value is
/// 1000.
/// </param>
/// <param name='skip'>
/// Excludes the specified number of items of the queried collection from the
/// result.
/// </param>
/// <param name='count'>
/// Indicates whether the total count of items within a collection are returned
/// in the result.
/// </param>
/// <param name='xUIPATHOrganizationUnitId'>
/// Folder/OrganizationUnit Id
/// </param>
public static ODataValueOfIEnumerableOfQueueProcessingStatusDto RetrieveQueuesProcessingStatus(this IQueueProcessingRecords operations, string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), int? top = default(int?), int? skip = default(int?), bool? count = default(bool?), long? xUIPATHOrganizationUnitId = default(long?))
{
return operations.RetrieveQueuesProcessingStatusAsync(expand, filter, select, orderby, top, skip, count, xUIPATHOrganizationUnitId).GetAwaiter().GetResult();
}
/// <summary>
/// Returns the processing status for all queues. Allows odata query options.
/// </summary>
/// <remarks>
/// Client Credentials Flow required permissions: Queues or Queues.Read.
///
/// Required permissions: Queues.View.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='expand'>
/// Indicates the related entities to be represented inline. The maximum depth
/// is 2.
/// </param>
/// <param name='filter'>
/// Restricts the set of items returned. The maximum number of expressions is
/// 100.
/// </param>
/// <param name='select'>
/// Limits the properties returned in the result.
/// </param>
/// <param name='orderby'>
/// Specifies the order in which items are returned. The maximum number of
/// expressions is 5.
/// </param>
/// <param name='top'>
/// Limits the number of items returned from a collection. The maximum value is
/// 1000.
/// </param>
/// <param name='skip'>
/// Excludes the specified number of items of the queried collection from the
/// result.
/// </param>
/// <param name='count'>
/// Indicates whether the total count of items within a collection are returned
/// in the result.
/// </param>
/// <param name='xUIPATHOrganizationUnitId'>
/// Folder/OrganizationUnit Id
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ODataValueOfIEnumerableOfQueueProcessingStatusDto> RetrieveQueuesProcessingStatusAsync(this IQueueProcessingRecords operations, string expand = default(string), string filter = default(string), string select = default(string), string orderby = default(string), int? top = default(int?), int? skip = default(int?), bool? count = default(bool?), long? xUIPATHOrganizationUnitId = default(long?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RetrieveQueuesProcessingStatusWithHttpMessagesAsync(expand, filter, select, orderby, top, skip, count, xUIPATHOrganizationUnitId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 51.361111
| 510
| 0.574094
|
[
"MIT"
] |
zell12/MondayAppOne
|
Zell.UiPathAutomation/Orchestrator/QueueProcessingRecordsExtensions.cs
| 11,094
|
C#
|
namespace BotsDotNet.Palringo.PacketTypes
{
using Networking.Mapping;
public class PingRequest : IPacketMap
{
public string Command => "P";
}
}
| 17
| 42
| 0.658824
|
[
"MIT"
] |
JTOne123/botsdotnet
|
BotsDotNet.Palringo/PacketTypes/PingRequest.cs
| 172
|
C#
|
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 08.05.2021.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete.NullableInt64.NullableDECIMAL_6_1{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.Int64>;
using T_DATA2 =System.Nullable<System.Decimal>;
using T_DATA1_U=System.Int64;
using T_DATA2_U=System.Decimal;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields__01__VV
public static class TestSet_001__fields__01__VV
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_BIGINT";
private const string c_NameOf__COL_DATA2 ="COL2_DEC_6_1";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2, TypeName="DECIMAL(6,1)")]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1_U c_value1=4;
const T_DATA2_U c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ == /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" = ").N("t",c_NameOf__COL_DATA2).T(") OR ((").N("t",c_NameOf__COL_DATA1).IS_NULL().T(") AND (").N("t",c_NameOf__COL_DATA2).IS_NULL().T("))) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001
//Helper methods --------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete.NullableInt64.NullableDECIMAL_6_1
| 30.907285
| 254
| 0.569959
|
[
"MIT"
] |
ibprovider/Lcpi.EFCore.LcpiOleDb
|
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/Equal/Complete/NullableInt64/NullableDECIMAL_6_1/TestSet_001__fields__01__VV.cs
| 4,669
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Ploeh.AutoFixture;
using SimpleDataGenerator.Core.Customization.Specimens;
using SimpleDataGenerator.Core.Mapping.Interfaces;
using SimpleDataGenerator.Core.Model;
namespace SimpleDataGenerator.Core.Mapping.Implementations
{
public class NumericPropertyConfiguration<TProperty> : PropertyConfiguration<TProperty>, INumericPropertyConfiguration<TProperty>
{
public NumericPropertyConfiguration(PropertyInfo propertyInfo)
:base(propertyInfo)
{
}
public void InRange(TProperty minimum, TProperty maximum)
{
AddCustomSpecimen(new RangedNumberSpecimenBuilder(SelectedProperty, new NumberRange(minimum, maximum)));
}
}
}
| 28.9
| 133
| 0.748558
|
[
"MIT"
] |
FilipPaluch/SimpleDataGenerator
|
Source/SimpleDataGenerator.Core/Mapping/Implementations/NumericPropertyConfiguration.cs
| 869
|
C#
|
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace moddingSuite.View.Edata
{
/// <summary>
/// Interaction logic for EdataManagerView.xaml
/// </summary>
public partial class EdataManagerView : Window
{
public EdataManagerView()
{
InitializeComponent();
}
}
}
| 21.235294
| 51
| 0.639889
|
[
"MIT"
] |
RemiGC/moddingSuite
|
moddingSuite/View/Edata/EdataManagerView.xaml.cs
| 363
|
C#
|
using System.Diagnostics;
using System.Diagnostics.Metrics;
namespace Stl.Fusion.Diagnostics;
public static class FusionDiagnostics
{
public static ActivitySource FusionTrace { get; } =
new("Stl.Fusion", ThisAssembly.AssemblyInformationalVersion);
public static Meter FusionMeter { get; } =
new("Stl.Fusion", ThisAssembly.AssemblyInformationalVersion);
}
| 29.307692
| 69
| 0.75853
|
[
"MIT"
] |
ScriptBox21/Stl.Fusion
|
src/Stl.Fusion/Diagnostics/FusionDiagnostics.cs
| 381
|
C#
|
#region Using directives
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle ("Wisp.Comtrade")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("Wisp.Comtrade")]
[assembly: AssemblyCopyright ("Copyright 2017")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible (false)]
// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion ("0.9.2.0")]
[assembly: CLSCompliant (true)]
[assembly: Guid ("e9dba8b8-9961-49f4-8aae-6f6de24cd366")]
| 38.233333
| 78
| 0.755013
|
[
"MIT"
] |
gabrieldelaparra/Wisp.Comtrade
|
Properties/AssemblyInfo.cs
| 1,147
|
C#
|
namespace SF.Entitys.Abstraction
{
/// <summary>
/// Version information about the entity, stored as a byte array
/// </summary>
public interface IHaveVersionAsByteArray : IHaveVersion<byte[]>
{
}
}
| 20.545455
| 68
| 0.650442
|
[
"Apache-2.0"
] |
ZHENGZHENGRONG/SF-Boilerplate
|
SF.Entitys/Abstraction/IHaveVersionAsByteArray.cs
| 228
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movementCS : MonoBehaviour {
float speed = 3.0f;
float jumpSpeed = 8.0f;
float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
// We are grounded, so recalculate
// move direction directly from axes
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0,
Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
}
}
| 25.264706
| 72
| 0.715949
|
[
"MIT"
] |
tmscarla/3DTour
|
Project/prova3D/Assets/MyYBotControlScript/movementCS.cs
| 861
|
C#
|
/*
* Notes
*/
using System;
using System.Collections.Generic;
using Rhino.Geometry;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Types;
using SpatialSlur.Rhino;
namespace SpatialSlur.Grasshopper.Components
{
/// <summary>
///
/// </summary>
public class MeshLoft : GH_Component
{
/// <summary>
///
/// </summary>
public MeshLoft()
: base("Mesh Loft", "Loft",
"Creates a mesh through a list of polylines",
"Mesh", "Util")
{
}
/// <inheritdoc />
protected override void RegisterInputParams(GH_InputParamManager pManager)
{
pManager.AddCurveParameter("polylines", "polys", "", GH_ParamAccess.list);
}
/// <inheritdoc />
protected override void RegisterOutputParams(GH_OutputParamManager pManager)
{
pManager.AddMeshParameter("result", "result", "Lofted mesh", GH_ParamAccess.item);
}
/// <inheritdoc />
protected override void SolveInstance(IGH_DataAccess DA)
{
List<Curve> curves = new List<Curve>();
if (!DA.GetDataList(0, curves)) return;
var polys = curves.ConvertAll(crv =>
{
if (!crv.TryGetPolyline(out Polyline poly))
throw new ArgumentException();
return poly;
});
var mesh = RhinoFactory.Mesh.CreateLoft(polys);
DA.SetData(0, new GH_Mesh(mesh));
}
/// <summary>
/// Provides an Icon for every component that will be visible in the User Interface.
/// Icons need to be 24x24 pixels.
/// </summary>
protected override System.Drawing.Bitmap Icon
{
get { return null; }
}
/// <summary>
/// Each component must have a unique Guid to identify it.
/// It is vital this Guid doesn't change otherwise old ghx files
/// that use the old ID will partially fail during loading.
/// </summary>
public override Guid ComponentGuid
{
get { return new Guid("{BCFCF1AE-046B-4164-AF5A-12E5EE9F71CD}"); }
}
}
}
| 25.443182
| 94
| 0.556498
|
[
"MIT"
] |
daveReeves/SpatialSlur
|
SlurGH/Components/Mesh/MeshLoft.cs
| 2,241
|
C#
|
/*************************************************************************************
Extended WPF Toolkit
Copyright (C) 2007-2013 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
For more features, controls, and fast professional support,
pick up the Plus Edition at http://xceed.com/wpf_toolkit
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using Xceed.Utils.Wpf;
namespace Xceed.Wpf.DataGrid
{
public class ObservableColumnCollection : ObservableCollection<ColumnBase>
{
#region [] Property
public ColumnBase this[ string fieldName ]
{
get
{
if( fieldName != null )
{
ColumnBase value;
if( m_fieldNameToColumn.TryGetValue( fieldName, out value ) )
return value;
}
return null;
}
}
#endregion
#region SyncRoot Private Property
private object SyncRoot
{
get
{
return ( ( ICollection )this ).SyncRoot;
}
}
#endregion
// This method has better performance than the one on the base class.
public new bool Contains( ColumnBase item )
{
if( item == null )
return false;
return object.ReferenceEquals( item, this[ item.FieldName ] );
}
protected virtual void OnItemAdding( ColumnBase item )
{
}
protected virtual void OnItemAdded( ColumnBase item )
{
}
protected virtual void OnItemRemoving( ColumnBase item )
{
}
protected virtual void OnItemRemoved( ColumnBase item )
{
}
protected override void RemoveItem( int index )
{
var item = this[ index ];
Debug.Assert( item != null );
this.OnItemRemovingCore( item );
base.RemoveItem( index );
this.OnItemRemovedCore( item );
}
protected override void InsertItem( int index, ColumnBase item )
{
if( item == null )
throw new ArgumentNullException( "item" );
var fieldName = item.FieldName;
if( string.IsNullOrEmpty( fieldName ) )
throw new ArgumentException( "A column must have a fieldname.", "item" );
if( m_fieldNameToColumn.ContainsKey( fieldName ) )
throw new DataGridException( "A column with same field name already exists in collection." );
this.OnItemAddingCore( item );
base.InsertItem( index, item );
this.OnItemAddedCore( item );
}
protected override void ClearItems()
{
var items = new List<ColumnBase>( this );
foreach( var item in items )
{
this.OnItemRemovingCore( item );
}
Debug.Assert( m_fieldNameToColumn.Count == 0 );
m_fieldNameToColumn.Clear();
base.ClearItems();
foreach( var item in items )
{
this.OnItemRemovedCore( item );
}
}
protected override void SetItem( int index, ColumnBase item )
{
if( item == null )
throw new ArgumentNullException( "item" );
var fieldName = item.FieldName;
if( string.IsNullOrEmpty( fieldName ) )
throw new ArgumentException( "A column must have a fieldname.", "item" );
var oldItem = this[ index ];
Debug.Assert( oldItem != null );
if( oldItem.FieldName != fieldName )
{
if( m_fieldNameToColumn.ContainsKey( fieldName ) )
throw new DataGridException( "A column with same field name already exists in collection." );
}
this.OnItemRemovingCore( oldItem );
this.OnItemAddingCore( item );
base.SetItem( index, item );
this.OnItemRemovedCore( oldItem );
this.OnItemAddedCore( item );
}
protected override void OnPropertyChanged( PropertyChangedEventArgs e )
{
lock( this.SyncRoot )
{
if( m_deferCount != 0 )
{
if( m_deferPropertyChangedEventArgs == null )
{
m_deferPropertyChangedEventArgs = e;
}
else if( !string.IsNullOrEmpty( m_deferPropertyChangedEventArgs.PropertyName ) && !object.Equals( m_deferPropertyChangedEventArgs.PropertyName, e.PropertyName ) )
{
m_deferPropertyChangedEventArgs = new PropertyChangedEventArgs( string.Empty );
}
return;
}
}
base.OnPropertyChanged( e );
}
protected override void OnCollectionChanged( NotifyCollectionChangedEventArgs e )
{
lock( this.SyncRoot )
{
if( m_deferCount != 0 )
{
if( m_deferCollectionChangedEventArgs == null )
{
m_deferCollectionChangedEventArgs = e;
}
else if( m_deferCollectionChangedEventArgs.Action != NotifyCollectionChangedAction.Reset )
{
m_deferCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Reset );
}
return;
}
}
base.OnCollectionChanged( e );
}
internal IDisposable DeferNotifications()
{
return new DeferredDisposable( new DeferState( this ) );
}
private void OnItemAddingCore( ColumnBase item )
{
m_fieldNameToColumn.Add( item.FieldName, item );
this.OnItemAdding( item );
}
private void OnItemAddedCore( ColumnBase item )
{
this.OnItemAdded( item );
}
private void OnItemRemovingCore( ColumnBase item )
{
var fieldName = item.FieldName;
this.OnItemRemoving( item );
m_fieldNameToColumn.Remove( fieldName );
}
private void OnItemRemovedCore( ColumnBase item )
{
this.OnItemRemoved( item );
}
private int m_deferCount; //0
private PropertyChangedEventArgs m_deferPropertyChangedEventArgs; //null
private NotifyCollectionChangedEventArgs m_deferCollectionChangedEventArgs; //null
private readonly Dictionary<string, ColumnBase> m_fieldNameToColumn = new Dictionary<string, ColumnBase>();
#region DeferState Private Class
private sealed class DeferState : DeferredDisposableState
{
internal DeferState( ObservableColumnCollection target )
{
Debug.Assert( target != null );
m_target = target;
}
protected override object SyncRoot
{
get
{
return m_target.SyncRoot;
}
}
protected override bool IsDeferred
{
get
{
return ( m_target.m_deferCount != 0 );
}
}
protected override void Increment()
{
m_target.m_deferCount++;
}
protected override void Decrement()
{
m_target.m_deferCount--;
}
protected override void OnDeferEnding( bool disposing )
{
m_propertyChangedEventArgs = m_target.m_deferPropertyChangedEventArgs;
m_collectionChangedEventArgs = m_target.m_deferCollectionChangedEventArgs;
m_target.m_deferPropertyChangedEventArgs = null;
m_target.m_deferCollectionChangedEventArgs = null;
base.OnDeferEnding( disposing );
}
protected override void OnDeferEnded( bool disposing )
{
if( m_collectionChangedEventArgs != null )
{
m_target.OnCollectionChanged( m_collectionChangedEventArgs );
}
if( m_propertyChangedEventArgs != null )
{
m_target.OnPropertyChanged( m_propertyChangedEventArgs );
}
}
private readonly ObservableColumnCollection m_target;
private PropertyChangedEventArgs m_propertyChangedEventArgs;
private NotifyCollectionChangedEventArgs m_collectionChangedEventArgs;
}
#endregion
}
}
| 25.685897
| 172
| 0.626154
|
[
"Unlicense"
] |
visiontrail/LMT2018
|
Src/SCMT/UI/DataGrid/Xceed.Wpf.DataGrid/ObservableColumnCollection.cs
| 8,016
|
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.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.TestModels.Northwind;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Query
{
public partial class SimpleQueryCosmosTest
{
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_add(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => o.OrderID + 10 == 10258),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND ((c[""OrderID""] + 10) = 10258))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_subtract(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => o.OrderID - 10 == 10238),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND ((c[""OrderID""] - 10) = 10238))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_multiply(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => o.OrderID * 1 == 10248),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND ((c[""OrderID""] * 1) = 10248))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_divide(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => o.OrderID / 1 == 10248),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND ((c[""OrderID""] / 1) = 10248))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_modulo(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => o.OrderID % 10248 == 0),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND ((c[""OrderID""] % 10248) = 0))");
}
[ConditionalTheory(Skip = "Issue #13168")]
public override async Task Where_bitwise_or(bool isAsync)
{
await base.Where_bitwise_or(isAsync);
AssertSql(" ");
}
public override async Task Where_bitwise_and(bool isAsync)
{
await base.Where_bitwise_and(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND ((c[""CustomerID""] = ""ALFKI"") & (c[""CustomerID""] = ""ANATR"")))");
}
[ConditionalTheory(Skip = "Issue #13168")]
public override async Task Where_bitwise_xor(bool isAsync)
{
await base.Where_bitwise_xor(isAsync);
AssertSql(" ");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_bitwise_leftshift(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => (o.OrderID << 1) == 20496),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND ((c[""OrderID""] << 1) = 20496))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_bitwise_rightshift(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => (o.OrderID >> 1) == 5124),
entryCount: 2);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND ((c[""OrderID""] >> 1) = 5124))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_logical_and(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
cs => cs.Where(c => c.City == "Seattle" && c.ContactTitle == "Owner"),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND ((c[""City""] = ""Seattle"") AND (c[""ContactTitle""] = ""Owner"")))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_logical_or(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
cs => cs.Where(c => c.CustomerID == "ALFKI" || c.CustomerID == "ANATR"),
entryCount: 2);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND ((c[""CustomerID""] = ""ALFKI"") OR (c[""CustomerID""] = ""ANATR"")))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_logical_not(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
cs => cs.Where(c => !(c.City != "Seattle")),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND NOT((c[""City""] != ""Seattle"")))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_equality(bool isAsync)
{
await AssertQuery<Employee>(
isAsync,
es => es.Where(e => e.ReportsTo == 2),
entryCount: 5);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = 2))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_inequality(bool isAsync)
{
await AssertQuery<Employee>(
isAsync,
es => es.Where(e => e.ReportsTo != 2),
entryCount: 4);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] != 2))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_greaterthan(bool isAsync)
{
await AssertQuery<Employee>(
isAsync,
es => es.Where(e => e.ReportsTo > 2),
entryCount: 3);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] > 2))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_greaterthanorequal(bool isAsync)
{
await AssertQuery<Employee>(
isAsync,
es => es.Where(e => e.ReportsTo >= 2),
entryCount: 8);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] >= 2))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_lessthan(bool isAsync)
{
await AssertQuery<Employee>(
isAsync,
es => es.Where(e => e.ReportsTo < 2));
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] < 2))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_lessthanorequal(bool isAsync)
{
await AssertQuery<Employee>(
isAsync,
es => es.Where(e => e.ReportsTo <= 2),
entryCount: 5);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] <= 2))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_string_concat(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
cs => cs.Where(c => c.CustomerID + "END" == "ALFKIEND"),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND ((c[""CustomerID""] || ""END"") = ""ALFKIEND""))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_unary_minus(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => -o.OrderID == -10248),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND (-(c[""OrderID""]) = -10248))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_bitwise_not(bool isAsync)
{
await AssertQuery<Order>(
isAsync,
os => os.Where(o => ~o.OrderID == -10249),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND (~(c[""OrderID""]) = -10249))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_ternary(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
#pragma warning disable IDE0029 // Use coalesce expression
cs => cs.Where(c => (c.Region != null ? c.Region : "SP") == "BC"),
#pragma warning restore IDE0029 // Use coalesce expression
entryCount: 2);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (((c[""Region""] != null) ? c[""Region""] : ""SP"") = ""BC""))");
}
[ConditionalTheory]
[MemberData(nameof(IsAsyncData))]
public virtual async Task Where_coalesce(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
cs => cs.Where(c => (c.Region ?? "SP") == "BC"),
entryCount: 2);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (((c[""Region""] != null) ? c[""Region""] : ""SP"") = ""BC""))");
}
public override async Task Where_simple(bool isAsync)
{
await base.Where_simple(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = ""London""))");
}
private static readonly Expression<Func<Order, bool>> _filter = o => o.CustomerID == "ALFKI";
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_as_queryable_expression(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
cs => cs.Where(c => c.CustomerID == "ALFKI").Where(c => c.Orders.AsQueryable().Any(_filter)),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""CustomerID""] = ""ALFKI""))");
}
public override async Task Where_simple_closure(bool isAsync)
{
await base.Where_simple_closure(isAsync);
AssertSql(
@"@__city_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__city_0))");
}
public override async Task Where_indexer_closure(bool isAsync)
{
await base.Where_indexer_closure(isAsync);
AssertSql(
@"@__p_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__p_0))");
}
public override async Task Where_dictionary_key_access_closure(bool isAsync)
{
await base.Where_dictionary_key_access_closure(isAsync);
AssertSql(
@"@__get_Item_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__get_Item_0))");
}
public override async Task Where_tuple_item_closure(bool isAsync)
{
await base.Where_tuple_item_closure(isAsync);
AssertSql(
@"@__predicateTuple_Item2_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__predicateTuple_Item2_0))");
}
public override async Task Where_named_tuple_item_closure(bool isAsync)
{
await base.Where_named_tuple_item_closure(isAsync);
AssertSql(
@"@__predicateTuple_Item2_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__predicateTuple_Item2_0))");
}
public override async Task Where_simple_closure_constant(bool isAsync)
{
await base.Where_simple_closure_constant(isAsync);
AssertSql(
@"@__predicate_0='true'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND @__predicate_0)");
}
public override async Task Where_simple_closure_via_query_cache(bool isAsync)
{
await base.Where_simple_closure_via_query_cache(isAsync);
AssertSql(
@"@__city_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__city_0))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_method_call_nullable_type_closure_via_query_cache(bool isAsync)
{
await base.Where_method_call_nullable_type_closure_via_query_cache(isAsync);
AssertSql(
@"@__p_0='2'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = @__p_0))",
//
@"@__p_0='5'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = @__p_0))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_method_call_nullable_type_reverse_closure_via_query_cache(bool isAsync)
{
await base.Where_method_call_nullable_type_reverse_closure_via_query_cache(isAsync);
AssertSql(
@"@__p_0='1'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""EmployeeID""] > @__p_0))",
//
@"@__p_0='5'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""EmployeeID""] > @__p_0))");
}
public override async Task Where_method_call_closure_via_query_cache(bool isAsync)
{
await base.Where_method_call_closure_via_query_cache(isAsync);
AssertSql(
@"@__GetCity_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__GetCity_0))");
}
public override async Task Where_field_access_closure_via_query_cache(bool isAsync)
{
await base.Where_field_access_closure_via_query_cache(isAsync);
AssertSql(
@"@__city_InstanceFieldValue_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__city_InstanceFieldValue_0))");
}
public override async Task Where_property_access_closure_via_query_cache(bool isAsync)
{
await base.Where_property_access_closure_via_query_cache(isAsync);
AssertSql(
@"@__city_InstancePropertyValue_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__city_InstancePropertyValue_0))");
}
public override async Task Where_static_field_access_closure_via_query_cache(bool isAsync)
{
await base.Where_static_field_access_closure_via_query_cache(isAsync);
AssertSql(
@"@__StaticFieldValue_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__StaticFieldValue_0))");
}
public override async Task Where_static_property_access_closure_via_query_cache(bool isAsync)
{
await base.Where_static_property_access_closure_via_query_cache(isAsync);
AssertSql(
@"@__StaticPropertyValue_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__StaticPropertyValue_0))");
}
public override async Task Where_nested_field_access_closure_via_query_cache(bool isAsync)
{
await base.Where_nested_field_access_closure_via_query_cache(isAsync);
AssertSql(
@"@__city_Nested_InstanceFieldValue_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__city_Nested_InstanceFieldValue_0))");
}
public override async Task Where_nested_property_access_closure_via_query_cache(bool isAsync)
{
await base.Where_nested_property_access_closure_via_query_cache(isAsync);
AssertSql(
@"@__city_Nested_InstancePropertyValue_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__city_Nested_InstancePropertyValue_0))");
}
public override async Task Where_new_instance_field_access_query_cache(bool isAsync)
{
await base.Where_new_instance_field_access_query_cache(isAsync);
AssertSql(
@"@__InstanceFieldValue_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__InstanceFieldValue_0))",
//
@"@__InstanceFieldValue_0='Seattle'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__InstanceFieldValue_0))");
}
public override async Task Where_new_instance_field_access_closure_via_query_cache(bool isAsync)
{
await base.Where_new_instance_field_access_closure_via_query_cache(isAsync);
AssertSql(
@"@__InstanceFieldValue_0='London'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = @__InstanceFieldValue_0))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_simple_closure_via_query_cache_nullable_type(bool isAsync)
{
await base.Where_simple_closure_via_query_cache_nullable_type(isAsync);
AssertSql(
@"@__p_0='2'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = @__p_0))",
//
@"@__p_0='5'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = @__p_0))",
//
@"@__p_0=null
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = @__p_0))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_simple_closure_via_query_cache_nullable_type_reverse(bool isAsync)
{
await base.Where_simple_closure_via_query_cache_nullable_type_reverse(isAsync);
AssertSql(
@"@__p_0=null
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = @__p_0))",
//
@"@__p_0='5'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = @__p_0))",
//
@"@__p_0='2'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = @__p_0))");
}
[ConditionalFact(Skip = "Issue #17246")]
public override void Where_subquery_closure_via_query_cache()
{
base.Where_subquery_closure_via_query_cache();
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_simple_shadow(bool isAsync)
{
await base.Where_simple_shadow(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""Title""] = ""Sales Representative""))");
}
public override async Task Where_simple_shadow_projection(bool isAsync)
{
await base.Where_simple_shadow_projection(isAsync);
AssertSql(
@"SELECT c[""Title""]
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""Title""] = ""Sales Representative""))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_shadow_subquery_FirstOrDefault(bool isAsync)
{
await base.Where_shadow_subquery_FirstOrDefault(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_client(bool isAsync)
{
await base.Where_client(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_subquery_correlated(bool isAsync)
{
await base.Where_subquery_correlated(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_subquery_correlated_client_eval(bool isAsync)
{
await base.Where_subquery_correlated_client_eval(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_client_and_server_top_level(bool isAsync)
{
await base.Where_client_and_server_top_level(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_client_or_server_top_level(bool isAsync)
{
await base.Where_client_or_server_top_level(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_client_and_server_non_top_level(bool isAsync)
{
await base.Where_client_and_server_non_top_level(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_client_deep_inside_predicate_and_server_top_level(bool isAsync)
{
await base.Where_client_deep_inside_predicate_and_server_top_level(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_equals_method_string(bool isAsync)
{
await base.Where_equals_method_string(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = ""London""))");
}
public override async Task Where_equals_method_int(bool isAsync)
{
await base.Where_equals_method_int(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""EmployeeID""] = 1))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_equals_using_object_overload_on_mismatched_types(bool isAsync)
{
await base.Where_equals_using_object_overload_on_mismatched_types(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
public override async Task Where_equals_using_int_overload_on_mismatched_types(bool isAsync)
{
await base.Where_equals_using_int_overload_on_mismatched_types(isAsync);
AssertSql(
@"@__p_0='1'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""EmployeeID""] = @__p_0))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_equals_on_mismatched_types_nullable_int_long(bool isAsync)
{
await base.Where_equals_on_mismatched_types_nullable_int_long(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_equals_on_mismatched_types_nullable_long_nullable_int(bool isAsync)
{
await base.Where_equals_on_mismatched_types_nullable_long_nullable_int(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_equals_on_mismatched_types_int_nullable_int(bool isAsync)
{
await base.Where_equals_on_mismatched_types_int_nullable_int(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_equals_on_matched_nullable_int_types(bool isAsync)
{
await base.Where_equals_on_matched_nullable_int_types(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_equals_on_null_nullable_int_types(bool isAsync)
{
await base.Where_equals_on_null_nullable_int_types(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
public override async Task Where_comparison_nullable_type_not_null(bool isAsync)
{
await base.Where_comparison_nullable_type_not_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = 2))");
}
public override async Task Where_comparison_nullable_type_null(bool isAsync)
{
await base.Where_comparison_nullable_type_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Employee"") AND (c[""ReportsTo""] = null))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_string_length(bool isAsync)
{
await base.Where_string_length(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_string_indexof(bool isAsync)
{
await base.Where_string_indexof(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_string_replace(bool isAsync)
{
await base.Where_string_replace(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_string_substring(bool isAsync)
{
await base.Where_string_substring(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_now(bool isAsync)
{
await base.Where_datetime_now(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_utcnow(bool isAsync)
{
await base.Where_datetime_utcnow(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_today(bool isAsync)
{
await base.Where_datetime_today(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_date_component(bool isAsync)
{
await base.Where_datetime_date_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_date_add_year_constant_component(bool isAsync)
{
await base.Where_date_add_year_constant_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_year_component(bool isAsync)
{
await base.Where_datetime_year_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_month_component(bool isAsync)
{
await base.Where_datetime_month_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_dayOfYear_component(bool isAsync)
{
await base.Where_datetime_dayOfYear_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_day_component(bool isAsync)
{
await base.Where_datetime_day_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_hour_component(bool isAsync)
{
await base.Where_datetime_hour_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_minute_component(bool isAsync)
{
await base.Where_datetime_minute_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_second_component(bool isAsync)
{
await base.Where_datetime_second_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetime_millisecond_component(bool isAsync)
{
await base.Where_datetime_millisecond_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetimeoffset_now_component(bool isAsync)
{
await base.Where_datetimeoffset_now_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_datetimeoffset_utcnow_component(bool isAsync)
{
await base.Where_datetimeoffset_utcnow_component(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
public override async Task Where_simple_reversed(bool isAsync)
{
await base.Where_simple_reversed(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (""London"" = c[""City""]))");
}
public override async Task Where_is_null(bool isAsync)
{
await base.Where_is_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = null))");
}
public override async Task Where_null_is_null(bool isAsync)
{
await base.Where_null_is_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_constant_is_null(bool isAsync)
{
await base.Where_constant_is_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND false)");
}
public override async Task Where_is_not_null(bool isAsync)
{
await base.Where_is_not_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] != null))");
}
public override async Task Where_null_is_not_null(bool isAsync)
{
await base.Where_null_is_not_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND false)");
}
public override async Task Where_constant_is_not_null(bool isAsync)
{
await base.Where_constant_is_not_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_identity_comparison(bool isAsync)
{
await base.Where_identity_comparison(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""City""] = c[""City""]))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_in_optimization_multiple(bool isAsync)
{
await base.Where_in_optimization_multiple(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_not_in_optimization1(bool isAsync)
{
await base.Where_not_in_optimization1(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_not_in_optimization2(bool isAsync)
{
await base.Where_not_in_optimization2(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_not_in_optimization3(bool isAsync)
{
await base.Where_not_in_optimization3(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_not_in_optimization4(bool isAsync)
{
await base.Where_not_in_optimization4(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_select_many_and(bool isAsync)
{
await base.Where_select_many_and(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_primitive(bool isAsync)
{
await base.Where_primitive(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Employee"")");
}
public override async Task Where_bool_member(bool isAsync)
{
await base.Where_bool_member(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND c[""Discontinued""])");
}
public override async Task Where_bool_member_false(bool isAsync)
{
await base.Where_bool_member_false(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND NOT(c[""Discontinued""]))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_bool_client_side_negated(bool isAsync)
{
await base.Where_bool_client_side_negated(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Product"")");
}
public override async Task Where_bool_member_negated_twice(bool isAsync)
{
await base.Where_bool_member_negated_twice(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND NOT(NOT((c[""Discontinued""] = true))))");
}
public override async Task Where_bool_member_shadow(bool isAsync)
{
await base.Where_bool_member_shadow(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND c[""Discontinued""])");
}
public override async Task Where_bool_member_false_shadow(bool isAsync)
{
await base.Where_bool_member_false_shadow(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND NOT(c[""Discontinued""]))");
}
public override async Task Where_bool_member_equals_constant(bool isAsync)
{
await base.Where_bool_member_equals_constant(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (c[""Discontinued""] = true))");
}
public override async Task Where_bool_member_in_complex_predicate(bool isAsync)
{
await base.Where_bool_member_in_complex_predicate(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (((c[""ProductID""] > 100) AND c[""Discontinued""]) OR (c[""Discontinued""] = true)))");
}
public override async Task Where_bool_member_compared_to_binary_expression(bool isAsync)
{
await base.Where_bool_member_compared_to_binary_expression(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (c[""Discontinued""] = (c[""ProductID""] > 50)))");
}
public override async Task Where_not_bool_member_compared_to_not_bool_member(bool isAsync)
{
await base.Where_not_bool_member_compared_to_not_bool_member(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (NOT(c[""Discontinued""]) = NOT(c[""Discontinued""])))");
}
public override async Task Where_negated_boolean_expression_compared_to_another_negated_boolean_expression(bool isAsync)
{
await base.Where_negated_boolean_expression_compared_to_another_negated_boolean_expression(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (NOT((c[""ProductID""] > 50)) = NOT((c[""ProductID""] > 20))))");
}
public override async Task Where_not_bool_member_compared_to_binary_expression(bool isAsync)
{
await base.Where_not_bool_member_compared_to_binary_expression(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (NOT(c[""Discontinued""]) = (c[""ProductID""] > 50)))");
}
public override async Task Where_bool_parameter(bool isAsync)
{
await base.Where_bool_parameter(isAsync);
AssertSql(
@"@__prm_0='true'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND @__prm_0)");
}
public override async Task Where_bool_parameter_compared_to_binary_expression(bool isAsync)
{
await base.Where_bool_parameter_compared_to_binary_expression(isAsync);
AssertSql(
@"@__prm_0='true'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND ((c[""ProductID""] > 50) != @__prm_0))");
}
public override async Task Where_bool_member_and_parameter_compared_to_binary_expression_nested(bool isAsync)
{
await base.Where_bool_member_and_parameter_compared_to_binary_expression_nested(isAsync);
AssertSql(
@"@__prm_0='true'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (c[""Discontinued""] = ((c[""ProductID""] > 50) != @__prm_0)))");
}
public override async Task Where_de_morgan_or_optimized(bool isAsync)
{
await base.Where_de_morgan_or_optimized(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND NOT((c[""Discontinued""] OR (c[""ProductID""] < 20))))");
}
public override async Task Where_de_morgan_and_optimized(bool isAsync)
{
await base.Where_de_morgan_and_optimized(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND NOT((c[""Discontinued""] AND (c[""ProductID""] < 20))))");
}
public override async Task Where_complex_negated_expression_optimized(bool isAsync)
{
await base.Where_complex_negated_expression_optimized(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND NOT((NOT((NOT(c[""Discontinued""]) AND (c[""ProductID""] < 60))) OR NOT((c[""ProductID""] > 30)))))");
}
public override async Task Where_short_member_comparison(bool isAsync)
{
await base.Where_short_member_comparison(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (c[""UnitsInStock""] > 10))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_comparison_to_nullable_bool(bool isAsync)
{
await base.Where_comparison_to_nullable_bool(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_true(bool isAsync)
{
await base.Where_true(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_false(bool isAsync)
{
await base.Where_false(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND false)");
}
public override async Task Where_bool_closure(bool isAsync)
{
await base.Where_bool_closure(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND false)");
}
public override async Task Where_default(bool isAsync)
{
await base.Where_default(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""Fax""] = null))");
}
public override async Task Where_expression_invoke(bool isAsync)
{
await base.Where_expression_invoke(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""CustomerID""] = ""ALFKI""))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_concat_string_int_comparison1(bool isAsync)
{
await base.Where_concat_string_int_comparison1(isAsync);
AssertSql(
@"@__i_0='10'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND ((c[""CustomerID""] || @__i_0) = c[""CompanyName""]))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_concat_string_int_comparison2(bool isAsync)
{
await base.Where_concat_string_int_comparison2(isAsync);
AssertSql(
@"@__i_0='10'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND ((@__i_0 + c[""CustomerID""]) = c[""CompanyName""]))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_concat_string_int_comparison3(bool isAsync)
{
await base.Where_concat_string_int_comparison3(isAsync);
AssertSql(
@"@__p_0='30'
@__j_1='21'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND ((((@__p_0 + c[""CustomerID""]) || @__j_1) || 42) = c[""CompanyName""]))");
}
public override async Task Where_ternary_boolean_condition_true(bool isAsync)
{
await base.Where_ternary_boolean_condition_true(isAsync);
AssertSql(
@"@__flag_0='true'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (@__flag_0 ? (c[""UnitsInStock""] >= 20) : (c[""UnitsInStock""] < 20)))");
}
public override async Task Where_ternary_boolean_condition_false(bool isAsync)
{
await base.Where_ternary_boolean_condition_false(isAsync);
AssertSql(
@"@__flag_0='false'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (@__flag_0 ? (c[""UnitsInStock""] >= 20) : (c[""UnitsInStock""] < 20)))");
}
public override async Task Where_ternary_boolean_condition_with_another_condition(bool isAsync)
{
await base.Where_ternary_boolean_condition_with_another_condition(isAsync);
AssertSql(
@"@__productId_0='15'
@__flag_1='true'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND ((c[""ProductID""] < @__productId_0) AND (@__flag_1 ? (c[""UnitsInStock""] >= 20) : (c[""UnitsInStock""] < 20))))");
}
public override async Task Where_ternary_boolean_condition_with_false_as_result_true(bool isAsync)
{
await base.Where_ternary_boolean_condition_with_false_as_result_true(isAsync);
AssertSql(
@"@__flag_0='true'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (@__flag_0 ? (c[""UnitsInStock""] >= 20) : false))");
}
public override async Task Where_ternary_boolean_condition_with_false_as_result_false(bool isAsync)
{
await base.Where_ternary_boolean_condition_with_false_as_result_false(isAsync);
AssertSql(
@"@__flag_0='false'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Product"") AND (@__flag_0 ? (c[""UnitsInStock""] >= 20) : false))");
}
public override async Task Where_compare_constructed_equal(bool isAsync)
{
await base.Where_compare_constructed_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_constructed_multi_value_equal(bool isAsync)
{
await base.Where_compare_constructed_multi_value_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_constructed_multi_value_not_equal(bool isAsync)
{
await base.Where_compare_constructed_multi_value_not_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_tuple_constructed_equal(bool isAsync)
{
await base.Where_compare_tuple_constructed_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_tuple_constructed_multi_value_equal(bool isAsync)
{
await base.Where_compare_tuple_constructed_multi_value_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_tuple_constructed_multi_value_not_equal(bool isAsync)
{
await base.Where_compare_tuple_constructed_multi_value_not_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_tuple_create_constructed_equal(bool isAsync)
{
await base.Where_compare_tuple_create_constructed_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_tuple_create_constructed_multi_value_equal(bool isAsync)
{
await base.Where_compare_tuple_create_constructed_multi_value_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_tuple_create_constructed_multi_value_not_equal(bool isAsync)
{
await base.Where_compare_tuple_create_constructed_multi_value_not_equal(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (c[""Discriminator""] = ""Customer"")");
}
public override async Task Where_compare_null(bool isAsync)
{
await base.Where_compare_null(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND ((c[""City""] = null) AND (c[""Country""] = ""UK"")))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_Is_on_same_type(bool isAsync)
{
await base.Where_Is_on_same_type(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""Discriminator""] = ""Customer""))");
}
public override async Task Where_chain(bool isAsync)
{
await base.Where_chain(isAsync);
AssertSql(
@"SELECT c
FROM root c
WHERE (((c[""Discriminator""] = ""Order"") AND (c[""CustomerID""] = ""QUICK"")) AND (c[""OrderDate""] > ""1998-01-01T00:00:00""))");
}
[ConditionalFact(Skip = "Issue #17246")]
public override void Where_navigation_contains()
{
base.Where_navigation_contains();
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""CustomerID""] = ""ALFKI""))");
}
public override async Task Where_array_index(bool isAsync)
{
await base.Where_array_index(isAsync);
AssertSql(
@"@__p_0='ALFKI'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""CustomerID""] = @__p_0))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_multiple_contains_in_subquery_with_or(bool isAsync)
{
await AssertQuery<OrderDetail, Product, Order>(
isAsync,
(ods, ps, os) =>
ods.Where(od => od.OrderID < 10250).Where(
od =>
ps.OrderBy(p => p.ProductID).Take(1).Select(p => p.ProductID).Contains(od.ProductID)
|| os.OrderBy(o => o.OrderID).Take(1).Select(o => o.OrderID).Contains(od.OrderID)),
entryCount: 3);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""OrderDetail"") AND (c[""OrderID""] < 10250))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_multiple_contains_in_subquery_with_and(bool isAsync)
{
await AssertQuery<OrderDetail, Product, Order>(
isAsync,
(ods, ps, os) =>
ods.Where(od => od.OrderID < 10260).Where(
od =>
ps.OrderBy(p => p.ProductID).Take(20).Select(p => p.ProductID).Contains(od.ProductID)
&& os.OrderBy(o => o.OrderID).Take(10).Select(o => o.OrderID).Contains(od.OrderID)),
entryCount: 5);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""OrderDetail"") AND (c[""OrderID""] < 10260))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_contains_on_navigation(bool isAsync)
{
await AssertQuery<Order, Customer>(
isAsync,
(os, cs) => os.Where(o => o.OrderID > 10354 && o.OrderID < 10360)
.Where(
o => cs.Where(c => c.City == "London")
.Any(c => c.Orders.Contains(o))),
entryCount: 2);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND ((c[""OrderID""] > 10354) AND (c[""OrderID""] < 10360)))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_subquery_FirstOrDefault_is_null(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
cs => cs.Where(c => c.CustomerID == "PARIS").Where(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault() == null),
entryCount: 1);
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""CustomerID""] = ""PARIS""))");
}
[ConditionalTheory(Skip = "Issue #17246")]
public override async Task Where_subquery_FirstOrDefault_compared_to_entity(bool isAsync)
{
await AssertQuery<Customer>(
isAsync,
cs => cs.Where(c => c.CustomerID == "ALFKI").Where(
c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault() == new Order { OrderID = 10243 }));
AssertSql(
@"SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Customer"") AND (c[""CustomerID""] = ""ALFKI""))");
}
public override async Task Time_of_day_datetime(bool isAsync)
{
await base.Time_of_day_datetime(isAsync);
AssertSql(
@"SELECT c[""OrderDate""]
FROM root c
WHERE (c[""Discriminator""] = ""Order"")");
}
public override async Task TypeBinary_short_circuit(bool isAsync)
{
await base.TypeBinary_short_circuit(isAsync);
AssertSql(
@"@__p_0='false'
SELECT c
FROM root c
WHERE ((c[""Discriminator""] = ""Order"") AND @__p_0)");
}
[ConditionalTheory(Skip = "Issue#16391")]
public override Task Where_is_conditional(bool isAsync)
{
return base.Where_is_conditional(isAsync);
}
[ConditionalTheory(Skip = "Issue#17246")]
public override Task Filter_non_nullable_value_after_FirstOrDefault_on_empty_collection(bool isAsync)
{
return base.Filter_non_nullable_value_after_FirstOrDefault_on_empty_collection(isAsync);
}
[ConditionalTheory(Skip = "Issue #17246")]
public override Task Like_with_non_string_column_using_ToString(bool isAsync)
{
return base.Like_with_non_string_column_using_ToString(isAsync);
}
[ConditionalTheory(Skip = "Issue #17246")]
public override Task Like_with_non_string_column_using_double_cast(bool isAsync)
{
return base.Like_with_non_string_column_using_double_cast(isAsync);
}
}
}
| 31.130984
| 164
| 0.575701
|
[
"Apache-2.0"
] |
CygnusBill/EntityFrameworkCore
|
test/EFCore.Cosmos.FunctionalTests/Query/SimpleQueryCosmosTest.Where.cs
| 59,180
|
C#
|
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.ExcelApi;
namespace NetOffice.ExcelApi.Behind
{
/// <summary>
/// DispatchInterface ODBCError
/// SupportByVersion Excel, 9,10,11,12,14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff837150.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
public class ODBCError : COMObject, NetOffice.ExcelApi.ODBCError
{
#pragma warning disable
#region Type Information
/// <summary>
/// Contract Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type ContractType
{
get
{
if(null == _contractType)
_contractType = typeof(NetOffice.ExcelApi.ODBCError);
return _contractType;
}
}
private static Type _contractType;
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(ODBCError);
return _type;
}
}
#endregion
#region Ctor
/// <summary>
/// Stub Ctor, not indented to use
/// </summary>
public ODBCError() : base()
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838248.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public virtual NetOffice.ExcelApi.Application Application
{
get
{
return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", typeof(NetOffice.ExcelApi.Application));
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193658.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public virtual NetOffice.ExcelApi.Enums.XlCreator Creator
{
get
{
return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator");
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836454.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16), ProxyResult]
public virtual object Parent
{
get
{
return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff823199.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public virtual string SqlState
{
get
{
return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "SqlState");
}
}
/// <summary>
/// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff835612.aspx </remarks>
[SupportByVersion("Excel", 9,10,11,12,14,15,16)]
public virtual string ErrorString
{
get
{
return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "ErrorString");
}
}
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
| 26.625
| 167
| 0.634742
|
[
"MIT"
] |
igoreksiz/NetOffice
|
Source/Excel/Behind/DispatchInterfaces/ODBCError.cs
| 4,262
|
C#
|
using System.Collections.ObjectModel;
using System.Windows.Media;
using SciChart.Charting.Model.ChartSeries;
using SciChart.Charting.Model.DataSeries;
using SciChart.Data.Model;
namespace SciChart.Mvvm.Tutorial
{
public class MainViewModel : BindableObject
{
private string _chartTitle = "Hello SciChart World!";
private string _xAxisTitle = "XAxis";
private string _yAxisTitle = "YAxis";
private ObservableCollection<IRenderableSeriesViewModel> _renderableSeries;
private bool _enablePan;
private bool _enableZoom = true;
public MainViewModel()
{
var dummyDataProvider = new DummyDataProvider();
var lineData = new XyDataSeries<double, double>() { SeriesName = "TestingSeries" };
_renderableSeries = new ObservableCollection<IRenderableSeriesViewModel>();
RenderableSeries.Add(new LineRenderableSeriesViewModel()
{
StrokeThickness = 2,
Stroke = Colors.SteelBlue,
DataSeries = lineData,
StyleKey = "LineSeriesStyle"
});
// Append the initial values to the chart
var initialDataValues = dummyDataProvider.GetHistoricalData();
lineData.Append(initialDataValues.XValues, initialDataValues.YValues);
// Subscribe to future updates
dummyDataProvider.SubscribeUpdates((newValues) =>
{
// Append when new values arrive
lineData.Append(newValues.XValues, newValues.YValues);
// Zoom the chart to fit
lineData.InvalidateParentSurface(RangeMode.ZoomToFit);
});
}
public ObservableCollection<IRenderableSeriesViewModel> RenderableSeries
{
get { return _renderableSeries; }
set
{
_renderableSeries = value;
OnPropertyChanged("RenderableSeries");
}
}
public string ChartTitle
{
get { return _chartTitle; }
set
{
_chartTitle = value;
OnPropertyChanged("ChartTitle");
}
}
public string XAxisTitle
{
get { return _xAxisTitle; }
set
{
_xAxisTitle = value;
OnPropertyChanged("XAxisTitle");
}
}
public string YAxisTitle
{
get { return _yAxisTitle; }
set
{
_yAxisTitle = value;
OnPropertyChanged("YAxisTitle");
}
}
public bool EnableZoom
{
get { return _enableZoom; }
set
{
if (_enableZoom != value)
{
_enableZoom = value;
OnPropertyChanged("EnableZoom");
if (_enableZoom) EnablePan = false;
}
}
}
public bool EnablePan
{
get { return _enablePan; }
set
{
if (_enablePan != value)
{
_enablePan = value;
OnPropertyChanged("EnablePan");
if (_enablePan) EnableZoom = false;
}
}
}
}
}
| 29.594828
| 95
| 0.516749
|
[
"MIT"
] |
babusoundrarajan/scichart.wpf.examples
|
v5.x/Tutorials/MVVM/Tutorial 06b - Adding Realtime Updates with MVVM/MainViewModel.cs
| 3,435
|
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.Runtime;
using Internal.Runtime.CompilerServices;
namespace System
{
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MulticastDelegate : Delegate
{
// This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a
// "protected-and-internal" rather than "internal" but C# has no keyword for the former.
internal MulticastDelegate() { }
private bool InvocationListEquals(MulticastDelegate d)
{
Delegate[] invocationList = m_helperObject as Delegate[];
if (d.m_extraFunctionPointerOrData != m_extraFunctionPointerOrData)
return false;
int invocationCount = (int)m_extraFunctionPointerOrData;
for (int i = 0; i < invocationCount; i++)
{
Delegate dd = invocationList[i];
Delegate[] dInvocationList = d.m_helperObject as Delegate[];
if (!dd.Equals(dInvocationList[i]))
return false;
}
return true;
}
public override sealed bool Equals(Object obj)
{
if (obj == null || !InternalEqualTypes(this, obj))
return false;
MulticastDelegate d = obj as MulticastDelegate;
if (d == null)
return false;
// there are 2 kind of delegate kinds for comparision
// 1- Multicast (m_helperObject is Delegate[])
// 2- Single-cast delegate, which can be compared with a structural comparision
if (m_functionPointer == GetThunk(MulticastThunk))
{
return InvocationListEquals(d);
}
else
{
if (!Object.ReferenceEquals(m_helperObject, d.m_helperObject) ||
(!FunctionPointerOps.Compare(m_extraFunctionPointerOrData, d.m_extraFunctionPointerOrData)) ||
(m_functionPointer != d.m_functionPointer))
{
return false;
}
// Those delegate kinds with thunks put themselves into the m_firstParamter, so we can't
// blindly compare the m_firstParameter fields for equality.
if (Object.ReferenceEquals(m_firstParameter, this))
{
return Object.ReferenceEquals(d.m_firstParameter, d);
}
return Object.ReferenceEquals(m_firstParameter, d.m_firstParameter);
}
}
public override sealed int GetHashCode()
{
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
return base.GetHashCode();
}
else
{
int hash = 0;
for (int i = 0; i < (int)m_extraFunctionPointerOrData; i++)
{
hash = hash * 33 + invocationList[i].GetHashCode();
}
return hash;
}
}
public static bool operator ==(MulticastDelegate d1, MulticastDelegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator !=(MulticastDelegate d1, MulticastDelegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
public override sealed Delegate[] GetInvocationList()
{
return base.GetInvocationList();
}
}
}
| 35.118182
| 141
| 0.553974
|
[
"MIT"
] |
ZZHGit/corert
|
src/System.Private.CoreLib/src/System/MulticastDelegate.cs
| 3,863
|
C#
|
namespace Zu.ChromeDevTools.Runtime
{
using Newtonsoft.Json;
/// <summary>
/// Object containing abbreviated remote object value.
/// </summary>
public sealed class ObjectPreview
{
/// <summary>
/// Object type.
///</summary>
[JsonProperty("type")]
public string Type
{
get;
set;
}
/// <summary>
/// Object subtype hint. Specified for `object` type values only.
///</summary>
[JsonProperty("subtype", DefaultValueHandling = DefaultValueHandling.Ignore)]
public string Subtype
{
get;
set;
}
/// <summary>
/// String representation of the object.
///</summary>
[JsonProperty("description", DefaultValueHandling = DefaultValueHandling.Ignore)]
public string Description
{
get;
set;
}
/// <summary>
/// True iff some of the properties or entries of the original object did not fit.
///</summary>
[JsonProperty("overflow")]
public bool Overflow
{
get;
set;
}
/// <summary>
/// List of the properties.
///</summary>
[JsonProperty("properties")]
public PropertyPreview[] Properties
{
get;
set;
}
/// <summary>
/// List of the entries. Specified for `map` and `set` subtype values only.
///</summary>
[JsonProperty("entries", DefaultValueHandling = DefaultValueHandling.Ignore)]
public EntryPreview[] Entries
{
get;
set;
}
}
}
| 26.569231
| 90
| 0.50608
|
[
"Apache-2.0"
] |
DoctorDump/AsyncChromeDriver
|
ChromeDevToolsClient/Runtime/ObjectPreview.cs
| 1,727
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Jingle
{
class Scanner
{
private static readonly Dictionary<string, TokenType> keywords = new Dictionary<string, TokenType>();
private static bool _keywordsInitialized = false;
static void _initializeKeywords()
{
if (_keywordsInitialized)
return;
keywords.Add("and", TokenType.AND);
keywords.Add("class", TokenType.CLASS);
keywords.Add("else", TokenType.ELSE);
keywords.Add("false", TokenType.FALSE);
keywords.Add("for", TokenType.FOR);
keywords.Add("end", TokenType.END);
keywords.Add("fn", TokenType.FN);
keywords.Add("if", TokenType.IF);
keywords.Add("nil", TokenType.NIL);
keywords.Add("or", TokenType.OR);
keywords.Add("echo", TokenType.ECHO);
keywords.Add("return", TokenType.RETURN);
keywords.Add("super", TokenType.SUPER);
keywords.Add("this", TokenType.THIS);
keywords.Add("true", TokenType.TRUE);
keywords.Add("var", TokenType.VAR);
keywords.Add("while", TokenType.WHILE);
_keywordsInitialized = true;
}
private readonly string source;
private readonly List<Token> tokens = new List<Token>();
private int start = 0;
private int current = 0;
private int line = 1;
public Scanner(string source)
{
this.source = source;
_initializeKeywords();
}
public List<Token> scanTokens()
{
while (!isAtEnd())
{
start = current;
scanToken();
}
tokens.Add(new Token(TokenType.EOF, "", null, line));
return tokens;
}
private void scanToken()
{
char c = advance();
switch (c)
{
case '(':
addToken(TokenType.LEFT_PAREN);
break;
case ')':
addToken(TokenType.RIGHT_PAREN);
break;
case ':':
addToken(TokenType.COLON);
break;
case ',':
addToken(TokenType.COMMA);
break;
case '.':
addToken(TokenType.DOT);
break;
case '-':
addToken(TokenType.MINUS);
break;
case '+':
addToken(TokenType.PLUS);
break;
case ';':
addToken(TokenType.SEMICOLON);
break;
case '*':
addToken(TokenType.STAR);
break;
case '%':
addToken(TokenType.MODULO);
break;
case '#':
while (peek() != '\n' && !isAtEnd())
advance();
break;
case '!':
addToken(match('=') ? TokenType.BANG_EQUAL : TokenType.BANG);
break;
case '=':
addToken(match('=') ? TokenType.EQUAL_EQUAL : TokenType.EQUAL);
break;
case '<':
addToken(match('=') ? TokenType.LESS_EQUAL : TokenType.LESS);
break;
case '>':
addToken(match('=') ? TokenType.GREATER_EQUAL : TokenType.GREATER);
break;
case '/':
if (match('/'))
{
addToken(TokenType.INTDIV);
}
else
{
addToken(TokenType.SLASH);
}
break;
case ' ':
case '\r':
case '\t':
break;
case '\n':
line++;
break;
case '"':
string_();
break;
default:
if (isDigit(c))
{
number();
}
else if (isAlpha(c))
{
identifier();
}
else
{
Jingle.Error(line, "Unexpected character.");
}
break;
}
}
private void identifier()
{
while (isAlphaNumeric(peek()))
advance();
string text = source.Substring(start, current - start);
TokenType type;
if (!keywords.ContainsKey(text))
type = TokenType.IDENTIFIER;
else
type = keywords[text];
addToken(type);
}
private void number()
{
while (isDigit(peek()))
advance();
if (peek() == '.' && isDigit(peekNext()))
{
advance();
while (isDigit(peek()))
advance();
}
addToken(TokenType.NUMBER, Double.Parse(source.Substring(start, current - start)));
}
private void string_()
{
while (peek() != '"' && !isAtEnd())
{
if (peek() == '\n')
line++;
advance();
}
if (isAtEnd())
{
Jingle.Error(line, "Unterminated string.");
return;
}
advance();
string value = source.Substring(start + 1, current - start - 2);
addToken(TokenType.STRING, value);
}
bool match(char expected)
{
if (isAtEnd())
return false;
if (source[current] != expected)
return false;
current++;
return true;
}
private char peek()
{
if (isAtEnd())
return '\0';
return source[current];
}
private char peekNext()
{
if (current + 1 >= source.Length)
return '\0';
return source[current + 1];
}
private bool isAlpha(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
private bool isAlphaNumeric(char c)
{
return isAlpha(c) || isDigit(c);
}
private bool isDigit(char c)
{
return c >= '0' && c <= '9';
}
private bool isAtEnd()
{
return current >= source.Length;
}
private char advance()
{
current++;
return source[current - 1];
}
private void addToken(TokenType type)
{
addToken(type, null);
}
private void addToken(TokenType type, object literal)
{
string text = source.Substring(start, current - start);
tokens.Add(new Token(type, text, literal, line));
}
}
}
| 28.268939
| 109
| 0.398767
|
[
"MPL-2.0",
"MPL-2.0-no-copyleft-exception",
"BSD-3-Clause"
] |
42sol-eu/jingle
|
source/Scanner.cs
| 7,465
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Workspace service that provides <see cref="IAsynchronousOperationListener"/> instance.
/// </summary>
internal interface IWorkspaceAsynchronousOperationListenerProvider : IWorkspaceService
{
IAsynchronousOperationListener GetListener();
}
}
| 34.352941
| 94
| 0.753425
|
[
"MIT"
] |
333fred/roslyn
|
src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/IWorkspaceAsynchronousOperationListenerProvider.cs
| 586
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Mackiloha.Render
{
public struct Vertex3
{
public float X;
public float Y;
public float Z;
public float NormalX;
public float NormalY;
public float NormalZ;
public float ColorR;
public float ColorG;
public float ColorB;
public float ColorA;
public float U;
public float V;
}
public struct Face
{
public ushort V1;
public ushort V2;
public ushort V3;
}
public struct FaceGroup
{
public int Size;
public List<int> Sections;
public List<int> VertexIndicies;
}
public struct Bone
{
public string Name;
public Matrix4 Mat;
}
public interface IMesh : IRenderObject
{
string Material { get; set; }
string MainMesh { get; set; }
int Unknown { get; set; }
List<Vertex3> Vertices { get; }
List<Face> Faces { get; }
List<FaceGroup> Groups { get; }
List<Bone> Bones { get; }
}
public class Mesh : RenderObject, IMesh, ITrans, IDraw
{
internal Trans Trans { get; } = new Trans();
internal Draw Draw { get; } = new Draw();
// Trans
public Matrix4 Mat1 { get => Trans.Mat1; set => Trans.Mat1 = value; }
public Matrix4 Mat2 { get => Trans.Mat2; set => Trans.Mat2 = value; }
public List<string> Transformables => Trans.Transformables;
public int UnknownInt { get => Trans.UnknownInt; set => Trans.UnknownInt = value; }
public string Camera { get => Trans.Camera; set => Trans.Camera = value; }
public bool UnknownBool { get => Trans.UnknownBool; set => Trans.UnknownBool = value; }
public string Transform { get => Trans.Transform; set => Trans.Transform = value; }
// Draw
public bool Showing { get => Draw.Showing; set => Draw.Showing = value; }
public List<string> Drawables => Draw.Drawables;
public Sphere Boundry { get => Draw.Boundry; set => Draw.Boundry = value; }
// Mesh
public string Material { get; set; }
public string MainMesh { get; set; }
public int Unknown { get; set; }
public List<Vertex3> Vertices { get; } = new List<Vertex3>();
public List<Face> Faces { get; } = new List<Face>();
public List<FaceGroup> Groups { get; } = new List<FaceGroup>();
public List<Bone> Bones { get; } = new List<Bone>();
public override string Type => "Mesh";
}
}
| 26.846939
| 95
| 0.575447
|
[
"MIT"
] |
PikminGuts92/Mackiloha
|
Src/Core/Mackiloha/Render/Mesh.cs
| 2,633
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class skillCooldown : MonoBehaviour
{
public Image imageCooldown;
public float cooldown = 2;
bool isCooldown;
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
isCooldown = true;
}
if (isCooldown)
{
imageCooldown.fillAmount += 1 / cooldown * Time.deltaTime;
if (imageCooldown.fillAmount >= 1)
{
imageCooldown.fillAmount = 0;
isCooldown = false;
}
}
}
}
| 20.741935
| 70
| 0.545879
|
[
"MIT"
] |
OscarH1998/Project-03--Mechanics-Analysis
|
Project03/Assets/Scripts/skillCooldown.cs
| 645
|
C#
|
/*
* THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR
*/
using System.Text.Json.Serialization;
using System.Runtime.Serialization;
#pragma warning disable 1591
namespace Plotly.Blazor.Traces.StreamTubeLib.ColorBarLib
{
/// <summary>
/// Sets this color bar's horizontal position anchor. This anchor binds
/// the <c>x</c> position to the <c>left</c>, <c>center</c> or <c>right</c>
/// of the color bar. Defaults to <c>left</c> when <c>orientation</c> is <c>v</c>
/// and <c>center</c> when <c>orientation</c> is <c>h</c>.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")]
[JsonConverter(typeof(EnumConverter))]
public enum XAnchorEnum
{
[EnumMember(Value=@"left")]
Left,
[EnumMember(Value=@"center")]
Center,
[EnumMember(Value=@"right")]
Right
}
}
| 32.392857
| 89
| 0.624035
|
[
"MIT"
] |
ScriptBox99/Plotly.Blazor
|
Plotly.Blazor/Traces/StreamTubeLib/ColorBarLib/XAnchorEnum.cs
| 907
|
C#
|
using System.Reflection;
namespace OpenApiGeneration.Utils
{
public static class PathUtils
{
public static string? GetCurrentDirectory()
{
var assembly = Assembly.GetExecutingAssembly();
var currentDir = Path.GetDirectoryName(assembly.Location);
return currentDir;
}
}
}
| 23
| 70
| 0.634783
|
[
"MIT"
] |
knoepdan/Bom
|
Tools/OpenApiGeneration_Source/OpenApiGeneration/Utils/PathUtils.cs
| 347
|
C#
|
namespace AMO.IoC.Implementation
{
internal class ResolveContext : IResolveContext
{
public IResolver Resolver { get; set; }
public IResolveOverrides Overrides { get; set; }
}
}
| 24.888889
| 60
| 0.616071
|
[
"MIT"
] |
alexoparin/IoC
|
AMO.IoC/Implementation/ResolveContext.cs
| 226
|
C#
|
// Copyright 2019 谭杰鹏. All Rights Reserved //https://github.com/JiepengTan
using System;
using System.Collections.Generic;
using System.Linq;
using Lockstep.Logging;
using Lockstep.Math;
using Lockstep.Util;
namespace Lockstep.PathFinding {
public class TriangleGraph : IndexedGraph<Triangle> {
private NavMeshData _navMeshData;
public List<Triangle> _triangles = new List<Triangle>();
private Dictionary<Triangle, List<Connection<Triangle>>> _sharedEdges;
private Dictionary<Triangle, List<Connection<Triangle>>> _isolatedEdgesMap;
private Dictionary<int,Triangle> _id2Tri = new Dictionary<int, Triangle>();
private int _numDisconnectedEdges;
private int _numConnectedEdges;
private int _numTotalEdges;
public BspTree bspTree;
public TriangleGraph(NavMeshData navMeshData, int scale){
this._navMeshData = navMeshData;
navMeshData.check(scale);
var pathTriangles = CreateTriangles(scale);
foreach (var triangle in pathTriangles) {
_id2Tri[triangle.index] = triangle;
}
var pathIndexConnections = GetIndexConnections(navMeshData.GetPathTriangles());
_sharedEdges =
CreateSharedEdgesMap(pathIndexConnections, pathTriangles, navMeshData.GetPathVertices());
_isolatedEdgesMap = CreateIsolatedEdgesMap(_sharedEdges);
bspTree = new BspTree();
bspTree.Init(pathTriangles);
// Count edges of different types
foreach (var edges in _isolatedEdgesMap.Values) {
_numDisconnectedEdges += edges.Count;
}
foreach (var edges in _sharedEdges.Values) {
_numConnectedEdges += edges.Count;
}
_numConnectedEdges /= 2;
_numTotalEdges = _numConnectedEdges + _numDisconnectedEdges;
Debug.Log(
$"mapId{navMeshData.getMapID()} triangles{getTriangleCont()} totalEdges{_numTotalEdges} connEdges{_numConnectedEdges} disConnEdges{_numDisconnectedEdges}");
}
public List<Connection<Triangle>> GetConnections(Triangle fromNode){
return _sharedEdges.TryGetValue(fromNode, out var val) ? val : null;
}
public int GetIndex(Triangle node){
return node.getIndex();
}
public int GetNodeCount(){
return _sharedEdges.Count;
}
public NavMeshData getNavMeshData(){
return _navMeshData;
}
private List<Triangle> CreateTriangles(int scale){
var vertexIndexs = _navMeshData.GetPathTriangles();
var vertices = _navMeshData.GetPathVertices();
int triangleIndex = 0; // 三角形下标
int length = vertexIndexs.Length - 3;
for (int i = 0; i <= length;) {
int aIndex = vertexIndexs[i++];
int bIndex = vertexIndexs[i++];
int cIndex = vertexIndexs[i++];
try {
Triangle triangle = null;
if (scale != 1) {
triangle = new Triangle(vertices[aIndex], vertices[bIndex], vertices[cIndex], triangleIndex++,
aIndex,
bIndex, cIndex);
}
else {
triangle = new Triangle(vertices[aIndex], vertices[bIndex], vertices[cIndex], triangleIndex++);
}
_triangles.Add(triangle);
}
catch (Exception e) {
Console.WriteLine(e);
throw;
}
}
return _triangles;
}
private static HashSet<IndexConnection> GetIndexConnections(int[] indices){
var indexConnections = new HashSet<IndexConnection>();
int[] edge = {-1, -1};
short i = 0;
int j, a0, a1, a2, b0, b1, b2, triAIndex, triBIndex;
while (i < indices.Length) {
triAIndex = (short) (i / 3); // A三角形编号
a0 = indices[i++];
a1 = indices[i++];
a2 = indices[i++];
j = i;
while (j < indices.Length) {
triBIndex = (short) (j / 3); // B三角形编号
b0 = indices[j++];
b1 = indices[j++];
b2 = indices[j++];
if (HasSharedEdgeIndices(a0, a1, a2, b0, b1, b2, edge)) {
var indexConnection1 = new IndexConnection(edge[0], edge[1], triAIndex, triBIndex);
var indexConnection2 = new IndexConnection(edge[1], edge[0], triBIndex, triAIndex);
indexConnections.Add(indexConnection1);
indexConnections.Add(indexConnection2);
edge[0] = -1;
edge[1] = -1;
// Debug.LogError("共享边:{} ->
// {}",indexConnection1.ToString(),indexConnection2.ToString());
}
}
}
Debug.Log($"连接个数:{indexConnections.Count}");
return indexConnections;
}
/** Checks if the two triangles have shared vertex indices. The edge
* will always follow the vertex winding order of the triangle A. Since all
* triangles have the same winding order, triangle A should have the opposite
* edge direction to triangle B.
*/
private static bool HasSharedEdgeIndices(int a0, int a1, int a2, int b0, int b1, int b2, int[] edge){
bool match0 = (a0 == b0 || a0 == b1 || a0 == b2);
bool match1 = (a1 == b0 || a1 == b1 || a1 == b2);
if (!match0 && !match1) { // 无两个共享点
return false;
}
else if (match0 && match1) {
edge[0] = a0;
edge[1] = a1;
return true;
}
bool match2 = (a2 == b0 || a2 == b1 || a2 == b2);
if (match0 && match2) {
edge[0] = a2;
edge[1] = a0;
return true;
}
else if (match1 && match2) {
edge[0] = a1;
edge[1] = a2;
return true;
}
return false;
}
private static Dictionary<Triangle, List<Connection<Triangle>>> CreateSharedEdgesMap(
HashSet<IndexConnection> indexConnections, List<Triangle> triangles, LVector3[] vertexVectors){
var connectionMap = new Dictionary<Triangle, List<Connection<Triangle>>>();
foreach (Triangle tri in triangles) {
connectionMap.Add(tri, new List<Connection<Triangle>>());
}
foreach (IndexConnection indexConnection in indexConnections) {
var fromNode = triangles.get(indexConnection.fromTriIndex);
var toNode = triangles.get(indexConnection.toTriIndex);
var edgeVertexA = vertexVectors[indexConnection.edgeVertexIndex1];
var edgeVertexB = vertexVectors[indexConnection.edgeVertexIndex2];
var edge = new TriangleEdge(fromNode, toNode, edgeVertexA, edgeVertexB);
connectionMap.get(fromNode).Add(edge);
fromNode.connections.Add(edge);
Debug.LogFormat( $"Triangle:{fromNode.getIndex()} -->{toNode.getIndex()} {fromNode}-->{toNode}");
}
return connectionMap;
}
/**
* 存储相互连接三角形的关系 Class for storing the edge connection data between two adjacent
* triangles.
*/
public class IndexConnection {
// The vertex indices which makes up the edge shared between two triangles.
public int edgeVertexIndex1;
public int edgeVertexIndex2;
// The indices of the two triangles sharing this edge.
public int fromTriIndex;
public int toTriIndex;
public IndexConnection(int sharedEdgeVertex1Index, int edgeVertexIndex2, int fromTriIndex, int toTriIndex){
this.edgeVertexIndex1 = sharedEdgeVertex1Index;
this.edgeVertexIndex2 = edgeVertexIndex2;
this.fromTriIndex = fromTriIndex;
this.toTriIndex = toTriIndex;
}
public override String ToString(){
return "IndexConnection [edgeVertexIndex1=" + edgeVertexIndex1 + ", edgeVertexIndex2=" +
edgeVertexIndex2
+ ", fromTriIndex=" + fromTriIndex + ", toTriIndex=" + toTriIndex + "]";
}
public override int GetHashCode(){
int prime = 31;
int result = 1;
result = prime * result + edgeVertexIndex1;
result = prime * result + edgeVertexIndex2;
result = prime * result + fromTriIndex;
result = prime * result + toTriIndex;
return result;
}
public override bool Equals(object obj){
if (this == obj)
return true;
if (obj == null)
return false;
if (GetType() != obj.GetType())
return false;
IndexConnection other = (IndexConnection) obj;
if (edgeVertexIndex1 != other.edgeVertexIndex1)
return false;
if (edgeVertexIndex2 != other.edgeVertexIndex2)
return false;
if (fromTriIndex != other.fromTriIndex)
return false;
if (toTriIndex != other.toTriIndex)
return false;
return true;
}
}
public Dictionary<Triangle, List<Connection<Triangle>>> getPathSharedEdges(){
return _sharedEdges;
}
/**获取所有三角形列表 */
public List<Triangle> getTriangles(){
return _triangles;
}
public Triangle GetTriangle(LVector3 point){
//TODO space partition bsp
Profiler.BeginSample("_GetTriangle");
var ret = _GetTriangle(point);
Profiler.EndSample();
return ret;
}
private Triangle _GetTriangle(LVector3 point){
var triId = bspTree.GetTriangle(point);
if (_id2Tri.TryGetValue(triId, out var tri)) {
return tri;
}
//foreach (var triangle in _triangles) {
// if (triangle.IsInnerPoint(point)) {
// return triangle;
// }
//}
return null;
}
private static Dictionary<Triangle, List<Connection<Triangle>>> CreateIsolatedEdgesMap(
Dictionary<Triangle, List<Connection<Triangle>>> connectionMap){
var disconnectionMap = new Dictionary<Triangle, List<Connection<Triangle>>>();
foreach (Triangle tri in connectionMap.Keys) {
var connectedEdges = connectionMap.get(tri);
var disconnectedEdges = new List<Connection<Triangle>>();
disconnectionMap.Add(tri, disconnectedEdges);
if (connectedEdges.Count < 3) {
// This triangle does not have all edges connected to other triangles
bool ab = true;
bool bc = true;
bool ca = true;
foreach (var item in connectedEdges) {
var edge = item as TriangleEdge;
if (edge.rightVertex == tri.a && edge.leftVertex == tri.b)
ab = false;
else if (edge.rightVertex == tri.b && edge.leftVertex == tri.c)
bc = false;
else if (edge.rightVertex == tri.c && edge.leftVertex == tri.a)
ca = false;
}
if (ab)
disconnectedEdges.Add(new TriangleEdge(tri, null, tri.a, tri.b));
if (bc)
disconnectedEdges.Add(new TriangleEdge(tri, null, tri.b, tri.c));
if (ca)
disconnectedEdges.Add(new TriangleEdge(tri, null, tri.c, tri.a));
}
int totalEdges = (connectedEdges.Count + disconnectedEdges.Count);
if (totalEdges != 3) {
Debug.LogError("Wrong number of edges (" + totalEdges + ") in triangle " +
tri.getIndex());
}
}
return disconnectionMap;
}
public int getNumDisconnectedEdges(){
return _numDisconnectedEdges;
}
public int getNumConnectedEdges(){
return _numConnectedEdges;
}
public int getNumTotalEdges(){
return _numTotalEdges;
}
public int getTriangleCont(){
return _triangles.Count;
}
}
}
| 39.272997
| 172
| 0.524821
|
[
"MIT"
] |
XingHong/SimpleLockStepClient
|
Assets/Engine.LockstepEngine/Src/PathFinding/NavMesh/NavMesh/TriangleGraph.cs
| 13,345
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.