text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using BPMInterfaceDAL;
namespace BPMInterfaceBLL
{
public class ReportDemoBLL
{
ReportDemoDAL rdd = new ReportDemoDAL();
public DataTable ReportDemo(string vendorname)
{
return rdd.ReportDemo(vendorname);
}
}
}
|
#region License
/*
* Copyright 2002-2010 the original author or 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.
*/
#endregion
using System;
using System.Threading;
using Common.Logging;
using RabbitMQ.Client;
using Spring.Collections.Generic;
using Spring.Messaging.Amqp.Core;
using Spring.Messaging.Amqp.Rabbit.Connection;
using Spring.Messaging.Amqp.Support.Converter;
using Spring.Threading.Collections.Generic;
using Spring.Util;
using IConnection = Spring.Messaging.Amqp.Rabbit.Connection.IConnection;
namespace Spring.Messaging.Amqp.Rabbit.Core
{
/// <summary>
/// Helper class that simplifies synchronous RabbitMQ access code.
/// </summary>
/// <author>Mark Pollack</author>
/// <author>Joe Fitzgerald</author>
public class RabbitTemplate : RabbitAccessor, IRabbitOperations
{
/// <summary>
/// The logger.
/// </summary>
protected static readonly ILog logger = LogManager.GetLogger(typeof(RabbitTemplate));
/// <summary>
/// The default exchange.
/// </summary>
private static readonly string DEFAULT_EXCHANGE = string.Empty; // alias for amq.direct default exchange
/// <summary>
/// The default routing key.
/// </summary>
private static readonly string DEFAULT_ROUTING_KEY = string.Empty;
/// <summary>
/// The default reply timeout.
/// </summary>
private static readonly long DEFAULT_REPLY_TIMEOUT = 5000;
/// <summary>
/// The default encoding.
/// </summary>
private static readonly string DEFAULT_ENCODING = "UTF-8";
#region Fields
/// <summary>
/// The exchange
/// </summary>
private string exchange = DEFAULT_EXCHANGE;
/// <summary>
/// The routing key.
/// </summary>
private string routingKey = DEFAULT_ROUTING_KEY;
/// <summary>
/// The default queue name that will be used for synchronous receives.
/// </summary>
private string queue;
/// <summary>
/// The reply timeout.
/// </summary>
private long replyTimeout = DEFAULT_REPLY_TIMEOUT;
/// <summary>
/// The message converter.
/// </summary>
private IMessageConverter messageConverter = new SimpleMessageConverter();
/// <summary>
/// The encoding.
/// </summary>
private string encoding = DEFAULT_ENCODING;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="RabbitTemplate"/> class.
/// </summary>
public RabbitTemplate()
{
InitDefaultStrategies();
}
/// <summary>
/// Initializes a new instance of the <see cref="RabbitTemplate"/> class.
/// </summary>
/// <param name="connectionFactory">
/// The connection factory.
/// </param>
public RabbitTemplate(IConnectionFactory connectionFactory) : this()
{
ConnectionFactory = connectionFactory;
AfterPropertiesSet();
}
#endregion
#region Properties
/// <summary>
/// Sets Queue.
/// </summary>
public string Queue
{
set { this.queue = value; }
}
/// <summary>
/// Sets Exchange.
/// </summary>
public string Exchange
{
set { this.exchange = value; }
}
/// <summary>
/// Sets RoutingKey.
/// </summary>
public string RoutingKey
{
set { this.routingKey = value; }
}
/// <summary>
/// Sets Encoding.
/// </summary>
public string Encoding
{
set { this.encoding = value; }
}
/// <summary>
/// Gets or sets MessageConverter.
/// </summary>
public IMessageConverter MessageConverter
{
get { return this.messageConverter; }
set { this.messageConverter = value; }
}
#endregion
#region Implementation of IAmqpTemplate
/// <summary>
/// Send a message, given the message.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
public void Send(Message message)
{
Send(this.exchange, this.routingKey, message);
}
/// <summary>
/// Send a message, given a routing key and the message.
/// </summary>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message.
/// </param>
public void Send(string routingKey, Message message)
{
Send(this.exchange, routingKey, message);
}
/// <summary>
/// Send a message, given an exchange, a routing key, and the message.
/// </summary>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message.
/// </param>
public void Send(string exchange, string routingKey, Message message)
{
Execute<object>(channel =>
{
DoSend(channel, exchange, routingKey, message);
return null;
});
}
/// <summary>
/// Convert and send a message, given the message.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
public void ConvertAndSend(object message)
{
this.ConvertAndSend(this.exchange, this.routingKey, message);
}
/// <summary>
/// Convert and send a message, given a routing key and the message.
/// </summary>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message.
/// </param>
public void ConvertAndSend(string routingKey, object message)
{
this.ConvertAndSend(this.exchange, routingKey, message);
}
/// <summary>
/// Convert and send a message, given an exchange, a routing key, and the message.
/// </summary>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message.
/// </param>
public void ConvertAndSend(string exchange, string routingKey, object message)
{
this.Send(exchange, routingKey, Execute<Message>(channel => this.GetRequiredMessageConverter().ToMessage(message, new MessageProperties())));
}
/// <summary>
/// Convert and send a message, given the message.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
/// <param name="messagePostProcessorDelegate">
/// The message post processor delegate.
/// </param>
public void ConvertAndSend(object message, MessagePostProcessorDelegate messagePostProcessorDelegate)
{
this.ConvertAndSend(this.exchange, this.routingKey, message, messagePostProcessorDelegate);
}
/// <summary>
/// Convert and send a message, given a routing key and the message.
/// </summary>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message.
/// </param>
/// <param name="messagePostProcessorDelegate">
/// The message post processor delegate.
/// </param>
public void ConvertAndSend(string routingKey, object message, MessagePostProcessorDelegate messagePostProcessorDelegate)
{
this.ConvertAndSend(this.exchange, routingKey, message, messagePostProcessorDelegate);
}
/// <summary>
/// Convert and send a message, given an exchange, a routing key, and the message.
/// </summary>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message.
/// </param>
/// <param name="messagePostProcessorDelegate">
/// The message post processor delegate.
/// </param>
public void ConvertAndSend(string exchange, string routingKey, object message, MessagePostProcessorDelegate messagePostProcessorDelegate)
{
this.Send(exchange, routingKey, messagePostProcessorDelegate(Execute<Message>(channel => this.GetRequiredMessageConverter().ToMessage(message, new MessageProperties()))));
}
/// <summary>
/// Receive a message.
/// </summary>
/// <returns>
/// The message.
/// </returns>
public Message Receive()
{
return this.Receive(this.GetRequiredQueue());
}
/// <summary>
/// Receive a message, given the name of a queue.
/// </summary>
/// <param name="queueName">
/// The queue name.
/// </param>
/// <returns>
/// The message.
/// </returns>
public Message Receive(string queueName)
{
return Execute<Message>(channel =>
{
var response = channel.BasicGet(queueName, !IsChannelTransacted);
// Response can be null is the case that there is no message on the queue.
if (response != null)
{
var deliveryTag = response.DeliveryTag;
if (ChannelLocallyTransacted(channel))
{
channel.BasicAck(deliveryTag, false);
channel.TxCommit();
}
else if (IsChannelTransacted)
{
// Not locally transacted but it is transacted so it
// could be synchronized with an external transaction
ConnectionFactoryUtils.RegisterDeliveryTag(ConnectionFactory, channel, (long)deliveryTag);
}
var messageProps = RabbitUtils.CreateMessageProperties(response.BasicProperties, response, encoding);
messageProps.MessageCount = (int)response.MessageCount;
return new Message(response.Body, messageProps);
}
return null;
});
}
/// <summary>
/// Receive and convert a message.
/// </summary>
/// <returns>
/// The object.
/// </returns>
public object ReceiveAndConvert()
{
return ReceiveAndConvert(this.GetRequiredQueue());
}
/// <summary>
/// Receive and covert a message, given the name of a queue.
/// </summary>
/// <param name="queueName">
/// The queue name.
/// </param>
/// <returns>
/// The object.
/// </returns>
public object ReceiveAndConvert(string queueName)
{
var response = Receive(queueName);
if (response != null)
{
return this.GetRequiredMessageConverter().FromMessage(response);
}
return null;
}
/// <summary>
/// Send and receive a message, given the message.
/// </summary>
/// <param name="message">
/// The message to send.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public Message SendAndReceive(Message message)
{
return this.DoSendAndReceive(this.exchange, this.routingKey, message);
}
/// <summary>
/// Send and receive a message, given a routing key and the message.
/// </summary>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message to send.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public Message SendAndReceive(string routingKey, Message message)
{
return this.DoSendAndReceive(this.exchange, routingKey, message);
}
/// <summary>
/// Send and receive a message, given an exchange, a routing key, and the message.
/// </summary>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message to send.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public Message SendAndReceive(string exchange, string routingKey, Message message)
{
return this.DoSendAndReceive(exchange, routingKey, message);
}
/// <summary>
/// Convert, send, and receive a message, given the message.
/// </summary>
/// <param name="message">
/// The message to send.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public object ConvertSendAndReceive(object message)
{
return this.ConvertSendAndReceive(this.exchange, this.routingKey, message);
}
/// <summary>
/// Convert, send, and receive a message, given a routing key and the message.
/// </summary>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message to send.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public object ConvertSendAndReceive(string routingKey, object message)
{
return this.ConvertSendAndReceive(this.exchange, routingKey, message);
}
/// <summary>
/// Convert, send, and receive a message, given an exchange, a routing key and the message.
/// </summary>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message to send.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public object ConvertSendAndReceive(string exchange, string routingKey, object message)
{
var messageProperties = new MessageProperties();
var requestMessage = this.GetRequiredMessageConverter().ToMessage(message, messageProperties);
var replyMessage = this.DoSendAndReceive(exchange, routingKey, requestMessage);
if (replyMessage == null)
{
return null;
}
return this.GetRequiredMessageConverter().FromMessage(replyMessage);
}
/// <summary>
/// Convert, send, and receive a message, given the message.
/// </summary>
/// <param name="message">
/// The message to send.
/// </param>
/// <param name="messagePostProcessorDelegate">
/// The message post processor delegate.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public object ConvertSendAndReceive(object message, MessagePostProcessorDelegate messagePostProcessorDelegate)
{
return this.ConvertSendAndReceive(this.exchange, this.routingKey, message, messagePostProcessorDelegate);
}
/// <summary>
/// Convert, send, and receive a message, given a routing key and the message.
/// </summary>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message to send.
/// </param>
/// <param name="messagePostProcessorDelegate">
/// The message post processor delegate.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public object ConvertSendAndReceive(string routingKey, object message, MessagePostProcessorDelegate messagePostProcessorDelegate)
{
return this.ConvertSendAndReceive(this.exchange, routingKey, message, messagePostProcessorDelegate);
}
/// <summary>
/// Convert, send, and receive a message, given an exchange, a routing key and the message.
/// </summary>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message to send.
/// </param>
/// <param name="messagePostProcessorDelegate">
/// The message post processor delegate.
/// </param>
/// <returns>
/// The message received.
/// </returns>
public object ConvertSendAndReceive(string exchange, string routingKey, object message, MessagePostProcessorDelegate messagePostProcessorDelegate)
{
var messageProperties = new MessageProperties();
var requestMessage = this.GetRequiredMessageConverter().ToMessage(message, messageProperties);
var replyMessage = this.DoSendAndReceive(exchange, routingKey, messagePostProcessorDelegate(requestMessage));
if (replyMessage == null)
{
return null;
}
return this.GetRequiredMessageConverter().FromMessage(replyMessage);
}
/// <summary>
/// Do the send and receive operation, given an exchange, a routing key and the message.
/// </summary>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message to send.
/// </param>
/// <returns>
/// The message received.
/// </returns>
/// <exception cref="NotImplementedException">
/// </exception>
private Message DoSendAndReceive(string exchange, string routingKey, Message message)
{
var replyMessage = this.Execute<Message>(delegate(IModel channel)
{
var replyHandoff = new SynchronousQueue<Message>();
AssertUtils.IsTrue(message.MessageProperties.ReplyTo == null, "Send-and-receive methods can only be used if the Message does not already have a replyTo property.");
var queueDeclaration = channel.QueueDeclare();
var replyToAddress = new Address(ExchangeTypes.Direct, DEFAULT_EXCHANGE, queueDeclaration);
message.MessageProperties.ReplyTo = replyToAddress;
var noAck = false;
var consumerTag = Guid.NewGuid().ToString();
var noLocal = true;
var exclusive = true;
var consumer = new AdminDefaultBasicConsumer(channel, replyHandoff, this.encoding);
channel.BasicConsume(replyToAddress.RoutingKey, noAck, consumerTag, noLocal, exclusive, null, consumer);
DoSend(channel, exchange, routingKey, message);
Message reply;
if (this.replyTimeout < 0)
{
reply = replyHandoff.Take();
}
else
{
replyHandoff.Poll(new TimeSpan(0, 0, 0, 0, (int)this.replyTimeout), out reply);
}
channel.BasicCancel(consumerTag);
return reply;
});
return replyMessage;
}
#endregion
#region Implementation of IRabbitOperations
/// <summary>
/// Execute an action.
/// </summary>
/// <param name="action">
/// The action.
/// </param>
/// <typeparam name="T">
/// Type T
/// </typeparam>
/// <returns>
/// An object of Type T
/// </returns>
/// <exception cref="SystemException">
/// </exception>
public T Execute<T>(ChannelCallbackDelegate<T> action)
{
AssertUtils.ArgumentNotNull(action, "Callback object must not be null");
var resourceHolder = GetTransactionalResourceHolder();
var channel = resourceHolder.Channel;
try
{
if (logger.IsDebugEnabled)
{
logger.Debug("Executing callback on RabbitMQ Channel: " + channel);
}
return action(channel);
}
catch (Exception ex)
{
if (this.ChannelLocallyTransacted(channel))
{
resourceHolder.RollbackAll();
}
throw ConvertRabbitAccessException(ex);
}
finally
{
ConnectionFactoryUtils.ReleaseResources(resourceHolder);
}
}
/// <summary>
/// Execute an action.
/// </summary>
/// <param name="action">
/// The action.
/// </param>
/// <typeparam name="T">
/// Type T
/// </typeparam>
/// <returns>
/// An object of Type T
/// </returns>
public T Execute<T>(IChannelCallback<T> action)
{
return Execute<T>(action.DoInRabbit);
}
#endregion
/// <summary>
/// Initialize with default strategies.
/// </summary>
protected virtual void InitDefaultStrategies()
{
this.MessageConverter = new SimpleMessageConverter();
}
/// <summary>
/// Get the connection from a resource holder.
/// </summary>
/// <param name="resourceHolder">
/// The resource holder.
/// </param>
/// <returns>
/// The connection.
/// </returns>
protected new virtual IConnection GetConnection(RabbitResourceHolder resourceHolder)
{
return resourceHolder.Connection;
}
/// <summary>
/// Get the channel from a resource holder.
/// </summary>
/// <param name="resourceHolder">
/// The resource holder.
/// </param>
/// <returns>
/// The channel.
/// </returns>
protected new virtual RabbitMQ.Client.IModel GetChannel(RabbitResourceHolder resourceHolder)
{
return resourceHolder.Channel;
}
/// <summary>
/// Do the send operation.
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="message">
/// The message.
/// </param>
private void DoSend(RabbitMQ.Client.IModel channel, string exchange, string routingKey, Message message)
{
if (logger.IsDebugEnabled)
{
logger.Debug("Publishing message on exchange [" + exchange + "], routingKey = [" + routingKey + "]");
}
if (exchange == null)
{
// try to send to configured exchange
exchange = this.exchange;
}
if (routingKey == null)
{
// try to send to configured routing key
routingKey = this.routingKey;
}
channel.BasicPublish(exchange, routingKey, false, false, RabbitUtils.ExtractBasicProperties(channel, message, this.encoding), message.Body);
// Check commit - avoid commit call within a JTA transaction.
if (this.ChannelLocallyTransacted(channel))
{
// Transacted channel created by this template -> commit.
RabbitUtils.CommitIfNecessary(channel);
}
}
/// <summary>
/// Flag indicating whether the channel is locally transacted.
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
/// <returns>
/// True if locally transacted, else false.
/// </returns>
protected bool ChannelLocallyTransacted(RabbitMQ.Client.IModel channel)
{
return IsChannelTransacted && !ConnectionFactoryUtils.IsChannelTransactional(channel, ConnectionFactory);
}
/// <summary>
/// Get the required message converter.
/// </summary>
/// <returns>
/// The message converter.
/// </returns>
/// <exception cref="InvalidOperationException">
/// </exception>
private IMessageConverter GetRequiredMessageConverter()
{
var converter = this.MessageConverter;
if (converter == null)
{
throw new InvalidOperationException("No 'messageConverter' specified. Check configuration of RabbitTemplate.");
}
return converter;
}
/// <summary>
/// Get the required queue.
/// </summary>
/// <returns>
/// The name of the queue.
/// </returns>
/// <exception cref="InvalidOperationException">
/// </exception>
private string GetRequiredQueue()
{
var name = this.queue;
if (name == null)
{
throw new InvalidOperationException("No 'queue' specified. Check configuration of RabbitTemplate.");
}
return name;
}
}
/// <summary>
/// The admin default basic consumer.
/// </summary>
internal class AdminDefaultBasicConsumer : DefaultBasicConsumer
{
/// <summary>
/// The reply handoff.
/// </summary>
private readonly SynchronousQueue<Message> replyHandoff;
/// <summary>
/// The encoding.
/// </summary>
private readonly string encoding;
/// <summary>
/// Initializes a new instance of the <see cref="AdminDefaultBasicConsumer"/> class.
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
/// <param name="replyHandoff">
/// The reply handoff.
/// </param>
/// <param name="encoding">
/// The encoding.
/// </param>
public AdminDefaultBasicConsumer(IModel channel, SynchronousQueue<Message> replyHandoff, string encoding) : base(channel)
{
this.replyHandoff = replyHandoff;
this.encoding = encoding;
}
/// <summary>
/// Handle delivery.
/// </summary>
/// <param name="consumerTag">
/// The consumer tag.
/// </param>
/// <param name="envelope">
/// The envelope.
/// </param>
/// <param name="properties">
/// The properties.
/// </param>
/// <param name="body">
/// The body.
/// </param>
public void HandleDelivery(string consumerTag, BasicGetResult envelope, IBasicProperties properties, byte[] body)
{
var messageProperties = RabbitUtils.CreateMessageProperties(properties, envelope, this.encoding);
var reply = new Message(body, messageProperties);
try
{
this.replyHandoff.Put(reply);
}
catch (ThreadInterruptedException e)
{
Thread.CurrentThread.Interrupt();
}
}
/// <summary>
/// Handle basic deliver.
/// </summary>
/// <param name="consumerTag">
/// The consumer tag.
/// </param>
/// <param name="deliveryTag">
/// The delivery tag.
/// </param>
/// <param name="redelivered">
/// The redelivered.
/// </param>
/// <param name="exchange">
/// The exchange.
/// </param>
/// <param name="routingKey">
/// The routing key.
/// </param>
/// <param name="properties">
/// The properties.
/// </param>
/// <param name="body">
/// The body.
/// </param>
public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body)
{
var envelope = new BasicGetResult(deliveryTag, redelivered, exchange, routingKey, 1, properties, body);
this.HandleDelivery(consumerTag, envelope, properties, body);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// In the given line, reverse the order of words (words are separated by spaces).
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
string enterString;
Console.WriteLine("Enter string");
enterString = Console.ReadLine();
string[] words = enterString.Split(' ');//splitting into words
Console.WriteLine("reversed:");
Array.Reverse(words);
for (int i = 0; i < words.Length; i++)
{
Console.Write(words[i] + " ");
}
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication1.Controllers;
namespace WebApplication1.Models
{
public class CustomerSearchController : ApiController
{
// GET: api/Customer/5
public IEnumerable<Customer> Get(string id)
{
try
{
string custSearchQuery = CustomerController.select +
string.Format(
" WHERE (CustomerID = '{0}') OR (BillPhone like'%{0}%') OR (Misc1 like'%{0}%') or (BillLname like '{0}%')",
id);
return SharedDb.PosimDb.GetMany<Customer>(custSearchQuery);
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw ex;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
//Escribe un programa que imprima los número del 1 al 100, pero aplicando las siguientes normas:
//Devuelve Fizz si el número es = 3 o divisible por 3.
//Devuelve Buzz si el número es = 5 o divisible por 5.
//Devuelve FizzBuzz si el número es divisible por 3 y por 5.
namespace EjercicioFizz
{
public class ClaseFizz
{
public static string Comprobar(int numero)
{
string resultado = "";
if (numero % 3 == 0 && numero % 5 == 0)
{
resultado = "FizzBuzz";
}
else
{
if (numero % 3 == 0)
{
resultado = "Fizz";
}
else
{
if (numero % 5 == 0)
{
resultado = "Buzz";
}
else
{
resultado = numero.ToString();
}
}
}
return resultado;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.EventSystems;
public class RestartGame : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public void Restart()
{
SceneManager.LoadScene("SampleScene");
}
public void OnPointerDown(PointerEventData eventData)
{
transform.localScale = new Vector3(1.1f, 1.1f, 1.1f);
}
public void OnPointerUp(PointerEventData eventData)
{
transform.localScale = new Vector3(1f, 1f, 1f);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZY.OA.Common;
using ZY.OA.IBLL;
using ZY.OA.Model.Enum;
namespace ZY.OA.UI.PortalNew.Controllers
{
public class UserLoginController : Controller
{
public IUserInfoService UserInfoService { get; set; }
public ActionResult Index()
{
CheckCookiesInfo(Request["return"]);
return View();
}
//验证码
public ActionResult ShowCode()
{
ValidateCode validateCode = new ValidateCode();
string code= validateCode.CreateValidateCode(4);
//将验证码存入Session
Session["VCode"] = code;
byte[] codeBuffer = validateCode.CreateValidateGraphic(code);
return File(codeBuffer, "image/jpeg");
}
//处理登录
public ActionResult ProcessLogin()
{
//判断验证码是否正确
string SessionCode = Session["VCode"] as string;
Session["VCode"] = null;
string txtCode=Request["code"];
if (string.IsNullOrEmpty(SessionCode)||SessionCode!= txtCode)
{
return Content("no,验证码输入有误!");
}
//判断用户名密码是否正确
string userName= Request["login"];
string userPwd= Request["pwd"];
short delNormal = (short)DelFlagEnum.Normal;
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(userPwd))
{
var userInfo = UserInfoService.GetEntities(u => u.UName == userName && u.Pwd == userPwd && u.DelFlag == delNormal).FirstOrDefault();
if (userInfo != null)
{
//模拟的SessionId
string usersLoginId = Guid.NewGuid().ToString();
//Session["userInfo"] = userInfo;
//将用户信息写入memcache,模拟SessionId
memcachedHelper.set(usersLoginId, SerializerHelper.SerializerToString(userInfo), DateTime.Now.AddMinutes(20));
//将模拟的SessionId写入客户端Cookie中
Response.Cookies["usersLoginId"].Value = usersLoginId;
//如果用户选择“记住我”,则将用户信息存入Cookie
if (!string.IsNullOrEmpty(Request["rememberMe"]))
{
HttpCookie cookie1 = new HttpCookie("ck1",userInfo.UName);
HttpCookie cookie2 = new HttpCookie("ck2", MD5Helper.GetMd5String((MD5Helper.GetMd5String(userInfo.Pwd))));
cookie1.Expires = DateTime.Now.AddDays(7);
cookie2.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(cookie1);
Response.Cookies.Add(cookie2);
}
string Url = Request["returnUrl"];
if (!string.IsNullOrEmpty(Url))
{
return Content("ok,"+ Url);
}
else
{
return Content("ok,");
}
}
else
{
return Content("no,用户名或密码错误!");
}
}
else
{
return Content("no,用户名和密码不能为空!");
}
}
//检查Cookies的值是否正确,正确则直接跳转
public void CheckCookiesInfo(string url)
{
var ck1 = Request.Cookies["ck1"];
var ck2 = Request.Cookies["ck2"];
if (ck1!=null&&ck2!=null)
{
string userName = ck1.Value;
string Pwd = ck2.Value;
short delFlag = (short)DelFlagEnum.Normal;
var userInfo=UserInfoService.GetEntities(u => u.UName == userName && u.DelFlag == delFlag).FirstOrDefault();
if (userInfo!=null)
{
if (Pwd== MD5Helper.GetMd5String(MD5Helper.GetMd5String(userInfo.Pwd)))
{
string usersLoginId = Guid.NewGuid().ToString();
Response.Cookies["usersLoginId"].Value = usersLoginId;
memcachedHelper.set(usersLoginId, SerializerHelper.SerializerToString(userInfo),DateTime.Now.AddMinutes(20));
if (!string.IsNullOrEmpty(url))
{
Response.Redirect(url);//如果验证用户记住了密码,并通过,则跳转至访问页
}
else
{
Response.Redirect("/Home/Index");//如果验证用户记住了密码,并通过,且直接访问的登录页,则跳转首页
}
}
}
Response.Cookies["ck1"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["ck2"].Expires = DateTime.Now.AddDays(-1);
}
}
//退出登录
public ActionResult LoginOut()
{
if (Request.Cookies["usersLoginId"] != null)
{
memcachedHelper.Delete(Request.Cookies["usersLoginId"].Value);
}
Response.Cookies["ck1"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["ck2"].Expires = DateTime.Now.AddDays(-1);
return RedirectToAction("Index");
}
}
} |
using HROADS_WebApi.Domains;
using HROADS_WebApi.Interfaces;
using HROADS_WebApi.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HROADS_WebApi.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class TiposUsuariosController : ControllerBase
{
private ITiposUsuarioRepository _tiposUsuarioRepository { get; set; }
public TiposUsuariosController()
{
_tiposUsuarioRepository = new TiposUsuarioRepository();
}
[Authorize]
[HttpGet]
public IActionResult Get()
{
try
{
return Ok(_tiposUsuarioRepository.Listar());
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
[Authorize]
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
TiposUsuario tipoBuscado = _tiposUsuarioRepository.BuscarPorId(id);
if (tipoBuscado == null)
{
return NotFound("Nenhum Tipo de usuario foi encontrado");
}
try
{
return Ok(tipoBuscado);
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
[Authorize(Roles = "1")]
[HttpPost]
public IActionResult Post(TiposUsuario novoTipo)
{
try
{
_tiposUsuarioRepository.Cadastrar(novoTipo);
return StatusCode(201);
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
[Authorize(Roles = "1")]
[HttpPut("{id}")]
public IActionResult Put(int id, TiposUsuario tiposAtualizado)
{
TiposUsuario tipoBuscado = _tiposUsuarioRepository.BuscarPorId(id);
if (tipoBuscado == null)
{
return NotFound(new
{
mensagem = "Tipo de usuario não encontrado!",
erro = true
});
}
try
{
_tiposUsuarioRepository.Atualizar(id, tiposAtualizado);
return StatusCode(204);
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
[Authorize(Roles = "1")]
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
TiposUsuario tipoBuscado = _tiposUsuarioRepository.BuscarPorId(id);
if (tipoBuscado == null)
{
return NotFound(new
{
mensagem = "Tipo de usuario não encontrado!",
erro = true
});
}
try
{
_tiposUsuarioRepository.Deletar(id);
return StatusCode(204);
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
[Authorize]
[HttpGet("tipousers")]
public IActionResult GetU()
{
try
{
return Ok(_tiposUsuarioRepository.ListarUsuarios());
}
catch (Exception erro)
{
return BadRequest(erro);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class IAParasite : MonoBehaviour
{
public GameObject Target;
public float DetectionDistance = 10f;
public float AttackDistance = 2f;
public float MinSpeed=0.9f, MaxSpeed=1.1f;
public int Damages = 10;
public AudioClip SoundAttack;
private NavMeshAgent agent;
private Animator animator;
[SerializeField]
private float distance;
// Use this for initialization
void Start ()
{
agent = GetComponent<NavMeshAgent> ();
animator = GetComponent<Animator> ();
agent.speed = Random.Range (MinSpeed, MaxSpeed);
Target = GameObject.Find ("FPSController");
}
// Update is called once per frame
void Update ()
{
distance = Vector3.Distance (Target.transform.position, transform.position);
if (distance < DetectionDistance)
{
animator.SetBool ("walk", true);
agent.SetDestination (Target.transform.position);
if (distance < AttackDistance)
{
animator.SetBool ("attack", true);
agent.SetDestination (transform.position);
}
else
{
animator.SetBool ("attack", false);
}
}
else
{
animator.SetBool ("walk", false);
agent.SetDestination (transform.position);
}
}
public void damageToPlayerEvent()
{
GameObject.Find ("FPSController").GetComponent<HealthScript> ().DamagePlayer (Damages);
GetComponent<AudioSource> ().PlayOneShot (SoundAttack);
}
}
|
using DentWhiteTest.Contacts;
using WhiteFrameDemo.TestCase;
using TestStack.White.UIItems.WindowItems;
namespace WhiteFrameDemo.Module
{
public class LoginModule
{
public static void LoginAllTest()
{
//登陆成功
//启动一个客户端
bool res_Launch = LoginTest.Launch(out Window appWin, out string msg);
if (res_Launch)
{
Global.win_Dent = appWin;
Global.LstInfo.Add(msg);
}
else
{
Global.LstInfo.Add(msg);
return;
}
//测试登录窗口,登录成功
res_Launch = LoginTest.LoginDocker_Success(Global.win_Dent, out string msg1);
if (res_Launch)
{
Global.LstInfo.Add(msg1);
}
else
{
Global.LstInfo.Add(msg1);
return;
}
//关闭客户端
Global.win_Dent.Close();
//登陆账号密码为空
//启动一个客户端
res_Launch = LoginTest.Launch(out Window appWin1, out string msg2);
if (res_Launch)
{
Global.win_Dent = appWin1;
Global.LstInfo.Add(msg2);
}
else
{
Global.LstInfo.Add(msg2);
return;
}
//测试登录窗口,账号密码为空
res_Launch = LoginTest.LoginDocker_UserNull_PwdNull(Global.win_Dent, out string msg3);
if (res_Launch)
{
Global.LstInfo.Add(msg3);
}
else
{
Global.LstInfo.Add(msg3);
return;
}
//关闭客户端
Global.win_Dent.Close();
//登陆账号为空
//启动一个客户端
res_Launch = LoginTest.Launch(out Window appWin2, out string msg4);
if (res_Launch)
{
Global.win_Dent = appWin2;
Global.LstInfo.Add(msg4);
}
else
{
Global.LstInfo.Add(msg4);
return;
}
//测试登录窗口,账号为空
res_Launch = LoginTest.LoginDocker_UserNull(Global.win_Dent, out string msg5);
if (res_Launch)
{
Global.LstInfo.Add(msg5);
}
else
{
Global.LstInfo.Add(msg5);
return;
}
//关闭客户端
Global.win_Dent.Close();
//登陆密码为空
//启动一个客户端
res_Launch = LoginTest.Launch(out Window appWin3, out string msg6);
if (res_Launch)
{
Global.win_Dent = appWin3;
Global.LstInfo.Add(msg6);
}
else
{
Global.LstInfo.Add(msg6);
return;
}
//测试登录窗口,密码为空
res_Launch = LoginTest.LoginDocker_PwdNull(Global.win_Dent, out string msg7);
if (res_Launch)
{
Global.LstInfo.Add(msg7);
}
else
{
Global.LstInfo.Add(msg7);
return;
}
//关闭客户端
Global.win_Dent.Close();
}
}
}
|
using System;
using Autofac;
using Tests.Pages.ActionID;
using Framework.Core.Common;
using NUnit.Framework;
using Tests.Data.Oberon;
using Tests.Pages.Oberon.Contact;
using Tests.Pages.Oberon.Dashboard;
using Tests.Pages.Oberon.Contribution;
namespace Tests.Projects.Oberon.Contribution
{
public class CreateWithAllField : BaseTest
{
private Driver Driver {get { return Scope.Resolve<Driver>(); }}
public static long TenantId;
/// <summary>
/// Create a contribution with all fields and then load the details page and verify
/// that the fields are set.
/// </summary>
[Ignore("bank account does not appear in contribution create account select")] //build agent requires db access for this test to run
[Test]
[Category("oberon"), Category("oberon_smoketest"), Category("oberon_contributions"), Category("oberon_PRODUCTION")]
public void CreateWithAllFieldTest()
{
// add banking info
TenentDbSqlAccess.AddBankAccount(TenantId, "My Checking (123456789)");
var actionIdLogin = Scope.Resolve<ActionIdLogIn>();
actionIdLogin.LogInTenant();
// create contact
var contact = Scope.Resolve<ContactCreate>();
var testContact = Scope.Resolve<TestContact>();
testContact.Id = contact.CreateContact(testContact);
// create contribution
var testContribution = new TestContribution(testContact.Id, DateTime.Now.ToString("MM/dd/yyyy"), 10)
{
//BatchNumber = FakeData.RandomInteger(10000), //todo batch field now select
Method = "Check",
CheckDate = DateTime.Now.ToString("MM/dd/yyyy"),
CheckNumber = FakeData.RandomInteger(10000),
OnlineReferenceNumber = FakeData.RandomLetterString(5),
DepositDate = DateTime.Now.ToString("MM/dd/yyyy"),
DepositNumber = FakeData.RandomInteger(10000),
BankAccount = "My Checking (123456789)",
Status = "Deposited",
InternalNote = FakeData.RandomLetterString(50)
};
var form = Scope.Resolve<ContributionCreate>();
form.Create(testContribution);
// verify contribution details
var details = Scope.Resolve<ContributionDetail>();
details.ExpandHeader(details.AdditionalInformationExpandHeader, details.AdditionalInformationCollapseHeader);
Assert.AreEqual("$"+testContribution.Amount+".00", details.Amount.Text);
//Assert.AreEqual(testContribution.BatchNumber.ToString(), details.Batch.Text);
Assert.AreEqual(testContribution.Method, details.Method.Text);
Assert.AreEqual(testContribution.CheckDate.ToString(), details.CheckDate.Text);
Assert.AreEqual(testContribution.CheckNumber.ToString(), details.CheckNumber.Text);
Assert.AreEqual(testContribution.OnlineReferenceNumber, details.OnlineReferenceNumber.Text);
Assert.AreEqual(testContribution.DepositDate.ToString(), details.DepositeDate.Text);
Assert.AreEqual(details.BankAccountId.Text, testContribution.BankAccount);
Assert.AreEqual(testContribution.Status, details.Status.Text);
Assert.AreEqual(testContribution.InternalNote, details.InternalNote.Text);
// delete contact
//var contactDetail = new ContactDetail(_driver);
//contactDetail.GoToContactDetail(contactId);
//contactDetail.ClickDeleteLink;
}
}
}
|
using System;
// All players ai or human need to implement this interface
public abstract class Player
{
// Random instance this player is using
private Random _rand;
// Whether this is an X(true) or an O(false)
private bool _player;
protected Random rand
{
get
{
return _rand;
}
private set
{
_rand = value;
}
}
public bool player
{
get
{
return _player;
}
private set
{
_player = value;
}
}
public Player( bool p, Random r )
{
rand = r;
player = p;
}
// chooses the move to make next
// Also responsible for printing out some text
public abstract int MakeMove( GameBoard g );
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIPause : View
{
public override string M_Name
{
get
{
return Consts.V_Pause;
}
}
public Text m_textDis;
public Text m_textCoin;
public Text m_textScore;
[SerializeField]
private SkinnedMeshRenderer skm;
[SerializeField]
private MeshRenderer render;
public void Show()
{
gameObject.SetActive(true);
UpdateUI();
}
public void Hide()
{
gameObject.SetActive(false);
}
void UpdateUI()
{
//TODO:
}
public void OnResumeClick()
{
Hide();
Game.M_Instance.M_Sound.PlayEffect(Consts.S_Se_UI_Button);
MVC.SendEvent(Consts.E_ResumeGameController);
}
public void OnHomeClick()
{
Game.M_Instance.M_Sound.PlayEffect(Consts.S_Se_UI_Button);
Game.M_Instance.LoadLevel(1);
}
private void Awake()
{
UpdateUI();
}
public override void RegisterAttentionEvent()
{
}
public override void HandleEvent(string name, object data)
{
}
}
|
using UnityEngine;
using System.Collections;
public class StageAction : MonoBehaviour {
public static bool isStart;
// 最大描画ステージ
public const int MAX_STAGE_INFO = 8;
// オブジェクト情報
public GameObject[] StageIcon = new GameObject[MAX_STAGE_INFO];
// 現在のページ表示用
public UILabel page_number;
// ステージアイコンの番号
public UILabel[] stage_number = new UILabel[MAX_STAGE_INFO-1];
public static bool isDrawStageNumber;
// 外部参照可能な保存不要のアニメーションフラグ
public static bool ExtraOpenFlag;
void Start(){
isDrawStageNumber = true;
// チュートリアルの設定
// 初めてステージセレクトに遷移した時
if (GameMemory.GuideFlag[0] == 0) {
GameGuide.NowTutorial = TUTORIAL.STAGE_SELECT;
GameMemory.GuideFlag[0] = 1;
}
// ステージ1-1をクリアした後
if (GameMemory.GuideFlag[2] == 0 && GameMemory.StageRank[0] == 3) {
GameGuide.NowTutorial = TUTORIAL.STAGE_CLEAR1;
GameMemory.GuideFlag[2] = 1;
}
// ステージ1-2をクリアした後
if (GameMemory.GuideFlag[4] == 0 && GameMemory.StageRank[1] == 3) {
GameGuide.NowTutorial = TUTORIAL.STAGE_CLEAR2;
GameMemory.GuideFlag[4] = 1;
}
// ステージ1-3をクリアした後
if (GameMemory.GuideFlag[7] == 0 && GameMemory.StageRank[2] == 3) {
GameGuide.NowTutorial = TUTORIAL.STAGE_CLEAR3;
GameMemory.GuideFlag[7] = 1;
}
// チュートリアルの表示
if (GameGuide.NowTutorial != TUTORIAL.NONE)
GameMain.GuideFlag = true;
// アニメーションの確認
if (GameMemory.ExtraAnimationFlag [GameMemory.StagePage] == 0) {
int count = 0;
for(int i=0;i<MAX_STAGE_INFO-1;i++){
// 現在のページの総獲得ランクを計算
count += GameMemory.StageRank[GameMemory.StagePage*MAX_STAGE_INFO+i];
}
if(count >= StageInfo.MAX_RANK * (MAX_STAGE_INFO-1)){
ExtraOpenFlag = true;
}
}
}
// Update is called once per frame
void Update () {
if (isStart) {
Start ();
isStart = false;
}
if (CheckStage.isCheck)
return;
if (isDrawStageNumber) {
DrawStageNumber ();
isDrawStageNumber = false;
}
}
// 各ステージの描画関数
public void DrawStageNumber(){
// 大ステージのテキストの更新
page_number.text = "STAGE " + (GameMemory.StagePage + 1);
int StageIndex = 0;
for(int i=0;i<MAX_STAGE_INFO;i++){
// ステージ用の添え字を確定
StageIndex = GameMemory.StagePage * MAX_STAGE_INFO + i;
if(i == MAX_STAGE_INFO-1){
// エクストラステージの描画(ステージがロックされていれば表示しない)
if(GameMemory.StageRock[StageIndex] == 1 && GameMemory.ExtraAnimationFlag [GameMemory.StagePage] == 1){
StageIcon[i].SetActive(true);
StageIcon[i].GetComponent<UISprite>().color = GameMemory.BackgroundColor[GameMemory.StagePage];
}
else
StageIcon[i].SetActive(false);
}
else{
// ステージアンロック時の描画
if(GameMemory.StageRock[StageIndex] == 1){
// ステージ背景の描画
StageIcon[i].GetComponent<UISprite> ().spriteName = "StageBackground";
// ステージ番号の更新
stage_number[i].text = "" + (i+1);
}else{
// ステージロック時の描画
StageIcon[i].GetComponent<UISprite> ().spriteName = "RockStage";
// ステージ番号を描画しない
stage_number[i].text = "";
}
// 色の更新
StageIcon[i].GetComponent<UISprite>().color = GameMemory.BackgroundColor[GameMemory.StagePage];
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using ZavenDotNetInterview.Common.Enums;
namespace ZavenDotNetInterview.Common.ViewModels
{
public class JobViewModel
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public JobStatus Status { get; set; }
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date.")]
public DateTime? DoAfter { get; set; }
public List<LogViewModel> Logs { get; set; } = new List<LogViewModel>();
public DateTime CreatedAt { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projet2Cpi
{
class Activite
{
/// <summary>
/// Cette classe représente une activité quelconque, dans l'application on en préparera certaines par
/// défaut mais l'utilisateur a le droit d'en créer de nouvelles.
/// Le nombre d'activités créables est limité par l'attribut static (maxNumberOfActivities)
/// </summary>
private string _designation; // désignation de l'activité
public string designation
{
get { return _designation; }
set { _designation = value; }
}
private string _typeOfActivity;// type de l'activité
public string typeOfActivity
{
get { return _typeOfActivity; }
set { _typeOfActivity = value; }
}
private List<Tache> _listOfTaches; // représente la liste des tâches.
public List<Tache> listOfTaches
{
get { return _listOfTaches; }
set { _listOfTaches = value; }
}
private List<Evenement> _listOfEvents; // représente la liste des tâches.
public List<Evenement> listOfEvents
{
get { return _listOfEvents; }
set { _listOfEvents = value; }
}
//Différents constructeurs pour cette classe
public Activite(string designation="Aucune designation", string typeOfActivity="Aucun type",List<Tache> listOfTaches= null, List<Evenement> listOfEvents = null)
{
_designation = designation;
_typeOfActivity = typeOfActivity;
_listOfTaches = listOfTaches;
_listOfEvents = listOfEvents;
}
}
} |
using System;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
namespace CODE.Framework.Wpf.Utilities
{
/// <summary>This class provides helpful features for focus management</summary>
public static class FocusHelper
{
/// <summary>
/// Can move the focus to a true control within a hierarchy of items.
/// For instance, this method can be called by passing a Grid which in turn contains a Panel
/// which in turn contains a TextBox. The TextBox will receive focus.
/// </summary>
/// <param name="parent">Root element that is to receive focus.</param>
/// <param name="delay">The delay in milliseconds before the focus is moved (100ms is the default).</param>
/// <returns>True if a focusable element was found</returns>
public static bool FocusFirstControlDelayed(UIElement parent, int delay = 100)
{
var itemsControl = parent as ItemsControl;
if (itemsControl != null)
{
foreach (var element in itemsControl.Items.OfType<UIElement>())
if (FocusFirstControlDelayed(element)) return true;
return false;
}
var panel = parent as Panel;
if (panel != null)
{
foreach (var child in panel.Children.OfType<UIElement>())
if (FocusFirstControlDelayed(child)) return true;
}
var content = parent as ContentControl;
if (content != null && content.Content != null)
{
var innerControl = content.Content as UIElement;
if (innerControl != null)
return FocusFirstControlDelayed(innerControl);
}
if (parent is Control && !(parent is Label))
{
FocusDelayed(parent, delay: delay);
return true;
}
return false;
}
/// <summary>
/// Sets the focus to the specified control(s) but after a slight delay to allow the calling method to finish before the focus is moved (by routing through a background thread and the message pump)
/// </summary>
/// <param name="focusElement1">The element to set the focus to.</param>
/// <param name="focusElement2">An (optional) next element to set the focus to (typically a parent of the prior element).</param>
/// <param name="focusElement3">An (optional) next element to set the focus to (typically a parent of the prior element).</param>
/// <param name="focusElement4">An (optional) next element to set the focus to (typically a parent of the prior element).</param>
/// <param name="delay">The delay in milliseconds before the focus is moved (100ms is the default).</param>
public static void FocusDelayed(UIElement focusElement1, UIElement focusElement2 = null, UIElement focusElement3 = null, UIElement focusElement4 = null, int delay = 100)
{
var action = new Action<UIElement, UIElement, UIElement, UIElement, int>(FocusDelayed2);
action.BeginInvoke(focusElement1, focusElement2, focusElement3, focusElement4, delay, null, null);
}
private static void FocusDelayed2(UIElement focusElement1, UIElement focusElement2, UIElement focusElement3, UIElement focusElement4, int delay)
{
Thread.Sleep(delay);
var action = new Action<UIElement, UIElement, UIElement, UIElement, int>(FocusDelayed3);
if (Application.Current != null && Application.Current.Dispatcher != null)
try
{
Application.Current.Dispatcher.BeginInvoke(action, DispatcherPriority.Normal, focusElement1, focusElement2, focusElement3, focusElement4, delay);
}
catch
{
// Nothing we can do
}
//Dispatcher.CurrentDispatcher.BeginInvoke(action, DispatcherPriority.ApplicationIdle, new object[] {focusElement1, focusElement2, focusElement3, focusElement4, delay});
}
private static void FocusDelayed3(UIElement focusElement1, UIElement focusElement2, UIElement focusElement3, UIElement focusElement4, int delay)
{
MoveFocusIfPossible(focusElement1);
MoveFocusIfPossible(focusElement2);
MoveFocusIfPossible(focusElement3);
MoveFocusIfPossible(focusElement4);
}
private static void MoveFocusIfPossible(UIElement element)
{
if (element == null) return;
if (element.IsVisible)
element.Focus();
else
element.IsVisibleChanged += TryAgainWhenVisible; // We try again when the control changes visibility
}
private static void TryAgainWhenVisible(object sender, DependencyPropertyChangedEventArgs e)
{
// Not there yet... we can try again
var element = sender as UIElement;
if (element == null) return;
element.IsVisibleChanged -= TryAgainWhenVisible;
FocusDelayed(element);
}
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Administration_Search_Intermediate_Page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strFEDFJCID = "";
if (Request.QueryString["FEDFJCID"] != null)
{
strFEDFJCID = Request.QueryString["FEDFJCID"].ToString();
Array arrTemp = strFEDFJCID.Split(',');
Session["FedId"] = ((string[])(arrTemp))[0];
Session["FJCID"] = ((string[])(arrTemp))[1];
Session["STATUS"] = ((string[])(arrTemp))[2];
Response.Redirect("~/Administration/Search/CamperSummary.aspx?page=wrkq", true);
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using Welic.Dominio.Models.Acesso.Mapeamentos;
namespace Infra.Mapeamentos
{
public class MappingDispositivos
: EntityTypeConfiguration<DispositivosMap>
{
public MappingDispositivos()
{
ToTable("Dispositivos");
HasKey(x => x.Id);
Property(x => x.Id)
.IsRequired()
.HasColumnType("varchar");
Property(x => x.Sharedkey)
.HasColumnType("varchar");
Property(x => x.Plataforma)
.IsRequired()
.HasColumnType("varchar");
Property(x => x.DeviceName)
.IsRequired()
.HasColumnType("varchar");
Property(x => x.Version)
.IsRequired()
.HasColumnType("varchar");
Property(x => x.NameUser)
.HasColumnType("varchar");
Property(x => x.DateSynced)
.IsRequired()
.HasColumnType("datetime");
Property(x => x.DateLastSynced)
.IsRequired()
.HasColumnType("datetime");
Property(x => x.Status)
.IsRequired()
.HasColumnType("varchar");
Property(x => x.EmailUsuario)
.IsRequired()
.HasColumnType("varchar");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using Events;
using UnityEngine.AI;
public class Player_Controller : MonoBehaviour
{
public float fadeSpeed = 1f;
public float targetAlpha;
private Color color;
private Shader shader;
public Camera gameCamera;
private RaycastHit hit;
private bool isBlocking;
private Ray camRaycast;
private GameObject objectHit;
private GameObject objectFaded;
Dictionary<int, GameObject> objectsFaded;
Dictionary<int, GameObject> objectsHit;
private Vector3 cam_player;
private Vector3 screenPos;
// public bool ortograph;
public float movSpeed;
private bool verify;
public Material opaqueMat;
public Material transMat;
private Material[] currentMats;
public float MaxTurnSpeed;
[SerializeField] private float zoomlevel;
[SerializeField] private Animator cameraAnimator;
[SerializeField] private Animator playerAnimator;
[SerializeField] private int targetPicks;
[SerializeField] private int targetCollectables;
private int currentarea;
public enum camstate
{
idle = 0,
zoomin = 1,
zoomout = 2,
}
private bool cameraplaying = false;
private int _camstate = 0;
public int collectables;
public int picks;
private int heals;
private int buffs;
public int money;
private bool dialogueactive;
private bool checkingarea;
private bool enableinput = false;
private WaitForSecondsRealtime waitforseconds = new WaitForSecondsRealtime(0.5f);
private WaitForSecondsRealtime waitenableinput = new WaitForSecondsRealtime(1f);
//// Events ////
private readonly CollectEvent ev_collect = new CollectEvent();
private readonly BuyEvent ev_buy = new BuyEvent();
private readonly ExpandBoundariesEvent ev_expand = new ExpandBoundariesEvent();
private void OnEnable()
{
EventController.AddListener<BeforeSceneUnloadEvent>(BeforeSceneUnloadEvent);
EventController.AddListener<AfterSceneLoadEvent>(AfterSceneLoadEvent);
EventController.AddListener<DialogueStatusEvent>(DialogueStatusEvent);
EventController.AddListener<QuitGameEvent>(QuitGameEvent);
}
private void OnDisable()
{
EventController.RemoveListener<BeforeSceneUnloadEvent>(BeforeSceneUnloadEvent);
EventController.RemoveListener<AfterSceneLoadEvent>(AfterSceneLoadEvent);
EventController.RemoveListener<DialogueStatusEvent>(DialogueStatusEvent);
EventController.RemoveListener<QuitGameEvent>(QuitGameEvent);
}
void Start()
{
objectsHit = new Dictionary<int, GameObject>();
cam_player = gameCamera.transform.position - this.transform.position;
StartCoroutine(WaitEnableInput());
//Por el momento para testear
//money = 1000;
}
void Update()
{
WorldTransparency();
if(dialogueactive)
{
return;
}
if (!checkingarea)
{
checkingarea = true;
StartCoroutine(CheckCurrentArea()); //Checks if the player has met the requisites to advance to the next area
}
//Input routines
if ((Input.GetKey(KeyCode.W) ||
Input.GetKey(KeyCode.A) ||
Input.GetKey(KeyCode.S) ||
Input.GetKey(KeyCode.D)) && enableinput)
{
playerAnimator.SetBool("Walking", true);
PlayerMovement();
}
else
{
playerAnimator.SetBool("Walking", false);
}
if (Input.GetKey(KeyCode.UpArrow) && enableinput)
{
if (_camstate == (int)camstate.idle && !cameraplaying)
{
cameraAnimator.SetBool("CamIdle", false);
cameraAnimator.SetBool("CamOut", false);
cameraAnimator.SetBool("CamIn", true);
_camstate = (int)camstate.zoomin;
cameraplaying = true;
StartCoroutine(WaitforCamera());
}
if (_camstate == (int)camstate.zoomout && !cameraplaying)
{
cameraAnimator.SetBool("CamIdle", true);
cameraAnimator.SetBool("CamOut", false);
cameraAnimator.SetBool("CamIn", false);
_camstate = (int)camstate.idle;
cameraplaying = true;
StartCoroutine(WaitforCamera());
}
}
if (Input.GetKey(KeyCode.DownArrow) && enableinput)
{
if (_camstate == (int)camstate.idle && !cameraplaying)
{
cameraAnimator.SetBool("CamIdle", false);
cameraAnimator.SetBool("CamOut", true);
cameraAnimator.SetBool("CamIn", false);
_camstate = (int)camstate.zoomout;
cameraplaying = true;
StartCoroutine(WaitforCamera());
}
if (_camstate == (int)camstate.zoomin && !cameraplaying)
{
cameraAnimator.SetBool("CamIdle", true);
cameraAnimator.SetBool("CamOut", false);
cameraAnimator.SetBool("CamIn", false);
_camstate = (int)camstate.idle;
cameraplaying = true;
StartCoroutine(WaitforCamera());
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Collectable")
{
Debug.Log("Collectable!");
//Sumar puntos
collectables++;
Player_Status.Collectables++;
other.gameObject.SetActive(false);
EventController.TriggerEvent(ev_collect);
}
}
private void WorldTransparency()
{
screenPos = gameCamera.WorldToScreenPoint(this.transform.position);
camRaycast = gameCamera.ScreenPointToRay(screenPos);
RaycastHit[] hits;
hits = Physics.RaycastAll(camRaycast);
for (int i = 0; i < hits.Length; i++)
{
RaycastHit hit = hits[i];
Debug.Log($"Raycast target: {hit.transform.gameObject.name}");
if (hit.transform.gameObject.tag == "Transparent")
{
//Debug.Log("Hit!");
objectFaded = hit.transform.gameObject;
// Si es nuevo, lo agrego al listado.
if (!objectsHit.ContainsKey(hit.transform.gameObject.GetInstanceID()))
{
//Debug.Log("Asignar material transparente");
//currentMats = objectFaded.GetComponent<MeshRenderer>().materials;
//currentMats[0] = transMat;
objectFaded.GetComponent<MeshRenderer>().material = transMat;
objectsHit.Add(hit.transform.gameObject.GetInstanceID(), hit.transform.gameObject);
}
color = objectFaded.GetComponent<MeshRenderer>().material.color;
if (color.a >= targetAlpha) //Quitar Alpha
//if (Mathf.Approximately(color.a, targetAlpha))
{
color.a -= Time.deltaTime * fadeSpeed;
}
objectFaded.GetComponent<MeshRenderer>().material.color = color;
}
}
//Si el objeto había estado bloqueando pero ya no está mas, le voy sacando alpha hasta que lo quito.
for (int j = 0; j < objectsHit.Count; j++)
{
verify = false;
for (int i = 0; i < hits.Length; i++)
{
if (objectsHit.ElementAt(j).Key == hits[i].transform.gameObject.GetInstanceID())
{
verify = true; //Sigue estando, no hacer nada
}
}
if (verify == false) //No está mas, devolver alpha
{
//Devolver el Alpha
color = objectsHit.ElementAt(j).Value.GetComponent<MeshRenderer>().material.color;
if (color.a < 1.0f)
{
color.a += Time.deltaTime * fadeSpeed;
}
objectsHit.ElementAt(j).Value.GetComponent<MeshRenderer>().material.color = color;
}
}
List<int> keys = new List<int>(objectsHit.Keys);
foreach (int key in keys)
{
//dict[key] = ...
color = objectsHit[key].GetComponent<MeshRenderer>().material.color;
if (color.a >= 1.0f)
//if (Mathf.Approximately(color.a, 1.0f))
{
//Debug.Log("Te devuelvo el opaco");
objectsHit[key].GetComponent<MeshRenderer>().material = opaqueMat;
objectsHit.Remove(key);
}
}
//Si ya volvió a alpha 1, quitarlo.
//for (int j = 0; j < objectsHit.Count; j++)
//{
// //objectFaded.GetComponent<MeshRenderer>().material = opaqueMat;
// color = objectsHit.ElementAt(j).Value.GetComponent<MeshRenderer>().material.color;
// if (color.a >= 1.0f)
// //if (Mathf.Approximately(color.a, 1.0f))
// {
// Debug.Log("Te devuelvo el opaco");
// objectFaded.GetComponent<MeshRenderer>().material = opaqueMat;
// objectsHit.Remove(objectsHit.ElementAt(j).Key);
// }
// //Debug.Log(objectsHit.ElementAt(j).Key);
//}
}
private void PlayerMovement()
{
float changeangle = 45f;
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0, vertical);
direction = Quaternion.AngleAxis(changeangle, Vector3.up) * direction;
direction = direction.normalized * movSpeed;
//this.transform.Translate(direction * Time.deltaTime);
Quaternion wanted_rotation = Quaternion.LookRotation(direction);
this.transform.rotation = Quaternion.RotateTowards(this.transform.rotation, wanted_rotation, MaxTurnSpeed * Time.deltaTime);
this.transform.Translate(Vector3.forward * Time.deltaTime);
gameCamera.transform.position = this.transform.position + cam_player;
}
bool AnimatorIsPlaying(Animator animator)
{
return animator.GetCurrentAnimatorStateInfo(0).length >
animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
}
IEnumerator WaitforCamera()
{
yield return waitforseconds;
cameraplaying = false;
}
private void BeforeSceneUnloadEvent(BeforeSceneUnloadEvent before)
{
//Items
Player_Status.Collectables = collectables;
Player_Status.Picks = picks;
Player_Status.Heals = heals;
Player_Status.Buffs = buffs;
Player_Status.Money = money;
Player_Status.CurrentArea = currentarea;
////Player position
Map_Status.PlayerRotation = this.transform.rotation;
Map_Status.PlayerPosition = this.transform.position;
////Camera position
Map_Status.CameraRotation = gameCamera.transform.rotation;
Map_Status.CameraPosition = gameCamera.transform.position;
}
private void AfterSceneLoadEvent(AfterSceneLoadEvent after)
{
//Restore Items
collectables = Player_Status.Collectables;
picks = Player_Status.Picks;
heals = Player_Status.Heals;
buffs = Player_Status.Buffs;
money = Player_Status.Money;
currentarea = Player_Status.CurrentArea;
//Restore positions
//if (!Map_Status.FirstTime)
if (!PlayerOptions.NewGame)
{
this.transform.position = Map_Status.PlayerPosition;
this.transform.rotation = Map_Status.PlayerRotation;
gameCamera.transform.position = Map_Status.CameraPosition;
gameCamera.transform.rotation = Map_Status.CameraRotation;
this.transform.GetComponent<NavMeshAgent>().Warp(this.transform.position);
}
}
public void BuyHeal(int price)
{
if (money > price)
{
ev_buy.isheal = true;
ev_buy.price = price;
money -= price;
Player_Status.Money -= price;
heals++;
Player_Status.Heals++;
EventController.TriggerEvent(ev_buy);
}
}
public void BuyBuff(int price)
{
if (money > price)
{
ev_buy.isheal = false;
ev_buy.price = price;
money -= price;
Player_Status.Money -= price;
buffs++;
Player_Status.Buffs++;
EventController.TriggerEvent(ev_buy);
}
}
private void DialogueStatusEvent(DialogueStatusEvent status)
{
dialogueactive = status.dialogueactive;
}
private void QuitGameEvent(QuitGameEvent quitgame)
{
////Player position
Map_Status.PlayerRotation = this.transform.rotation;
Map_Status.PlayerPosition = this.transform.position;
////Camera position
Map_Status.CameraRotation = gameCamera.transform.rotation;
Map_Status.CameraPosition = gameCamera.transform.position;
}
IEnumerator WaitEnableInput()
{
yield return waitenableinput;
enableinput = true;
}
IEnumerator CheckCurrentArea() // A futuro, mejorar con un diccionario, lista, array o lo que sea
{
yield return waitenableinput;
if (picks >= targetPicks && collectables >= targetCollectables && currentarea <2)
{
currentarea = 2;
ev_expand.currentarea = 2;
EventController.TriggerEvent(ev_expand);
Player_Status.CurrentArea = currentarea;
}
checkingarea = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Fuzzing.Fuzzers.Impl
{
public class Fuzzer : IFuzzer
{
private readonly IFuzzer _defaultFuzzer;
private readonly IFuzzer _enumFuzzer;
private readonly IDictionary<Type, IFuzzer> _fuzzers;
public Fuzzer()
{
_defaultFuzzer = new ReflectionFuzzer(this);
_enumFuzzer = new EnumFuzzer();
var typesAssignableFromIFuzzer = AppDomain.CurrentDomain
.GetAssemblies()
.Where(x => x.GlobalAssemblyCache == false)
.Where(x => x.IsDynamic == false)
.SelectMany(x => x.GetExportedTypes())
.Where(x => (x.IsInterface == false) && (x.IsAbstract == false))
.Where(x => typeof (IFuzzer).IsAssignableFrom(x))
.Where(x => typeof (Fuzzer) != x)
.Where(x => typeof (ReflectionFuzzer) != x)
.Where(x => typeof (EnumFuzzer) != x);
_fuzzers = typesAssignableFromIFuzzer
.Select(x => (IFuzzer) Activator.CreateInstance(x))
.Where(x => x.FuzzedType != null)
.ToDictionary(x => x.FuzzedType, x => x);
}
public Type FuzzedType
{
get { throw new NotImplementedException(); }
}
public object Fuzz(Type type)
{
IFuzzer fuzzer;
if (_fuzzers.TryGetValue(type, out fuzzer) == false)
{
if (type.IsPrimitive)
{
throw new ArgumentException(String.Format("Cannot fuzz primitive type '{0}'. It is unrecognized.", type.Name));
}
if (type.IsPointer)
{
throw new NotSupportedException(String.Format("Cannot fuzz pointer type '{0}'. The fuzzing of pointers is unsupported.", type.Name));
}
fuzzer = type.IsEnum
? _enumFuzzer
: _defaultFuzzer;
}
var result = fuzzer.Fuzz(type);
return result;
}
public IEnumerable<object> Fuzz(Type type, int count)
{
return Enumerable.Range(0, count)
.Select(x => Fuzz(type));
}
}
}
|
using System;
namespace Reversed_Chars
{
class Program
{
static void Main(string[] args)
{
char Character1 = char.Parse(Console.ReadLine());
char Character2 = char.Parse(Console.ReadLine());
char Character3 = char.Parse(Console.ReadLine());
Console.WriteLine($"{Character3} {Character2} {Character1}");
}
}
}
|
// talis.xivplugin.twintania
// TwintaniaHPWidgetViewModel.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
using FFXIVAPP.Common.Core.Memory;
using System.Timers;
using FFXIVAPP.Common.Helpers;
using FFXIVAPP.Common.Utilities;
using NLog;
using System;
using talis.xivplugin.twintania.Properties;
using System.Collections.Generic;
using talis.xivplugin.twintania.Helpers;
using MicroTimerLib;
using System.Threading;
using System.Windows.Threading;
using talis.xivplugin.twintania.Events;
namespace talis.xivplugin.twintania.Windows
{
internal sealed class TwintaniaHPWidgetViewModel : INotifyPropertyChanged
{
#region Property Bindings
private static TwintaniaHPWidgetViewModel _instance;
private bool _testMode;
private bool _forceTop;
private ActorEntity _twintaniaEntity;
private double _twintaniaHPPercent;
private bool _twintaniaIsValid;
private bool _twintaniaEngaged;
private ActorEntity _dreadknightEntity;
private double _dreadknightHPPercent;
private bool _dreadknightIsValid;
private TimerHelper _twintaniaDivebombTimer;
private TimerHelper _twintaniaEnrageTimer;
private int _twintaniaDivebombCount;
private double _twintaniaDivebombTimeToNextCur;
private double _twintaniaDivebombTimeToNextMax;
private int _twintaniaDivebombTimeFull;
private double _twintaniaEnrageTime;
private ActorEntity _twintaniaTestActor;
private ActorEntity _dreadknightTestActor;
private System.Timers.Timer _twintaniaTestTimer;
private double _twintaniaTestTimeToNextCur;
private double _twintaniaTestTimeToNextMax;
private Queue<Tuple<string, double>> _twintaniaTestList;
public static TwintaniaHPWidgetViewModel Instance
{
get { return _instance ?? (_instance = new TwintaniaHPWidgetViewModel()); }
}
public bool TestMode
{
get { return _testMode; }
set
{
_testMode = value;
RaisePropertyChanged();
}
}
public bool ForceTop
{
get { return _forceTop; }
set
{
_forceTop = value;
RaisePropertyChanged();
}
}
public ActorEntity TwintaniaEntity
{
get { return _twintaniaEntity ?? (_twintaniaEntity = new ActorEntity()); }
set
{
_twintaniaEntity = value;
RaisePropertyChanged();
}
}
public ActorEntity TwintaniaTestActor
{
get { return _twintaniaTestActor ?? (_twintaniaTestActor = new ActorEntity()); }
set
{
_twintaniaTestActor = value;
RaisePropertyChanged();
}
}
public ActorEntity DreadknightTestActor
{
get { return _dreadknightTestActor ?? (_dreadknightTestActor = new ActorEntity()); }
set
{
_dreadknightTestActor = value;
RaisePropertyChanged();
}
}
public bool TwintaniaIsValid
{
get { return _twintaniaIsValid; }
set
{
_twintaniaIsValid = value;
RaisePropertyChanged();
}
}
public bool TwintaniaEngaged
{
get { return _twintaniaEngaged; }
set
{
_twintaniaEngaged = value;
RaisePropertyChanged();
}
}
public double TwintaniaHPPercent
{
get { return _twintaniaHPPercent; }
set
{
_twintaniaHPPercent = value;
RaisePropertyChanged();
}
}
public ActorEntity DreadknightEntity
{
get { return _dreadknightEntity ?? (_dreadknightEntity = new ActorEntity()); }
set
{
_dreadknightEntity = value;
RaisePropertyChanged();
}
}
public bool DreadknightIsValid
{
get { return _dreadknightIsValid; }
set
{
_dreadknightIsValid = value;
RaisePropertyChanged();
}
}
public double DreadknightHPPercent
{
get { return _dreadknightHPPercent; }
set
{
_dreadknightHPPercent = value;
RaisePropertyChanged();
}
}
public TimerHelper TwintaniaDivebombTimer
{
get { return _twintaniaDivebombTimer ?? (_twintaniaDivebombTimer = new TimerHelper(delegate(object sender, TimerUpdateEventArgs e) { TwintaniaDivebombTimeToNextCur = e.TimeToEvent; })); }
set
{
_twintaniaDivebombTimer = value;
RaisePropertyChanged();
}
}
public TimerHelper TwintaniaEnrageTimer
{
get { return _twintaniaEnrageTimer ?? (_twintaniaEnrageTimer = new TimerHelper(delegate(object sender, TimerUpdateEventArgs e) { TwintaniaEnrageTime = e.TimeToEvent; })); }
set
{
_twintaniaEnrageTimer = value;
RaisePropertyChanged();
}
}
public int TwintaniaDivebombCount
{
get { return _twintaniaDivebombCount; }
set
{
_twintaniaDivebombCount = value;
RaisePropertyChanged();
}
}
public double TwintaniaDivebombTimeToNextCur
{
get { return _twintaniaDivebombTimeToNextCur; }
set
{
_twintaniaDivebombTimeToNextCur = value;
RaisePropertyChanged();
}
}
public double TwintaniaDivebombTimeToNextMax
{
get { return _twintaniaDivebombTimeToNextMax; }
set
{
_twintaniaDivebombTimeToNextMax = value;
RaisePropertyChanged();
}
}
public int TwintaniaDivebombTimeFull
{
get { return _twintaniaDivebombTimeFull; }
set
{
_twintaniaDivebombTimeFull = value;
RaisePropertyChanged();
}
}
public double TwintaniaEnrageTime
{
get { return _twintaniaEnrageTime; }
set
{
_twintaniaEnrageTime = value;
RaisePropertyChanged();
}
}
public System.Timers.Timer TwintaniaTestTimer
{
get
{
if (_twintaniaTestTimer == null)
{
_twintaniaTestTimer = new System.Timers.Timer(100);
_twintaniaTestTimer.Elapsed += delegate
{
TwintaniaTestTimeToNextCur -= 0.1;
TwintaniaEntity = TwintaniaTestActor;
if (TwintaniaTestTimeToNextCur <= 0.00)
{
Tuple<string, double> next = TwintaniaTestList.Dequeue();
if (next.Item2 == 0)
{
_twintaniaTestTimer.Stop();
}
else
{
switch (next.Item1)
{
case "Divebomb":
TriggerDiveBomb();
break;
case "Twister":
SoundHelper.Play(@"\AlertSounds\aruba.wav", Settings.Default.TwintaniaHPWidgetTwisterVolume);
break;
case "End":
TestModeStop();
break;
}
TwintaniaTestTimeToNextCur = next.Item2;
}
}
};
}
return _twintaniaTestTimer;
}
}
public double TwintaniaTestTimeToNextCur
{
get { return _twintaniaTestTimeToNextCur; }
set
{
_twintaniaTestTimeToNextCur = value;
RaisePropertyChanged();
}
}
public double TwintaniaTestTimeToNextMax
{
get { return _twintaniaTestTimeToNextMax; }
set
{
_twintaniaTestTimeToNextMax = value;
RaisePropertyChanged();
}
}
public Queue<Tuple<string, double>> TwintaniaTestList
{
get { return _twintaniaTestList ?? (_twintaniaTestList = new Queue<Tuple<string, double>>()); }
set
{
_twintaniaTestList = value;
RaisePropertyChanged();
}
}
#endregion
#region Declarations
#endregion
public TwintaniaHPWidgetViewModel()
{
}
#region Loading Functions
#endregion
#region Utility Functions
public void TriggerDiveBomb()
{
TwintaniaDivebombCount++;
if (TwintaniaIsValid && TwintaniaDivebombCount <= 6)
{
if (TwintaniaDivebombCount == 4)
{
TwintaniaDivebombTimeToNextCur = Settings.Default.TwintaniaHPWidgetDivebombTimeSlow;
TwintaniaDivebombTimeToNextMax = Settings.Default.TwintaniaHPWidgetDivebombTimeSlow;
TwintaniaDivebombTimeFull = (int)Math.Floor(Settings.Default.TwintaniaHPWidgetDivebombTimeSlow) + 1;
}
else
{
TwintaniaDivebombTimeToNextCur = Settings.Default.TwintaniaHPWidgetDivebombTimeFast;
TwintaniaDivebombTimeToNextMax = Settings.Default.TwintaniaHPWidgetDivebombTimeFast;
TwintaniaDivebombTimeFull = (int)Math.Floor(Settings.Default.TwintaniaHPWidgetDivebombTimeFast) + 1;
}
DivebombTimerStart();
}
}
public void TestModeStart()
{
if (TestMode)
TestModeStop();
Widgets.Instance.ShowTwintaniaHPWidget();
ForceTop = true;
TestMode = true;
TwintaniaTestActor.Name = "Twintania";
TwintaniaTestActor.HPMax = 514596;
TwintaniaTestActor.HPCurrent = 514596;
TwintaniaEntity = TwintaniaTestActor;
TwintaniaIsValid = true;
TwintaniaEngaged = true;
EnrageTimerStart();
TwintaniaHPPercent = 1;
TwintaniaDivebombCount = 1;
TwintaniaDivebombTimeToNextCur = 0;
TwintaniaDivebombTimeToNextMax = 0;
DreadknightTestActor.Name = "Dreadknight";
DreadknightTestActor.HPMax = 11250;
DreadknightTestActor.HPCurrent = 11250;
DreadknightEntity = DreadknightTestActor;
DreadknightIsValid = true;
DreadknightHPPercent = 1;
TwintaniaTestTimeToNextCur = 0.3;
TwintaniaTestList.Enqueue(Tuple.Create("Divebomb", Settings.Default.TwintaniaHPWidgetDivebombTimeFast + 0.5));
TwintaniaTestList.Enqueue(Tuple.Create("Divebomb", Settings.Default.TwintaniaHPWidgetDivebombTimeFast + 0.5));
TwintaniaTestList.Enqueue(Tuple.Create("Divebomb", Settings.Default.TwintaniaHPWidgetDivebombTimeSlow + 0.5));
TwintaniaTestList.Enqueue(Tuple.Create("Divebomb", Settings.Default.TwintaniaHPWidgetDivebombTimeFast + 0.5));
TwintaniaTestList.Enqueue(Tuple.Create("Divebomb", Settings.Default.TwintaniaHPWidgetDivebombTimeFast + 0.5));
TwintaniaTestList.Enqueue(Tuple.Create("Twister", 1.0));
TwintaniaTestList.Enqueue(Tuple.Create("End", (double)0));
TwintaniaTestTimer.Start();
}
public void TestModeStop()
{
if (!TestMode)
return;
ForceTop = false;
DivebombTimerStop();
EnrageTimerStop();
TwintaniaTestList.Clear();
TwintaniaEntity = null;
TwintaniaIsValid = false;
TwintaniaEngaged = false;
TwintaniaHPPercent = 0;
TwintaniaDivebombCount = 1;
TwintaniaDivebombTimeToNextCur = 0;
TwintaniaDivebombTimeToNextMax = 0;
DreadknightIsValid = false;
DreadknightHPPercent = 0;
TestMode = false;
}
public void DivebombTimerStart()
{
TwintaniaDivebombTimer.soundWhenFinished = Settings.Default.TwintaniaHPWidgetDivebombAlertFile;
TwintaniaDivebombTimer.volume = Settings.Default.TwintaniaHPWidgetDivebombVolume;
TwintaniaDivebombTimer.counting = Settings.Default.TwintaniaHPWidgetDivebombCounting;
TwintaniaDivebombTimer.Start(TwintaniaDivebombTimeToNextMax, 25);
RaisePropertyChanged("TwintaniaDivebombTimer");
}
public void DivebombTimerStop()
{
TwintaniaDivebombTimer.Stop();
RaisePropertyChanged("TwintaniaDivebombTimer");
}
public void EnrageTimerStart()
{
TwintaniaEnrageTimer.soundWhenFinished = Settings.Default.TwintaniaHPWidgetEnrageAlertFile;
TwintaniaEnrageTimer.volume = Settings.Default.TwintaniaHPWidgetEnrageVolume;
TwintaniaEnrageTimer.counting = Settings.Default.TwintaniaHPWidgetEnrageCounting;
TwintaniaEnrageTimer.Start(Settings.Default.TwintaniaHPWidgetEnrageTime, 25);
RaisePropertyChanged("TwintaniaEnrageTimer");
}
public void EnrageTimerStop()
{
TwintaniaEnrageTimer.Stop();
RaisePropertyChanged("TwintaniaEnrageTimer");
}
#endregion
#region Command Bindings
#endregion
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Kingdee.CAPP.Model;
namespace Kingdee.CAPP.DAL
{
/// <summary>
/// 类型说明:典型工艺DAL
/// 作 者:jason.tang
/// 完成时间:2013-06-20
/// </summary>
public class TypicalProcessDAL
{
private static Database db = DatabaseFactory.Instance();
/// <summary>
/// 方法说明:根据父节点获取工艺文件
/// 作 者:jason.tang
/// 完成时间:2013-06-20
/// </summary>
/// <param name="parentNode">父节点</param>
/// <returns></returns>
public static DataSet GetTypicalProcesByParentNode(int parentNode)
{
try
{
string strsql = @"SELECT
[TypicalProcessId]
,[BussinessId]
,[Name]
,[Type]
,[ParentNode]
,[CurrentNode]
,[Sort]
FROM [TypicalProcess]
WHERE [ParentNode] = @ParentNode";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
db.AddInParameter(cmd, "@ParentNode", DbType.Int32, parentNode);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 方法说明:根据名称获取典型工艺类型
/// 作者:jason.tang
/// 完成时间:2013-07-23
/// </summary>
/// <param name="name">类型名</param>
/// <returns></returns>
public static DataSet GetTypicalCategory(string name)
{
try
{
string strsql = @"SELECT Name, CurrentNode, Type FROM TypicalProcess ";
if (!string.IsNullOrEmpty(name))
{
strsql += string.Format(" Where Name like '%{0}%' ", name);
}
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch
{
return null;
}
}
/// <summary>
/// 方法说明:检查卡片是否已转为典型
/// 作 者:jason.tang
/// 完成时间:2013-07-24
/// </summary>
/// <param name="businessId">卡片业务ID</param>
/// <param name="parentNode">分类</param>
/// <returns></returns>
public static DataSet ExistTypcialProcessCard(Guid businessId, int parentNode)
{
try
{
string strsql = @"SELECT * FROM TypicalProcess Where BussinessId=@BussinessId And ParentNode=@ParentNode";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
db.AddInParameter(cmd, "@BussinessId", DbType.Guid, businessId);
db.AddInParameter(cmd, "@ParentNode", DbType.Int32, parentNode);
DataSet ds = db.ExecuteDataSet(cmd);
return ds;
}
}
catch
{
return null;
}
}
/// <summary>
/// 方法说明:新增典型工艺
/// 作 者:jason.tang
/// 完成时间:2013-06-20
/// </summary>
/// <param name="typical">典型工艺实体</param>
/// <returns></returns>
public static int AddTypicalProcess(TypicalProcess typical)
{
string strsql = @"INSERT INTO [dbo].[TypicalProcess]
(
[TypicalProcessId]
,[BussinessId]
,[Name]
,[Type]
,[ParentNode]
,[Sort])
VALUES
(
@TypicalProcessId
,@BussinessId
,@Name
,@Type
,@ParentNode
,@Sort);
Select @@Identity;";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
Guid id = Guid.NewGuid();
db.AddInParameter(cmd, "@TypicalProcessId", DbType.Guid, id);
db.AddInParameter(cmd, "@BussinessId", DbType.Guid, typical.BusinessId);
db.AddInParameter(cmd, "@Name", DbType.String, typical.Name);
db.AddInParameter(cmd, "@Type", DbType.Int16, Convert.ToInt16(typical.BType));
db.AddInParameter(cmd, "@ParentNode", DbType.Int32, typical.ParentNode);
db.AddInParameter(cmd, "@Sort", DbType.Int32, typical.Sort);
object currentNode = db.ExecuteScalar(cmd);
return Convert.ToInt32(currentNode);
}
}
/// <summary>
/// 方法说明:新增典型工艺
/// 作 者:jason.tang
/// 完成时间:2013-06-20
/// </summary>
/// <param name="typicalList">典型工艺实体集合</param>
/// <returns></returns>
public static void AddTypicalProcess(List<TypicalProcess> typicalList)
{
string strsql = @"INSERT INTO [dbo].[TypicalProcess]
(
[TypicalProcessId]
,[BussinessId]
,[Name]
,[Type]
,[ParentNode]
,[Sort])
VALUES
(
@TypicalProcessId
,@BussinessId
,@Name
,@Type
,@ParentNode
,@Sort)
Select @@Identity;";
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction trans = conn.BeginTransaction();
DbCommand cmd = null;
try
{
foreach (TypicalProcess ppm in typicalList)
{
cmd = db.GetSqlStringCommand(strsql);
Guid id = Guid.NewGuid();
db.AddInParameter(cmd, "@TypicalProcessId", DbType.Guid, id);
db.AddInParameter(cmd, "@BussinessId", DbType.Guid, ppm.BusinessId);
db.AddInParameter(cmd, "@Name", DbType.String, ppm.Name);
db.AddInParameter(cmd, "@Type", DbType.Int16, Convert.ToInt16(ppm.BType));
db.AddInParameter(cmd, "@ParentNode", DbType.Int32, ppm.ParentNode);
db.AddInParameter(cmd, "@Sort", DbType.Int32, ppm.Sort);
ppm.CurrentNode = Convert.ToInt32(db.ExecuteScalar(cmd));
}
trans.Commit();
}
catch
{
trans.Rollback();
}
finally
{
cmd.Dispose();
}
}
}
/// <summary>
/// 方法说明:根据ID删除典型工艺
/// 作 者:jason.tang
/// 完成时间:2013-07-30
/// </summary>
/// <param name="typicalprocessid">典型工艺ID</param>
/// <returns></returns>
public static bool DeleteTypicalById(Guid typicalprocessid)
{
bool result = true;
string strsql = @"Delete from TypicalProcess Where TypicalProcessId=@TypicalProcessId";
using (DbCommand cmd = db.GetSqlStringCommand(strsql))
{
db.AddInParameter(cmd, "@TypicalProcessId", DbType.Guid, typicalprocessid);
result = db.ExecuteNonQuery(cmd) > 0;
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Windows_Project
{
public partial class shippers : Form
{
SqlConnection conn = new SqlConnection(Properties.Settings.Default.NorthwindConnectionString);
int ShipperID;
bool isAdd = false;
private void LoadcboShipper()
{
try
{
SqlDataReader rd;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
cboShipper.DataSource = null;
cboShipper.Items.Clear();
SqlCommand comm = new SqlCommand();
comm.CommandText = "usp_SSelectShippers";
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
rd = comm.ExecuteReader();
DataTable tblShi = new DataTable();
tblShi.Load(rd);
cboShipper.DataSource = tblShi;
cboShipper.DisplayMember = "CompanyName";
cboShipper.ValueMember = "ShipperID";
if (rd.IsClosed == false)
{
rd.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
public shippers()
{
InitializeComponent();
}
private void shippers_Load(object sender, EventArgs e)
{
LoadcboShipper();
}
private bool ValidateData()
{
try
{
if (txtID.Text == "")
{
err.SetError(txtID, "Please enter a Supplier ID");
return false;
}
else
err.SetError(txtID, "");
if (txtName.Text == "")
{
err.SetError(txtName, "Please enter a Company Name");
return false;
}
else
err.SetError(txtName, "");
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
private void ShipperDetails()
{
try
{
ShipperID = int.Parse(cboShipper.SelectedValue.ToString());
txtID.Text = ShipperID.ToString();
txtName.Text = cboShipper.Text;
SqlDataReader rd;
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "usp_SSelectShippersById";
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("@ShipperID", SqlDbType.Int).Value = ShipperID;
rd = comm.ExecuteReader();
while (rd.Read())
{
txtPhone.Text = rd["Phone"].ToString();
}
if (rd.IsClosed == false)
{
rd.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception Info", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void UpdateSupplier()
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "usp_SUpdateSuppliers";
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("@ShipperID", SqlDbType.NChar, 5).Value = ShipperID;
comm.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 50).Value = txtName.Text.ToString();
comm.Parameters.Add("@Phone", SqlDbType.NVarChar, 50).Value = txtPhone.Text.ToString();
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Record not saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void InsertSupplier()
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "SInsertShipper";
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("@ShipperID", SqlDbType.NChar, 5).Value = txtID.Text.ToString();
comm.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 50).Value = txtName.Text.ToString();
comm.Parameters.Add("@Phone", SqlDbType.NVarChar, 50).Value = txtPhone.Text.ToString();
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Record not saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void cboShipper_SelectedIndexChanged(object sender, EventArgs e)
{
isAdd = false;
if (cboShipper.SelectedIndex > 0)
ShipperDetails();
}
private void btnAdd_Click(object sender, EventArgs e)
{
isAdd = true;
txtID.Clear();
txtName.Clear();
txtPhone.Clear();
txtID.Select();
}
private void btnAccept_Click(object sender, EventArgs e)
{
if (ValidateData() == false)
return;
if (isAdd == true)
{
InsertSupplier();
}
else
InsertSupplier();
MessageBox.Show("Record successfully saved", "Save Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
LoadcboShipper();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Hide();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.Models;
using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Extensions;
using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Models.AzureSearch;
using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.ServiceBus.Converters;
using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.ServiceBus.Interfaces;
using DFC.ServiceTaxonomy.PageLocation.Models;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.ContentManagement;
using OrchardCore.Title.Models;
namespace DFC.ServiceTaxonomy.JobProfiles.DataTransfer.AzureSearch.Converters
{
public class JobProfileIndexMessageConverter : IMessageConverter<JobProfileIndex>
{
private readonly IServiceProvider _serviceProvider;
public JobProfileIndexMessageConverter(IServiceProvider serviceProvider) =>
_serviceProvider = serviceProvider;
public async Task<JobProfileIndex> ConvertFromAsync(ContentItem contentItem)
{
var contentManager = _serviceProvider.GetRequiredService<IContentManager>();
IEnumerable<string> socCode = await Helper.GetContentItemNamesAsync(contentItem.Content.JobProfile.SOCCode, contentManager);
IEnumerable<ContentItem> jobCategories = await Helper.GetContentItemsAsync(contentItem.Content.JobProfile.JobProfileCategory, contentManager);
var jobProfileIndex = new JobProfileIndex();
jobProfileIndex.IdentityField = contentItem.As<GraphSyncPart>().ExtractGuid().ToString();
jobProfileIndex.SocCode = socCode.FirstOrDefault();
jobProfileIndex.Title = contentItem.As<TitlePart>().Title;
string altText = string.IsNullOrEmpty(contentItem.Content.JobProfile.AlternativeTitle.Text.ToString()) ? string.Empty : contentItem.Content.JobProfile.AlternativeTitle.Text.ToString();
jobProfileIndex.AlternativeTitle = altText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
jobProfileIndex.Overview = contentItem.Content.JobProfile.Overview.Text ?? string.Empty;
jobProfileIndex.SalaryStarter = string.IsNullOrEmpty(contentItem.Content.JobProfile.Salarystarterperyear.Value.ToString()) ? default : (double)contentItem.Content.JobProfile.Salarystarterperyear.Value;
jobProfileIndex.SalaryExperienced = string.IsNullOrEmpty(contentItem.Content.JobProfile.Salaryexperiencedperyear.Value.ToString()) ? default : (double)contentItem.Content.JobProfile.Salaryexperiencedperyear.Value;
jobProfileIndex.UrlName = contentItem.As<PageLocationPart>().UrlName ?? string.Empty;
jobProfileIndex.JobProfileCategories = await Helper.GetContentItemNamesAsync(contentItem.Content.JobProfile.JobProfileCategory, contentManager);
jobProfileIndex.JobProfileSpecialism = await Helper.GetContentItemNamesAsync(contentItem.Content.JobProfile.JobProfileSpecialism, contentManager);
jobProfileIndex.HiddenAlternativeTitle = await Helper.GetContentItemNamesAsync(contentItem.Content.JobProfile.HiddenAlternativeTitle, contentManager);
jobProfileIndex.JobProfileCategoriesWithUrl = GetJobCategoriesWithUrl(jobCategories);
jobProfileIndex.JobProfileCategoryUrls = GetJobCategoryUrls(jobCategories);
// These are search enablers from legacy Sitefinity functionality and are not used anymore but kept here so it does not break anything
// These can be removed later if not required.
jobProfileIndex.Interests = new List<string>();
jobProfileIndex.Enablers = new List<string>();
jobProfileIndex.EntryQualifications = new List<string>();
jobProfileIndex.TrainingRoutes = new List<string>();
jobProfileIndex.PreferredTaskTypes = new List<string>();
jobProfileIndex.JobAreas = new List<string>();
jobProfileIndex.EntryQualificationLowestLevel = default;
jobProfileIndex.Skills = await Helper.GetRelatedSkillsAsync(contentItem.Content.JobProfile.Relatedskills, contentManager);
jobProfileIndex.CollegeRelevantSubjects = GetHtml(contentItem.Content.JobProfile.Collegerelevantsubjects);
jobProfileIndex.ApprenticeshipRelevantSubjects = GetHtml(contentItem.Content.JobProfile.Apprenticeshiprelevantsubjects);
jobProfileIndex.UniversityRelevantSubjects = GetHtml(contentItem.Content.JobProfile.Universityrelevantsubjects);
jobProfileIndex.WYDDayToDayTasks = GetHtml((contentItem.Content.JobProfile.Daytodaytasks));
jobProfileIndex.CareerPathAndProgression = GetHtml(contentItem.Content.JobProfile.Careerpathandprogression);
jobProfileIndex.WorkingPattern = await Helper.GetContentItemNamesAsync(contentItem.Content.JobProfile.WorkingPattern, contentManager);
jobProfileIndex.WorkingPatternDetails = await Helper.GetContentItemNamesAsync(contentItem.Content.JobProfile.WorkingPatternDetails, contentManager);
jobProfileIndex.WorkingHoursDetails = await Helper.GetContentItemNamesAsync(contentItem.Content.JobProfile.WorkingHoursDetails, contentManager);
jobProfileIndex.MinimumHours = string.IsNullOrEmpty(contentItem.Content.JobProfile.Minimumhours.Value.ToString()) ? default : (double)contentItem.Content.JobProfile.Minimumhours.Value;
jobProfileIndex.MaximumHours = string.IsNullOrEmpty(contentItem.Content.JobProfile.Maximumhours.Value.ToString()) ? default : (double)contentItem.Content.JobProfile.Maximumhours.Value;
return jobProfileIndex;
}
private static IEnumerable<string> GetJobCategoriesWithUrl(IEnumerable<ContentItem> contentItems) =>
contentItems.Select(x => $"{x.As<TitlePart>().Title}|{x.As<PageLocationPart>().UrlName}");
private static IEnumerable<string> GetJobCategoryUrls(IEnumerable<ContentItem> contentItems) =>
contentItems.Select(x => $"{x.As<PageLocationPart>().UrlName}");
private static string GetHtml(dynamic html)
{
string strValue = html is null ? string.Empty : html.Html.ToString();
return strValue.HTMLToText();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
public class ModelImportProcessor : AssetPostprocessor
{
public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
const string MODEL_PATH = "Assets/Art/Model/Chess/";
foreach (string str in importedAssets)
{
var importer = AssetImporter.GetAtPath(str);
if (importer == null)
continue;
string ext = Path.GetExtension(str).ToLower();
string assetName = Path.GetFileNameWithoutExtension(str);
if (ext.EqualsOrdinal(".fbx") && assetName.Contains("@"))
{
assetName = assetName.Replace("@", "_");
importer.assetBundleName = string.Format("animations/anim_{0}.bundle", assetName);
}
else if (ext.EqualsOrdinal(".prefab") && str.StartsWith(MODEL_PATH))
{
importer.assetBundleName = string.Format("model/{0}.bundle", assetName);
}
if (importer is ModelImporter)
{
var modelImporter = importer as ModelImporter;
modelImporter.isReadable = false;
}
}
}
}
|
using System;
namespace Effigy.Entity.DBContext
{
public class PaymentDetails : BaseEntity
{
public int PaymentID { get; set; }
public string TransitionID { get; set; }
public int UserID { get; set; }
public decimal PaidAmount { get; set; }
public bool IsGstInvoice { get; set; }
public string GstNumber { get; set; }
public string GstHolderName { get; set; }
public string GstHolderAddress { get; set; }
public DateTime? PaymentDateTime { get; set; }
}
}
|
using System;
using System.Runtime.InteropServices;
namespace NStandard
{
public static class Native
{
[Obsolete("Do not use this function in PRODUCTION environment. GC may change the pointer of MANAGED OBJECT.")]
public unsafe static IntPtr AddressOf<T>(T obj, bool skipPrefix) where T : class
{
var oref = __makeref(obj);
var pref = (IntPtr**)&oref;
var pobj = **pref;
var offset = skipPrefix ? IntPtr.Size : 0;
#if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_0_OR_GREATER || NET451_OR_GREATER
return pobj + offset;
#else
return new IntPtr(pobj.ToInt64() + offset);
#endif
}
public unsafe static IntPtr AddressOf<T>(ref T obj) where T : struct
{
var oref = __makeref(obj);
var pref = (IntPtr*)&oref;
var pobj = *pref;
return pobj;
}
[Obsolete("Do not use this function in PRODUCTION environment. GC may change the pointer of MANAGED OBJECT.")]
public static bool AreSame<T>(T obj1, T obj2) where T : class => AddressOf(obj1, false) == AddressOf(obj2, false);
public static bool AreSame<T>(ref T obj1, ref T obj2) where T : struct => AddressOf(ref obj1) == AddressOf(ref obj2);
public static byte[] ReadMemory(IntPtr ptr, int length)
{
var ret = new byte[length];
Marshal.Copy(ptr, ret, 0, length);
return ret;
}
public static void WriteMemory(IntPtr ptr, byte[] bytes)
{
Marshal.Copy(bytes, 0, ptr, bytes.Length);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class uisoITEM_ScoreTimeline : MonoBehaviour
{
public GameObject[] gameObjectWhat;
public UISprite[] spriteHitIcon;
public UILabel[] labelHitName;
public UILabel[] labelHitScore;
public UILabel[] labelWin;
public UILabel labelTime;
public UILabel labelRoundCnt;
//public UILabel labelRedWin;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace WebApplication8.Models
{
public class SignUpSessionViewModel
{
[Display(Name = "Название фильма")]
public string FilmName { get; set; }
[Display(Name = "Дата фильма")]
public DateTime FilmTime { get; set; }
[Display(Name = "Имя покупателя")]
[DataType(DataType.Text)]
public string Customer { get; set; }
}
}
|
using Ibit.Core.Data;
using Ibit.Core.Util;
using UnityEngine;
namespace Ibit.MainMenu.UI
{
public class PlayerMenuUI : MonoBehaviour
{
private void OnEnable()
{
if (!Pacient.Loaded.IsCalibrationDone)
{
SysMessage.Info("Para começar a jogar, você precisa \n calibrar todas 5 ações no menu de calibração!");
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebsiteManagerPanel.Data.Configurations.BaseConfigurations;
using WebsiteManagerPanel.Data.Entities;
namespace WebsiteManagerPanel.Data.Configurations
{
public class DefinitionConfiguration : AuditEntityTypeConfiguration<Definition>
{
public override void ConfigureEntity(EntityTypeBuilder<Definition> builder)
{
builder.ToTable("Definitions");
builder.Property(p => p.Name).HasMaxLength(150).IsRequired();
builder.Property(p => p.Description).HasMaxLength(8000);
builder.HasOne(p => p.Site);
}
}
}
|
using System.Web.Mvc;
namespace DevExpress.Web.Demos {
public partial class ReportController : DemoController {
public ActionResult ThumbnailsReport() {
return DemoView("ThumbnailsReport", "ThumbnailsViewer", ReportDemoHelper.CreateModel("Thumbnails"));
}
public FileResult ThumbnailsImageHandler(string img) {
return File(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Thumbnails/" + img), "image/png");
}
}
}
|
using System;
using System.Threading.Tasks;
namespace FBS.Domain.Core
{
public class EventSourcingRepository<TAggregate> : IRepository<TAggregate>
where TAggregate : AggregateBase, IAggregate
{
private readonly IEventStore eventStore;
public EventSourcingRepository(IEventStore eventStore)
{
this.eventStore = eventStore;
}
public async Task<TAggregate> GetByIdAsync(Guid id)
{
try
{
var aggregate = AggregateBase.CreateEmptyAggregate<TAggregate>();
string aggregateId = typeof(TAggregate).Name + "-" + id;
IEventSourcingAggregate aggregatePersistence = aggregate;
foreach (var @event in await eventStore.ReadEventsAsync(aggregateId))
{
aggregatePersistence.ApplyEvent(@event.DomainEvent, @event.EventNumber);
}
return aggregate;
}
catch (EventStoreAggregateNotFoundException)
{
return null;
}
catch (EventStoreCommunicationException ex)
{
throw new RepositoryException("Unable to access event store.", ex);
}
}
public async Task SaveAsync(TAggregate aggregate)
{
try
{
IEventSourcingAggregate aggregatePersistence = aggregate;
foreach (var @event in aggregatePersistence.GetUncommittedEvents())
{
await eventStore.AppendEventAsync(@event);
}
aggregatePersistence.ClearUncommittedEvents();
}
catch (EventStoreCommunicationException ex)
{
throw new RepositoryException("Unable to access event store.", ex);
}
}
}
} |
using UnityEngine;
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine.UI;
using System.Collections.Generic;
using PlayFab.DataModels;
using EntityKey = PlayFab.DataModels.EntityKey;
using PlayFab.CloudScriptModels;
using PlayFab.Json;
public class PlayFabController : MonoBehaviour
{
public static PlayFabController PFC;
private string username;
private string email;
private string password;
private string passwordC;
private string entityId;
private string entityType;
public GameObject panel;
private void OnEnable()
{
if(PlayFabController.PFC == null)
PlayFabController.PFC = this;
else
if(PlayFabController.PFC != this)
Destroy(this.gameObject);
DontDestroyOnLoad(this.gameObject);
}
public void Start()
{
#if UNITY_ANDROID
var request = new LoginWithAndroidDeviceIDRequest { AndroidDeviceId = ReturnMobileID(), CreateAccount = true };
PlayFabClientAPI.LoginWithAndroidDeviceID(request, OnLoginSuccess, OnLoginFailure);
#elif UNITY_IOS
var request = new LoginWithIOSDeviceIDRequest { DeviceId = ReturnMobileID(), CreateAccount = true };
PlayFabClientAPI.LoginWithIOSDeviceID(request, OnLoginSuccess, OnLoginFailure);
#else
var request = new LoginWithCustomIDRequest { CustomId = ReturnMobileID(), CreateAccount = true };
PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnLoginFailure);
#endif
}
#region Login
private void OnLoginSuccess(LoginResult result)
{
// Get Entity Information
entityId = result.EntityToken.Entity.Id;
entityType = result.EntityToken.Entity.Type;
// Get Account info to see if user has a linked account.
var request = new GetAccountInfoRequest { PlayFabId = result.PlayFabId };
PlayFabClientAPI.GetAccountInfo(request,
resultA => {
// If no linked account show the link account panel.
if(resultA.AccountInfo.Username == "" || resultA.AccountInfo.Username == null &&
(!PlayerPrefs.HasKey("LINK_ACCOUNT_REMINDER") || PlayerPrefs.GetInt("LINK_ACCOUNT_REMINDER") == 1))
panel.SetActive(true);
},
error => { Debug.LogError(error.GenerateErrorReport()); });
// Get object of title entity.
var getRequest = new GetObjectsRequest { Entity = new EntityKey { Id = entityId, Type = entityType } };
PlayFabDataAPI.GetObjects(getRequest,
r => {
// If user has no pc yet, create one with the server function.
if (!r.Objects.ContainsKey("pc1"))
{
var cloudscriptrequest = new ExecuteEntityCloudScriptRequest { FunctionName = "createFirstComputer", GeneratePlayStreamEvent = true };
PlayFabCloudScriptAPI.ExecuteEntityCloudScript(cloudscriptrequest,
re => {
GameManager.gm.SetComputer("cpu1", "mem1");
},
error => { Debug.LogError(error.GenerateErrorReport()); });
}
else
{
JsonObject jsonResult = (JsonObject)r.Objects["pc1"].DataObject;
GameManager.gm.SetComputer(jsonResult["cpu"].ToString(), jsonResult["memory"].ToString());
}
// A way to loop through dictionary.
/*foreach(KeyValuePair<string, ObjectResult> obj in r.Objects)
{
Debug.Log(obj.Key);
Debug.Log(obj.Value.ObjectName);
}*/
},
error => { });
}
private void OnLoginFailure(PlayFabError error)
{
Debug.LogError(error.GenerateErrorReport());
}
public static string ReturnMobileID()
{
string deviceID = SystemInfo.deviceUniqueIdentifier;
return deviceID;
}
#endregion
#region Account
public void SetUsername(string usernameIn)
{
username = usernameIn;
}
public void SetEmail(string emailIn)
{
email = emailIn;
}
public void SetPassword(string passwordIn)
{
password = passwordIn;
}
public void SetPasswordC(string passwordCIn)
{
passwordC = passwordCIn;
}
public void clickCreateEmailAccount()
{
if (password != passwordC)
{
Debug.Log("Password do not match!");
}
else
{
var request = new AddUsernamePasswordRequest { Email = email, Password = password, Username = username };
PlayFabClientAPI.AddUsernamePassword(request, OnAddLoginSuccess, OnAddLoginFailure);
}
}
private void OnAddLoginSuccess(AddUsernamePasswordResult result)
{
Debug.Log("Succesfully Linked!");
}
private void OnAddLoginFailure(PlayFabError error)
{
Debug.LogError(error.GenerateErrorReport());
}
#endregion
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisplayBehavior : MonoBehaviour {
// Use this for initialization
void Start () {
transform.forward = GameObject.FindGameObjectWithTag("MainCamera").transform.position - transform.position;
}
// Update is called once per frame
void Update () {
}
public void SetGazedAt(bool gazedAt) {
if (gazedAt) {
Debug.Log ("poo");
transform.localScale = new Vector3 (transform.localScale.x * 2, transform.localScale.y * 2, transform.localScale.z * 2);
}
}
public void SetNotGazedAt(bool notGazedAt) {
if (notGazedAt) {
Debug.Log ("pee");
transform.localScale = new Vector3 (transform.localScale.x / 2, transform.localScale.y / 2, transform.localScale.z / 2);
}
}
}
|
using System.Text.RegularExpressions;
using Welic.Dominio.Utilitarios.Entidades;
namespace Welic.Dominio.TiposDados
{
public class Cnpj : CpfCnpj
{
public override string ValorFormatado => Formatar();
public Cnpj(string cnpj)
{
Valor = cnpj;
}
public override bool Validar()
{
return ValidarDocumentos.ValidarCnpj(Valor);
}
protected Cnpj()
{
}
private string Formatar()
{
return FormatarRegex(Valor);
}
private static string FormatarRegex(string valor)
{
return Regex.Replace(valor, @"(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})", "$1.$2.$3/$4-$5");
}
public static string Formatar(string cnpf)
{
return FormatarRegex(cnpf);
}
}
} |
using Ave.Extensions.Text;
using FluentAssertions;
using Xunit;
namespace UnitTests.Extensions.Text
{
public class Luhn32Tests
{
[Theory(DisplayName = "L-001: GetCheckSum should return correct check sum.")]
[InlineData("BW7L2X7R4RRAN", 'V')]
[InlineData("SHALM2JMHCEYY", 'Q')]
[InlineData("435PYOXWDDHW2", 'D')]
[InlineData("6UVNHCZNET4GA", 'Z')]
[InlineData("PVMAG27UJZUO4", 'P')]
[InlineData("RR5FHL6XWRC4M", '3')]
[InlineData("47A5UF2C65GLH", 'S')]
[InlineData("J6MCDUFZHSZOA", 'F')]
public void L001(string base32, char expectedCheck)
{
// act
var check = Luhn32.GetCheckSum(base32);
// assert
check.Should().Be(expectedCheck);
}
[Theory(DisplayName = "L-002: IsValid should return true when valid, otherwise false.")]
[InlineData("BW7L2X7R4RRANV", true)]
[InlineData("SHALM2JMHCEYYQ", true)]
[InlineData("435PYOXWDDHW2D", true)]
[InlineData("6UVNHCZNET4GAZ", true)]
[InlineData("PVMAG27UJZUO4J", false)]
[InlineData("RR5FHL6XWRC4MD3", false)]
[InlineData("47A5UF2C65GLHA", false)]
[InlineData("J6MCDUFZHSZOAC", false)]
public void L002(string base32, bool expectedValid)
{
// act
var isValid = Luhn32.IsValid(base32);
// assert
isValid.Should().Be(expectedValid);
}
}
}
|
using Irony.Interpreter;
namespace Bitbrains.AmmyParser
{
public partial class AstAmmyBindSourceThis
{
protected override object DoEvaluate(ScriptThread thread) => GetData(thread);
public IAstAmmyBindSourceSource GetData(ScriptThread thread) => new AstAmmyBindSourceThisData();
}
public class AstAmmyBindSourceThisData : IAstAmmyBindSourceSource
{
public override string ToString() => "$this";
}
} |
using Microsoft.SqlServer.Dac.Extensions.Prototype;
namespace SSDTDevPack.Common.Dac
{
public class Model
{
public static TSqlTypedModel Get(string path)
{
return new TSqlTypedModel(path);
}
public static void Close(TSqlTypedModel model)
{
model.Dispose();
}
}
} |
using UnityEngine;
using UnityEditor;
using Looxid.Link;
using UnityEngine.Playables;
[CustomEditor(typeof(Record1))]
public class buttonininspector1 : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
Record1 a = (Record1)target;
if (GUILayout.Button("start record"))
{
a.startrecord();
}
else if (GUILayout.Button("start without record"))
{
}
else if (GUILayout.Button("write to excel 1"))
{
a.number = 0;
a.savetoexcel();
}
else if (GUILayout.Button("write to excel 2"))
{
a.number = 1;
a.savetoexcel();
}
else if (GUILayout.Button("write to excel 3"))
{
a.number = 2;
a.savetoexcel();
}
}
}
|
using kata_payslip_v2.DataObjects;
using kata_payslip_v2.Interfaces;
namespace kata_payslip_v2
{
public class PayslipGenerator : IPayslipGenerator
{
private IInputHandler FileInputHandler;
private IOutputHandler FileOutputHandler;
private IPayslipInformationCalculator _monthlyPayslipInformationCalculator;
public PayslipGenerator(IInputHandler fileInputHandler, IOutputHandler fileOutputHandler, IPayslipInformationCalculator monthlyPayslipInformationCalculator)
{
FileInputHandler = fileInputHandler;
FileOutputHandler = fileOutputHandler;
_monthlyPayslipInformationCalculator = monthlyPayslipInformationCalculator;
}
public void GeneratePayslip()
{
while (true)
{
var userInputInformation = FileInputHandler.GetNextUserInputInformation();
if (userInputInformation == null)
{
break;
}
var payslipInformation = _monthlyPayslipInformationCalculator.CreatePayslipInformation(userInputInformation);
FileOutputHandler.WritePayslipInformation(payslipInformation);
}
}
}
} |
using Lidgren.Network;
using Modulus2D.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Modulus2D.Network
{
/// <summary>
/// Client-specific networking system
/// </summary>
public class ClientSystem : NetSystem
{
public event NetUpdate UpdateReceived;
private NetClient client;
private NetIncomingMessage message;
public ClientSystem(string host, int port) : base()
{
NetPeerConfiguration config = new NetPeerConfiguration(Identifier);
client = new NetClient(config);
client.Start();
client.Connect(host, port);
}
public override void Update(float deltaTime)
{
while ((message = client.ReadMessage()) != null)
{
switch (message.MessageType)
{
case NetIncomingMessageType.Data:
PacketType type = (PacketType)message.ReadByte();
switch (type)
{
case PacketType.Update:
{
uint count = message.ReadUInt32();
for (int i = 0; i < count; i++)
{
uint id = message.ReadUInt32();
if (networkedEntities.TryGetValue(id, out Entity entity))
{
netComponents.Get(entity).Read(message);
}
}
UpdateReceived?.Invoke((float)stopwatch.Elapsed.TotalSeconds);
stopwatch.Restart();
break;
}
case PacketType.Event:
{
string name = message.ReadString();
MemoryStream stream = new MemoryStream(message.ReadBytes(message.ReadInt32()));
object[] args = (object[])formatter.Deserialize(stream);
netEvents[name](args);
break;
}
case PacketType.Create:
{
string name = message.ReadString();
uint id = message.ReadUInt32();
MemoryStream stream = new MemoryStream(message.ReadBytes(message.ReadInt32()));
object[] args = (object[])formatter.Deserialize(stream);
if (creators.TryGetValue(name, out NetCreate creator))
{
// Create entity
Entity entity = World.Create();
NetComponent network = new NetComponent(id);
entity.AddComponent(network);
// Add to networked entities
networkedEntities.Add(network.Id, entity);
creator(entity, args);
}
break;
}
case PacketType.Remove:
{
uint id = message.ReadUInt32();
if (networkedEntities.TryGetValue(id, out Entity entity))
{
entity.Destroy();
networkedEntities.Remove(id);
}
break;
}
case PacketType.Buffer:
{
int count = message.ReadInt32();
Console.WriteLine(count);
for(int i = 0; i < count; i++)
{
string name = message.ReadString();
uint id = message.ReadUInt32();
MemoryStream stream = new MemoryStream(message.ReadBytes(message.ReadInt32()));
object[] args = (object[])formatter.Deserialize(stream);
if (creators.TryGetValue(name, out NetCreate creator))
{
// Create entity
Entity entity = World.Create();
NetComponent network = new NetComponent(id);
entity.AddComponent(network);
// Add to networked entities
if (networkedEntities.TryGetValue(id, out Entity spawned)) {
Console.WriteLine(id + " Already here");
} else
{
networkedEntities.Add(id, entity);
creator(entity, args);
}
}
}
break;
}
}
break;
default:
break;
}
}
accumulator += deltaTime;
// Send update
if (accumulator > updateTime)
{
NetOutgoingMessage message = client.CreateMessage();
message.Write((byte)PacketType.Update);
message.Write(networkedEntities.Count);
foreach (Entity entity in networkedEntities.Values)
{
netComponents.Get(entity).Write(message);
}
client.SendMessage(message, NetDeliveryMethod.UnreliableSequenced);
accumulator = 0f;
}
}
/// <summary>
/// Register a networked event
/// </summary>
/// <param name="name"></param>
/// <param name="netEvent"></param>
public void RegisterEvent(string name, NetEvent netEvent)
{
netEvents.Add(name, netEvent);
}
/// <summary>
/// Register an entity creator
/// </summary>
/// <param name="name"></param>
/// <param name="creator"></param>
public void RegisterEntity(string name, NetCreate creator)
{
creators.Add(name, creator);
}
/// <summary>
/// Disconnect from the server
/// </summary>
public void Disconnect()
{
client.Disconnect(null);
}
}
}
|
using INOTE.Core.Domain;
using INOTE.Core.Helper;
using INOTE.View;
using INOTE.View.Pages;
using INOTE.ViewModel.Commands;
using INOTE.ViewModel.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace INOTE.ViewModel
{
public class NoteVm : ViewModelBase
{
private User _loggedInUser;
private int _currentPageNumber;
public int CurrentPageNumber
{
get { return _currentPageNumber; }
set
{
_currentPageNumber = value;
OnPropertyChanged("CurrentPageNumber");
}
}
private int _totalPageCount;
public int TotalPageCount
{
get { return _totalPageCount; }
set
{
_totalPageCount = value;
OnPropertyChanged("TotalPageCount");
}
}
private string _searchText;
public string SearchText
{
get { return _searchText; }
set
{
_searchText = value;
CurrentPageNumber = 1;
CalculateTotalPageCount();
GetNotes();
OnPropertyChanged("SearchText");
}
}
private Note _selectedNote;
public Note SelectedNote
{
get { return _selectedNote; }
set
{
_selectedNote = value;
OnPropertyChanged("SelectedNote");
}
}
private IEnumerable<Note> _userNotes;
public IEnumerable<Note> UserNotes
{
get { return _userNotes; }
set
{
_userNotes = value;
OnPropertyChanged("UserNotes");
}
}
private ICommand _previousCommand;
public ICommand PreviousCommand
{
get
{
if (_previousCommand == null)
{
_previousCommand = new RelayCommand(this.Previous);
}
return _previousCommand;
}
}
private ICommand _nextCommand;
public ICommand NextCommand
{
get
{
if (_nextCommand == null)
{
_nextCommand = new RelayCommand(this.Next);
}
return _nextCommand;
}
}
private ICommand _createOrUpdateNoteCommand;
public ICommand CreateOrUpdateNoteCommand
{
get
{
if (_createOrUpdateNoteCommand == null)
{
_createOrUpdateNoteCommand = new RelayCommand(this.CreateOrUpdateNote);
}
return _createOrUpdateNoteCommand;
}
}
private ICommand _deleteNoteCommand;
public ICommand DeleteNoteCommand
{
get
{
if (_deleteNoteCommand == null)
{
_deleteNoteCommand = new RelayCommand(this.DeleteNote);
}
return _deleteNoteCommand;
}
}
private void CreateOrUpdateNote()
{
NavigateCreateOrUpdateNotePage(SelectedNote);
}
private void DeleteNote()
{
var Result = MessageBox.Show($"Would you like to remove {SelectedNote.Title}?", "Note Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (Result == MessageBoxResult.Yes)
{
UnitOfWork.Notes.Remove(SelectedNote);
if (UnitOfWork.Complete() > 0)
{
UserNotes = UnitOfWork.Notes.GetUserNotes(_loggedInUser, SearchText, _currentPageNumber, 10);
}
}
}
private void Next()
{
if (CurrentPageNumber < TotalPageCount)
{
++CurrentPageNumber;
GetNotes();
}
}
private void Previous()
{
if (CurrentPageNumber > 1)
{
--CurrentPageNumber;
GetNotes();
}
}
public void NavigateCreateOrUpdateNotePage(Note note)
{
Frame.Navigate(new CreateOrUpdateNotePage(_loggedInUser, note));
}
public NoteVm(User loggedInUser)
{
MainWindow.SetMainToolbarVisibility(true, loggedInUser);
_loggedInUser = loggedInUser;
CalculateTotalPageCount();
CurrentPageNumber = 1;
GetNotes();
}
private void CalculateTotalPageCount()
{
TotalPageCount = UnitOfWork.Notes.GetNotesCount(_loggedInUser, SearchText, 10);
}
private void GetNotes()
{
UserNotes = UnitOfWork.Notes.GetUserNotes(_loggedInUser, SearchText, _currentPageNumber, 10);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TodoListBusinessLayer
{
public class TodoListBusinessLayer
{
private TodoList.TodoList list;
public TodoListBusinessLayer()
{
list = new TodoList.TodoList();
}
public List<string> GetList()
{
return list.GetList();
}
public int WriteList(string input)
{
list.WriteList(input);
return 0;
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.Wallet.Win.Common;
using FiiiCoin.Wallet.Win.Models;
using System.Collections.ObjectModel;
using System.Linq;
namespace FiiiCoin.Wallet.Win.ViewModels.ShellPages
{
public class FeesViewModel : PopupShellBase
{
private ObservableCollection<TimeGoalItem> _timeGoals;
public ObservableCollection<TimeGoalItem> TimeGoals
{
get
{
if (_timeGoals == null)
_timeGoals = new ObservableCollection<TimeGoalItem>();
return _timeGoals;
}
set
{
_timeGoals = value;
RaisePropertyChanged("TimeGoals");
}
}
private double _defaultFee = 0.001;
private double _otherFee = 0.00001024;
private double _tradeFee = 0.001;
public double TradeFee
{
get { return _tradeFee; }
set { _tradeFee = value; RaisePropertyChanged("TradeFee"); }
}
public override void Init()
{
base.Init();
AppSettingConfig.Default.AppConfig.TimeGoalItems.ForEach(x => TimeGoals.Add(x));
RegeistMessenger<double>(OnRequestFee);
}
void OnRequestFee(double fee)
{
if (fee == _defaultFee)
{
TimeGoal = TimeGoals.FirstOrDefault(x => x.Key == fee);
if (TimeGoal == null)
TimeGoal = TimeGoals.FirstOrDefault();
}
else if (fee == _otherFee)
{
OtherChecked = true;
}
else
{
TradeFee = fee;
CustomerChecked = true;
}
}
public override void OnOkClick()
{
double fee = 0;
if (CustomerChecked)
{
if (TradeFee <= 0)
{
ShowMessage(LanguageService.Default.GetLanguageValue("Error_Fee"));
return;
}
fee = TradeFee;
}
else if (OtherChecked)
{
fee = _otherFee;
}
else
{
fee = _defaultFee;
}
base.OnOkClick();
SendMessenger(Pages.SendPage, fee);
}
protected override string GetPageName()
{
return Pages.FeesPage;
}
private TimeGoalItem _timeGoal;
public TimeGoalItem TimeGoal
{
get { return _timeGoal; }
set
{
_timeGoal = value; RaisePropertyChanged("TimeGoal");
OtherChecked = false;
CustomerChecked = false;
}
}
private bool _otherChecked = false;
public bool OtherChecked
{
get { return _otherChecked; }
set { _otherChecked = value; RaisePropertyChanged("OtherChecked"); }
}
private bool _customerChecked = true;
public bool CustomerChecked
{
get { return _customerChecked; }
set { _customerChecked = value; RaisePropertyChanged("CustomerChecked"); }
}
private bool _recommendChecked = true;
public bool RecommendChecked
{
get { return _recommendChecked; }
set { _recommendChecked = value; RaisePropertyChanged("RecommendChecked"); }
}
}
} |
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Pobs.Domain.Entities;
using Pobs.Tests.Integration.Helpers;
using Xunit;
namespace Pobs.Tests.Integration.Watching
{
public class WatchDatabaseTests : IDisposable
{
private readonly User _user;
private readonly Question _question;
private readonly Answer _answer;
public WatchDatabaseTests()
{
_user = DataHelpers.CreateUser();
_question = DataHelpers.CreateQuestions(_user, 1, _user, 1).Single();
_answer = _question.Answers.First();
}
[Fact]
public void ShouldNotSaveDuplicateTagWatches()
{
var tag = DataHelpers.CreateTag(_user, questions: _question);
using (var dbContext = TestSetup.CreateDbContext())
{
dbContext.Watches.Add(new Watch(_user.Id) { TagId = tag.Id });
dbContext.Watches.Add(new Watch(_user.Id) { TagId = tag.Id });
Assert.Throws<DbUpdateException>(() => dbContext.SaveChanges());
}
}
[Fact]
public void ShouldNotSaveDuplicateQuestionWatches()
{
using (var dbContext = TestSetup.CreateDbContext())
{
dbContext.Watches.Add(new Watch(_user.Id) { QuestionId = _question.Id });
dbContext.Watches.Add(new Watch(_user.Id) { QuestionId = _question.Id });
Assert.Throws<DbUpdateException>(() => dbContext.SaveChanges());
}
}
[Fact]
public void ShouldNotSaveDuplicateAnswerWatches()
{
using (var dbContext = TestSetup.CreateDbContext())
{
dbContext.Watches.Add(new Watch(_user.Id) { AnswerId = _answer.Id });
dbContext.Watches.Add(new Watch(_user.Id) { AnswerId = _answer.Id });
Assert.Throws<DbUpdateException>(() => dbContext.SaveChanges());
}
}
[Fact]
public void ShouldNotSaveDuplicateCommentWatches()
{
var comment = DataHelpers.CreateComments(_answer, _user, 1).Single();
using (var dbContext = TestSetup.CreateDbContext())
{
dbContext.Watches.Add(new Watch(_user.Id) { CommentId = comment.Id });
dbContext.Watches.Add(new Watch(_user.Id) { CommentId = comment.Id });
Assert.Throws<DbUpdateException>(() => dbContext.SaveChanges());
}
}
public void Dispose()
{
DataHelpers.DeleteUser(_user.Id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sparda.Contracts
{
public class ServiceLocator
{
private static ServiceLocator _instance;
private static object _lockInstance = new object();
private readonly Dictionary<Type, object> _instancesByType = new Dictionary<Type, object>();
//private readonly Dictionary<string, object> _instancesById = new Dictionary<string, object>();
private ServiceLocator()
{
}
public TInterface Register<TClass, TInterface>() where TClass : class, TInterface, new()
{
object instance = null;
if (!this._instancesByType.TryGetValue(typeof(TInterface), out instance))
{
instance = new TClass();
this._instancesByType[typeof(TInterface)] = instance;
}
return instance != null ? (TInterface)instance : default(TInterface);
}
public TInterface Register<TClass, TInterface>(Func<TClass> valueFactory) where TClass : class, TInterface
{
object instance = null;
if (!this._instancesByType.TryGetValue(typeof(TInterface), out instance))
{
instance = valueFactory();
this._instancesByType[typeof(TInterface)] = instance;
}
return instance != null ? (TInterface)instance : default(TInterface);
}
public TInterface Get<TInterface>()
{
object instance = null;
this._instancesByType.TryGetValue(typeof(TInterface), out instance);
return instance != null ? (TInterface)instance : default(TInterface);
}
//public TClass Register<TClass>(string id, TClass obj = null) where TClass : class, new()
//{
// if (string.IsNullOrEmpty(id))
// {
// throw new ArgumentNullException("id can not be null");
// }
// object instance = null;
// if (!this._instancesById.TryGetValue(id, out instance))
// {
// instance = new TClass();
// this._instancesById[id] = instance;
// }
// return instance != null ? (TClass)instance : default(TClass);
//}
//public TClass Get<TClass>(string id)
//{
// if (string.IsNullOrEmpty(id))
// {
// throw new ArgumentNullException("id can not be null");
// }
// object instance = null;
// this._instancesById.TryGetValue(id, out instance);
// return instance != null ? (TClass)instance : default(TClass);
//}
public static ServiceLocator Instance
{
get
{
if (_instance == null)
{
lock (_lockInstance)
{
_instance = new ServiceLocator();
}
}
return _instance;
}
}
public static TInterface GetInstance<TInterface>()
{
return Instance.Get<TInterface>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSG东莞路测客户端
{
class DeviceInfo
{
public string DeviceID { get; set; }
public string Kind { get; set; }
public string DeviceNickName { get; set; }
public string OnlineTime { get; set; }
public string Status { get; set; }
public bool IsTasking { get; set; }
public bool IsReadyForWork { get; set; }
public string RunMode { get; set; }
public double Lng { get; set; }
public double Lat { get; set; }
public string IP { get; set; }
public int Port { get; set; }
public string RunKind { get; set; }
public string Province { get; set; }
public string City { get; set; }
public string District { get; set; }
public string Address { get; set; }
public string DSGWGDeviceId { get; set; }
public double TodayFlow { get; set; }
public double MonthFlow { get; set; }
public double YearFlow { get; set; }
public bool IsOnline { get; set; }
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Entity.MD
{
[Serializable]
public partial class SpecialTime : EntityBase, IAuditable
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
[StringLength(50, ErrorMessageResourceName = "Errors_Common_FieldLengthExceed", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "SpecialTime_Region", ResourceType = typeof(Resources.MD.WorkingCalendar))]
public string Region { get; set; }
[Display(Name = "SpecialTime_Flow", ResourceType = typeof(Resources.MD.WorkingCalendar))]
public string Flow { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "SpecialTime_StartTime", ResourceType = typeof(Resources.MD.WorkingCalendar))]
public DateTime StartTime { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "SpecialTime_EndTime", ResourceType = typeof(Resources.MD.WorkingCalendar))]
public DateTime EndTime { get; set; }
[Display(Name = "SpecialTime_Description", ResourceType = typeof(Resources.MD.WorkingCalendar))]
public string Description { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "SpecialTime_Type", ResourceType = typeof(Resources.MD.WorkingCalendar))]
public com.Sconit.CodeMaster.WorkingCalendarType Type { get; set; }
[Display(Name = "SpecialTime_Remarks", ResourceType = typeof(Resources.MD.WorkingCalendar))]
public string Remarks { get; set; }
/// <summary>
/// ÐÝÏ¢ÀàÐÍ
/// </summary>
public CodeMaster.HolidayType HolidayType { get; set; }
public Int32 CreateUserId { get; set; }
public string CreateUserName { get; set; }
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
public string LastModifyUserName { get; set; }
public DateTime LastModifyDate { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
SpecialTime another = obj as SpecialTime;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using ArkSavegameToolkitNet.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArkSavegameToolkitNet
{
public static class IGameObjectContainerExtensions
{
public static GameObject GetObject(this IGameObjectContainer self, ObjectReference reference)
{
if (reference == null || reference.ObjectType != ObjectReference.TYPE_ID) return null;
if (reference.ObjectId > -1 && reference.ObjectId < self.Objects.Count)
return self.Objects.ElementAt(reference.ObjectId);
else return null;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragObject : MonoBehaviour
{
[SerializeField]
private Vector2 mousePosition;
public Transform knifePlace;
private Vector2 initialPosition;
private float deltaX, deltaY;
public static bool used;
public LayerMask Box;
public GameObject Yellow;
// Start is called before the first frame update
void Start()
{
initialPosition = transform.position;
Yellow.SetActive(false);
}
private void OnMouseDown(){
if(!used){
deltaX = Camera.main.ScreenToWorldPoint(Input.mousePosition).x - transform.position.x;
deltaY = Camera.main.ScreenToWorldPoint(Input.mousePosition).y - transform.position.y;
}
}
private void OnMouseDrag(){
if (!used){
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector2(mousePosition.x - deltaX, mousePosition.y - deltaY);
}
}
private void OnMouseUp(){
Vector2 RayPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(RayPosition, Vector2.zero, 100, Box);
if (hit.collider != null && hit.collider.gameObject.tag == "Box"){
gameObject.SetActive(false);
used = true;
Yellow.SetActive(true);
Debug.Log("cut box!");
}
else {
transform.position = new Vector2(initialPosition.x, initialPosition.y);
Debug.Log("not hit");
}
}
// Update is called once per frame
void Update()
{
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Characters
{
[ExecuteInEditMode]
public class WeaponPickupPoint : MonoBehaviour
{
[SerializeField] WeaponConfig weaponConfig;
[SerializeField] AudioClip weaponPickupSfx;
void Start ()
{
}
void Update ()
{
if ( !Application.isPlaying )
{
DestroyChildren ();
InstantiateWeapon ();
}
}
private void DestroyChildren ()
{
foreach ( Transform child in transform )
{
DestroyImmediate ( child.gameObject );
}
}
private void InstantiateWeapon ()
{
var weapon = weaponConfig.GetWeaponPrefab ();
weapon.transform.position = Vector3.zero;
Instantiate ( weapon, gameObject.transform );
}
private void OnTriggerEnter ( Collider collider )
{
FindObjectOfType<PlayerControl>().GetComponent<WeaponSystem>().PutWeaponInHand ( weaponConfig );
AudioSource.PlayClipAtPoint ( weaponPickupSfx, transform.position );
}
}
}
|
namespace Egret3DExportTools
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using UnityEngine;
public enum BlendMode
{
None,
Blend,
Blend_PreMultiply,
Add,
Add_PreMultiply,
Subtractive,
Subtractive_PreMultiply,
Multiply,
Multiply_PreMultiply,
}
public enum EnableState
{
BLEND = 3042,
CULL_FACE = 2884,
DEPTH_TEST = 2929,
POLYGON_OFFSET_FILL = 32823,
SAMPLE_ALPHA_TO_COVERAGE = 32926,
}
public enum FunctionState
{
DepthFunc,
DepthMask,
FrontFace,
CullFace,
BlendEquationSeparate,
BlendFuncSeparate,
}
public enum BlendEquation
{
FUNC_ADD = 32774,
FUNC_SUBTRACT = 32778,
FUNC_REVERSE_SUBTRACT = 32779,
}
public enum BlendFactor
{
ZERO = 0,
ONE = 1,
SRC_COLOR = 768,
ONE_MINUS_SRC_COLOR = 769,
DST_COLOR = 774,
ONE_MINUS_DST_COLOR = 775,
SRC_ALPHA = 770,
ONE_MINUS_SRC_ALPHA = 771,
DST_ALPHA = 772,
ONE_MINUS_DST_ALPHA = 773,
CONSTANT_COLOR = 32769,
ONE_MINUS_CONSTANT_COLOR = 32770,
CONSTANT_ALPHA = 32771,
ONE_MINUS_CONSTANT_ALPHA = 32772,
SRC_ALPHA_SATURATE = 776,
}
public enum CullFace
{
FRONT = 1028,
BACK = 1029,
FRONT_AND_BACK = 1032,
}
public enum FrontFace
{
CW = 2304,
CCW = 2305,
}
public enum DepthFunc
{
NEVER = 512,
LESS = 513,
LEQUAL = 515,
EQUAL = 514,
GREATER = 516,
NOTEQUAL = 517,
GEQUAL = 518,
ALWAYS = 519,
}
public enum RenderQueue
{
Background = 1000,
Geometry = 2000,
AlphaTest = 2450,
Transparent = 3000,
Overlay = 4000,
}
public abstract class BaseMaterialParser
{
public static readonly List<string> UNITY_RENDER_TYPE = new List<string> { "Opaque", "Transparent", "TransparentCutout", "Background", "Overlay" };
protected string shaderAsset;
protected Material source;
protected MaterialData data;
public void Init(string shaderAsset)
{
this.shaderAsset = shaderAsset;
}
public void Parse(Material source, MaterialData data)
{
this.source = source;
this.data = data;
//Unifrom
this.CollectUniformValues();
//Defines
this.CollectDefines();
//States
this.CollectStates();
//Egret
this.data.asset.asset = this.shaderAsset;
}
public virtual void CollectUniformValues()
{
}
public virtual void CollectDefines()
{
var defines = this.data.asset.defines;
var cutoff = 0.0f;
var tag = source.GetTag("RenderType", false, "");
if (UNITY_RENDER_TYPE.Contains(tag))
{
if (tag == "TransparentCutout")
{
cutoff = this.source.GetFloat("_Cutoff", 0.0f);
}
}
else if (source.HasProperty("_Cutoff"))
{
cutoff = this.source.GetFloat("_Cutoff", 0.0f);
}
//
if (cutoff > 0.0f)
{
defines.Add(new Define { name = "ALPHATEST " + cutoff.ToString("0.0####") });
}
}
public virtual void CollectStates()
{
var customConfig = ExportSetting.instance.GetCustomShader(this.shaderName);
var isDoubleSide = this.isDoubleSide;
var isTransparent = this.isTransparent;
var blend = this.blendMode;
if (isDoubleSide || blend != BlendMode.None || isTransparent || (customConfig != null && customConfig.enable != null))
{
if (customConfig != null && customConfig.enable != null)
{
foreach (var value in customConfig.enable)
{
this.data.technique.states.enable.Add((EnableState)value);
}
//
if (customConfig.blendEquationSeparate != null)
{
this.SetBlendEquationSeparate(this.data.technique.states.functions, customConfig.blendEquationSeparate);
}
if (customConfig.blendFuncSeparate != null)
{
this.SetBlendFuncSeparate(this.data.technique.states.functions, customConfig.blendFuncSeparate);
}
if (customConfig.frontFace != null)
{
this.SetFrontFace(this.data.technique.states.functions, customConfig.frontFace);
}
if (customConfig.cullFace != null)
{
this.SetCullFace(this.data.technique.states.functions, customConfig.cullFace);
}
if (customConfig.depthFunc != null)
{
this.SetDepthFunc(this.data.technique.states.functions, customConfig.depthFunc);
}
if (customConfig.depthMask != null)
{
this.SetDepthMask(this.data.technique.states.functions, customConfig.depthMask);
}
}
else
{
this.SetBlend(this.data.technique.states.enable, this.data.technique.states.functions, blend);
this.SetCull(this.data.technique.states.enable, this.data.technique.states.functions, !isDoubleSide);
this.SetDepth(this.data.technique.states.enable, this.data.technique.states.functions, true, !isTransparent);
}
}
}
protected void SetBlendEquationSeparate(Functions functions, int[] blendEquationSeparateValue)
{
functions.blendEquationSeparate = new BlendEquation[blendEquationSeparateValue.Length];
for (int i = 0; i < blendEquationSeparateValue.Length; i++)
{
functions.blendEquationSeparate[i] = (BlendEquation)blendEquationSeparateValue[i];
}
}
protected void SetBlendFuncSeparate(Functions functions, int[] blendFuncSeparateValue)
{
functions.blendFuncSeparate = new BlendFactor[blendFuncSeparateValue.Length];
for (int i = 0; i < blendFuncSeparateValue.Length; i++)
{
functions.blendFuncSeparate[i] = (BlendFactor)blendFuncSeparateValue[i];
}
}
protected void SetFrontFace(Functions functions, int[] frontFaceValue)
{
functions.frontFace = new FrontFace[frontFaceValue.Length];
for (int i = 0; i < frontFaceValue.Length; i++)
{
functions.frontFace[i] = (FrontFace)frontFaceValue[i];
}
}
protected void SetCullFace(Functions functions, int[] cullFaceValue)
{
functions.cullFace = new CullFace[cullFaceValue.Length];
for (int i = 0; i < cullFaceValue.Length; i++)
{
functions.cullFace[i] = (CullFace)cullFaceValue[i];
}
}
protected void SetDepthFunc(Functions functions, int[] depthFuncValue)
{
functions.depthFunc = new DepthFunc[depthFuncValue.Length];
for (int i = 0; i < depthFuncValue.Length; i++)
{
functions.depthFunc[i] = (DepthFunc)depthFuncValue[i];
}
}
protected void SetDepthMask(Functions functions, int[] depthMaskValue)
{
functions.depthMask = new bool[depthMaskValue.Length];
for (int i = 0; i < depthMaskValue.Length; i++)
{
functions.depthMask[i] = depthMaskValue[i] > 0 ? true : false;
}
}
protected void SetBlend(List<EnableState> enables, Functions functions, BlendMode blend)
{
if (blend == BlendMode.None)
{
return;
}
enables.Add(EnableState.BLEND);
var blendFuncSeparate = new int[4];
switch (blend)
{
case BlendMode.Add:
blendFuncSeparate[0] = (int)BlendFactor.SRC_ALPHA;
blendFuncSeparate[1] = (int)BlendFactor.ONE;
blendFuncSeparate[2] = (int)BlendFactor.SRC_ALPHA;
blendFuncSeparate[3] = (int)BlendFactor.ONE;
break;
case BlendMode.Blend:
blendFuncSeparate[0] = (int)BlendFactor.SRC_ALPHA;
blendFuncSeparate[1] = (int)BlendFactor.ONE_MINUS_SRC_ALPHA;
blendFuncSeparate[2] = (int)BlendFactor.ONE;
blendFuncSeparate[3] = (int)BlendFactor.ONE_MINUS_SRC_ALPHA;
break;
case BlendMode.Add_PreMultiply:
blendFuncSeparate[0] = (int)BlendFactor.ONE;
blendFuncSeparate[1] = (int)BlendFactor.ONE;
blendFuncSeparate[2] = (int)BlendFactor.ONE;
blendFuncSeparate[3] = (int)BlendFactor.ONE;
break;
case BlendMode.Blend_PreMultiply:
blendFuncSeparate[0] = (int)BlendFactor.ONE;
blendFuncSeparate[1] = (int)BlendFactor.ONE_MINUS_CONSTANT_ALPHA;
blendFuncSeparate[2] = (int)BlendFactor.ONE;
blendFuncSeparate[3] = (int)BlendFactor.ONE_MINUS_CONSTANT_ALPHA;
break;
case BlendMode.Multiply:
blendFuncSeparate[0] = (int)BlendFactor.ZERO;
blendFuncSeparate[1] = (int)BlendFactor.SRC_COLOR;
blendFuncSeparate[2] = (int)BlendFactor.ZERO;
blendFuncSeparate[3] = (int)BlendFactor.SRC_COLOR;
break;
case BlendMode.Multiply_PreMultiply:
blendFuncSeparate[0] = (int)BlendFactor.ZERO;
blendFuncSeparate[1] = (int)BlendFactor.SRC_COLOR;
blendFuncSeparate[2] = (int)BlendFactor.ZERO;
blendFuncSeparate[3] = (int)BlendFactor.SRC_ALPHA;
break;
}
int[] blendEquationSeparate = { (int)BlendEquation.FUNC_ADD, (int)BlendEquation.FUNC_ADD };
this.SetBlendEquationSeparate(functions, blendEquationSeparate);
this.SetBlendFuncSeparate(functions, blendFuncSeparate);
}
protected void SetCull(List<EnableState> enables, Functions functions, bool cull, FrontFace front = FrontFace.CCW, CullFace face = CullFace.BACK)
{
if (cull)
{
int[] frontFace = { (int)front };
this.SetFrontFace(functions, frontFace);
int[] cullFace = { (int)face };
this.SetCullFace(functions, cullFace);
enables.Add(EnableState.CULL_FACE);
}
}
protected void SetDepth(List<EnableState> enables, Functions functions, bool zTest, bool zWrite)
{
if (zTest && zWrite)
{
return;
}
if (zTest)
{
int[] depthFunc = { (int)DepthFunc.LEQUAL };
this.SetDepthFunc(functions, depthFunc);
enables.Add(EnableState.DEPTH_TEST);
}
int[] depthMask = { zWrite ? 1 : 0 };
this.SetDepthMask(functions, depthMask);
}
protected virtual bool isDoubleSide
{
get
{
var isDoubleSide = source.HasProperty("_Cull") && source.GetInt("_Cull") == (float)UnityEngine.Rendering.CullMode.Off;
if (!isDoubleSide)
{
//others
var shaderName = this.shaderName.ToLower();
isDoubleSide = shaderName.Contains("both") || shaderName.Contains("side");
}
return isDoubleSide;
}
}
protected virtual bool isTransparent
{
get
{
if (source.GetTag("RenderType", false, "") == "Transparent")
{
return true;
}
return false;
}
}
protected virtual BlendMode blendMode
{
get
{
var blend = BlendMode.None;
var shaderName = this.shaderName;
if (source.GetTag("RenderType", false, "") == "Transparent")
{
var premultiply = shaderName.Contains("Premultiply");
if (shaderName.Contains("Additive"))
{
blend = premultiply ? BlendMode.Add_PreMultiply : BlendMode.Add;
}
else if (shaderName.Contains("Multiply"))
{
blend = premultiply ? BlendMode.Multiply_PreMultiply : BlendMode.Multiply;
}
else
{
blend = premultiply ? BlendMode.Blend_PreMultiply : BlendMode.Blend;
}
}
return blend;
}
}
protected virtual string shaderName
{
get
{
return this.source.shader.name;
}
}
}
} |
using UnityEngine;
namespace Delegates
{
public delegate void VoidDelegate();
}
public static class Layer
{
private static int _interactable = LayerMask.GetMask("Interactable");
public static int Interactable
{
get { return _interactable; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Elm327.Core.ObdModes
{
class OBD2Table
{
/// <summary>
/// Engine RPM
/// Bytes length: 2
/// Min: 0
/// Max: 16,383.75
/// Formula: value = ((A * 256) + B) / 4
/// </summary>
public static byte EngineRPM = 0x0C;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GraphUpdater : MonoBehaviour
{
private void OnTriggerStay2D(Collider2D collision)
{
if(collision.tag == "Player")
{
Bounds bounds = GetComponent<Collider2D>().bounds;
AstarPath.active.UpdateGraphs(bounds);
}
}
}
|
using System;
namespace OOMALL.WEB.ViewModels
{
public class CarParkRequest
{
public Guid ParkingSpaceId { get; set; }
public Guid CarCategoryId { get; set; }
public string PlateNumber { get; set; }
}
}
|
using Market.Data.DataBaseModel;
using Microsoft.EntityFrameworkCore;
using System;
namespace Market.Data.EF
{
public class EFDBContext : DbContext
{
public EFDBContext(string connectionString) : base(_getContextOptions(connectionString))
{
}
private static DbContextOptions<EFDBContext> _getContextOptions(string connectionString)
{
var optionsBuilder = new DbContextOptionsBuilder<EFDBContext>();
optionsBuilder.UseSqlServer(connectionString);
return optionsBuilder.Options;
}
public DbSet<Order> Orders { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductAttribute> ProductAttributes { get; set; }
public DbSet<ProductCategory> ProductCategorys { get; set; }
public DbSet<ProductAttributeValue> ProductAttributeValues { get; set; }
public DbSet<ProductImage> ProductImages { get; set; }
public DbSet<Purchaser> Purchasers { get; set; }
public DbSet<Seller> Sellers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.SellerId)
.IsRequired(true);
builder.Property(x => x.PurchaseId)
.IsRequired(true);
builder.Property(x => x.IsPaid)
.IsRequired(true);
builder.Property(x => x.IsSent)
.IsRequired(true);
builder.HasOne<Seller>() //Описание связи
.WithMany()
.HasForeignKey(x => x.SellerId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne<Purchaser>()
.WithMany()
.HasForeignKey(x => x.PurchaseId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<OrderItem>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.ProductId)
.IsRequired(true);
builder.Property(x => x.Count)
.IsRequired(true);
builder.Property(x => x.OrderId)
.IsRequired(true);
builder.HasOne<Order>()
.WithMany()
.HasForeignKey(x => x.OrderId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne<Product>()
.WithMany()
.HasForeignKey(x => x.ProductId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<Product>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.Name)
.IsRequired(true);
builder.Property(x => x.Name)
.HasMaxLength(100);
builder.Property(x => x.Count)
.IsRequired(true);
builder.Property(x => x.Price)
.IsRequired(true);
builder.Property(x => x.Description)
.IsRequired(true);
builder.Property(x => x.Description)
.HasMaxLength(1000);
builder.Property(x => x.MarketingInfo)
.IsRequired(true);
builder.Property(x => x.MarketingInfo)
.HasMaxLength(10000);
builder.Property(x => x.SellerId)
.IsRequired(true);
builder.Property(x => x.ProductCategoryId)
.IsRequired(true);
builder.HasOne<Seller>()
.WithMany()
.HasForeignKey(x => x.SellerId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne<ProductCategory>()
.WithMany()
.HasForeignKey(x => x.ProductCategoryId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<ProductAttribute>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.Name)
.IsRequired(true);
builder.Property(x => x.Name)
.HasMaxLength(100);
builder.Property(x => x.Description)
.IsRequired(true);
builder.Property(x => x.Description)
.HasMaxLength(1000);
});
modelBuilder.Entity<ProductAttributeValue>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.ProductAttributeId)
.IsRequired(true);
builder.Property(x => x.ProductId)
.IsRequired(true);
builder.Property(x => x.Value)
.IsRequired(true);
builder.Property(x => x.Value)
.HasMaxLength(100);
builder.HasOne<ProductAttribute>()
.WithMany()
.HasForeignKey(x => x.ProductAttributeId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne<Product>()
.WithMany()
.HasForeignKey(x => x.ProductId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<ProductCategory>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.Name)
.IsRequired(true);
builder.Property(x => x.Name)
.HasMaxLength(100);
builder.Property(x => x.ParentId)
.IsRequired(false);
builder.HasOne<ProductCategory>()
.WithMany()
.HasForeignKey(x => x.ParentId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<ProductImage>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.URL)
.IsRequired(true);
builder.Property(x => x.ProductId)
.IsRequired(true);
builder.HasOne<Product>()
.WithMany()
.HasForeignKey(x => x.ProductId)
.HasPrincipalKey(x => x.Id)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<Purchaser>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.Name)
.IsRequired(true);
builder.Property(x => x.Mail)
.IsRequired(true);
builder.Property(x => x.Phone)
.IsRequired(true);
});
modelBuilder.Entity<Seller>(builder =>
{
builder.HasKey(x => x.Id);
builder.Property(x => x.Name)
.IsRequired(true);
builder.Property(x => x.Mail)
.IsRequired(true);
builder.Property(x => x.Phone)
.IsRequired(true);
});
}
}
}
|
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Egret3DExportTools
{
public static class ExportScene
{
public static void Export(List<GameObject> roots, string exportPath)
{
string sceneName = PathHelper.CurSceneName;
SerializeObject.Clear();
//路径
string scenePath = sceneName + ".scene.json";
PathHelper.SetSceneOrPrefabPath(scenePath);
var scene = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene();
var sceneEntity = SerializeObject.currentData.CreateEntity();
var sceneComp = SerializeObject.currentData.CreateComponent(SerializeClass.Scene);
sceneComp.properties.SetString("name", sceneName.Substring(sceneName.LastIndexOf('/') + 1));
sceneEntity.AddComponent(sceneComp);
var treeComp = SerializeObject.currentData.CreateComponent(SerializeClass.TreeNode);
treeComp.properties.SetString("name", "Root");
treeComp.properties.SetReference("scene", sceneComp.uuid);
sceneEntity.AddComponent(treeComp);
var sceneSetting = ExportSetting.instance.scene;
// 环境光和光照贴图
var sceneLightComp = SerializeObject.currentData.CreateComponent(SerializeClass.SceneLight);
sceneLightComp.properties.SetColor("ambientColor", RenderSettings.ambientLight);
if(sceneSetting.lightmap)
{
sceneLightComp.properties.SetNumber("lightmapIntensity", UnityEditor.Lightmapping.indirectOutputScale);
sceneLightComp.properties.SetLightmaps(exportPath);
}
sceneEntity.AddComponent(sceneLightComp);
if(sceneSetting.staticBatching)
{
var staticBatching = SerializeObject.currentData.CreateComponent(SerializeClass.StaticBatching);
sceneEntity.AddComponent(staticBatching);
}
// 雾
if (RenderSettings.fog && sceneSetting.fog)
{
var fogComp = SerializeObject.currentData.CreateComponent(SerializeClass.Fog);
if (RenderSettings.fogMode == FogMode.Linear)
{
fogComp.properties.SetInt("mode", 0);
fogComp.properties.SetNumber("near", RenderSettings.fogStartDistance);
fogComp.properties.SetNumber("far", RenderSettings.fogEndDistance);
}
else
{
fogComp.properties.SetInt("mode", 1);
fogComp.properties.SetNumber("density", RenderSettings.fogDensity);
}
fogComp.properties.SetColor("color", RenderSettings.fogColor);
sceneEntity.AddComponent(fogComp);
}
foreach (var child in roots)
{
var childEntity = SerializeObject.SerializeEntity(child);
if (childEntity != null)
{
treeComp.AddChild(childEntity.treeNode);
}
}
SerializeContext.Export(exportPath, scenePath);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseSway : MonoBehaviour
{
public float sway = 2.0f;
[Range(0, 1)]
public float lerp = 0.1f;
public bool invertX = false;
public bool invertY = false;
Vector3 t = new Vector3(0, 0, 0);
// Update is called once per frame
void Update()
{
// whyyy
t = Input.mousePosition;
t.x /= Screen.width;
t.y /= Screen.height;
t.x = 0.5f - t.x;
t.y = 0.5f - t.y;
if(invertX) {
t.x *= -1;
}
if(invertY) {
t.y *= -1;
}
t.z = t.y;
t.y = t.x / 4.0f;
t *= sway;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(t.x, t.y, t.z), lerp);
if(Input.GetKey(KeyCode.Escape)) {
Application.Quit();
}
}
}
|
using System;
using System.Linq;
using System.Web;
using System.Web.Security;
using NBlog.Web.Application.Service.Entity;
using Facebook;
using System.Configuration;
using NBlog.Web.Application.Storage;
namespace NBlog.Web.Application.Service.Internal
{
public class UserService : IUserService
{
private readonly IConfigService _configService;
private readonly IRepository _repository;
public UserService(IConfigService configService, IRepository repository)
{
_configService = configService;
_repository = repository;
var identity = HttpContext.Current.User.Identity;
if (identity.IsAuthenticated)
{
var fbClient = new FacebookClient(identity.Name);
dynamic me = fbClient.Get("me");
Current = _repository.Single<User>(me.id);
}
}
public User Current { get; private set; }
public void Save(User user)
{
if (string.IsNullOrEmpty(user._id))
throw new ArgumentNullException("user", "User must have an Facebook Id value to Save()");
_repository.Save<User>(user);
}
public bool Exists(string id)
{
return _repository.Exists<User>(id);
}
public User Get(string id)
{
return _repository.Single<User>(id);
}
}
} |
using System.Data;
using System.Data.SQLite;
using System.Linq;
using Dapper;
using Nancy;
using Nancy.ModelBinding;
using Testr.Models;
using Testr.Models.Commands;
using Testr.Models.Queries;
using System;
using System.IO;
namespace Testr.Modules
{
public class QuizModule : NancyModule
{
public QuizModule(Repository repository) : base("/quiz")
{
Get["/list/"] = o =>
{
ViewBag.Title = "Quiz List";
var quizes = repository.Load(new AllQuizesQuery());
return View["Quiz/List", quizes];
};
Get["/{id}/edit/"] = o =>
{
ViewBag.Title = "Edit Quiz";
var quiz = repository.Load(new QuizByIdQuery(o.id));
return View["Quiz/Edit", quiz];
};
Get["/new/"] = o =>
{
ViewBag.Title = "New Quiz";
return View["Quiz/Edit", null];
};
Post["/new/"] = o =>
{
var quiz = this.Bind<Quiz>();
var quizSaveNewQuery = new QuizSaveNewQuery(quiz);
quiz = repository.Save(quizSaveNewQuery);
return Response.AsRedirect(string.Format("/quiz/{0}/", quiz.Id));
};
Get["/{id}/take/"] = o =>
{
var quiz = repository.Load(new QuizByIdQuery(o.id));
ViewBag.Title = "Taking " + quiz.Name;
return View["Quiz/Take", quiz];
};
Get["/{id}/review/"] = o =>
{
return Response.AsRedirect("/");
};
Get["/{id}/take/{step}/"] = o =>
{
var step = (int)(o.step ?? 0);
var quiz = repository.Load(new QuizByIdQuery(o.id));
var contents = "";
if (step >= quiz.Questions.Count())
{
using (var stream = new MemoryStream())
{
var x = View["Quiz/Review", quiz];
x.Contents(stream);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
contents = reader.ReadToEnd();
}
}
return Response.AsJson(new
{
type = "Review",
value = contents
});
}
var question = quiz.Questions.Skip(step).First();
return Response.AsJson(new
{
type = "Question",
value = question
});
};
Get["/{id}/"] = o =>
{
var quiz = repository.Load(new QuizByIdQuery(o.id));
ViewBag.Title = quiz.Name;
return View["Quiz/View", quiz];
};
}
}
} |
using UnityEngine;
/// <summary>
/// This is an extremely primitive script where the sole purpose is to move a GameObject right at a fixed speed.
/// This is used on the main menu just to add some atmosphere where zombies can run across the screen.
/// </summary>
public class DumbMove : MonoBehaviour
{
[Header("Configurables")]
[SerializeField]
private Vector3 destinationOffset = new Vector3();
[SerializeField]
private float moveSpeedMinimum = 5f;
[SerializeField]
private float moveSpeedMaximum = 10f;
private float moveSpeed = 0f;
private Rigidbody2D rb = null;
private Vector3 targetDestination = new Vector3();
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void OnEnable()
{
moveSpeed = Random.Range(moveSpeedMinimum, moveSpeedMaximum);
targetDestination = transform.position + destinationOffset;
}
private void Update()
{
rb.MovePosition(transform.position + (Vector3.right * (moveSpeed * Time.deltaTime)));
if (Vector3.Distance(transform.position, targetDestination) < 0.25f)
gameObject.SetActive(false);
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using EventFeed.Producer.EventFeed;
using EventFeed.Producer.EventFeed.Atom;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
namespace EventFeed.Producer.Controllers
{
[ApiController]
public class EventFeedController: ControllerBase, IEventFeedUriProvider
{
[HttpGet("events/latest")]
public async Task<IActionResult> GetLatestEventsAsync()
{
if (!ClientAcceptsAtomResponse())
return StatusCode(StatusCodes.Status406NotAcceptable);
var page = _storage.GetLatestEvents();
return await RenderFeedAsync(page);
}
private bool ClientAcceptsAtomResponse()
{
var acceptHeader = Request.GetTypedHeaders().Accept;
return acceptHeader == null
|| !acceptHeader.Any()
|| acceptHeader.Any(h => _atomMediaType.IsSubsetOf(h));
}
private async Task<IActionResult> RenderFeedAsync(EventFeedPage page)
{
var renderer = new AtomRenderer(page, _storage, this);
var stream = new MemoryStream();
await renderer.RenderAsync(stream);
stream.Position = 0;
return File(stream, contentType: AtomContentType);
}
[HttpGet("events/{pageId}")]
public async Task<IActionResult> GetArchivedEventsAsync(string pageId)
{
if (!ClientAcceptsAtomResponse())
return StatusCode(StatusCodes.Status406NotAcceptable);
EventFeedPage page;
try
{
page = _storage.GetArchivedEvents(pageId);
}
catch (EventFeedPageNotFoundException)
{
return NotFound();
}
return await RenderFeedAsync(page);
}
[NonAction]
public Uri GetLatestEventsUri() =>
new Uri(
Url.Action(
action: "GetLatestEvents",
controller: "EventFeed",
values: null,
protocol: Request.Scheme
)
);
[NonAction]
public Uri GetArchivedPageUri(string pageId) =>
new Uri(
Url.Action(
action: "GetArchivedEvents",
controller: "EventFeed",
values: new { pageId = pageId },
protocol: Request.Scheme
)
);
[NonAction]
public Uri? GetNotificationsUri() =>
_settings.Value.EnableSignalR
? new Uri(new Uri(Request.GetEncodedUrl()), Url.Content("~/events/notification"))
: null;
public EventFeedController(
IReadEventStorage storage,
IOptions<Settings> settings
)
{
_storage = storage;
_settings = settings;
}
private readonly IReadEventStorage _storage;
private readonly IOptions<Settings> _settings;
private const string AtomContentType = "application/atom+xml";
private static readonly MediaTypeHeaderValue _atomMediaType = new MediaTypeHeaderValue(AtomContentType);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dataweb.NShape;
using Dataweb.NShape.Advanced;
using Dataweb.NShape.GeneralShapes;
using Dataweb.NShape.Layouters;
using TableroComando.Clases;
using TableroComando.GUIWrapper;
using Repositorios;
using System.Runtime.InteropServices;
using TableroComando.Dominio;
using Dominio;
namespace TableroComando.Clases
{
class MapaEstrategico
{
[DllImport("shfolder.dll", CharSet = CharSet.Auto)]
private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
private static string GetSharedDocumentsPath()
{
StringBuilder sb = new StringBuilder(260);
SHGetFolderPath(IntPtr.Zero, 46, IntPtr.Zero, 0, sb);
return sb.ToString();
}
private static Project configurarMapaEstrategico(Template Blanco,Template Verde,Template Amarillo,Template Rojo,Project project1, XmlStore xmlStore1)
{
// Open the NShape project
// Path to the NShape sample diagrams
xmlStore1.DirectoryName = AppDomain.CurrentDomain.BaseDirectory;
project1.Name = "Circles";
// Path to the NShape shape library assemblies
project1.LibrarySearchPaths.Add(AppDomain.CurrentDomain.BaseDirectory);
project1.Open();
// Template Blanco
Blanco = new Template("Blanco", project1.ShapeTypes["Ellipse"].CreateInstance());
((IPlanarShape)Blanco.Shape).FillStyle = project1.Design.FillStyles.White;
project1.Repository.InsertTemplate(Blanco);
// Template Verde
Verde = new Template("Verde", project1.ShapeTypes["Ellipse"].CreateInstance());
((IPlanarShape)Verde.Shape).FillStyle = project1.Design.FillStyles.Green;
project1.Repository.InsertTemplate(Verde);
// Template Amarillo
Amarillo = new Template("Amarillo", project1.ShapeTypes["Ellipse"].CreateInstance());
((IPlanarShape)Amarillo.Shape).FillStyle = project1.Design.FillStyles.Yellow;
project1.Repository.InsertTemplate(Amarillo);
// Template Rojo
Rojo = new Template("Rojo", project1.ShapeTypes["Ellipse"].CreateInstance());
((IPlanarShape)Rojo.Shape).FillStyle = project1.Design.FillStyles.Red;
project1.Repository.InsertTemplate(Rojo);
return project1;
}
public static Diagram CrearMapa(Project project1, Diagram diagram, XmlStore xmlStore1)
{
Template Blanco = null;
Template Verde = null;
Template Amarillo = null;
Template Rojo = null;
project1 = configurarMapaEstrategico(Blanco,Verde, Amarillo, Rojo, project1, xmlStore1);
Dictionary<string, RectangleBase> shapeDict = new Dictionary<string, RectangleBase>(1000);
diagram.Height = 1123;
diagram.Width = 1200;
int x1 = 50;
int x2 = 50;
int x3 = 50;
int x4 = 50;
diagram.Shapes.Add(TextoPerspectiva(project1,"Aprendizaje y Crecimiento", 20, 1010));
diagram.Shapes.Add(TextoPerspectiva(project1, "Procesos Internos", 20, 750));
diagram.Shapes.Add(TextoPerspectiva(project1, "Cliente", 20, 450));
diagram.Shapes.Add(TextoPerspectiva(project1, "Financiera", 20, 150));
LineaDePerspectiva(project1,diagram, 900);
LineaDePerspectiva(project1, diagram, 600);
LineaDePerspectiva(project1, diagram, 300);
IList<Objetivo> ListaObj = ObjetivoRepository.Instance.All();
Verde = project1.Repository.GetTemplate("Verde");
Amarillo = project1.Repository.GetTemplate("Amarillo");
Rojo = project1.Repository.GetTemplate("Rojo");
IList<RestriccionObjetivo> restricciones = RestriccionGeneralRepository.Instance.All<RestriccionObjetivo>();
foreach (Objetivo Objetivo in ListaObj)
{
RectangleBase referringShape;
if (!shapeDict.TryGetValue(Objetivo.Nombre, out referringShape))
{
System.Drawing.Color Color = VisualHelper.GetColor(Objetivo.Estado(restricciones));
Template TColorObejtivo = SetColor(Blanco,Verde, Amarillo, Rojo, Color);
referringShape = (RectangleBase)TColorObejtivo.CreateShape();
referringShape.Width = 120;
referringShape.Height = 70;
switch (Objetivo.Perspectiva.Id)
{
// Aprendizaje y crecimiento
case 4:
CoordenadasPersp(x1, 1000, referringShape);
x1 += 150;
break;
// Procesos internos
case 3:
CoordenadasPersp(x2, 700, referringShape);
x2 += 150;
break;
// Clientes
case 2:
CoordenadasPersp(x3, 400, referringShape);
x3 += 150;
break;
// Financiera
case 1:
CoordenadasPersp(x4, 100, referringShape);
x4 += 150;
break;
}
referringShape.SetCaptionText(0, Objetivo.Nombre);
shapeDict.Add(Objetivo.Nombre, referringShape);
diagram.Shapes.Add(referringShape);
}
foreach (Objetivo objetivoHijo in Objetivo.ObjetivosHijos)
{
RectangleBase referredShape;
if (!shapeDict.TryGetValue(objetivoHijo.Nombre, out referredShape))
{
System.Drawing.Color Color = VisualHelper.GetColor(objetivoHijo.Estado(restricciones));
Template TColorObejtivo = SetColor(Blanco,Verde, Amarillo, Rojo, Color);
referredShape = (RectangleBase)TColorObejtivo.CreateShape();
referredShape.Width = 120;
referredShape.Height = 70;
switch (objetivoHijo.Perspectiva.Id)
{
// Aprendizaje y crecimiento
case 4:
CoordenadasPersp(x1, 1000, referredShape);
x1 += 150;
break;
// Procesos internos
case 3:
CoordenadasPersp(x2, 700, referredShape);
x2 += 150;
break;
// Clientes
case 2:
CoordenadasPersp(x3, 400, referredShape);
x3 += 150;
break;
// Financiera
case 1:
CoordenadasPersp(x4, 100, referredShape);
x4 += 150;
break;
}
referredShape.SetCaptionText(0, objetivoHijo.Nombre);
shapeDict.Add(objetivoHijo.Nombre, referredShape);
diagram.Shapes.Add(referredShape);
}
// Add the connection
Polyline arrow = (Polyline)project1.ShapeTypes["Polyline"].CreateInstance();
diagram.Shapes.Add(arrow);
arrow.Connect(ControlPointId.FirstVertex, referringShape, ControlPointId.Reference);
arrow.Connect(ControlPointId.LastVertex, referredShape, ControlPointId.Reference);
//
}
}
project1.Close();
return diagram;
}
private static void LineaDePerspectiva(Project project1, Diagram diagram, int y)
{
Polyline shape = (Polyline)project1.ShapeTypes["Polyline"].CreateInstance();
shape.MoveControlPointTo(ControlPointId.FirstVertex, 0, y, ResizeModifiers.None);
shape.MoveControlPointTo(ControlPointId.LastVertex, 1200, y, ResizeModifiers.None);
diagram.Shapes.Add(shape);
}
private static void CoordenadasPersp(int x, int y, RectangleBase Shape)
{
Shape.X = x + 100;
Shape.Y = y;
}
private static RectangleBase TextoPerspectiva(Project project1,string texto, int x, int y)
{
RectangleBase shape = (RectangleBase)project1.ShapeTypes["Text"].CreateInstance();
shape.X = x;
shape.Y = y;
shape.SetCaptionText(0, texto);
shape.Rotate(2700, x, y);
return shape;
}
private static Template SetColor(Template Blanco,Template Verde,Template Amarillo,Template Rojo, System.Drawing.Color Color)
{
// Compruebo el color del objetivo
Template TColor = null;
if (Color == System.Drawing.Color.White)
{
TColor = Blanco;
}
else
{
if (Color == System.Drawing.Color.Green)
{
TColor = Verde;
}
else
{
if (Color == System.Drawing.Color.Yellow)
{
TColor = Amarillo;
}
else
{
if (Color == System.Drawing.Color.Red)
{
TColor = Rojo;
}
}
}
}
return TColor;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Musical_WebStore_BlazorApp.Shared;
using Musical_WebStore_BlazorApp.Client;
using Musical_WebStore_BlazorApp.Server.Data;
using Microsoft.EntityFrameworkCore;
using Admin.Models;
using AutoMapper;
using Admin.Decisions;
using Admin.ViewModels;
using Admin.ResultModels;
using Microsoft.AspNetCore.Identity;
using Musical_WebStore_BlazorApp.Server.Data.Models;
using Admin.Services;
namespace Musical_WebStore_BlazorApp.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ManagementController : Controller
{
private readonly MusicalShopIdentityDbContext ctx;
private readonly IMapper _mapper;
private readonly UserManager<User> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ServicesDecisionHendler _decisionHendler;
private readonly IFileSavingService fileSavingService;
public ManagementController(MusicalShopIdentityDbContext ctx, IMapper mapper, UserManager<User> userManager, RoleManager<IdentityRole> roleManager, ServicesDecisionHendler decisionHendler, IFileSavingService ifileSavingService)
{
this.ctx = ctx;
_mapper = mapper;
_userManager = userManager;
_roleManager = roleManager;
_decisionHendler = decisionHendler;
fileSavingService = ifileSavingService;
}
[Route("getservices")]
public async Task<ServiceViewModel[]> GetServices()
{
return await ctx.Services.Select(s => _mapper.Map<ServiceViewModel>(s)).ToArrayAsync();
}
[Route("getcompanies")]
public async Task<CompanyModel[]> GetCompanies()
{
return await ctx.Companies.Select(s => _mapper.Map<CompanyModel>(s)).ToArrayAsync();
}
[Route("getserviceusers/{serviceId}")]
public async Task<UserLimited[]> GetServiceUsers(int serviceId)
{
return await ctx.ServiceUsers.Where(su => su.ServiceId == serviceId).Select(su => _mapper.Map<UserLimited>(su.User)).ToArrayAsync();
}
[Route("getcompanyusers/{companyId}")]
public async Task<UserLimited[]> GetCompanyUsers(int companyId)
{
return await ctx.CompanyUsers.Where(cu => cu.CompanyId == companyId).Select(cu => _mapper.Map<UserLimited>(cu.User)).ToArrayAsync();
}
[Route("getserviceusers")]
public async Task<UserLimited[]> GetServiceUsers()
{
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
int serviceId = ctx.ServiceUsers.Single(su => su.UserId == user.Id).ServiceId;
return await ctx.ServiceUsers.Where(su => su.ServiceId == serviceId).Select(su => _mapper.Map<UserLimited>(su.User)).ToArrayAsync();
}
[Route("getcompanyusers")]
public async Task<UserLimited[]> GetCompanyUsers()
{
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
int companyId = ctx.CompanyUsers.Single(cu => cu.UserId == user.Id).CompanyId;
var us = await ctx.CompanyUsers.Where(cu => cu.CompanyId == companyId).Select(cu => _mapper.Map<UserLimited>(cu.User)).ToArrayAsync();
foreach(var u in us)
{
var roles =await _userManager.GetRolesAsync(_userManager.FindByIdAsync(u.Id).Result);
u.Role = roles.First();
}
return us;
}
[Route("getroles")]
public async Task<RoleModel[]> GetRoles()
{
RoleModel[] roles;
if(User.IsInRole("CompanyAdmin"))
{
roles = new RoleModel[] {new RoleModel() { Name = "CompanyAdmin"}, new RoleModel() { Name = "CompanyOperator"}};
}
else if(User.IsInRole("ServiceAdmin"))
{
roles = new RoleModel[] {new RoleModel() { Name = "ServiceAdmin"}, new RoleModel() { Name = "ServiceOperator"}, new RoleModel() { Name = "Worker"}};
}
else
throw new Exception("Fuck you!");
return roles;
}
[Route("editemp")]
public async Task<Result> EditEmp(EditEmpModel model)
{
var user = await _userManager.FindByIdAsync(model.Id);
var userroles = await _userManager.GetRolesAsync(user);
await _userManager.RemoveFromRolesAsync(user, userroles);
await _userManager.AddToRoleAsync(user, model.NewRole);
var userroles1 = await _userManager.GetRolesAsync(user);
user.Position = model.Position;
await _userManager.UpdateAsync(user);
return new Result() {Successful = true};
}
[Route("decisions/{city}")]
public List<ServiceViewModel> Decision(string city)
{
var services = _decisionHendler.InitServices(city);
return services.Select(s => _mapper.Map<ServiceViewModel>(s)).ToList();
}
[Route("addorg")]
public async Task<Result> AddService(AddOrgModel model)
{
var user = await _userManager.FindByEmailAsync(model.OwnersEmail);
switch(model.Type)
{
case "Service":
await _userManager.AddToRoleAsync(user, "ServiceAdmin");
var service = new Service() {CreationDate = DateTime.Now};
ctx.Services.Add(service);
await ctx.SaveChangesAsync();
ctx.ServiceUsers.Add(
new ServiceUser()
{
ServiceId = service.Id,
UserId = user.Id
}
);
break;
case "Company":
await _userManager.AddToRoleAsync(user, "CompanyAdmin");
var company = new Company() {CreationDate = DateTime.Now};
ctx.Companies.Add(company);
await ctx.SaveChangesAsync();
ctx.CompanyUsers.Add(
new CompanyUser()
{
CompanyId = company.Id,
UserId = user.Id
}
);
break;
}
await ctx.SaveChangesAsync();
return new Result() {Successful = true};
//TODO constraints
}
[Route("getuserinfo")]
public async Task<ProfileModel> GetUserInfo()
{
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
var profileModel = _mapper.Map<ProfileModel>(user);
if(ctx.CompanyUsers.Select(cu => cu.UserId).Contains(user.Id))
{
var company = ctx.CompanyUsers.Single(cu => cu.UserId == user.Id).Company;
profileModel.Company = _mapper.Map<CompanyModel>(company);
}
else if(ctx.ServiceUsers.Select(cu => cu.UserId).Contains(user.Id))
{
var service = ctx.ServiceUsers.Single(cu => cu.UserId == user.Id).Service;
profileModel.Company = _mapper.Map<CompanyModel>(service);
}
else
{
}
return profileModel;
}
[Route("getuserinfo/{userId}")]
public async Task<ProfileModel> GetUserInfo(string userId)
{
var user = await _userManager.FindByIdAsync(userId);
var profileModel = _mapper.Map<ProfileModel>(user);
if(ctx.CompanyUsers.Select(cu => cu.UserId).Contains(user.Id))
{
var company = ctx.CompanyUsers.Single(cu => cu.UserId == user.Id).Company;
profileModel.Company = _mapper.Map<CompanyModel>(company);
}
else if(ctx.ServiceUsers.Select(cu => cu.UserId).Contains(user.Id))
{
var service = ctx.ServiceUsers.Single(cu => cu.UserId == user.Id).Service;
profileModel.Company = _mapper.Map<CompanyModel>(service);
}
else
{
}
return profileModel;
}
[Route("changepersinfo")]
public async Task<Result> ChangePersInfo(PersonalInfo info)
{
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
var isValid = await _userManager.CheckPasswordAsync(user, info.OldPassword);
if(isValid)
{
await _userManager.ChangePasswordAsync(user, info.OldPassword, info.NewPassword);
return new Result() { Successful = true, Error = "Password was changed successfully" };
}
else
{
return new Result() { Successful = false, Error = "You entered wrong password" };
}
}
[Route("changegeninfo")]
public async Task<Result> ChangeGenInfo(EditGenUserInfo info)
{
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
user.Name = info.Name;
user.PhoneNumber = info.Phone;
await _userManager.UpdateAsync(user);
return new Result(){ Successful = true};
}
[Route("fireemp")]
public async Task<Result> FireEmp(FireModel model)
{
var user = await _userManager.FindByIdAsync(model.Id);
if(model.IsInService)
{
var su = ctx.ServiceUsers.Single(su => su.UserId == model.Id);
ctx.ServiceUsers.Remove(su);
}
else
{
var cu = ctx.CompanyUsers.Single(cu => cu.UserId == model.Id);
ctx.CompanyUsers.Remove(cu);
}
await ctx.SaveChangesAsync();
return new Result(){ Successful = true};
}
[Route("hireemp")]
public async Task<Result> HireEmp(UserLimited model)
{
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
var isInService = ctx.ServiceUsers.Select(su => su.UserId).Contains(user.Id);
var emp = await _userManager.FindByEmailAsync(model.Email);
if(emp == null)
{
return new Result() {Successful = false, Error = $"There are no users registered with email {model.Email}" };
}
var alreadyHired = ctx.ServiceUsers.Select(su => su.UserId).Contains(emp.Id);
if(alreadyHired) return new Result() { Successful = false, Error = $"{emp.Name} is already hired by another service"};
alreadyHired = ctx.CompanyUsers.Select(su => su.UserId).Contains(emp.Id);
if(alreadyHired) return new Result() { Successful = false, Error = $"{emp.Name} is already hired by another company"};
if(isInService)
{
int serviceId = ctx.ServiceUsers.Single(su => su.UserId == user.Id).ServiceId;
ctx.ServiceUsers.Add(new ServiceUser() { UserId = emp.Id, ServiceId = serviceId});
}
else
{
int companyId = ctx.CompanyUsers.Single(su => su.UserId == user.Id).CompanyId;
ctx.CompanyUsers.Add(new CompanyUser() { UserId = emp.Id, CompanyId = companyId});
}
await ctx.SaveChangesAsync();
return new Result(){ Successful = true, Error = $"{emp.Name} was hired successfully!"};
}
[Route("changeuserpicture")]
public async Task<Result> ChangeUserPicture(AddUserPicture model)
{
var localFilePath = await SaveAndGetLocalFilePathIfNewerPhoto(model);
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
user.Image = localFilePath;
await _userManager.UpdateAsync(user);
return new Result(){ Successful = true };
}
private async Task<string> SaveAndGetLocalFilePathIfNewerPhoto(AddUserPicture model)
{
bool ValidateImage(AddUserPicture model) => model.ImageBytes != null && model.ImageType != null;
var localFilePath =
ValidateImage(model)
? await fileSavingService.SaveFileAsync(model.ImageBytes, model.ImageType, "images")
: null;
return localFilePath;
}
}
}
|
using UnityEngine;
namespace Thesis {
public class BalconyRail : DrawableObject
{
/*************** FIELDS ***************/
public readonly BalconyFloor parentFloor;
public BuildingMesh parentBuilding
{
get { return parentFloor.parentBuilding; }
}
public Face parentFace
{
get { return parentFloor.parentBalcony.parentFace; }
}
public BalconyRail (BalconyFloor parent)
: base("balcony_rail")
{
parentFloor = parent;
var height = 1f;
boundaries = new Vector3[8];
boundaries[0] = parentFloor.boundaries[4];
boundaries[1] = parentFloor.boundaries[5];
boundaries[2] = boundaries[1] - parentFloor.depth * parentFace.normal;
boundaries[3] = boundaries[0] - parentFloor.depth * parentFace.normal;
for (var i = 0; i < 4; ++i)
boundaries[i + 4] = boundaries[i] + height * Vector3.up;
FindMeshOrigin(boundaries[0],
boundaries[6],
boundaries[2],
boundaries[4]);
for (var i = 0; i < boundaries.Length; ++i)
boundaries[i] -= meshOrigin;
}
public override void FindVertices ()
{
// make length * 4 for inside sides of rails
vertices = new Vector3[boundaries.Length * 2];
for (int i = 0; i < 2; ++i)
System.Array.Copy(boundaries, 0, vertices, i * boundaries.Length, boundaries.Length);
}
public override void FindTriangles ()
{
triangles = new int[18];
// from outside
// front
triangles[0] = 0;
triangles[1] = 1;
triangles[2] = 4;
triangles[3] = 1;
triangles[4] = 5;
triangles[5] = 4;
//// left
//triangles[6] = 1;
//triangles[7] = 2;
//triangles[8] = 5;
//triangles[9] = 2;
//triangles[10] = 6;
//triangles[11] = 5;
//// right
//triangles[12] = 0;
//triangles[13] = 4;
//triangles[14] = 3;
//triangles[15] = 3;
//triangles[16] = 4;
//triangles[17] = 7;
// left
triangles[6] = 9; // 1 + 8
triangles[7] = 10; // 2 + 8
triangles[8] = 13; // 5 + 8
triangles[9] = 10; // 2 + 8
triangles[10] = 14; // 6 + 8
triangles[11] = 13; // 5 + 8
// right
triangles[12] = 8; // 0 + 8
triangles[13] = 12; // 4 + 8
triangles[14] = 11; // 3 + 8
triangles[15] = 11; // 3 + 8
triangles[16] = 12; // 4 + 8
triangles[17] = 15; // 7 + 8
// from inside are the previous tris in reverse order
//var index = 18;
//for (var i = 17; i >= 0; --i)
// triangles[index++] = triangles[i] + 16;
}
public override void Draw ()
{
base.Draw();
var uvs = new Vector2[mesh.vertices.Length];
uvs[2 + 8] = new Vector2(.5f, 0f);
uvs[6 + 8] = new Vector2(.5f, 1f);
uvs[1 + 8] = new Vector2(1f, 0f);
uvs[5 + 8] = new Vector2(1f, 1f);
uvs[1] = new Vector2(0f, 0f);
uvs[5] = new Vector2(0f, 1f);
uvs[0] = new Vector2(1f, 0f);
uvs[4] = new Vector2(1f, 1f);
uvs[0 + 8] = new Vector2(1f, 0f);
uvs[4 + 8] = new Vector2(1f, 1f);
uvs[3 + 8] = new Vector2(.5f, 0f);
uvs[7 + 8] = new Vector2(.5f, 1f);
mesh.uv = uvs;
gameObject.transform.position = meshOrigin + parentBuilding.meshOrigin + parentFloor.meshOrigin;
gameObject.transform.parent = parentBuilding.parent.gameObject.transform;
}
private Texture2D CreateTexture ()
{
var tex = new Texture2D(256, 128);
int y = -1;
int x = -1;
var thickness = 5;
do
{
x = 0;
do
{
tex.SetPixel(x, y, Color.black);
//Debug.Log(y);
} while (x++ < tex.width);
} while (y++ < thickness - 1);
do
{
x = 0;
do
{
if ((x & y) == 0)
tex.SetPixel(x, y, Color.black);
else
tex.SetPixel(x, y, Color.clear);
} while (x++ < tex.width);
} while (y++ < tex.height - thickness);
do
{
x = 0;
do
{
tex.SetPixel(x, y, Color.black);
Debug.Log(y);
} while (x++ < tex.width);
} while (y++ < tex.height);
tex.Apply();
return tex;
}
}
} // namespace Thesis |
using BUS;
using DTO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace QuanLySinhVien
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Canbogiaovien_DTO L = new Canbogiaovien_DTO();
DangNhap_Bus LopB = new DangNhap_Bus();
private void btndangnhap_Click(object sender, EventArgs e)
{
if(txttk.Text == "")
{
MessageBox.Show("Bạn cần nhập tài khoản !", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
txttk.Focus();
}else if(txtmk.Text =="")
{
MessageBox.Show("Bạn cần nhập mật khẩu !", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtmk.Focus();
}else
{
L.Taikhoan = txttk.Text;
L.Matkhau = txtmk.Text;
if (LopB.KTTK(L.Taikhoan, L.Matkhau)) // check pass and usedname
{
if (LopB.LoaiTaiKhoan(L.Taikhoan) == 1)
{
try
{
//Form1.UsedName = textTK.Text;
this.Hide();
QuanLyDiem mt = new QuanLyDiem();
mt.Show();
}
catch
{
MessageBox.Show("Tài khoản không khả dụng ");
}
}
else
{
try
{
//Form1.UsedName = textTK.Text;
this.Hide();
QuanLyHeThong mt = new QuanLyHeThong();
mt.Show();
}
catch
{
MessageBox.Show("Tài khoản không khả dụng ");
}
}
}
else
{
MessageBox.Show("Tài khoản không hợp lệ vui lòng nhập lại");
}
}
}
}
}
|
using System;
namespace Compiler.Exceptions
{
public class MissingReturnStatementException : Exception
{
public MissingReturnStatementException()
{
}
public MissingReturnStatementException(string message) : base(message)
{
Message = message;
}
public override string Message { get; }
}
} |
using Core;
using DBCore;
using MaterialDesignThemes.Wpf;
using ServiceCenter.Helpers;
using ServiceCenter.View.Repair;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
namespace ServiceCenter.ViewModel.Repair
{
class PageOrderWorkNewWorkViewModel : BaseViewModel
{
//наша форма
private FormOrderWork window = Application.Current.Windows.OfType<FormOrderWork>().FirstOrDefault();
//индикатор ожидания
private bool _isAwait = false;
public bool IsAwait { get => _isAwait; set => Set(ref _isAwait, value); }
private string _name;
public string Name { get => _name; set => Set(ref _name, value); }
private double _price = 0;
public double Price { get => _price; set => Set(ref _price, value); }
ICallbackAddToList callback;
public ICommand SaveCommand { get; }
public PageOrderWorkNewWorkViewModel(ICallbackAddToList callback)
{
this.callback = callback;
SaveCommand = new Command(SaveExecute, SaveCanExecute);
}
private bool SaveCanExecute(object arg)
{
return (String.IsNullOrEmpty(Name)) ? false : true;
}
private async void SaveExecute(object obj)
{
//проверка на существование
IsAwait = true;
bool result = await WorkDB.IsWorkExist(Name);
IsAwait = false;
if (!result)
{
//добавление
IsAwait = true;
Work work = await WorkDB.AddWorkAsync(Name, Price);
IsAwait = false;
if (work == null) Message("Ошибка добавления в базу данных!");
else
{
callback.AddToList(work);
window.frameOrderWork.GoBack();
}
}
else
Message("Данная работа уже существует.\nВоспользуйтесь поиском!");
}
//Wpf.DialogHost
private async void Message(string msg)
{
View.Dialog.InfoDialog infoDialog = new View.Dialog.InfoDialog();
Dialog.InfoDialogViewModel context = new Dialog.InfoDialogViewModel(msg);
infoDialog.DataContext = context;
await DialogHost.Show(infoDialog, "WorkDialog");
}
}
}
|
namespace Sitecore.AntiPackageWizard.Util
{
using Sitecore.Configuration;
using Sitecore.Data.Items;
using Sitecore.Install.Framework;
using Sitecore.Install.Zip;
using Sitecore.IO;
using Sitecore.Web;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
public class CreateAntiPackage
{
[NotNull]
public void Execute([NotNull] string fileName)
{
var sourceFileName = LocalFile.MapPath(fileName);
var targetFileName = GetTargetFileName(sourceFileName);
var packageAnalyzer = new PackageAnalyzer(new SimpleProcessingContext());
var reader = new PackageReader(sourceFileName);
reader.Populate(packageAnalyzer);
var newItems = new List<PackageAnalyzer.PackageItem>();
var newFiles = new List<PackageAnalyzer.PackageFile>();
var package = new ZipPackageBuilder(targetFileName)
{
PackageName = "Anti Package for " + Path.GetFileNameWithoutExtension(sourceFileName),
Readme = string.Format("Anti Package for {0}. Created {1} by {2}.", Path.GetFileNameWithoutExtension(sourceFileName), DateTime.Now.ToString(), Context.GetUserName())
};
AddItems(packageAnalyzer, package, newItems);
AddFiles(packageAnalyzer, package, newFiles);
AddPostStep(package, newItems, newFiles);
package.Build();
}
private void AddDescendants(ZipPackageBuilder package, Item item)
{
package.Items.Add(item);
foreach (Item child in item.Children)
{
AddDescendants(package, child);
}
}
private void AddFiles(PackageAnalyzer packageAnalyzer, ZipPackageBuilder package, List<PackageAnalyzer.PackageFile> newFiles)
{
foreach (var packageFile in packageAnalyzer.Files)
{
var file = FileUtil.MapPath(packageFile.FileName);
if (File.Exists(file))
{
package.Files.Add(packageFile.FileName);
}
else
{
newFiles.Add(packageFile);
}
}
}
private void AddItems(PackageAnalyzer packageAnalyzer, ZipPackageBuilder package, List<PackageAnalyzer.PackageItem> newItems)
{
var items = new List<Item>();
var paths = new Dictionary<string, PackageAnalyzer.PackageItem>();
foreach (var packageItem in packageAnalyzer.Items)
{
var database = Factory.GetDatabase(packageItem.DatabaseName);
if (database == null)
{
continue;
}
var item = database.GetItem(packageItem.ID);
if (item == null)
{
AddNewItem(paths, packageItem);
continue;
}
var isAdded = items.Any(i => i.ID == item.ID || i.Axes.IsAncestorOf(item));
if (!isAdded)
{
items.Add(item);
}
}
newItems.AddRange(paths.Values);
foreach (var item in items)
{
AddDescendants(package, item);
}
}
private void AddNewItem(Dictionary<string, PackageAnalyzer.PackageItem> paths, PackageAnalyzer.PackageItem packageItem)
{
var path = packageItem.Path;
if (paths.Keys.Any(p => path.StartsWith(p, StringComparison.InvariantCultureIgnoreCase)))
{
return;
}
var descendants = paths.Keys.Where(p => p.StartsWith(path, StringComparison.InvariantCultureIgnoreCase)).ToList();
foreach (var key in descendants)
{
paths.Remove(key);
}
paths[packageItem.Path] = packageItem;
}
private void AddPostStep(ZipPackageBuilder package, List<PackageAnalyzer.PackageItem> newItems, List<PackageAnalyzer.PackageFile> newFiles)
{
if (newItems.Count == 0 && newFiles.Count == 0)
{
return;
}
package.PostStep = "Sitecore.Rocks.Server.Requests.Packages.PackagePostStep,Sitecore.Rocks.Server";
package.Comment = GetPostStepData(newItems, newFiles);
}
[NotNull]
private string GetPostStepData([NotNull] List<PackageAnalyzer.PackageItem> newItems, [NotNull] List<PackageAnalyzer.PackageFile> newFiles)
{
var writer = new StringWriter();
var output = new XmlTextWriter(writer)
{
Formatting = Formatting.Indented
};
output.WriteStartElement("uninstall");
WriteItems(output, newItems);
WriteFiles(output, newFiles);
output.WriteEndElement();
return writer.ToString();
}
[NotNull]
public string GetTargetFileName([NotNull] string sourceFileName)
{
var result = Path.Combine(Path.GetDirectoryName(sourceFileName) ?? string.Empty, Path.GetFileNameWithoutExtension(sourceFileName) + ".anti" + Path.GetExtension(sourceFileName));
var index = 1;
while (File.Exists(result))
{
result = Path.Combine(Path.GetDirectoryName(sourceFileName) ?? string.Empty, Path.GetFileNameWithoutExtension(sourceFileName) + ".anti (" + index + ")" + Path.GetExtension(sourceFileName));
index++;
}
return result;
}
private void WriteFiles(XmlTextWriter output, List<PackageAnalyzer.PackageFile> newFiles)
{
if (!newFiles.Any())
{
return;
}
output.WriteStartElement("files");
foreach (var packageFile in newFiles)
{
output.WriteStartElement("file");
output.WriteAttributeString("filename", packageFile.FileName);
output.WriteEndElement();
}
output.WriteEndElement();
}
private void WriteItems(XmlTextWriter output, List<PackageAnalyzer.PackageItem> newItems)
{
if (!newItems.Any())
{
return;
}
output.WriteStartElement("items");
foreach (var packageItem in newItems)
{
output.WriteStartElement("item");
output.WriteAttributeString("database", packageItem.DatabaseName);
output.WriteAttributeString("id", packageItem.ID.ToString());
output.WriteEndElement();
}
output.WriteEndElement();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Dominio.Entities
{
public class TabelaCustas
{
public int TabelaCustasId { get; set; }
public int Atribuicao { get; set; }
public int Ordem { get; set; }
public string Tabela { get; set; }
public string Item { get; set; }
public string SubItem { get; set; }
public string Descricao { get; set; }
public decimal Valor { get; set; }
public int Ano { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Normal.Realtime.Serialization;
[RealtimeModel]
public partial class InteractionSyncModel
{
[RealtimeProperty(1, true, true)]
private string _interaction;
}
/* ----- Begin Normal Autogenerated Code ----- */
public partial class InteractionSyncModel : IModel
{
// Properties
public string interaction
{
get { return _cache.LookForValueInCache(_interaction, entry => entry.interactionSet, entry => entry.interaction); }
set { if (value == interaction) return; _cache.UpdateLocalCache(entry => { entry.interactionSet = true; entry.interaction = value; return entry; }); FireInteractionDidChange(value); }
}
// Events
public delegate void InteractionDidChange(InteractionSyncModel model, string value);
public event InteractionDidChange interactionDidChange;
// Delta updates
private struct LocalCacheEntry
{
public bool interactionSet;
public string interaction;
}
private LocalChangeCache<LocalCacheEntry> _cache;
public InteractionSyncModel()
{
_cache = new LocalChangeCache<LocalCacheEntry>();
}
// Events
public void FireInteractionDidChange(string value)
{
try
{
if (interactionDidChange != null)
interactionDidChange(this, value);
}
catch (System.Exception exception)
{
Debug.LogException(exception);
}
}
// Serialization
enum PropertyID
{
Interaction = 1,
}
public int WriteLength(StreamContext context)
{
int length = 0;
if (context.fullModel)
{
// Mark unreliable properties as clean and flatten the in-flight cache.
// TODO: Move this out of WriteLength() once we have a prepareToWrite method.
_interaction = interaction;
_cache.Clear();
// Write all properties
length += WriteStream.WriteStringLength((uint)PropertyID.Interaction, _interaction);
}
else
{
// Reliable properties
if (context.reliableChannel)
{
LocalCacheEntry entry = _cache.localCache;
if (entry.interactionSet)
length += WriteStream.WriteStringLength((uint)PropertyID.Interaction, entry.interaction);
}
}
return length;
}
public void Write(WriteStream stream, StreamContext context)
{
if (context.fullModel)
{
// Write all properties
stream.WriteString((uint)PropertyID.Interaction, _interaction);
}
else
{
// Reliable properties
if (context.reliableChannel)
{
LocalCacheEntry entry = _cache.localCache;
if (entry.interactionSet)
_cache.PushLocalCacheToInflight(context.updateID);
if (entry.interactionSet)
stream.WriteString((uint)PropertyID.Interaction, entry.interaction);
}
}
}
public void Read(ReadStream stream, StreamContext context)
{
bool interactionExistsInChangeCache = _cache.ValueExistsInCache(entry => entry.interactionSet);
// Remove from in-flight
if (context.deltaUpdatesOnly && context.reliableChannel)
_cache.RemoveUpdateFromInflight(context.updateID);
// Loop through each property and deserialize
uint propertyID;
while (stream.ReadNextPropertyID(out propertyID))
{
switch (propertyID)
{
case (uint)PropertyID.Interaction:
{
string previousValue = _interaction;
_interaction = stream.ReadString();
if (!interactionExistsInChangeCache && _interaction != previousValue)
FireInteractionDidChange(_interaction);
break;
}
default:
stream.SkipProperty();
break;
}
}
}
}
/* ----- End Normal Autogenerated Code ----- */
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CursoWindowsForms
{
public class Login
{
public string Nome { get; set; }
public string Senha { get; set; }
public Login()
{
Nome = "Joao";
Senha = "hiper123";
}
}
}
|
using System.Collections.Generic;
using ClassLibraryCommon.DTO;
using ClassLibraryDatabase.Mock;
namespace ClassLibraryDatabase
{
public class MockDb
{
// internal List<Book> GetBooks()
// {
// MockBooksTable _table = new MockBooksTable();
// return _table.Books;
// }
// TODO need GetAuthors
// TODO need GetGenre
// TODO need GetPublishers
// TODO need GetUsers
private MockUsersTable _tableUsers;
private MockRolesTable _tableRoles;
private MockBooksTable _tableBooks;
public MockDb()
{
_tableUsers = new MockUsersTable();
_tableRoles = new MockRolesTable();
_tableBooks = new MockBooksTable();
}
#region Users
// R-Read part of CRUD
public List<UserDTO> GetUsers()
{
return _tableUsers.GetUsers();
}
public void CreateUser(UserDTO u)
{
_tableUsers.Add(u);
}
public void DeleteUser(UserDTO u)
{
_tableUsers.Delete(u);
}
#endregion
#region Roles
// R part of CRUD
public List<RoleDTO> GetRoles()
{
MockRolesTable _table = new MockRolesTable();
return _table.Roles;
}
// C part of CRUD
internal void AddRole(RoleDTO inRoleDTO)
{
// implementation
MockRolesTable _table = new MockRolesTable();
_table.Add(inRoleDTO);
}
// U part of CRUD
internal void UpdateRole(RoleDTO inRoleDTO)
{
// implementation
}
// D part of CRUD
internal void DeleteRole(RoleDTO inRoleDTO)
{
// implementation
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JDWinService.Model
{
//采购订单 表头
public class Json_POOrder_Head
{
public page1 Page1 { get; set; }
public class page1
{
public string FCancellation { get; set; }
public string FClassTypeID { get; set; }
public string FEnterpriseID { get; set; }
public string FHeadSelfP0252 { get; set; }
public string FHeadSelfP0254 { get; set; }
public Fheadselfp0255 FHeadSelfP0255 { get; set; }
public string FSendStatus { get; set; }
public string FStatus { get; set; }
public string Fdate { get; set; }
public Fareaps FAreaPS { get; set; }
public Fsettleid FSettleID { get; set; }
public Fbrid FBrID { get; set; }
public Fpostyle FPOStyle { get; set; }
public Frelatebrid FRelateBrID { get; set; }
public string FSettleDate { get; set; }
public Fsupplyid FSupplyID { get; set; }
public string FPOOrdBillNo { get; set; }
public string FExplanation { get; set; }
public string FTranType { get; set; }
public Fcurrencyid FCurrencyID { get; set; }
public string FSelTranType { get; set; }
public string FSelBillNo { get; set; }
public string FExchangeRate { get; set; }
public string FBillNo { get; set; }
public string FMultiCheckStatus { get; set; }
public string FDeliveryPlace { get; set; }
public string Attachments { get; set; }
public Fplancategory FPlanCategory { get; set; }
public Fexchangeratetype FExchangeRateType { get; set; }
public Fpomode FPOMode { get; set; }
public Fcheckerid FCheckerID { get; set; }
public string FCheckDate { get; set; }
public Fmangerid FMangerID { get; set; }
public Fdeptid FDeptID { get; set; }
public Fempid FEmpID { get; set; }
public Fbillerid FBillerID { get; set; }
public string FManageType { get; set; }
public Fconsignee FConsignee { get; set; }
public string FSysStatus { get; set; }
public string FValidaterName { get; set; }
public string FVersionNo { get; set; }
public string FChangeDate { get; set; }
public Fchangeuser FChangeUser { get; set; }
public string FChangeCauses { get; set; }
public string FChangeMark { get; set; }
}
public class Fheadselfp0255
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fareaps
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fsettleid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fbrid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fpostyle
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Frelatebrid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fsupplyid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fcurrencyid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fplancategory
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fexchangeratetype
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fpomode
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fcheckerid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fmangerid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fdeptid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fempid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fbillerid
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fconsignee
{
public string FNumber { get; set; }
public string FName { get; set; }
}
public class Fchangeuser
{
public string FNumber { get; set; }
public string FName { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lighter.Domain.Share
{
public class ConstVoteSourceType
{
public const string Question = "question";
public const string Anwser = "answer";
}
}
|
using System;
namespace iSukces.Code
{
public struct NameAndTypeName
{
public NameAndTypeName(string propName, string propertyTypeName)
{
PropName = propName;
PropertyTypeName = propertyTypeName;
}
public string PropName { get; }
public string PropertyTypeName { get; }
}
public struct NameAndType
{
public NameAndType(string name, Type type)
{
Name = name;
Type = type;
}
public string Name { get; }
public Type Type { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Services.Transaction;
using com.Sconit.Entity.MRP.MD;
using com.Sconit.Service;
using com.Sconit.Web.Models;
using com.Sconit.Web.Models.SearchModels.MRP;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using com.Sconit.Entity.Exception;
namespace com.Sconit.Web.Controllers.MRP
{
public class IslandController : WebAppBaseController
{
//public IGenericMgr genericMgr { get; set; }
private static string selectCountStatement = "select count(*) from Island as i";
private static string selectStatement = "select i from Island as i";
//
// GET: /ProdLineEx/
#region Public Method
#region View
public ActionResult Index()
{
return View();
}
[GridAction]
[SconitAuthorize(Permissions = "Url_MRP_Island_View")]
public ActionResult List(GridCommand command, IslandSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_MRP_Island_View")]
public ActionResult _AjaxList(GridCommand command, IslandSearchModel searchModel)
{
SearchStatementModel searchStatementModel = this.PrepareSearchStatement(command, searchModel);
return PartialView(GetAjaxPageData<Island>(searchStatementModel, command));
}
#endregion
#region Edit
[HttpGet]
[SconitAuthorize(Permissions = "Url_MRP_Island_View")]
public ActionResult Edit(string Code)
{
if (string.IsNullOrEmpty(Code))
{
return HttpNotFound();
}
else
{
Island island = this.genericMgr.FindAll<Island>("select i from Island as i where i.Code=? ", new object[] { Code })[0];
return View(island);
}
}
[SconitAuthorize(Permissions = "Url_MRP_Island_View")]
public ActionResult Edit(Island island)
{
if (ModelState.IsValid)
{
this.genericMgr.UpdateWithTrim(island);
SaveSuccessMessage(Resources.MRP.Island.Island_Updated);
}
return View(island);
}
[SconitAuthorize(Permissions = "Url_MRP_Island_View")]
public ActionResult New()
{
return View();
}
[HttpPost]
[SconitAuthorize(Permissions = "Url_MRP_Island_View")]
public ActionResult New(Island island)
{
try
{
//ModelState.Remove("Qty");
if (ModelState.IsValid)
{
this.genericMgr.CreateWithTrim(island);
SaveSuccessMessage(Resources.MRP.Island.Island_Added);
string Code = island.Code;
//return RedirectToAction("Edit", new object[] { ProductLine, Item });
return new RedirectToRouteResult(new RouteValueDictionary { { "action", "Edit" }, { "controller", "Island" }, { "Code", Code } });
}
}
catch (Exception e)
{
if (e is CommitResourceException)
{
SaveErrorMessage(Resources.EXT.ControllerLan.Con_TheIslandAlreadyExits);
}
}
return View(island);
}
[SconitAuthorize(Permissions = "Url_MRP_Island_View")]
public ActionResult Delete(string Code)
{
try
{
if (string.IsNullOrEmpty(Code))
{
return HttpNotFound();
}
else
{
Island island = this.genericMgr.FindAll<Island>("select i from Island as i where i.Code=? ", new object[] { Code })[0];
this.genericMgr.Delete(island);
SaveSuccessMessage(Resources.MRP.Island.Island_Deleted);
return RedirectToAction("List");
}
}
catch (Exception ex)
{
SaveErrorMessage(Resources.EXT.ControllerLan.Con_IslandAlreadyBeenOccupiedCanNotDeleted);
return RedirectToAction("Edit", new { Code = Code });
}
}
#endregion
#endregion
private SearchStatementModel PrepareSearchStatement(GridCommand command, IslandSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
HqlStatementHelper.AddLikeStatement("Code", searchModel.Code, HqlStatementHelper.LikeMatchMode.Start, "i", ref whereStatement, param);
HqlStatementHelper.AddLikeStatement("Description", searchModel.Description, HqlStatementHelper.LikeMatchMode.Start, "i", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Region", searchModel.Region, "i", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("IsActive", searchModel.IsActive, "i", ref whereStatement, param);
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
if (command.SortDescriptors.Count == 0)
{
sortingStatement = " order by i.CreateDate desc";
}
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace Anywhere2Go.DataAccess.Entity
{
public class ILertUService
{
public int ID { get; set; }
public int ServiceID { get; set; }
public string ServiceNameEN { get; set; }
public string ServiceNameTH { get; set; }
public string InsuranceCompanyCode { get; set; }
public long IlertuUserID { get; set; }
public long IlertuServiceOfUserID { get; set; }
}
public class ILertUServiceConfig : EntityTypeConfiguration<ILertUService>
{
public ILertUServiceConfig()
{
ToTable("ILertUMapService");
Property(t => t.ID).HasColumnName("id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.ServiceID).HasColumnName("service_id");
Property(t => t.ServiceNameEN).HasColumnName("service_name_en");
Property(t => t.ServiceNameTH).HasColumnName("service_name_th");
Property(t => t.InsuranceCompanyCode).HasColumnName("insurance_company_code");
Property(t => t.IlertuUserID).HasColumnName("ilertu_user_id");
Property(t => t.IlertuServiceOfUserID).HasColumnName("ilertu_service_of_user_id");
}
}
}
|
/*
Dataphor
© Copyright 2000-2008 Alphora
This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt
*/
#define LOGDDLINSTRUCTIONS
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Alphora.Dataphor.BOP;
using Alphora.Dataphor.DAE.Compiling;
using Alphora.Dataphor.DAE.Device.ApplicationTransaction;
using Alphora.Dataphor.DAE.Device.Memory;
using Alphora.Dataphor.DAE.Language;
using Alphora.Dataphor.DAE.Language.D4;
using Alphora.Dataphor.DAE.Runtime;
using Alphora.Dataphor.DAE.Runtime.Data;
using Alphora.Dataphor.DAE.Runtime.Instructions;
using Alphora.Dataphor.DAE.Schema;
using Alphora.Dataphor.DAE.Server;
namespace Alphora.Dataphor.DAE.Device.Catalog
{
public class CatalogDeviceSession : MemoryDeviceSession
{
protected internal CatalogDeviceSession(Schema.Device device, ServerProcess serverProcess, DeviceSessionInfo deviceSessionInfo) : base(device, serverProcess, deviceSessionInfo){}
public Schema.Catalog Catalog { get { return ((Server.Engine)ServerProcess.ServerSession.Server).Catalog; } }
#region Execute
protected override object InternalExecute(Program program, PlanNode planNode)
{
if ((planNode is BaseTableVarNode) || (planNode is OrderNode))
{
Schema.TableVar tableVar = null;
if (planNode is BaseTableVarNode)
tableVar = ((BaseTableVarNode)planNode).TableVar;
else if (planNode is OrderNode)
tableVar = ((BaseTableVarNode)planNode.Nodes[0]).TableVar;
if (tableVar != null)
{
lock (Device.Headers)
{
CatalogHeader header = Device.Headers[tableVar];
if ((header.CacheLevel == CatalogCacheLevel.None) || ((header.CacheLevel == CatalogCacheLevel.Normal) && (Catalog.TimeStamp > header.TimeStamp)) || ((header.CacheLevel == CatalogCacheLevel.Maintained) && !header.Cached))
{
Device.PopulateTableVar(program, header);
if ((header.CacheLevel == CatalogCacheLevel.Maintained) && !header.Cached)
header.Cached = true;
}
}
}
}
object result = base.InternalExecute(program, planNode);
if (planNode is CreateTableNode)
{
Schema.TableVar tableVar = ((CreateTableNode)planNode).Table;
CatalogCacheLevel cacheLevel = (CatalogCacheLevel)Enum.Parse(typeof(CatalogCacheLevel), MetaData.GetTag(tableVar.MetaData, "Catalog.CacheLevel", "Normal"), true);
if (!((cacheLevel == CatalogCacheLevel.StoreTable) || (cacheLevel == CatalogCacheLevel.StoreView)))
{
lock (Device.Headers)
{
CatalogHeader header = new CatalogHeader(tableVar, Device.Tables[tableVar], Int64.MinValue, cacheLevel);
Device.Headers.Add(header);
}
}
}
return result;
}
#endregion
#region Instructions
#if LOGDDLINSTRUCTIONS
protected abstract class DDLInstruction
{
public virtual void Undo(CatalogDeviceSession session) {}
}
protected class DDLInstructionLog : List<DDLInstruction> {}
protected class BeginTransactionInstruction : DDLInstruction {}
protected class SetUserNameInstruction : DDLInstruction
{
public SetUserNameInstruction(Schema.User user, string originalName) : base()
{
_user = user;
_originalName = originalName;
}
private Schema.User _user;
private string _originalName;
public override void Undo(CatalogDeviceSession session)
{
_user.Name = _originalName;
}
}
protected class SetUserPasswordInstruction : DDLInstruction
{
public SetUserPasswordInstruction(Schema.User user, string originalPassword) : base()
{
_user = user;
_originalPassword = originalPassword;
}
private Schema.User _user;
private string _originalPassword;
public override void Undo(CatalogDeviceSession session)
{
_user.Password = _originalPassword;
}
}
protected class SetDeviceUserIDInstruction : DDLInstruction
{
public SetDeviceUserIDInstruction(Schema.DeviceUser deviceUser, string originalUserID) : base()
{
_deviceUser = deviceUser;
_originalUserID = originalUserID;
}
private Schema.DeviceUser _deviceUser;
private string _originalUserID;
public override void Undo(CatalogDeviceSession session)
{
_deviceUser.DeviceUserID = _originalUserID;
}
}
protected class SetDeviceUserPasswordInstruction : DDLInstruction
{
public SetDeviceUserPasswordInstruction(Schema.DeviceUser deviceUser, string originalPassword) : base()
{
_deviceUser = deviceUser;
_originalPassword = originalPassword;
}
private Schema.DeviceUser _deviceUser;
private string _originalPassword;
public override void Undo(CatalogDeviceSession session)
{
_deviceUser.DevicePassword = _originalPassword;
}
}
protected class SetDeviceUserConnectionParametersInstruction : DDLInstruction
{
public SetDeviceUserConnectionParametersInstruction(Schema.DeviceUser deviceUser, string originalConnectionParameters) : base()
{
_deviceUser = deviceUser;
_originalConnectionParameters = originalConnectionParameters;
}
private Schema.DeviceUser _deviceUser;
private string _originalConnectionParameters;
public override void Undo(CatalogDeviceSession session)
{
_deviceUser.ConnectionParameters = _originalConnectionParameters;
}
}
protected class InsertLoadedLibraryInstruction : DDLInstruction
{
public InsertLoadedLibraryInstruction(Schema.LoadedLibrary loadedLibrary) : base()
{
_loadedLibrary = loadedLibrary;
}
private Schema.LoadedLibrary _loadedLibrary;
public override void Undo(CatalogDeviceSession session)
{
session.ClearLoadedLibrary(_loadedLibrary);
}
}
protected class DeleteLoadedLibraryInstruction : DDLInstruction
{
public DeleteLoadedLibraryInstruction(Schema.LoadedLibrary loadedLibrary) : base()
{
_loadedLibrary = loadedLibrary;
}
private Schema.LoadedLibrary _loadedLibrary;
public override void Undo(CatalogDeviceSession session)
{
session.CacheLoadedLibrary(_loadedLibrary);
}
}
protected class RegisterAssemblyInstruction : DDLInstruction
{
public RegisterAssemblyInstruction(Schema.LoadedLibrary loadedLibrary, Assembly assembly) : base()
{
_loadedLibrary = loadedLibrary;
_assembly = assembly;
}
private Schema.LoadedLibrary _loadedLibrary;
private Assembly _assembly;
public override void Undo(CatalogDeviceSession session)
{
session.InternalUnregisterAssembly(_loadedLibrary, _assembly);
}
}
protected class UnregisterAssemblyInstruction : DDLInstruction
{
public UnregisterAssemblyInstruction(Schema.LoadedLibrary loadedLibrary, Assembly assembly) : base()
{
_loadedLibrary = loadedLibrary;
_assembly = assembly;
}
private Schema.LoadedLibrary _loadedLibrary;
private Assembly _assembly;
public override void Undo(CatalogDeviceSession session)
{
session.InternalRegisterAssembly(_loadedLibrary, _assembly);
}
}
protected class CreateCatalogObjectInstruction : DDLInstruction
{
public CreateCatalogObjectInstruction(Schema.CatalogObject catalogObject) : base()
{
_catalogObject = catalogObject;
}
private Schema.CatalogObject _catalogObject;
public override void Undo(CatalogDeviceSession session)
{
session.ClearCatalogObject(_catalogObject);
}
}
protected class DropCatalogObjectInstruction : DDLInstruction
{
public DropCatalogObjectInstruction(Schema.CatalogObject catalogObject) : base()
{
_catalogObject = catalogObject;
}
private Schema.CatalogObject _catalogObject;
public override void Undo(CatalogDeviceSession session)
{
session.CacheCatalogObject(_catalogObject);
}
}
protected class AddDependenciesInstruction : DDLInstruction
{
public AddDependenciesInstruction(Schema.Object objectValue) : base()
{
_object = objectValue;
}
private Schema.Object _object;
public override void Undo(CatalogDeviceSession session)
{
_object.Dependencies.Clear();
}
}
protected class RemoveDependenciesInstruction : DDLInstruction
{
public RemoveDependenciesInstruction(Schema.Object objectValue, Schema.ObjectList originalDependencies) : base()
{
_object = objectValue;
_originalDependencies = originalDependencies;
}
private Schema.Object _object;
private Schema.ObjectList _originalDependencies;
public override void Undo(CatalogDeviceSession session)
{
_object.AddDependencies(_originalDependencies);
_object.DetermineRemotable(session);
}
}
protected class CreateDeviceTableInstruction : DDLInstruction
{
public CreateDeviceTableInstruction(Schema.BaseTableVar baseTableVar) : base()
{
_baseTableVar = baseTableVar;
}
private Schema.BaseTableVar _baseTableVar;
public override void Undo(CatalogDeviceSession session)
{
session.DropDeviceTable(_baseTableVar);
}
}
protected class DropDeviceTableInstruction : DDLInstruction
{
public DropDeviceTableInstruction(Schema.BaseTableVar baseTableVar) : base()
{
_baseTableVar = baseTableVar;
}
private Schema.BaseTableVar _baseTableVar;
public override void Undo(CatalogDeviceSession session)
{
session.CreateDeviceTable(_baseTableVar);
}
}
protected class CreateSessionObjectInstruction : DDLInstruction
{
public CreateSessionObjectInstruction(Schema.CatalogObject sessionObject)
{
_sessionObject = sessionObject;
}
private Schema.CatalogObject _sessionObject;
public override void Undo(CatalogDeviceSession session)
{
session.DropSessionObject(_sessionObject);
}
}
protected class DropSessionObjectInstruction : DDLInstruction
{
public DropSessionObjectInstruction(Schema.CatalogObject sessionObject)
{
_sessionObject = sessionObject;
}
private Schema.CatalogObject _sessionObject;
public override void Undo(CatalogDeviceSession session)
{
session.CreateSessionObject(_sessionObject);
}
}
protected class CreateSessionOperatorInstruction : DDLInstruction
{
public CreateSessionOperatorInstruction(Schema.Operator sessionOperator)
{
_sessionOperator = sessionOperator;
}
private Schema.Operator _sessionOperator;
public override void Undo(CatalogDeviceSession session)
{
session.DropSessionOperator(_sessionOperator);
}
}
protected class DropSessionOperatorInstruction : DDLInstruction
{
public DropSessionOperatorInstruction(Schema.Operator sessionOperator)
{
_sessionOperator = sessionOperator;
}
private Schema.Operator _sessionOperator;
public override void Undo(CatalogDeviceSession session)
{
session.CreateSessionOperator(_sessionOperator);
}
}
protected class AddImplicitConversionInstruction : DDLInstruction
{
public AddImplicitConversionInstruction(Schema.Conversion conversion) : base()
{
_conversion = conversion;
}
private Schema.Conversion _conversion;
public override void Undo(CatalogDeviceSession session)
{
session.RemoveImplicitConversion(_conversion);
}
}
protected class RemoveImplicitConversionInstruction : DDLInstruction
{
public RemoveImplicitConversionInstruction(Schema.Conversion conversion) : base()
{
_conversion = conversion;
}
private Schema.Conversion _conversion;
public override void Undo(CatalogDeviceSession session)
{
session.AddImplicitConversion(_conversion);
}
}
protected class SetScalarTypeSortInstruction : DDLInstruction
{
public SetScalarTypeSortInstruction(Schema.ScalarType scalarType, Schema.Sort originalSort, bool isUnique)
{
_scalarType = scalarType;
_originalSort = originalSort;
_isUnique = isUnique;
}
private Schema.ScalarType _scalarType;
private Schema.Sort _originalSort;
private bool _isUnique;
public override void Undo(CatalogDeviceSession session)
{
session.SetScalarTypeSort(_scalarType, _originalSort, _isUnique);
}
}
protected class ClearScalarTypeEqualityOperatorInstruction : DDLInstruction
{
public ClearScalarTypeEqualityOperatorInstruction(Schema.ScalarType scalarType, Schema.Operator originalEqualityOperator)
{
_scalarType = scalarType;
_originalEqualityOperator = originalEqualityOperator;
}
private Schema.ScalarType _scalarType;
private Schema.Operator _originalEqualityOperator;
public override void Undo(CatalogDeviceSession session)
{
_scalarType.EqualityOperator = _originalEqualityOperator;
}
}
protected class ClearScalarTypeComparisonOperatorInstruction : DDLInstruction
{
public ClearScalarTypeComparisonOperatorInstruction(Schema.ScalarType scalarType, Schema.Operator originalComparisonOperator)
{
_scalarType = scalarType;
_originalComparisonOperator = originalComparisonOperator;
}
private Schema.ScalarType _scalarType;
private Schema.Operator _originalComparisonOperator;
public override void Undo(CatalogDeviceSession session)
{
_scalarType.ComparisonOperator = _originalComparisonOperator;
}
}
protected class ClearScalarTypeIsSpecialOperatorInstruction : DDLInstruction
{
public ClearScalarTypeIsSpecialOperatorInstruction(Schema.ScalarType scalarType, Schema.Operator originalIsSpecialOperator)
{
_scalarType = scalarType;
_originalIsSpecialOperator = originalIsSpecialOperator;
}
private Schema.ScalarType _scalarType;
private Schema.Operator _originalIsSpecialOperator;
public override void Undo(CatalogDeviceSession session)
{
_scalarType.IsSpecialOperator = _originalIsSpecialOperator;
}
}
protected class ClearRepresentationSelectorInstruction : DDLInstruction
{
public ClearRepresentationSelectorInstruction(Schema.Representation representation, Schema.Operator originalSelector)
{
_representation = representation;
_originalSelector = originalSelector;
}
private Schema.Representation _representation;
private Schema.Operator _originalSelector;
public override void Undo(CatalogDeviceSession session)
{
_representation.Selector = _originalSelector;
}
}
protected class ClearPropertyReadAccessorInstruction : DDLInstruction
{
public ClearPropertyReadAccessorInstruction(Schema.Property property, Schema.Operator originalReadAccessor)
{
_property = property;
_originalReadAccessor = originalReadAccessor;
}
private Schema.Property _property;
private Schema.Operator _originalReadAccessor;
public override void Undo(CatalogDeviceSession session)
{
_property.ReadAccessor = _originalReadAccessor;
}
}
protected class ClearPropertyWriteAccessorInstruction : DDLInstruction
{
public ClearPropertyWriteAccessorInstruction(Schema.Property property, Schema.Operator originalWriteAccessor)
{
_property = property;
_originalWriteAccessor = originalWriteAccessor;
}
private Schema.Property _property;
private Schema.Operator _originalWriteAccessor;
public override void Undo(CatalogDeviceSession session)
{
_property.WriteAccessor = _originalWriteAccessor;
}
}
protected class ClearSpecialSelectorInstruction : DDLInstruction
{
public ClearSpecialSelectorInstruction(Schema.Special special, Schema.Operator originalSelector)
{
_special = special;
_originalSelector = originalSelector;
}
private Schema.Special _special;
private Schema.Operator _originalSelector;
public override void Undo(CatalogDeviceSession session)
{
_special.Selector = _originalSelector;
}
}
protected class ClearSpecialComparerInstruction : DDLInstruction
{
public ClearSpecialComparerInstruction(Schema.Special special, Schema.Operator originalComparer)
{
_special = special;
_originalComparer = originalComparer;
}
private Schema.Special _special;
private Schema.Operator _originalComparer;
public override void Undo(CatalogDeviceSession session)
{
_special.Comparer = _originalComparer;
}
}
protected class AlterMetaDataInstruction : DDLInstruction
{
public AlterMetaDataInstruction(Schema.Object objectValue, MetaData originalMetaData)
{
_object = objectValue;
_originalMetaData = originalMetaData;
}
private Schema.Object _object;
private MetaData _originalMetaData;
public override void Undo(CatalogDeviceSession session)
{
_object.MetaData = _originalMetaData;
}
}
protected class AlterClassDefinitionInstruction : DDLInstruction
{
public AlterClassDefinitionInstruction(ClassDefinition classDefinition, AlterClassDefinition alterClassDefinition, ClassDefinition originalClassDefinition, object instance)
{
_classDefinition = classDefinition;
_alterClassDefinition = alterClassDefinition;
_originalClassDefinition = originalClassDefinition;
_instance = instance;
}
private ClassDefinition _classDefinition;
private AlterClassDefinition _alterClassDefinition;
private ClassDefinition _originalClassDefinition;
private object _instance;
public override void Undo(CatalogDeviceSession session)
{
AlterClassDefinition undoClassDefinition = new AlterClassDefinition();
undoClassDefinition.ClassName = _alterClassDefinition.ClassName == String.Empty ? String.Empty : _originalClassDefinition.ClassName;
foreach (ClassAttributeDefinition attributeDefinition in _alterClassDefinition.DropAttributes)
undoClassDefinition.CreateAttributes.Add(new ClassAttributeDefinition(attributeDefinition.AttributeName, _originalClassDefinition.Attributes[attributeDefinition.AttributeName].AttributeValue));
foreach (ClassAttributeDefinition attributeDefinition in _alterClassDefinition.AlterAttributes)
undoClassDefinition.AlterAttributes.Add(new ClassAttributeDefinition(attributeDefinition.AttributeName, _originalClassDefinition.Attributes[attributeDefinition.AttributeName].AttributeValue));
foreach (ClassAttributeDefinition attributeDefinition in _alterClassDefinition.CreateAttributes)
undoClassDefinition.DropAttributes.Add(new ClassAttributeDefinition(attributeDefinition.AttributeName, String.Empty));
AlterNode.AlterClassDefinition(_classDefinition, undoClassDefinition, _instance);
}
}
protected class AttachCatalogConstraintInstruction : DDLInstruction
{
public AttachCatalogConstraintInstruction(Schema.CatalogConstraint catalogConstraint)
{
_catalogConstraint = catalogConstraint;
}
private Schema.CatalogConstraint _catalogConstraint;
public override void Undo(CatalogDeviceSession session)
{
CreateConstraintNode.DetachConstraint(_catalogConstraint, _catalogConstraint.Node);
}
}
protected class DetachCatalogConstraintInstruction : DDLInstruction
{
public DetachCatalogConstraintInstruction(Schema.CatalogConstraint catalogConstraint)
{
_catalogConstraint = catalogConstraint;
}
private Schema.CatalogConstraint _catalogConstraint;
public override void Undo(CatalogDeviceSession session)
{
CreateConstraintNode.AttachConstraint(_catalogConstraint, _catalogConstraint.Node);
}
}
protected class SetCatalogConstraintNodeInstruction : DDLInstruction
{
public SetCatalogConstraintNodeInstruction(Schema.CatalogConstraint catalogConstraint, PlanNode originalNode)
{
_catalogConstraint = catalogConstraint;
_originalNode = originalNode;
}
private Schema.CatalogConstraint _catalogConstraint;
private PlanNode _originalNode;
public override void Undo(CatalogDeviceSession session)
{
_catalogConstraint.Node = _originalNode;
}
}
protected class AttachKeyInstruction : DDLInstruction
{
public AttachKeyInstruction(Schema.TableVar tableVar, Schema.Key key)
{
_tableVar = tableVar;
_key = key;
}
private Schema.TableVar _tableVar;
private Schema.Key _key;
public override void Undo(CatalogDeviceSession session)
{
session.DetachKey(_tableVar, _key);
}
}
protected class DetachKeyInstruction : DDLInstruction
{
public DetachKeyInstruction(Schema.TableVar tableVar, Schema.Key key)
{
_tableVar = tableVar;
_key = key;
}
private Schema.TableVar _tableVar;
private Schema.Key _key;
public override void Undo(CatalogDeviceSession session)
{
session.AttachKey(_tableVar, _key);
}
}
protected class AttachOrderInstruction : DDLInstruction
{
public AttachOrderInstruction(Schema.TableVar tableVar, Schema.Order order)
{
_tableVar = tableVar;
_order = order;
}
private Schema.TableVar _tableVar;
private Schema.Order _order;
public override void Undo(CatalogDeviceSession session)
{
session.DetachOrder(_tableVar, _order);
}
}
protected class DetachOrderInstruction : DDLInstruction
{
public DetachOrderInstruction(Schema.TableVar tableVar, Schema.Order order)
{
_tableVar = tableVar;
_order = order;
}
private Schema.TableVar _tableVar;
private Schema.Order _order;
public override void Undo(CatalogDeviceSession session)
{
session.AttachOrder(_tableVar, _order);
}
}
protected class AttachTableVarConstraintInstruction : DDLInstruction
{
public AttachTableVarConstraintInstruction(Schema.TableVar tableVar, Schema.TableVarConstraint tableVarConstraint)
{
_tableVar = tableVar;
_tableVarConstraint = tableVarConstraint;
}
private Schema.TableVar _tableVar;
private Schema.TableVarConstraint _tableVarConstraint;
public override void Undo(CatalogDeviceSession session)
{
session.DetachTableVarConstraint(_tableVar, _tableVarConstraint);
}
}
protected class DetachTableVarConstraintInstruction : DDLInstruction
{
public DetachTableVarConstraintInstruction(Schema.TableVar tableVar, Schema.TableVarConstraint tableVarConstraint)
{
_tableVar = tableVar;
_tableVarConstraint = tableVarConstraint;
}
private Schema.TableVar _tableVar;
private Schema.TableVarConstraint _tableVarConstraint;
public override void Undo(CatalogDeviceSession session)
{
session.AttachTableVarConstraint(_tableVar, _tableVarConstraint);
}
}
protected class AttachTableVarColumnInstruction : DDLInstruction
{
public AttachTableVarColumnInstruction(Schema.BaseTableVar tableVar, Schema.TableVarColumn tableVarColumn)
{
_tableVar = tableVar;
_tableVarColumn = tableVarColumn;
}
private Schema.BaseTableVar _tableVar;
private Schema.TableVarColumn _tableVarColumn;
public override void Undo(CatalogDeviceSession session)
{
session.DetachTableVarColumn(_tableVar, _tableVarColumn);
}
}
protected class DetachTableVarColumnInstruction : DDLInstruction
{
public DetachTableVarColumnInstruction(Schema.BaseTableVar tableVar, Schema.TableVarColumn tableVarColumn)
{
_tableVar = tableVar;
_tableVarColumn = tableVarColumn;
}
private Schema.BaseTableVar _tableVar;
private Schema.TableVarColumn _tableVarColumn;
public override void Undo(CatalogDeviceSession session)
{
session.AttachTableVarColumn(_tableVar, _tableVarColumn);
}
}
protected class AttachScalarTypeConstraintInstruction : DDLInstruction
{
public AttachScalarTypeConstraintInstruction(Schema.ScalarType scalarType, Schema.ScalarTypeConstraint scalarTypeConstraint)
{
_scalarType = scalarType;
_scalarTypeConstraint = scalarTypeConstraint;
}
private Schema.ScalarType _scalarType;
private Schema.ScalarTypeConstraint _scalarTypeConstraint;
public override void Undo(CatalogDeviceSession session)
{
session.DetachScalarTypeConstraint(_scalarType, _scalarTypeConstraint);
}
}
protected class DetachScalarTypeConstraintInstruction : DDLInstruction
{
public DetachScalarTypeConstraintInstruction(Schema.ScalarType scalarType, Schema.ScalarTypeConstraint scalarTypeConstraint)
{
_scalarType = scalarType;
_scalarTypeConstraint = scalarTypeConstraint;
}
private Schema.ScalarType _scalarType;
private Schema.ScalarTypeConstraint _scalarTypeConstraint;
public override void Undo(CatalogDeviceSession session)
{
session.AttachScalarTypeConstraint(_scalarType, _scalarTypeConstraint);
}
}
protected class AttachTableVarColumnConstraintInstruction : DDLInstruction
{
public AttachTableVarColumnConstraintInstruction(Schema.TableVarColumn tableVarColumn, Schema.TableVarColumnConstraint tableVarColumnConstraint)
{
_tableVarColumn = tableVarColumn;
_tableVarColumnConstraint = tableVarColumnConstraint;
}
private Schema.TableVarColumn _tableVarColumn;
private Schema.TableVarColumnConstraint _tableVarColumnConstraint;
public override void Undo(CatalogDeviceSession session)
{
session.DetachTableVarColumnConstraint(_tableVarColumn, _tableVarColumnConstraint);
}
}
protected class DetachTableVarColumnConstraintInstruction : DDLInstruction
{
public DetachTableVarColumnConstraintInstruction(Schema.TableVarColumn tableVarColumn, Schema.TableVarColumnConstraint tableVarColumnConstraint)
{
_tableVarColumn = tableVarColumn;
_tableVarColumnConstraint = tableVarColumnConstraint;
}
private Schema.TableVarColumn _tableVarColumn;
private Schema.TableVarColumnConstraint _tableVarColumnConstraint;
public override void Undo(CatalogDeviceSession session)
{
session.AttachTableVarColumnConstraint(_tableVarColumn, _tableVarColumnConstraint);
}
}
protected class AttachSpecialInstruction : DDLInstruction
{
public AttachSpecialInstruction(Schema.ScalarType scalarType, Schema.Special special)
{
_scalarType = scalarType;
_special = special;
}
private Schema.ScalarType _scalarType;
private Schema.Special _special;
public override void Undo(CatalogDeviceSession session)
{
session.DetachSpecial(_scalarType, _special);
}
}
protected class DetachSpecialInstruction : DDLInstruction
{
public DetachSpecialInstruction(Schema.ScalarType scalarType, Schema.Special special)
{
_scalarType = scalarType;
_special = special;
}
private Schema.ScalarType _scalarType;
private Schema.Special _special;
public override void Undo(CatalogDeviceSession session)
{
session.AttachSpecial(_scalarType, _special);
}
}
protected class AttachRepresentationInstruction : DDLInstruction
{
public AttachRepresentationInstruction(Schema.ScalarType scalarType, Schema.Representation representation)
{
_scalarType = scalarType;
_representation = representation;
}
private Schema.ScalarType _scalarType;
private Schema.Representation _representation;
public override void Undo(CatalogDeviceSession session)
{
session.DetachRepresentation(_scalarType, _representation);
}
}
protected class DetachRepresentationInstruction : DDLInstruction
{
public DetachRepresentationInstruction(Schema.ScalarType scalarType, Schema.Representation representation)
{
_scalarType = scalarType;
_representation = representation;
}
private Schema.ScalarType _scalarType;
private Schema.Representation _representation;
public override void Undo(CatalogDeviceSession session)
{
session.AttachRepresentation(_scalarType, _representation);
}
}
protected class AttachPropertyInstruction : DDLInstruction
{
public AttachPropertyInstruction(Schema.Representation representation, Schema.Property property)
{
_representation = representation;
_property = property;
}
private Schema.Representation _representation;
private Schema.Property _property;
public override void Undo(CatalogDeviceSession session)
{
session.DetachProperty(_representation, _property);
}
}
protected class DetachPropertyInstruction : DDLInstruction
{
public DetachPropertyInstruction(Schema.Representation representation, Schema.Property property)
{
_representation = representation;
_property = property;
}
private Schema.Representation _representation;
private Schema.Property _property;
public override void Undo(CatalogDeviceSession session)
{
session.AttachProperty(_representation, _property);
}
}
protected class SetScalarTypeDefaultInstruction : DDLInstruction
{
public SetScalarTypeDefaultInstruction(Schema.ScalarType scalarType, Schema.ScalarTypeDefault originalDefault)
{
_scalarType = scalarType;
_originalDefault = originalDefault;
}
private Schema.ScalarType _scalarType;
private Schema.ScalarTypeDefault _originalDefault;
public override void Undo(CatalogDeviceSession session)
{
_scalarType.Default = _originalDefault;
}
}
protected class SetTableVarColumnDefaultInstruction : DDLInstruction
{
public SetTableVarColumnDefaultInstruction(Schema.TableVarColumn tableVarColumn, Schema.TableVarColumnDefault originalDefault)
{
_tableVarColumn = tableVarColumn;
_originalDefault = originalDefault;
}
private Schema.TableVarColumn _tableVarColumn;
private Schema.TableVarColumnDefault _originalDefault;
public override void Undo(CatalogDeviceSession session)
{
_tableVarColumn.Default = _originalDefault;
}
}
protected class SetTableVarColumnIsNilableInstruction : DDLInstruction
{
public SetTableVarColumnIsNilableInstruction(Schema.TableVarColumn tableVarColumn, bool originalIsNilable)
{
_tableVarColumn = tableVarColumn;
_originalIsNilable = originalIsNilable;
}
private Schema.TableVarColumn _tableVarColumn;
private bool _originalIsNilable;
public override void Undo(CatalogDeviceSession session)
{
_tableVarColumn.IsNilable = _originalIsNilable;
}
}
protected class SetScalarTypeIsSpecialOperatorInstruction : DDLInstruction
{
public SetScalarTypeIsSpecialOperatorInstruction(Schema.ScalarType scalarType, Schema.Operator originalOperator)
{
_scalarType = scalarType;
_originalOperator = originalOperator;
}
private Schema.ScalarType _scalarType;
private Schema.Operator _originalOperator;
public override void Undo(CatalogDeviceSession session)
{
_scalarType.IsSpecialOperator = _originalOperator;
}
}
protected class SetOperatorBlockNodeInstruction : DDLInstruction
{
public SetOperatorBlockNodeInstruction(Schema.OperatorBlock operatorBlock, PlanNode originalNode)
{
_operatorBlock = operatorBlock;
_originalNode = originalNode;
}
private Schema.OperatorBlock _operatorBlock;
private PlanNode _originalNode;
public override void Undo(CatalogDeviceSession session)
{
_operatorBlock.BlockNode = _originalNode;
}
}
protected class AttachReferenceInstruction : DDLInstruction
{
public AttachReferenceInstruction(Schema.Reference reference)
{
_reference = reference;
}
private Schema.Reference _reference;
public override void Undo(CatalogDeviceSession session)
{
session.DetachReference(_reference);
}
}
protected class DetachReferenceInstruction : DDLInstruction
{
public DetachReferenceInstruction(Schema.Reference reference)
{
_reference = reference;
}
private Schema.Reference _reference;
public override void Undo(CatalogDeviceSession session)
{
session.AttachReference(_reference);
}
}
protected class AttachDeviceScalarTypeInstruction : DDLInstruction
{
public AttachDeviceScalarTypeInstruction(Schema.DeviceScalarType deviceScalarType)
{
_deviceScalarType = deviceScalarType;
}
private Schema.DeviceScalarType _deviceScalarType;
public override void Undo(CatalogDeviceSession session)
{
session.DetachDeviceScalarType(_deviceScalarType);
}
}
protected class DetachDeviceScalarTypeInstruction : DDLInstruction
{
public DetachDeviceScalarTypeInstruction(Schema.DeviceScalarType deviceScalarType)
{
_deviceScalarType = deviceScalarType;
}
private Schema.DeviceScalarType _deviceScalarType;
public override void Undo(CatalogDeviceSession session)
{
session.AttachDeviceScalarType(_deviceScalarType);
}
}
protected class AttachDeviceOperatorInstruction : DDLInstruction
{
public AttachDeviceOperatorInstruction(Schema.DeviceOperator deviceOperator)
{
_deviceOperator = deviceOperator;
}
private Schema.DeviceOperator _deviceOperator;
public override void Undo(CatalogDeviceSession session)
{
session.DetachDeviceOperator(_deviceOperator);
}
}
protected class DetachDeviceOperatorInstruction : DDLInstruction
{
public DetachDeviceOperatorInstruction(Schema.DeviceOperator deviceOperator)
{
_deviceOperator = deviceOperator;
}
private Schema.DeviceOperator _deviceOperator;
public override void Undo(CatalogDeviceSession session)
{
session.AttachDeviceOperator(_deviceOperator);
}
}
protected class AttachTableMapInstruction : DDLInstruction
{
public AttachTableMapInstruction(ApplicationTransactionDevice device, TableMap tableMap)
{
_device = device;
_tableMap = tableMap;
}
private ApplicationTransactionDevice _device;
private TableMap _tableMap;
public override void Undo(CatalogDeviceSession session)
{
session.DetachTableMap(_device, _tableMap);
}
}
protected class DetachTableMapInstruction : DDLInstruction
{
public DetachTableMapInstruction(ApplicationTransactionDevice device, TableMap tableMap)
{
_device = device;
_tableMap = tableMap;
}
private ApplicationTransactionDevice _device;
private TableMap _tableMap;
public override void Undo(CatalogDeviceSession session)
{
session.AttachTableMap(_device, _tableMap);
}
}
protected class AttachOperatorMapInstruction : DDLInstruction
{
public AttachOperatorMapInstruction(ApplicationTransaction.OperatorMap operatorMap, Schema.Operator operatorValue)
{
_operatorMap = operatorMap;
_operator = operatorValue;
}
private ApplicationTransaction.OperatorMap _operatorMap;
private Schema.Operator _operator;
public override void Undo(CatalogDeviceSession session)
{
session.DetachOperatorMap(_operatorMap, _operator);
}
}
protected class DetachOperatorMapInstruction : DDLInstruction
{
public DetachOperatorMapInstruction(ApplicationTransaction.OperatorMap operatorMap, Schema.Operator operatorValue)
{
_operatorMap = operatorMap;
_operator = operatorValue;
}
private ApplicationTransaction.OperatorMap _operatorMap;
private Schema.Operator _operator;
public override void Undo(CatalogDeviceSession session)
{
session.AttachOperatorMap(_operatorMap, _operator);
}
}
/*
protected class AttachDeviceScalarTypeDeviceOperatorInstruction : DDLInstruction
{
public AttachDeviceScalarTypeDeviceOperatorInstruction(Schema.DeviceScalarType ADeviceScalarType, Schema.DeviceOperator ADeviceOperator)
{
FDeviceScalarType = ADeviceScalarType;
FDeviceOperator = ADeviceOperator;
}
private Schema.DeviceScalarType FDeviceScalarType;
private Schema.DeviceOperator FDeviceOperator;
public override void Undo(CatalogDeviceSession ASession)
{
ASession.DetachDeviceScalarTypeDeviceOperator(FDeviceScalarType, FDeviceOperator);
}
}
protected class DetachDeviceScalarTypeDeviceOperatorInstruction : DDLInstruction
{
public DetachDeviceScalarTypeDeviceOperatorInstruction(Schema.DeviceScalarType ADeviceScalarType, Schema.DeviceOperator ADeviceOperator)
{
FDeviceScalarType = ADeviceScalarType;
FDeviceOperator = ADeviceOperator;
}
private Schema.DeviceScalarType FDeviceScalarType;
private Schema.DeviceOperator FDeviceOperator;
public override void Undo(CatalogDeviceSession ASession)
{
ASession.AttachDeviceScalarTypeDeviceOperator(FDeviceScalarType, FDeviceOperator);
}
}
*/
protected class SetDeviceReconcileModeInstruction : DDLInstruction
{
public SetDeviceReconcileModeInstruction(Schema.Device device, ReconcileMode originalReconcileMode)
{
_device = device;
_originalReconcileMode = originalReconcileMode;
}
private Schema.Device _device;
private ReconcileMode _originalReconcileMode;
public override void Undo(CatalogDeviceSession session)
{
_device.ReconcileMode = _originalReconcileMode;
}
}
protected class SetDeviceReconcileMasterInstruction : DDLInstruction
{
public SetDeviceReconcileMasterInstruction(Schema.Device device, ReconcileMaster originalReconcileMaster)
{
_device = device;
_originalReconcileMaster = originalReconcileMaster;
}
private Schema.Device _device;
private ReconcileMaster _originalReconcileMaster;
public override void Undo(CatalogDeviceSession session)
{
_device.ReconcileMaster = _originalReconcileMaster;
}
}
protected class StartDeviceInstruction : DDLInstruction
{
public StartDeviceInstruction(Schema.Device device) : base()
{
_device = device;
}
private Schema.Device _device;
public override void Undo(CatalogDeviceSession session)
{
session.StopDevice(_device, true);
}
}
protected class RegisterDeviceInstruction : DDLInstruction
{
public RegisterDeviceInstruction(Schema.Device device) : base()
{
_device = device;
}
private Schema.Device _device;
public override void Undo(CatalogDeviceSession session)
{
session.UnregisterDevice(_device);
}
}
protected class AttachEventHandlerInstruction : DDLInstruction
{
public AttachEventHandlerInstruction(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex, List<string> beforeOperatorNames)
{
_eventHandler = eventHandler;
_eventSource = eventSource;
_eventSourceColumnIndex = eventSourceColumnIndex;
_beforeOperatorNames = beforeOperatorNames;
}
private Schema.EventHandler _eventHandler;
private Schema.Object _eventSource;
private int _eventSourceColumnIndex;
private List<string> _beforeOperatorNames;
public override void Undo(CatalogDeviceSession session)
{
session.DetachEventHandler(_eventHandler, _eventSource, _eventSourceColumnIndex);
}
}
protected class MoveEventHandlerInstruction : DDLInstruction
{
public MoveEventHandlerInstruction(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex, List<string> beforeOperatorNames)
{
_eventHandler = eventHandler;
_eventSource = eventSource;
_eventSourceColumnIndex = eventSourceColumnIndex;
_beforeOperatorNames = beforeOperatorNames;
}
private Schema.EventHandler _eventHandler;
private Schema.Object _eventSource;
private int _eventSourceColumnIndex;
private List<string> _beforeOperatorNames;
public override void Undo(CatalogDeviceSession session)
{
session.MoveEventHandler(_eventHandler, _eventSource, _eventSourceColumnIndex, _beforeOperatorNames);
}
}
protected class DetachEventHandlerInstruction : DDLInstruction
{
public DetachEventHandlerInstruction(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex, List<string> beforeOperatorNames)
{
_eventHandler = eventHandler;
_eventSource = eventSource;
_eventSourceColumnIndex = eventSourceColumnIndex;
_beforeOperatorNames = beforeOperatorNames;
}
private Schema.EventHandler _eventHandler;
private Schema.Object _eventSource;
private int _eventSourceColumnIndex;
private List<string> _beforeOperatorNames;
public override void Undo(CatalogDeviceSession session)
{
session.AttachEventHandler(_eventHandler, _eventSource, _eventSourceColumnIndex, _beforeOperatorNames);
}
}
protected DDLInstructionLog _instructions = new DDLInstructionLog();
#endif
#endregion
#region Transactions
protected override void InternalBeginTransaction(IsolationLevel isolationLevel)
{
base.InternalBeginTransaction(isolationLevel);
#if LOGDDLINSTRUCTIONS
_instructions.Add(new BeginTransactionInstruction());
#endif
}
protected override void InternalPrepareTransaction()
{
base.InternalPrepareTransaction();
}
protected override void InternalCommitTransaction()
{
base.InternalCommitTransaction();
#if LOGDDLINSTRUCTIONS
if (Transactions.Count > 1)
{
for (int index = _instructions.Count - 1; index >= 0; index--)
if (_instructions[index] is BeginTransactionInstruction)
{
_instructions.RemoveAt(index);
break;
}
}
else
_instructions.Clear();
#endif
InternalAfterCommitTransaction();
ExecuteDeferredDeviceStops();
}
protected virtual void InternalAfterCommitTransaction()
{
// virtual
}
protected override void InternalRollbackTransaction()
{
base.InternalRollbackTransaction();
try
{
#if LOGDDLINSTRUCTIONS
for (int index = _instructions.Count - 1; index >= 0; index--)
{
DDLInstruction instruction = _instructions[index];
_instructions.RemoveAt(index);
if (instruction is BeginTransactionInstruction)
break;
else
{
try
{
instruction.Undo(this);
}
catch (Exception exception)
{
// Log the exception and continue, not really much that can be done, should try to undo as many operations as possible
// In at least one case, the error may be safely ignored anyway (storage object does not exist because it has already been rolled back by the device transaction rollback)
ServerProcess.ServerSession.Server.LogError(new ServerException(ServerException.Codes.RollbackError, ErrorSeverity.System, exception, exception.ToString()));
}
}
}
#endif
}
finally
{
InternalAfterRollbackTransaction();
ClearDeferredDeviceStops();
}
}
protected virtual void InternalAfterRollbackTransaction()
{
// virtual
}
#endregion
#region Object Selection
public virtual List<int> SelectOperatorHandlers(int operatorID)
{
return new List<int>();
}
public virtual List<int> SelectObjectHandlers(int sourceObjectID)
{
return new List<int>();
}
public virtual Schema.DependentObjectHeaders SelectObjectDependents(int objectID, bool recursive)
{
return new Schema.DependentObjectHeaders();
}
public virtual Schema.DependentObjectHeaders SelectObjectDependencies(int objectID, bool recursive)
{
throw new NotSupportedException();
}
public virtual Schema.CatalogObjectHeaders SelectLibraryCatalogObjects(string libraryName)
{
throw new NotSupportedException();
}
public virtual Schema.CatalogObjectHeaders SelectGeneratedObjects(int objectID)
{
throw new NotSupportedException();
}
#endregion
#region Updates
protected override void InternalInsertRow(Program program, Schema.TableVar tableVar, IRow row, BitArray valueFlags)
{
switch (tableVar.Name)
{
case "System.TableDum" : break;
case "System.TableDee" : break;
}
base.InternalInsertRow(program, tableVar, row, valueFlags);
}
protected override void InternalUpdateRow(Program program, Schema.TableVar tableVar, IRow oldRow, IRow newRow, BitArray valueFlags)
{
switch (tableVar.Name)
{
case "System.TableDee" : break;
case "System.TableDum" : break;
}
base.InternalUpdateRow(program, tableVar, oldRow, newRow, valueFlags);
}
protected override void InternalDeleteRow(Program program, Schema.TableVar tableVar, IRow row)
{
switch (tableVar.Name)
{
case "System.TableDee" : break;
case "System.TableDum" : break;
}
base.InternalDeleteRow(program, tableVar, row);
}
#endregion
#region Resolution
/// <summary>Resolves the given name and returns the catalog object, if an unambiguous match is found. Otherwise, returns null.</summary>
public virtual Schema.CatalogObject ResolveName(string name, NameResolutionPath path, List<string> names)
{
int index = Catalog.ResolveName(name, path, names);
return index >= 0 ? (Schema.CatalogObject)Catalog[index] : null;
}
/// <summary>Ensures that any potential match with the given operator name is in the cache so that operator resolution can occur.</summary>
public void ResolveOperatorName(string operatorName)
{
if (!ServerProcess.ServerSession.Server.IsEngine)
{
Schema.CatalogObjectHeaders headers = CachedResolveOperatorName(operatorName);
// Only resolve operators in loaded libraries
for (int index = 0; index < headers.Count; index++)
if ((headers[index].LibraryName == String.Empty) || Catalog.LoadedLibraries.Contains(headers[index].LibraryName))
ResolveCatalogObject(headers[index].ID);
}
}
/// <summary>Resolves the catalog object with the given id. If the object is not found, an error is raised.</summary>
public virtual Schema.CatalogObject ResolveCatalogObject(int objectID)
{
// TODO: Catalog deserialization concurrency
// Right now, use the same lock as the user's cache to ensure no deadlocks can occur during deserialization.
// This effectively places deserialization granularity at the server level, but until we
// can provide a solution to the deserialization concurrency deadlock problem, this is all we can do.
lock (Catalog)
{
// Lookup the object in the catalog index
string objectName;
if (Device.CatalogIndex.TryGetValue(objectID, out objectName))
return (Schema.CatalogObject)Catalog[objectName];
else
return null;
}
}
public virtual Schema.ObjectHeader GetObjectHeader(int objectID)
{
throw new NotSupportedException();
}
public Schema.Object ResolveObject(int objectID)
{
Schema.ObjectHeader header = GetObjectHeader(objectID);
if (header.CatalogObjectID == -1)
return ResolveCatalogObject(objectID);
Schema.CatalogObject catalogObject = ResolveCatalogObject(header.CatalogObjectID);
return catalogObject.GetObjectFromHeader(header);
}
#endregion
#region Cache
protected virtual Schema.CatalogObjectHeaders CachedResolveOperatorName(string name)
{
return Device.OperatorNameCache.Resolve(name);
}
/// <summary>Returns the cached object for the given object id, if it exists and is in the cache, null otherwise.</summary>
public Schema.CatalogObject ResolveCachedCatalogObject(int objectID)
{
return ResolveCachedCatalogObject(objectID, false);
}
/// <summary>Returns the cached object for the given object id, if it exists and is in the cache. An error is thrown if the object is not in the cache and AMustResolve is true, otherwise null is returned.</summary>
public Schema.CatalogObject ResolveCachedCatalogObject(int objectID, bool mustResolve)
{
lock (Catalog)
{
string objectName;
if (Device.CatalogIndex.TryGetValue(objectID, out objectName))
return (Schema.CatalogObject)Catalog[objectName];
if (mustResolve)
throw new Schema.SchemaException(Schema.SchemaException.Codes.ObjectNotCached, objectID);
return null;
}
}
/// <summary>Returns the cached object with the given name, if it exists and is in the cache, null otherwise.</summary>
public Schema.CatalogObject ResolveCachedCatalogObject(string name)
{
return ResolveCachedCatalogObject(name, false);
}
/// <summary>Returns the cached object with the given name, if it exists and is in the cache. An error is thrown if the object is not in the cache and AMustResolve is true, otherwise null is returned.</summary>
public Schema.CatalogObject ResolveCachedCatalogObject(string name, bool mustResolve)
{
lock (Catalog)
{
int index = Catalog.IndexOf(name);
if (index >= 0)
return (Schema.CatalogObject)Catalog[index];
if (mustResolve)
throw new Schema.SchemaException(Schema.SchemaException.Codes.ObjectNotFound, name);
return null;
}
}
public void ClearCachedCatalogObject(Schema.CatalogObject objectValue)
{
Schema.Objects objects = new Schema.Objects();
objects.Add(objectValue);
ClearCachedCatalogObjects(objects);
}
public void ClearCachedCatalogObjects(Schema.Objects objects)
{
string[] localObjects = new string[objects.Count];
for (int index = 0; index < objects.Count; index++)
localObjects[index] = objects[index].Name;
// Push a loading context so that the drops only occur in the cache, not the store
ServerProcess.PushLoadingContext(new LoadingContext(ServerProcess.ServerSession.Server.SystemUser, String.Empty));
try
{
Plan plan = new Plan(ServerProcess);
try
{
plan.PushSecurityContext(new SecurityContext(ServerProcess.ServerSession.Server.SystemUser));
try
{
Block block = (Block)plan.Catalog.EmitDropStatement(this, localObjects, String.Empty, true, true, true, true);
Program program = new Program(ServerProcess);
foreach (Statement statement in block.Statements)
{
program.Code = Compiler.Compile(plan, statement);
program.Execute(null);
}
}
finally
{
plan.PopSecurityContext();
}
}
finally
{
plan.Dispose();
}
}
/*
catch
{
// TODO: Determine recovery processing that should take place here.
// Basically, the cache is in a bad state at this point, and clearing
// the catalog cache is the only guaranteed way to get back to a consistent state
}
*/
finally
{
ServerProcess.PopLoadingContext();
}
}
/// <summary>Adds the given object to the catalog cache.</summary>
public void CacheCatalogObject(Schema.CatalogObject objectValue)
{
lock (Catalog)
{
// if the object is already in the cache (by name), then it must be there as a result of some error
// and the best course of action in a production scenario is to just replace it with the new object
#if !DEBUG
int index = Catalog.IndexOfName(objectValue.Name);
if (index >= 0)
ClearCatalogObject((Schema.CatalogObject)Catalog[index]);
#endif
// Add the object to the catalog cache
Catalog.Add(objectValue);
// Add the object to the cache index
Device.CatalogIndex.Add(objectValue.ID, Schema.Object.EnsureRooted(objectValue.Name));
}
}
/// <summary>Removes the given object from the catalog cache.</summary>
private void ClearCatalogObject(Schema.CatalogObject objectValue)
{
lock (Catalog)
{
// Remove the object from the cache index
Device.CatalogIndex.Remove(objectValue.ID);
// Remove the object from the cache
Catalog.SafeRemove(objectValue);
// Clear the name resolution cache
Device.NameCache.Clear(objectValue.Name);
// Clear the operator name resolution cache
Device.OperatorNameCache.Clear(objectValue.Name);
ClearCachedRightAssignments(objectValue.GetRights());
}
}
protected void ClearCachedRightAssignments(string[] rightNames)
{
foreach (Schema.User user in Device.UsersCache.Values)
user.ClearCachedRightAssignments(rightNames);
}
#endregion
#region Catalog object
/// <summary>Returns true if the given object is not an A/T object.</summary>
public bool ShouldSerializeCatalogObject(Schema.CatalogObject objectValue)
{
return !objectValue.IsATObject;
}
/// <summary>Inserts the given object into the catalog cache. If this is not a repository, also inserts the object into the catalog store.</summary>
public virtual void InsertCatalogObject(Schema.CatalogObject objectValue)
{
// Cache the object
CacheCatalogObject(objectValue);
// If we are not deserializing
if (!ServerProcess.InLoadingContext())
{
#if LOGDDLINSTRUCTIONS
// Log the DDL instruction
if (ServerProcess.InTransaction)
_instructions.Add(new CreateCatalogObjectInstruction(objectValue));
#endif
InternalInsertCatalogObject(objectValue);
}
}
protected virtual void InternalInsertCatalogObject(Schema.CatalogObject objectValue)
{
// virtual
}
/// <summary>Updates the given object in the catalog cache. If this is not a repository, also updates the object in the catalog store.</summary>
public void UpdateCatalogObject(Schema.CatalogObject objectValue)
{
// If we are not deserializing
if (!ServerProcess.InLoadingContext())
InternalUpdateCatalogObject(objectValue);
}
protected virtual void InternalUpdateCatalogObject(Schema.CatalogObject objectValue)
{
// virtual
}
/// <summary>Deletes the given object in the catalog cache. If this is not a repository, also deletes the object in the catalog store.</summary>
public void DeleteCatalogObject(Schema.CatalogObject objectValue)
{
lock (Catalog)
{
// Remove the object from the catalog cache
ClearCatalogObject(objectValue);
}
// If we are not deserializing
if (!ServerProcess.InLoadingContext())
{
#if LOGDDLINSTRUCTIONS
// Log the DDL instruction
if (ServerProcess.InTransaction)
_instructions.Add(new DropCatalogObjectInstruction(objectValue));
#endif
InternalDeleteCatalogObject(objectValue);
}
}
protected virtual void InternalDeleteCatalogObject(Schema.CatalogObject objectValue)
{
// virtual
}
public virtual bool CatalogObjectExists(string objectName)
{
return false;
}
#endregion
#region Loaded library
private void CacheLoadedLibrary(Schema.LoadedLibrary loadedLibrary)
{
Catalog.LoadedLibraries.Add(loadedLibrary);
}
private void ClearLoadedLibrary(Schema.LoadedLibrary loadedLibrary)
{
Catalog.LoadedLibraries.Remove(loadedLibrary);
}
public void InsertLoadedLibrary(Schema.LoadedLibrary loadedLibrary)
{
Catalog.UpdateTimeStamp();
CacheLoadedLibrary(loadedLibrary);
#if LOGDDLINSTRUCTIONS
if (ServerProcess.InTransaction)
_instructions.Add(new InsertLoadedLibraryInstruction(loadedLibrary));
#endif
InternalInsertLoadedLibrary(loadedLibrary);
}
protected virtual void InternalInsertLoadedLibrary(Schema.LoadedLibrary loadedLibrary)
{
// virtual
}
public void DeleteLoadedLibrary(Schema.LoadedLibrary loadedLibrary)
{
Catalog.UpdateTimeStamp();
ClearLoadedLibrary(loadedLibrary);
#if LOGDDLINSTRUCTIONS
if (ServerProcess.InTransaction)
_instructions.Add(new DeleteLoadedLibraryInstruction(loadedLibrary));
#endif
InternalDeleteLoadedLibrary(loadedLibrary);
}
protected virtual void InternalDeleteLoadedLibrary(Schema.LoadedLibrary loadedLibrary)
{
// virtual
}
public virtual void ResolveLoadedLibraries()
{
// virtual
}
public bool IsLoadedLibrary(string libraryName)
{
return ResolveLoadedLibrary(libraryName, false) != null;
}
public Schema.LoadedLibrary ResolveLoadedLibrary(string libraryName)
{
return ResolveLoadedLibrary(libraryName, true);
}
public Schema.LoadedLibrary ResolveLoadedLibrary(string libraryName, bool mustResolve)
{
Schema.Library library = Catalog.Libraries[libraryName];
int index = Catalog.LoadedLibraries.IndexOfName(library.Name);
if (index >= 0)
return Catalog.LoadedLibraries[index];
var result = InternalResolveLoadedLibrary(library);
if (result != null)
return result;
if (mustResolve)
throw new Schema.SchemaException(Schema.SchemaException.Codes.LibraryNotRegistered, library.Name);
return null;
}
protected virtual LoadedLibrary InternalResolveLoadedLibrary(Schema.Library LLibrary)
{
return null;
}
#endregion
#region Assembly registration
private SettingsList InternalRegisterAssembly(Schema.LoadedLibrary loadedLibrary, Assembly assembly)
{
SettingsList classes = Catalog.ClassLoader.RegisterAssembly(loadedLibrary, assembly);
loadedLibrary.Assemblies.Add(assembly);
return classes;
}
public void RegisterAssembly(Schema.LoadedLibrary loadedLibrary, Assembly assembly)
{
SettingsList classes = InternalRegisterAssembly(loadedLibrary, assembly);
if (!ServerProcess.InLoadingContext())
InsertRegisteredClasses(loadedLibrary, classes);
#if LOGDDLINSTRUCTIONS
if (ServerProcess.InTransaction)
_instructions.Add(new RegisterAssemblyInstruction(loadedLibrary, assembly));
#endif
}
private SettingsList InternalUnregisterAssembly(Schema.LoadedLibrary loadedLibrary, Assembly assembly)
{
SettingsList classes = Catalog.ClassLoader.UnregisterAssembly(loadedLibrary, assembly);
loadedLibrary.Assemblies.Remove(assembly);
return classes;
}
public void UnregisterAssembly(Schema.LoadedLibrary loadedLibrary, Assembly assembly)
{
SettingsList classes = InternalUnregisterAssembly(loadedLibrary, assembly);
if (!ServerProcess.InLoadingContext())
DeleteRegisteredClasses(loadedLibrary, classes);
#if LOGDDLINSTRUCTIONS
if (ServerProcess.InTransaction)
_instructions.Add(new UnregisterAssemblyInstruction(loadedLibrary, assembly));
#endif
}
protected virtual void InsertRegisteredClasses(Schema.LoadedLibrary loadedLibrary, SettingsList registeredClasses)
{
}
protected virtual void DeleteRegisteredClasses(Schema.LoadedLibrary loadedLibrary, SettingsList registeredClasses)
{
}
#endregion
#region Session objects
private void CreateSessionObject(Schema.CatalogObject sessionObject)
{
lock (ServerProcess.ServerSession.SessionObjects)
{
ServerProcess.ServerSession.SessionObjects.Add(new Schema.SessionObject(sessionObject.SessionObjectName, sessionObject.Name));
}
}
private void DropSessionObject(Schema.CatalogObject sessionObject)
{
ServerProcess.ServerSession.Server.DropSessionObject(sessionObject);
}
private void CreateSessionOperator(Schema.Operator sessionOperator)
{
lock (ServerProcess.ServerSession.SessionOperators)
{
if (!ServerProcess.ServerSession.SessionOperators.ContainsName(sessionOperator.SessionObjectName))
ServerProcess.ServerSession.SessionOperators.Add(new Schema.SessionObject(sessionOperator.SessionObjectName, sessionOperator.OperatorName));
}
}
private void DropSessionOperator(Schema.Operator sessionOperator)
{
ServerProcess.ServerSession.Server.DropSessionOperator(sessionOperator);
}
#endregion
#region Table
public void CreateTable(Schema.BaseTableVar table)
{
InsertCatalogObject(table);
if (table.SessionObjectName != null)
{
CreateSessionObject(table);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new CreateSessionObjectInstruction(table));
#endif
}
if (!ServerProcess.ServerSession.Server.IsEngine && ServerProcess.IsReconciliationEnabled())
{
CreateDeviceTable(table);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new CreateDeviceTableInstruction(table));
#endif
}
}
public void DropTable(Schema.BaseTableVar table)
{
DeleteCatalogObject(table);
if (table.SessionObjectName != null)
{
DropSessionObject(table);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DropSessionObjectInstruction(table));
#endif
}
if (!ServerProcess.ServerSession.Server.IsEngine && ServerProcess.IsReconciliationEnabled())
{
DropDeviceTable(table);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DropDeviceTableInstruction(table));
#endif
}
}
#endregion
#region View
public void CreateView(Schema.DerivedTableVar view)
{
InsertCatalogObject(view);
if (view.SessionObjectName != null)
{
CreateSessionObject(view);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new CreateSessionObjectInstruction(view));
#endif
}
}
public void DropView(Schema.DerivedTableVar view)
{
DeleteCatalogObject(view);
if (view.SessionObjectName != null)
{
DropSessionObject(view);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DropSessionObjectInstruction(view));
#endif
}
}
public void MarkViewForRecompile(int objectID)
{
string objectName;
if (Device.CatalogIndex.TryGetValue(objectID, out objectName))
((Schema.DerivedTableVar)Catalog[objectName]).ShouldReinferReferences = true;
}
#endregion
#region Conversions
private void AddImplicitConversion(Schema.Conversion conversion)
{
lock (Catalog)
{
conversion.SourceScalarType.ImplicitConversions.Add(conversion);
}
}
private void RemoveImplicitConversion(Schema.Conversion conversion)
{
lock (Catalog)
{
conversion.SourceScalarType.ImplicitConversions.SafeRemove(conversion);
}
}
public void CreateConversion(Schema.Conversion conversion)
{
InsertCatalogObject(conversion);
AddImplicitConversion(conversion);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AddImplicitConversionInstruction(conversion));
#endif
}
public void DropConversion(Schema.Conversion conversion)
{
DeleteCatalogObject(conversion);
RemoveImplicitConversion(conversion);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new RemoveImplicitConversionInstruction(conversion));
#endif
}
#endregion
#region Sort
private void SetScalarTypeSort(Schema.ScalarType scalarType, Schema.Sort sort, bool isUnique)
{
if (isUnique)
scalarType.UniqueSort = sort;
else
scalarType.Sort = sort;
}
public void CreateSort(Schema.Sort sort)
{
InsertCatalogObject(sort);
}
public void DropSort(Schema.Sort sort)
{
DeleteCatalogObject(sort);
}
public void AttachSort(Schema.ScalarType scalarType, Schema.Sort sort, bool isUnique)
{
#if LOGDDLINSTRUCTIONS
Schema.Sort originalSort = isUnique ? scalarType.UniqueSort : scalarType.Sort;
#endif
SetScalarTypeSort(scalarType, sort, isUnique);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetScalarTypeSortInstruction(scalarType, originalSort, isUnique));
#endif
}
public void DetachSort(Schema.ScalarType scalarType, Schema.Sort sort, bool isUnique)
{
SetScalarTypeSort(scalarType, null, isUnique);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetScalarTypeSortInstruction(scalarType, sort, isUnique));
#endif
}
#endregion
#region Metadata
public void AlterMetaData(Schema.Object objectValue, AlterMetaData alterMetaData)
{
if (alterMetaData != null)
{
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
{
MetaData metaData = null;
if (objectValue.MetaData != null)
{
metaData = new MetaData();
metaData.Merge(objectValue.MetaData);
}
_instructions.Add(new AlterMetaDataInstruction(objectValue, metaData));
}
#endif
AlterNode.AlterMetaData(objectValue, alterMetaData);
}
}
#endregion
#region Scalar type
public void CreateScalarType(Schema.ScalarType scalarType)
{
InsertCatalogObject(scalarType);
}
public void DropScalarType(Schema.ScalarType scalarType)
{
DeleteCatalogObject(scalarType);
}
#endregion
#region Operator
public void CreateOperator(Schema.Operator operatorValue)
{
InsertCatalogObject(operatorValue);
if (operatorValue.SessionObjectName != null)
{
CreateSessionOperator(operatorValue);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new CreateSessionOperatorInstruction(operatorValue));
#endif
}
}
public void AlterOperator(Schema.Operator oldOperator, Schema.Operator newOperator)
{
#if LOGDDLINSTRUCTIONS
ObjectList originalDependencies = new ObjectList();
oldOperator.Dependencies.CopyTo(originalDependencies);
#endif
oldOperator.Dependencies.Clear();
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new RemoveDependenciesInstruction(oldOperator, originalDependencies));
#endif
oldOperator.AddDependencies(newOperator.Dependencies);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AddDependenciesInstruction(oldOperator));
#endif
oldOperator.DetermineRemotable(this);
AlterOperatorBlockNode(oldOperator.Block, newOperator.Block.BlockNode);
}
public void AlterOperatorBlockNode(Schema.OperatorBlock operatorBlock, PlanNode newNode)
{
#if LOGDDLINSTRUCTIONS
PlanNode originalNode = operatorBlock.BlockNode;
#endif
operatorBlock.BlockNode = newNode;
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetOperatorBlockNodeInstruction(operatorBlock, originalNode));
#endif
}
public void DropOperator(Schema.Operator operatorValue)
{
DeleteCatalogObject(operatorValue);
if (operatorValue.SessionObjectName != null)
{
DropSessionOperator(operatorValue);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DropSessionOperatorInstruction(operatorValue));
#endif
}
}
#endregion
#region Constraint
public void CreateConstraint(Schema.CatalogConstraint constraint)
{
InsertCatalogObject(constraint);
if (!ServerProcess.ServerSession.Server.IsEngine && constraint.Enforced)
{
CreateConstraintNode.AttachConstraint(constraint, constraint.Node);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachCatalogConstraintInstruction(constraint));
#endif
}
if (constraint.SessionObjectName != null)
{
CreateSessionObject(constraint);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new CreateSessionObjectInstruction(constraint));
#endif
}
}
public void AlterConstraint(Schema.CatalogConstraint oldConstraint, Schema.CatalogConstraint newConstraint)
{
if (!ServerProcess.ServerSession.Server.IsEngine && oldConstraint.Enforced)
{
CreateConstraintNode.DetachConstraint(oldConstraint, oldConstraint.Node);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachCatalogConstraintInstruction(oldConstraint));
#endif
}
#if LOGDDLINSTRUCTIONS
ObjectList originalDependencies = new ObjectList();
oldConstraint.Dependencies.CopyTo(originalDependencies);
#endif
oldConstraint.Dependencies.Clear();
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new RemoveDependenciesInstruction(oldConstraint, originalDependencies));
#endif
oldConstraint.AddDependencies(newConstraint.Dependencies);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AddDependenciesInstruction(oldConstraint));
#endif
#if LOGDDLINSTRUCTIONS
PlanNode originalNode = oldConstraint.Node;
#endif
oldConstraint.Node = newConstraint.Node;
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetCatalogConstraintNodeInstruction(oldConstraint, originalNode));
#endif
if (!ServerProcess.ServerSession.Server.IsEngine && oldConstraint.Enforced)
{
CreateConstraintNode.AttachConstraint(oldConstraint, oldConstraint.Node);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachCatalogConstraintInstruction(oldConstraint));
#endif
}
}
public void DropConstraint(Schema.CatalogConstraint constraint)
{
DeleteCatalogObject(constraint);
if (!ServerProcess.ServerSession.Server.IsEngine && constraint.Enforced)
{
CreateConstraintNode.DetachConstraint(constraint, constraint.Node);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachCatalogConstraintInstruction(constraint));
#endif
}
if (constraint.SessionObjectName != null)
{
DropSessionObject(constraint);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DropSessionObjectInstruction(constraint));
#endif
}
}
#endregion
#region Reference
private void AttachReference(Schema.Reference reference)
{
if (!ServerProcess.ServerSession.Server.IsEngine && reference.Enforced)
{
if ((reference.SourceTable is Schema.BaseTableVar) && (reference.TargetTable is Schema.BaseTableVar))
{
reference.SourceTable.Constraints.Add(reference.SourceConstraint);
reference.SourceTable.InsertConstraints.Add(reference.SourceConstraint);
reference.SourceTable.UpdateConstraints.Add(reference.SourceConstraint);
if ((reference.UpdateReferenceAction == ReferenceAction.Require) || (reference.DeleteReferenceAction == ReferenceAction.Require))
{
reference.TargetTable.Constraints.Add(reference.TargetConstraint);
if (reference.UpdateReferenceAction == ReferenceAction.Require)
reference.TargetTable.UpdateConstraints.Add(reference.TargetConstraint);
if (reference.DeleteReferenceAction == ReferenceAction.Require)
reference.TargetTable.DeleteConstraints.Add(reference.TargetConstraint);
}
}
else
{
// This constraint is added only in the cache (never persisted)
CreateConstraintNode.AttachConstraint(reference.CatalogConstraint, reference.CatalogConstraint.Node);
}
if ((reference.UpdateReferenceAction == ReferenceAction.Cascade) || (reference.UpdateReferenceAction == ReferenceAction.Clear) || (reference.UpdateReferenceAction == ReferenceAction.Set))
{
// This object is added only in the cache (never persisted)
reference.TargetTable.EventHandlers.Add(reference.UpdateHandler);
}
if ((reference.DeleteReferenceAction == ReferenceAction.Cascade) || (reference.DeleteReferenceAction == ReferenceAction.Clear) || (reference.DeleteReferenceAction == ReferenceAction.Set))
{
// This object is added only in the cache (never persisted)
reference.TargetTable.EventHandlers.Add(reference.DeleteHandler);
}
}
//reference.SourceTable.SourceReferences.AddInCreationOrder(reference);
//reference.TargetTable.TargetReferences.AddInCreationOrder(reference);
reference.SourceTable.References.AddInCreationOrder(reference);
if (!reference.SourceTable.Equals(reference.TargetTable))
reference.TargetTable.References.AddInCreationOrder(reference);
reference.SourceTable.SetShouldReinferReferences(this);
reference.TargetTable.SetShouldReinferReferences(this);
}
private void DetachReference(Schema.Reference reference)
{
if ((reference.SourceTable is Schema.BaseTableVar) && (reference.TargetTable is Schema.BaseTableVar))
{
if (reference.SourceConstraint != null)
{
reference.SourceTable.InsertConstraints.SafeRemove(reference.SourceConstraint);
reference.SourceTable.UpdateConstraints.SafeRemove(reference.SourceConstraint);
reference.SourceTable.Constraints.SafeRemove(reference.SourceConstraint);
}
if (reference.TargetConstraint != null)
{
if ((reference.UpdateReferenceAction == ReferenceAction.Require) || (reference.DeleteReferenceAction == ReferenceAction.Require))
{
if (reference.UpdateReferenceAction == ReferenceAction.Require)
reference.TargetTable.UpdateConstraints.SafeRemove(reference.TargetConstraint);
if (reference.DeleteReferenceAction == ReferenceAction.Require)
reference.TargetTable.DeleteConstraints.SafeRemove(reference.TargetConstraint);
reference.TargetTable.Constraints.SafeRemove(reference.TargetConstraint);
}
}
}
else
{
if (reference.CatalogConstraint != null)
{
CreateConstraintNode.DetachConstraint(reference.CatalogConstraint, reference.CatalogConstraint.Node);
ServerProcess.ServerSession.Server.RemoveCatalogConstraintCheck(reference.CatalogConstraint);
}
}
if (((reference.UpdateReferenceAction == ReferenceAction.Cascade) || (reference.UpdateReferenceAction == ReferenceAction.Clear) || (reference.UpdateReferenceAction == ReferenceAction.Set)) && (reference.UpdateHandler != null))
{
reference.TargetTable.EventHandlers.SafeRemove((TableVarEventHandler)reference.UpdateHandler);
}
if (((reference.DeleteReferenceAction == ReferenceAction.Cascade) || (reference.DeleteReferenceAction == ReferenceAction.Clear) || (reference.DeleteReferenceAction == ReferenceAction.Set)) && (reference.DeleteHandler != null))
{
reference.TargetTable.EventHandlers.SafeRemove((TableVarEventHandler)reference.DeleteHandler);
}
//reference.SourceTable.SourceReferences.SafeRemove(reference);
//reference.TargetTable.TargetReferences.SafeRemove(reference);
reference.SourceTable.References.SafeRemove(reference);
reference.TargetTable.References.SafeRemove(reference);
reference.SourceTable.SetShouldReinferReferences(this);
reference.TargetTable.SetShouldReinferReferences(this);
}
public void CreateReference(Schema.Reference reference)
{
InsertCatalogObject(reference);
AttachReference(reference);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachReferenceInstruction(reference));
#endif
if (reference.SessionObjectName != null)
{
CreateSessionObject(reference);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new CreateSessionObjectInstruction(reference));
#endif
}
}
public void DropReference(Schema.Reference reference)
{
DeleteCatalogObject(reference);
DetachReference(reference);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachReferenceInstruction(reference));
#endif
if (reference.SessionObjectName != null)
{
DropSessionObject(reference);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DropSessionObjectInstruction(reference));
#endif
}
}
#endregion
#region Event handler
private void AttachEventHandler(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex, List<string> beforeOperatorNames)
{
Schema.TableVar tableVar = eventSource as Schema.TableVar;
if (tableVar != null)
{
if (eventSourceColumnIndex >= 0)
tableVar.Columns[eventSourceColumnIndex].EventHandlers.Add((TableVarColumnEventHandler)eventHandler, beforeOperatorNames);
else
tableVar.EventHandlers.Add((TableVarEventHandler)eventHandler, beforeOperatorNames);
tableVar.DetermineRemotable(this);
}
else
((Schema.ScalarType)eventSource).EventHandlers.Add((ScalarTypeEventHandler)eventHandler);
}
private void MoveEventHandler(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex, List<string> beforeOperatorNames)
{
Schema.TableVar tableVar = eventSource as Schema.TableVar;
if (tableVar != null)
{
if (eventSourceColumnIndex >= 0)
tableVar.Columns[eventSourceColumnIndex].EventHandlers.MoveBefore((TableVarColumnEventHandler)eventHandler, beforeOperatorNames);
else
tableVar.EventHandlers.MoveBefore((TableVarEventHandler)eventHandler, beforeOperatorNames);
tableVar.DetermineRemotable(this);
}
else
((Schema.ScalarType)eventSource).EventHandlers.MoveBefore((ScalarTypeEventHandler)eventHandler, beforeOperatorNames);
}
private void DetachEventHandler(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex)
{
Schema.TableVar tableVar = eventSource as Schema.TableVar;
if (tableVar != null)
{
if (eventSourceColumnIndex >= 0)
tableVar.Columns[eventSourceColumnIndex].EventHandlers.SafeRemove((TableVarColumnEventHandler)eventHandler);
else
tableVar.EventHandlers.SafeRemove((TableVarEventHandler)eventHandler);
tableVar.DetermineRemotable(this);
}
else
((Schema.ScalarType)eventSource).EventHandlers.SafeRemove((ScalarTypeEventHandler)eventHandler);
}
private List<string> GetEventHandlerBeforeOperatorNames(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex)
{
List<string> result = new List<string>();
EventHandlers handlers = null;
Schema.TableVar tableVar = eventSource as Schema.TableVar;
if (tableVar != null)
{
if (eventSourceColumnIndex >= 0)
handlers = tableVar.Columns[eventSourceColumnIndex].EventHandlers;
else
handlers = tableVar.EventHandlers;
}
else
handlers = ((Schema.ScalarType)eventSource).EventHandlers;
if (handlers != null)
{
int handlerIndex = handlers.IndexOfName(eventHandler.Name);
for (int index = handlerIndex; index >= 0; index--)
result.Add(handlers[index].Name);
}
return result;
}
public void CreateEventHandler(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex, List<string> beforeOperatorNames)
{
AttachEventHandler(eventHandler, eventSource, eventSourceColumnIndex, beforeOperatorNames);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachEventHandlerInstruction(eventHandler, eventSource, eventSourceColumnIndex, beforeOperatorNames));
#endif
// Note the event handlers must be attached first, otherwise properties on the event handler will not be set properly (CatalogObjectID, ParentObjectID, etc.,.)
InsertCatalogObject(eventHandler);
}
public void AlterEventHandler(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex, List<string> beforeOperatorNames)
{
#if LOGDDLINSTRUCTIONS
List<string> localBeforeOperatorNames = GetEventHandlerBeforeOperatorNames(eventHandler, eventSource, eventSourceColumnIndex);
#endif
MoveEventHandler(eventHandler, eventSource, eventSourceColumnIndex, beforeOperatorNames);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new MoveEventHandlerInstruction(eventHandler, eventSource, eventSourceColumnIndex, localBeforeOperatorNames));
#endif
}
public void DropEventHandler(Schema.EventHandler eventHandler, Schema.Object eventSource, int eventSourceColumnIndex)
{
DeleteCatalogObject(eventHandler);
#if LOGDDLINSTRUCTIONS
List<string> beforeOperatorNames = GetEventHandlerBeforeOperatorNames(eventHandler, eventSource, eventSourceColumnIndex);
#endif
DetachEventHandler(eventHandler, eventSource, eventSourceColumnIndex);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachEventHandlerInstruction(eventHandler, eventSource, eventSourceColumnIndex, beforeOperatorNames));
#endif
}
#endregion
#region Class definitions
public void AlterClassDefinition(ClassDefinition classDefinition, AlterClassDefinition alterClassDefinition)
{
AlterClassDefinition(classDefinition, alterClassDefinition, null);
}
public void AlterClassDefinition(ClassDefinition classDefinition, AlterClassDefinition alterClassDefinition, object instance)
{
if (alterClassDefinition != null)
{
ClassDefinition originalClassDefinition = classDefinition.Clone() as ClassDefinition;
AlterNode.AlterClassDefinition(classDefinition, alterClassDefinition, instance);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AlterClassDefinitionInstruction(classDefinition, alterClassDefinition, originalClassDefinition, instance));
#endif
}
}
#endregion
#region Key
private void AttachKey(TableVar tableVar, Key key)
{
tableVar.Keys.Add(key);
if (!tableVar.Constraints.Contains(key.Constraint))
tableVar.Constraints.Add(key.Constraint);
if (!tableVar.InsertConstraints.Contains(key.Constraint))
tableVar.InsertConstraints.Add(key.Constraint);
if (!tableVar.UpdateConstraints.Contains(key.Constraint))
tableVar.UpdateConstraints.Add(key.Constraint);
}
private void DetachKey(TableVar tableVar, Key key)
{
tableVar.Keys.SafeRemove(key);
tableVar.Constraints.SafeRemove(key.Constraint);
tableVar.InsertConstraints.SafeRemove(key.Constraint);
tableVar.UpdateConstraints.SafeRemove(key.Constraint);
}
public void CreateKey(TableVar tableVar, Key key)
{
AttachKey(tableVar, key);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachKeyInstruction(tableVar, key));
#endif
}
public void DropKey(TableVar tableVar, Key key)
{
DetachKey(tableVar, key);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachKeyInstruction(tableVar, key));
#endif
}
#endregion
#region Order
private void AttachOrder(TableVar tableVar, Order order)
{
tableVar.Orders.Add(order);
}
private void DetachOrder(TableVar tableVar, Order order)
{
tableVar.Orders.SafeRemove(order);
}
public void CreateOrder(TableVar tableVar, Order order)
{
AttachOrder(tableVar, order);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachOrderInstruction(tableVar, order));
#endif
}
public void DropOrder(TableVar tableVar, Order order)
{
DetachOrder(tableVar, order);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachOrderInstruction(tableVar, order));
#endif
}
#endregion
#region TableVar column
private void AttachTableVarColumn(Schema.BaseTableVar table, Schema.TableVarColumn column)
{
table.DataType.Columns.Add(column.Column);
table.Columns.Add(column);
table.DataType.ResetRowType();
}
private void DetachTableVarColumn(Schema.BaseTableVar table, Schema.TableVarColumn column)
{
table.DataType.Columns.SafeRemove(column.Column);
table.Columns.SafeRemove(column);
table.DataType.ResetRowType();
}
public void CreateTableVarColumn(Schema.BaseTableVar table, Schema.TableVarColumn column)
{
AttachTableVarColumn(table, column);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachTableVarColumnInstruction(table, column));
#endif
}
public void DropTableVarColumn(Schema.BaseTableVar table, Schema.TableVarColumn column)
{
DetachTableVarColumn(table, column);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachTableVarColumnInstruction(table, column));
#endif
}
public void SetTableVarColumnDefault(Schema.TableVarColumn LColumn, Schema.TableVarColumnDefault defaultValue)
{
TableVarColumnDefault originalDefault = LColumn.Default;
LColumn.Default = defaultValue;
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetTableVarColumnDefaultInstruction(LColumn, originalDefault));
#endif
}
public void SetTableVarColumnIsNilable(TableVarColumn LColumn, bool isNilable)
{
bool originalIsNilable = LColumn.IsNilable;
LColumn.IsNilable = isNilable;
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetTableVarColumnIsNilableInstruction(LColumn, originalIsNilable));
#endif
}
#endregion
#region TableVar constraint
private void AttachTableVarConstraint(Schema.TableVar tableVar, Schema.TableVarConstraint constraint)
{
tableVar.Constraints.Add(constraint);
if (constraint is Schema.RowConstraint)
tableVar.RowConstraints.Add(constraint);
else
{
Schema.TransitionConstraint transitionConstraint = (Schema.TransitionConstraint)constraint;
if (transitionConstraint.OnInsertNode != null)
tableVar.InsertConstraints.Add(transitionConstraint);
if (transitionConstraint.OnUpdateNode != null)
tableVar.UpdateConstraints.Add(transitionConstraint);
if (transitionConstraint.OnDeleteNode != null)
tableVar.DeleteConstraints.Add(transitionConstraint);
}
}
private void DetachTableVarConstraint(Schema.TableVar tableVar, Schema.TableVarConstraint constraint)
{
tableVar.Constraints.SafeRemove(constraint);
if (constraint is Schema.RowConstraint)
tableVar.RowConstraints.SafeRemove((Schema.RowConstraint)constraint);
else
{
Schema.TransitionConstraint transitionConstraint = (Schema.TransitionConstraint)constraint;
if (transitionConstraint.OnInsertNode != null)
tableVar.InsertConstraints.SafeRemove(transitionConstraint);
if (transitionConstraint.OnUpdateNode != null)
tableVar.UpdateConstraints.SafeRemove(transitionConstraint);
if (transitionConstraint.OnDeleteNode != null)
tableVar.DeleteConstraints.SafeRemove(transitionConstraint);
}
}
public void CreateTableVarConstraint(Schema.TableVar tableVar, Schema.TableVarConstraint constraint)
{
AttachTableVarConstraint(tableVar, constraint);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachTableVarConstraintInstruction(tableVar, constraint));
#endif
}
public void DropTableVarConstraint(Schema.TableVar tableVar, Schema.TableVarConstraint constraint)
{
DetachTableVarConstraint(tableVar, constraint);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachTableVarConstraintInstruction(tableVar, constraint));
#endif
}
#endregion
#region TableVar column constraint
private void AttachTableVarColumnConstraint(Schema.TableVarColumn tableVarColumn, Schema.TableVarColumnConstraint constraint)
{
tableVarColumn.Constraints.Add(constraint);
}
private void DetachTableVarColumnConstraint(Schema.TableVarColumn tableVarColumn, Schema.TableVarColumnConstraint constraint)
{
tableVarColumn.Constraints.SafeRemove(constraint);
}
public void CreateTableVarColumnConstraint(TableVarColumn column, TableVarColumnConstraint constraint)
{
AttachTableVarColumnConstraint(column, constraint);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachTableVarColumnConstraintInstruction(column, constraint));
#endif
}
public void DropTableVarColumnConstraint(TableVarColumn column, TableVarColumnConstraint constraint)
{
DetachTableVarColumnConstraint(column, constraint);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachTableVarColumnConstraintInstruction(column, constraint));
#endif
}
#endregion
#region Scalar type
private void AttachScalarTypeConstraint(Schema.ScalarType scalarType, Schema.ScalarTypeConstraint constraint)
{
scalarType.Constraints.Add(constraint);
}
private void DetachScalarTypeConstraint(Schema.ScalarType scalarType, Schema.ScalarTypeConstraint constraint)
{
scalarType.Constraints.SafeRemove(constraint);
}
public void CreateScalarTypeConstraint(ScalarType scalarType, ScalarTypeConstraint constraint)
{
AttachScalarTypeConstraint(scalarType, constraint);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachScalarTypeConstraintInstruction(scalarType, constraint));
#endif
}
public void DropScalarTypeConstraint(ScalarType scalarType, ScalarTypeConstraint constraint)
{
DetachScalarTypeConstraint(scalarType, constraint);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachScalarTypeConstraintInstruction(scalarType, constraint));
#endif
}
public void SetScalarTypeDefault(Schema.ScalarType scalarType, Schema.ScalarTypeDefault defaultValue)
{
Schema.ScalarTypeDefault originalDefault = scalarType.Default;
scalarType.Default = defaultValue;
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetScalarTypeDefaultInstruction(scalarType, originalDefault));
#endif
}
public void SetScalarTypeIsSpecialOperator(Schema.ScalarType scalarType, Schema.Operator operatorValue)
{
Schema.Operator originalOperator = scalarType.IsSpecialOperator;
scalarType.IsSpecialOperator = operatorValue;
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetScalarTypeIsSpecialOperatorInstruction(scalarType, originalOperator));
#endif
}
private void AttachSpecial(Schema.ScalarType scalarType, Schema.Special special)
{
scalarType.Specials.Add(special);
}
private void DetachSpecial(Schema.ScalarType scalarType, Schema.Special special)
{
scalarType.Specials.SafeRemove(special);
}
public void CreateSpecial(ScalarType scalarType, Special special)
{
AttachSpecial(scalarType, special);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachSpecialInstruction(scalarType, special));
#endif
}
public void DropSpecial(ScalarType scalarType, Special special)
{
DetachSpecial(scalarType, special);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachSpecialInstruction(scalarType, special));
#endif
}
private void AttachRepresentation(Schema.ScalarType scalarType, Schema.Representation representation)
{
if (!scalarType.Representations.Contains(representation))
scalarType.Representations.Add(representation);
}
private void DetachRepresentation(Schema.ScalarType scalarType, Schema.Representation representation)
{
scalarType.Representations.SafeRemove(representation);
}
public void CreateRepresentation(ScalarType scalarType, Representation representation)
{
AttachRepresentation(scalarType, representation);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachRepresentationInstruction(scalarType, representation));
#endif
}
public void DropRepresentation(ScalarType scalarType, Representation representation)
{
DetachRepresentation(scalarType, representation);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachRepresentationInstruction(scalarType, representation));
#endif
}
private void AttachProperty(Schema.Representation representation, Schema.Property property)
{
if (!representation.Properties.Contains(property))
representation.Properties.Add(property);
}
private void DetachProperty(Schema.Representation representation, Schema.Property property)
{
representation.Properties.SafeRemove(property);
}
public void CreateProperty(Schema.Representation representation, Schema.Property property)
{
AttachProperty(representation, property);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachPropertyInstruction(representation, property));
#endif
}
public void DropProperty(Schema.Representation representation, Schema.Property property)
{
DetachProperty(representation, property);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachPropertyInstruction(representation, property));
#endif
}
#endregion
#region Device
public new CatalogDevice Device { get { return (CatalogDevice)base.Device; } }
public void CreateDevice(Schema.Device device)
{
InsertCatalogObject(device);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
{
_instructions.Add(new StartDeviceInstruction(device));
}
#endif
}
public void StartDevice(Schema.Device device)
{
device.Start(ServerProcess);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new StartDeviceInstruction(device));
#endif
}
public void RegisterDevice(Schema.Device device)
{
if (!device.Registered)
{
device.Register(ServerProcess);
UpdateCatalogObject(device);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new RegisterDeviceInstruction(device));
#endif
}
}
public void UnregisterDevice(Schema.Device device)
{
device.ClearRegistered();
}
public void StopDevice(Schema.Device device)
{
StopDevice(device, false);
}
private List<Schema.Device> _deferredDeviceStops;
private void AddDeferredDeviceStop(Schema.Device device)
{
if (_deferredDeviceStops == null)
_deferredDeviceStops = new List<Schema.Device>();
_deferredDeviceStops.Add(device);
}
private void ExecuteDeferredDeviceStops()
{
if (_deferredDeviceStops != null)
{
while (_deferredDeviceStops.Count > 0)
{
InternalStopDevice(_deferredDeviceStops[0]);
_deferredDeviceStops.RemoveAt(0);
}
_deferredDeviceStops = null;
}
}
private void ClearDeferredDeviceStops()
{
if (_deferredDeviceStops != null)
_deferredDeviceStops = null;
}
private void InternalStopDevice(Schema.Device device)
{
if (device.Running)
{
if (device.Sessions.Count > 0)
for (int index = device.Sessions.Count - 1; index >= 0; index--)
device.Sessions.Dispose();
// TODO: implement checking and error handling for in use device sessions on this device
//throw new RuntimeException(RuntimeException.Codes.DeviceInUse, ADevice.Name);
device.Stop(ServerProcess);
}
}
private void StopDevice(Schema.Device device, bool isUndo)
{
if ((ServerProcess.InTransaction) && !isUndo)
AddDeferredDeviceStop(device);
else
InternalStopDevice(device);
}
public void DropDevice(Schema.Device device)
{
DeleteCatalogObject(device);
}
public void SetDeviceReconcileMode(Schema.Device device, ReconcileMode reconcileMode)
{
ReconcileMode originalReconcileMode = device.ReconcileMode;
device.ReconcileMode = reconcileMode;
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetDeviceReconcileModeInstruction(device, originalReconcileMode));
#endif
}
public void SetDeviceReconcileMaster(Schema.Device device, ReconcileMaster reconcileMaster)
{
ReconcileMaster originalReconcileMaster = device.ReconcileMaster;
device.ReconcileMaster = reconcileMaster;
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new SetDeviceReconcileMasterInstruction(device, originalReconcileMaster));
#endif
}
#endregion
#region Device user
public virtual Schema.DeviceUser ResolveDeviceUser(Schema.Device device, Schema.User user, bool mustResolve)
{
lock (device.Users)
{
Schema.DeviceUser deviceUser;
if (!device.Users.TryGetValue(user.ID, out deviceUser) && mustResolve)
throw new Schema.SchemaException(Schema.SchemaException.Codes.DeviceUserNotFound, user.ID);
return deviceUser;
}
}
public Schema.DeviceUser ResolveDeviceUser(Schema.Device device, Schema.User user)
{
return ResolveDeviceUser(device, user, true);
}
public bool DeviceUserExists(Schema.Device device, Schema.User user)
{
return ResolveDeviceUser(device, user, false) != null;
}
#endregion
#region Device scalar type
private void AttachDeviceScalarType(Schema.DeviceScalarType deviceScalarType)
{
deviceScalarType.Device.AddDeviceScalarType(deviceScalarType);
}
private void DetachDeviceScalarType(Schema.DeviceScalarType deviceScalarType)
{
deviceScalarType.Device.RemoveDeviceScalarType(deviceScalarType);
}
public void CreateDeviceScalarType(DeviceScalarType deviceScalarType)
{
InsertCatalogObject(deviceScalarType);
AttachDeviceScalarType(deviceScalarType);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachDeviceScalarTypeInstruction(deviceScalarType));
#endif
}
public void DropDeviceScalarType(DeviceScalarType deviceScalarType)
{
DeleteCatalogObject(deviceScalarType);
DetachDeviceScalarType(deviceScalarType);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachDeviceScalarTypeInstruction(deviceScalarType));
#endif
}
#endregion
#region Device table
private void CreateDeviceTable(Schema.BaseTableVar table)
{
var node = new CreateTableNode(table);
using (var plan = new Plan(ServerProcess))
{
table.Device.Prepare(plan, node);
}
var program = new Program(ServerProcess);
program.Start(null);
try
{
program.DeviceExecute(table.Device, node);
}
finally
{
program.Stop(null);
}
}
private void DropDeviceTable(Schema.BaseTableVar table)
{
var node = new DropTableNode(table);
using (var plan = new Plan(ServerProcess))
{
table.Device.Prepare(plan, node);
}
var program = new Program(ServerProcess);
program.Start(null);
try
{
program.DeviceExecute(table.Device, node);
}
finally
{
program.Stop(null);
}
}
private void AttachTableMap(ApplicationTransactionDevice device, TableMap tableMap)
{
device.TableMaps.Add(tableMap);
}
private void DetachTableMap(ApplicationTransactionDevice device, TableMap tableMap)
{
device.TableMaps.RemoveAt(device.TableMaps.IndexOfName(tableMap.SourceTableVar.Name));
}
public void AddTableMap(ApplicationTransactionDevice device, TableMap tableMap)
{
AttachTableMap(device, tableMap);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachTableMapInstruction(device, tableMap));
#endif
}
public void RemoveTableMap(ApplicationTransactionDevice device, TableMap tableMap)
{
DetachTableMap(device, tableMap);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachTableMapInstruction(device, tableMap));
#endif
}
#endregion
#region Device operator
private void AttachDeviceOperator(Schema.DeviceOperator deviceOperator)
{
deviceOperator.Device.AddDeviceOperator(deviceOperator);
}
private void DetachDeviceOperator(Schema.DeviceOperator deviceOperator)
{
deviceOperator.Device.RemoveDeviceOperator(deviceOperator);
}
public void CreateDeviceOperator(DeviceOperator deviceOperator)
{
InsertCatalogObject(deviceOperator);
AttachDeviceOperator(deviceOperator);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachDeviceOperatorInstruction(deviceOperator));
#endif
}
public void DropDeviceOperator(DeviceOperator deviceOperator)
{
DeleteCatalogObject(deviceOperator);
DetachDeviceOperator(deviceOperator);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachDeviceOperatorInstruction(deviceOperator));
#endif
}
private void AttachOperatorMap(ApplicationTransaction.OperatorMap operatorMap, Schema.Operator operatorValue)
{
operatorMap.Operators.Add(operatorValue);
}
private void DetachOperatorMap(ApplicationTransaction.OperatorMap operatorMap, Schema.Operator operatorValue)
{
operatorMap.Operators.Remove(operatorValue);
}
public void AddOperatorMap(ApplicationTransaction.OperatorMap operatorMap, Schema.Operator operatorValue)
{
AttachOperatorMap(operatorMap, operatorValue);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new AttachOperatorMapInstruction(operatorMap, operatorValue));
#endif
}
public void RemoveOperatorMap(ApplicationTransaction.OperatorMap operatorMap, Schema.Operator operatorValue)
{
DetachOperatorMap(operatorMap, operatorValue);
#if LOGDDLINSTRUCTIONS
if ((!ServerProcess.InLoadingContext()) && ServerProcess.InTransaction)
_instructions.Add(new DetachOperatorMapInstruction(operatorMap, operatorValue));
#endif
}
#endregion
#region Device objects
public virtual bool HasDeviceObjects(Schema.Device device)
{
return false;
}
public virtual Schema.DeviceObject ResolveDeviceObject(Schema.Device device, Schema.Object objectValue)
{
return null;
}
public Schema.DeviceOperator ResolveDeviceOperator(Schema.Device device, Schema.Operator operatorValue)
{
return ResolveDeviceObject(device, operatorValue) as Schema.DeviceOperator;
}
public Schema.DeviceScalarType ResolveDeviceScalarType(Schema.Device device, Schema.ScalarType scalarType)
{
return ResolveDeviceObject(device, scalarType) as Schema.DeviceScalarType;
}
#endregion
#region Security
public virtual Right ResolveRight(string rightName, bool mustResolve)
{
if (mustResolve)
throw new Schema.SchemaException(Schema.SchemaException.Codes.RightNotFound, rightName);
return null;
}
public Right ResolveRight(string rightName)
{
return ResolveRight(rightName, true);
}
public bool RightExists(string rightName)
{
return ResolveRight(rightName, false) != null;
}
public virtual void InsertRight(string rightName, string userID)
{
// virtual
}
public virtual void DeleteRight(string rightName)
{
lock (Catalog)
{
// TODO: Look at speeding this up with an index of users for each right? Memory usage may outweigh the benefits of this index...
foreach (Schema.User user in Device.UsersCache.Values)
user.ClearCachedRightAssignment(rightName);
}
}
public virtual bool UserHasRight(string userID, string rightName)
{
return true;
}
public void CheckUserHasRight(string userID, string rightName)
{
if (!UserHasRight(userID, rightName))
throw new ServerException(ServerException.Codes.UnauthorizedRight, ErrorSeverity.Environment, userID, rightName);
}
protected void ClearUserCachedRightAssignments(string userID)
{
Schema.User user;
if (Device.UsersCache.TryGetValue(userID, out user))
user.ClearCachedRightAssignments();
}
/// <summary>Adds the given user to the cache, without affecting the underlying store.</summary>
public void CacheUser(User user)
{
lock (Catalog)
{
InternalCacheUser(user);
}
}
protected void InternalCacheUser(User user)
{
Device.UsersCache.Add(user);
}
/// <summary>Removes the given user from the cache, without affecting the underlying store.</summary>
public void ClearUser(string userID)
{
lock (Catalog)
{
Device.UsersCache.Remove(userID);
}
}
/// <summary>Clears the users cache, without affecting the underlying store.</summary>
public void ClearUsers()
{
lock (Catalog)
{
Device.UsersCache.Clear();
}
}
public virtual void InsertUser(Schema.User user)
{
CacheUser(user);
#if LOGDDLINSTRUCTIONS
if (ServerProcess.InTransaction)
_instructions.Add(new CreateUserInstruction(user));
#endif
}
public Schema.User ResolveUser(string userID, bool mustResolve)
{
lock (Catalog)
{
Schema.User user;
if (!Device.UsersCache.TryGetValue(userID, out user))
{
user = InternalResolveUser(userID, user);
}
if ((user == null) && mustResolve)
throw new Schema.SchemaException(Schema.SchemaException.Codes.UserNotFound, userID);
return user;
}
}
protected virtual Schema.User InternalResolveUser(string userID, Schema.User LUser)
{
return null;
}
public Schema.User ResolveUser(string userID)
{
return ResolveUser(userID, true);
}
protected class CreateUserInstruction : DDLInstruction
{
public CreateUserInstruction(Schema.User user) : base()
{
_user = user;
}
private Schema.User _user;
public override void Undo(CatalogDeviceSession session)
{
session.ClearUser(_user.ID);
}
}
protected class DropUserInstruction : DDLInstruction
{
public DropUserInstruction(Schema.User user) : base()
{
_user = user;
}
private Schema.User _user;
public override void Undo(CatalogDeviceSession session)
{
session.CacheUser(_user);
}
}
public void InsertRole(Schema.Role role)
{
// Add the role to the Cache
CacheCatalogObject(role);
// Clear the name cache (this is done in InsertPersistentObject for all other catalog objects)
Device.NameCache.Clear(role.Name);
// If we are not deserializing
if (!ServerProcess.InLoadingContext())
{
#if LOGDDLINSTRUCTIONS
// log the DDL instruction
if (ServerProcess.InTransaction)
_instructions.Add(new CreateCatalogObjectInstruction(role));
#endif
InternalInsertRole(role);
}
}
protected virtual void InternalInsertRole(Schema.Role role)
{
// virtual
}
public void DeleteRole(Schema.Role role)
{
lock (Catalog)
{
// Remove the object from the catalog cache
ClearCatalogObject(role);
}
if (!ServerProcess.InLoadingContext())
{
#if LOGDDLINSTRUCTIONS
// log the DDL instruction
if (ServerProcess.InTransaction)
_instructions.Add(new DropCatalogObjectInstruction(role));
#endif
// If this is not a repository, remove it from the catalog store
InternalDeleteRole(role);
}
}
protected virtual void InternalDeleteRole(Schema.Role role)
{
// virtual
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebsiteQuanLyPhatHanhSach.Models;
namespace WebsiteQuanLyPhatHanhSach.ViewModels
{
public class OrderDetailVM
{
//select OD.OrderID, OD.ISBN, OD.OrderQuantity, OD.BookPrice, OD.BookTotal, AI.InventoryQua
public int OrderID { get; set; }
public long ISBN { get; set; }
public string BookName { get; set; }
public int OrderQuantity { get; set; }
public decimal BookPrice { get; set; }
public decimal BookTotal { get; set; }
public int InventoryQua { get; set; }
public decimal OrderTotal { get; set; }
public virtual Book Book { get; set; }
public virtual OrderA OrderA { get; set; }
}
} |
#if DEBUG
using Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.ServiceModel;
namespace Contracts.Promotions
{
[ServiceContract(SessionMode = SessionMode.Required, Namespace = "http://www.noof.com/", Name = "Promotions")]
public interface IPromotionsService
{
[OperationContract]
bool AddHistory(PromotionsProjectHistory data);
[OperationContract]
bool AddSchedules(List<PromotionsProjectProductionSchedule> schedules);
[OperationContract]
bool AddUpdateMovie(PromotionsProjectMovies data, bool isNew);
[OperationContract]
bool AddUpdatePersonnel(PromotionsProjectPersonnel data, bool isNew);
[OperationContract]
bool AddUpdateProject(PromotionsProject data, bool isNew);
[OperationContract]
bool AddUpdateTable(PromotionsPrintTable data, bool isNew);
[OperationContract]
bool CheckImageAssignmentExists(int id);
[OperationContract]
PromotionsProjectMovies CheckMovieRecordExists(int projectId, int movieId);
[OperationContract]
int? CheckOnArchive(int projectId, int movieId);
[OperationContract]
PromotionsPrintTable CheckTableExists(int projectId);
[OperationContract]
PromotionsProject CheckProjectExists(int projectId);
[OperationContract]
bool ClearUserProjectLocks(string userName);
[OperationContract]
void CreatePromotionsMethods(string connectionString, string userName);
[OperationContract]
bool DeleteSchedules(int projectId);
[OperationContract]
List<string> GetAspects();
[OperationContract]
List<Tuple<string, DateTime, string>> GetCommentHistory(int projectId);
[OperationContract]
List<string> GetDecks();
[OperationContract]
string GetDocumentPath();
[OperationContract]
List<string> GetEditBays();
[OperationContract]
List<string> GetEmployeeList(string list);
[OperationContract]
List<string> GetEmployeeListActiveRetired(bool retired);
[OperationContract]
List<string> GetEmployeeUserNameList(string list);
[OperationContract]
List<string> GetFileFormats();
[OperationContract]
List<string> GetFileFormats2();
[OperationContract]
List<string> GetFrameRates();
[OperationContract]
List<int> GetIdsFromSearch(string sql);
[OperationContract]
List<ImagesAssignments> GetImagesAssignments(int id);
[OperationContract]
List<ImagesAssignments> GetImagesAssignmentsDateChannel(DateTime date, string channels);
[OperationContract]
DataTable GetImageManagementData(int id);
[OperationContract]
DataTable GetMovieData(int projectId, int movieId);
[OperationContract]
List<int> GetMovieIdsByProjectId(int projectId);
[OperationContract]
List<Tuple<int, string, int>> GetMovies(int projectId);
[OperationContract]
Tuple<string, string> GetMovieTitleAndType(int id);
[OperationContract]
int GetNextProjectId();
[OperationContract]
PromotionsProject GetProject(int projectId);
[OperationContract]
List<string> GetProjectChannels(int projectId);
[OperationContract]
List<Tuple<string, DateTime, string>> GetProjectHistory(int projectId);
[OperationContract]
List<string> GetProjectPersonnel(int projectId);
[OperationContract]
List<PromotionsProjectPersonnel> GetProjectPersonnelRecords(int projectId);
[OperationContract]
string GetRating(int xxx);
[OperationContract]
List<PromotionsProjectProductionSchedule> GetSchedules(int projectId);
[OperationContract]
bool GetUserReadOnly();
[OperationContract]
bool MovieIdsEntered(int projectId);
[OperationContract]
bool RemoveProject(int projectId);
[OperationContract]
bool UpdateImageAssignment(int imageManagementId, int projectId);
[OperationContract]
bool UpdateImageAssignmentDate(int imageManagementId, int projectId, DateTime dueDate);
[OperationContract]
bool UpdateImageAssignmentRecord(ImagesAssignments data);
[OperationContract]
bool UpdatePersonnel(List<string> names, int projectId);
[OperationContract]
bool UpdateProjectLock(string userName, int projectId, int lockValue);
}
}
#endif |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Thingy.WebServerLite.Api;
namespace Thingy.WebServerLite
{
public class ControllerProviderFactory : IControllerProviderFactory
{
public IControllerProvider Create(IController[] controllers)
{
return new ControllerProvider(controllers);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Clock : MonoBehaviour
{
public static Clock Instance;
public float TimeRate = 1f;
public TMPro.TextMeshProUGUI FPS;
public float DeltaTime
{
get
{
return Time.deltaTime * TimeRate;
}
}
public float TimeMult
{
get
{
return Time.deltaTime * TimeRate * 60;
}
}
void Awake()
{
Instance = this;
}
float StartRate;
float TargetRate;
float LerpTimer;
float LerpTime;
bool Lerping;
Action Callback;
public void LerpTo(float target, float time, Action callback = null)
{
StartRate = TimeRate;
TargetRate = target;
LerpTimer = time;
LerpTime = time;
Callback = callback;
Lerping = true;
}
void Update()
{
if (Lerping)
{
if (LerpTimer > 0)
{
float ratio = 1 - LerpTimer / LerpTime;
TimeRate = Mathf.Lerp(StartRate, TargetRate, ratio);
LerpTimer = Mathf.Max(0, LerpTimer - Time.deltaTime);
}
else
{
TimeRate = TargetRate;
Lerping = false;
Callback?.Invoke();
}
}
}
}
|
using Compent.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UBaseline.Core.Node;
using UBaseline.Shared.Node;
using Uintra.Core.Activity;
using Uintra.Core.Activity.Entities;
using Uintra.Core.Localization;
using Uintra.Core.Member.Entities;
using Uintra.Core.Member.Services;
using Uintra.Features.Groups.Models;
using Uintra.Features.Groups.Services;
using Uintra.Features.Navigation.ApplicationSettings;
using Uintra.Features.Navigation.Models;
using Uintra.Features.Navigation.Models.MyLinks;
using Uintra.Features.Navigation.Services;
using Uintra.Features.Navigation.Sql;
using Uintra.Infrastructure.Extensions;
using Uintra.Infrastructure.Providers;
using Uintra.Infrastructure.TypeProviders;
namespace Uintra.Features.Navigation.Helpers
{
public class MyLinksHelper : IMyLinksHelper
{
private readonly IIntranetMemberService<IntranetMember> _intranetMemberService;
private readonly IMyLinksService _myLinksService;
private readonly IActivitiesServiceFactory _activitiesServiceFactory;
private readonly INavigationApplicationSettings _navigationApplicationSettings;
private readonly IGroupService _groupService;
private readonly IDocumentTypeAliasProvider _documentTypeAliasProvider;
private readonly IActivityTypeProvider _activityTypeProvider;
private readonly INodeModelService _nodeModelService;
private readonly IIntranetLocalizationService _intranetLocalizationService;
public MyLinksHelper(
IDocumentTypeAliasProvider documentTypeAliasProvider,
IIntranetMemberService<IntranetMember> intranetMemberService,
IMyLinksService myLinksService,
IActivitiesServiceFactory activitiesServiceFactory,
INavigationApplicationSettings navigationApplicationSettings,
IGroupService groupService,
INodeModelService nodeModelService,
IActivityTypeProvider activityTypeProvider,
IIntranetLocalizationService intranetLocalizationService)
{
_intranetMemberService = intranetMemberService;
_myLinksService = myLinksService;
_activitiesServiceFactory = activitiesServiceFactory;
_navigationApplicationSettings = navigationApplicationSettings;
_groupService = groupService;
_nodeModelService = nodeModelService;
_documentTypeAliasProvider = documentTypeAliasProvider;
_activityTypeProvider = activityTypeProvider;
_intranetLocalizationService = intranetLocalizationService;
}
public IEnumerable<MyLinkItemModel> GetMenu()
{
var links = _myLinksService
.GetMany(_intranetMemberService.GetCurrentMember().Id)
.OrderByDescending(link => link.CreatedDate)
.ToList();
var contents = _nodeModelService.GetByIds(links.Select(el => el.ContentId));
var models = links.Join(contents,
link => link.ContentId,
content => content.Id,
(link, content) => new MyLinkItemModel
{
Id = link.Id,
ContentId = content.Id,
ActivityId = link.ActivityId,
Name = link.ActivityId.HasValue ? GetLinkName(link.ActivityId.Value) : GetNavigationName(content),
Url = GetUrl(link, content.Url)
});
return MapLinks(models);
}
public async Task<IEnumerable<MyLinkItemModel>> GetMenuAsync()
{
var memberId = (await _intranetMemberService.GetCurrentMemberAsync()).Id;
var links = (await _myLinksService.GetManyAsync(memberId))
.OrderByDescending(link => link.CreatedDate)
.ToList();
var contents = _nodeModelService.GetByIds(links.Select(el => el.ContentId));
var models = links.Join(contents,
link => link.ContentId,
content => content.Id,
(link, content) => new MyLinkItemModel
{
Id = link.Id,
ActivityId = link.ActivityId,
ContentId = content.Id,
Name = link.ActivityId.HasValue ? GetLinkName(link.ActivityId.Value) : GetNavigationName(content),
Url = GetUrl(link, content.Url)
});
return MapLinks(models);
}
public bool IsActivityLink(int contentId)
{
var page = _nodeModelService.Get(contentId);
foreach (var type in _activityTypeProvider.All)
{
if (page.ContentTypeAlias.Equals(_documentTypeAliasProvider.GetDetailsPage(type)) ||
page.ContentTypeAlias.Equals(_documentTypeAliasProvider.GetEditPage(type)))
{
return true;
}
}
return false;
}
public bool IsGroupPage(int contentId)
{
var page = _nodeModelService.Get(contentId);
return page.ContentTypeAlias.Equals(_documentTypeAliasProvider.GetGroupRoomPage());
}
private string GetLinkName(Guid entityId)
{
var linkName = GetGroupLink(entityId);
if (linkName.IsNullOrEmpty())
{
return GetActivityLink(entityId);
}
return linkName;
}
private async Task<string> GetLinkNameAsync(Guid entityId)
{
var linkName = await GetGroupLinkAsync(entityId);
if (linkName.IsNullOrEmpty())
{
return GetActivityLink(entityId);
}
return linkName;
}
private string GetActivityLink(Guid entityId)
{
var service = _activitiesServiceFactory.GetService<IIntranetActivityService<IIntranetActivity>>(entityId);
var activity = service.Get(entityId);
if (activity.Type is IntranetActivityTypeEnum.Social)
{
var lengthForPreview = _navigationApplicationSettings.MyLinksActivityTitleLength;
var description = activity.Description.StripHtml();
return description.Length > lengthForPreview ? description.Substring(0, lengthForPreview) + "..." : description;
}
return activity.Title;
}
private static string GetUrl(MyLink link, string path)
{
var trimmedPath = path.TrimLastCharacter();
return link.QueryString.IsNullOrEmpty()
? trimmedPath
: $"{trimmedPath}?{link.QueryString}";
}
private string GetGroupLink(Guid entityId)
{
var groupModel = _groupService.Get(entityId);
return groupModel?.Title;
}
private async Task<string> GetGroupLinkAsync(Guid entityId)
{
var groupModel = await _groupService.GetAsync(entityId);
return groupModel?.Title;
}
protected virtual string GetNavigationName(INodeModel content)
{
if (content is IUintraNavigationComposition navigationModel)
{
if (navigationModel.Navigation.NavigationTitle.Value.HasValue())
{
return navigationModel.Navigation.NavigationTitle.Value;
}
}
if (content is IGroupNavigationComposition groupNavigationModel)
{
if (groupNavigationModel.GroupNavigation.NavigationTitle.Value.HasValue())
{
return groupNavigationModel.GroupNavigation.NavigationTitle.Value;
}
}
return content.Name;
}
protected IEnumerable<MyLinkItemModel> MapLinks(IEnumerable<MyLinkItemModel> links)
{
var result = links.Select(link =>
{
if (!link.ActivityId.HasValue) return link;
if (!link.Name.IsEmpty()) return link;
var intranetActivityService = _activitiesServiceFactory.GetService<IIntranetActivityService<IIntranetActivity>>(link.ActivityId.Value);
var activity = intranetActivityService.Get(link.ActivityId.Value);
link.Name = $"{_intranetLocalizationService.Translate("MyLinks.Social.lbl")} {activity.CreatedDate}";
return link;
});
return result;
}
}
} |
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.CommandContract.Contractual;
using Pe.Stracon.SGC.Infraestructura.Repository.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Infraestructura.Repository.Command.Contractual
{
/// <summary>
/// Implementación del Repositorio de ConsultaAdjunto
/// </summary>
/// <remarks>
/// Creación :GMD 20150710 <br />
/// Modificación :<br />
/// </remarks>
public class ConsultaAdjuntoEntityRepository : ComandRepository<ConsultaAdjuntoEntity>, IConsultaAdjuntoEntityRepository
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using Core.DAL;
using System.ComponentModel.DataAnnotations;
namespace Core.BIZ
{
public class PhieuXuat
{
public PhieuXuat() { }
public PhieuXuat(PHIEUXUAT phieu)
{
MaSoPhieuXuat = phieu.masophieuxuat;
MaSoDaiLy = phieu.masodaily;
NgayLap = phieu.ngaylap;
NguoiNhan = phieu.nguoinhasach;
TongTien = phieu.tongtien;
TrangThai = phieu.trangthai;
}
public PhieuXuat(PHIEUXUAT phieu, DAILY daily)
:this(phieu)
{
Daily = new DaiLy(daily);
}
#region Private Properties
private DaiLy _daily;
private List<ChiTietPhieuXuat> _chitiet;
private static List<string> _searchKeys;
#endregion
#region Public Properties
[Required]
[DisplayName(PhieuXuatManager.Properties.MaSoPhieuXuat)]
public int MaSoPhieuXuat { get; set; }
[Required]
[DisplayName(PhieuXuatManager.Properties.MaSoDaiLy)]
public int MaSoDaiLy { get; set; }
[DisplayName(PhieuXuatManager.Properties.DaiLy)]
public DaiLy Daily
{
get
{
if (_daily == null)
{
_daily = DaiLyManager.find(this.MaSoDaiLy);
}
return _daily;
}
set
{
_daily = value;
}
}
[Required]
[DisplayName(PhieuXuatManager.Properties.NgayLap)]
public DateTime NgayLap { get; set; }
[Required]
[DisplayName(PhieuXuatManager.Properties.NguoiNhan)]
public string NguoiNhan { get; set; }
[Required]
[DisplayName(PhieuXuatManager.Properties.TongTien)]
public decimal TongTien { get; set; }
//Chi tiết phiếu xuát
[DisplayName(PhieuXuatManager.Properties.ChiTiet)]
public List<ChiTietPhieuXuat> ChiTiet
{
get
{
if (_chitiet == null)
{
_chitiet = PhieuXuatManager.Chitiet.find(this.MaSoPhieuXuat);
}
return _chitiet;
}
set
{
_chitiet = value;
}
}
[DisplayName(PhieuXuatManager.Properties.TrangThai)]
public int? TrangThai { get; set; }
#endregion
#region Services
/// <summary>
/// Kiểm tra chi tiết đã có trong danh sách chưa
/// </summary>
/// <param name="chitiet"></param>
/// <returns></returns>
public bool isDetailExisted(ChiTietPhieuXuat chitiet)
{
return _chitiet.Contains(chitiet);
}
/// <summary>
/// Thêm chi tiết vào danh sách chi tiết của phiếu
/// </summary>
/// <param name="chitiet"></param>
/// <returns></returns>
public bool addDetail(ChiTietPhieuXuat chitiet)
{
if (isDetailExisted(chitiet))
{
return false;
}
_chitiet.Add(chitiet);
return true;
}
public bool addDetail(Sach sach, decimal soluong)
{
var chitiet = new ChiTietPhieuXuat
{
MaSoSach = sach.MaSoSach,
Sach = sach,
SoLuong = soluong,
DonGia = sach.GiaBan
};
foreach(var ct in ChiTiet)
{
if (ct.Equals(chitiet))
{
ct.SoLuong += chitiet.SoLuong;
return true;
}
}
ChiTiet.Add(chitiet);
return true;
}
public static List<string> searchKeys()
{
if (_searchKeys == null)
{
_searchKeys = new List<string>();
_searchKeys.Add(nameof(PhieuXuatManager.Properties.MaSoPhieuXuat));
_searchKeys.Add(nameof(PhieuXuatManager.Properties.NguoiNhan));
_searchKeys.Add(nameof(PhieuXuatManager.Properties.NgayLap));
_searchKeys.Add(nameof(PhieuXuatManager.Properties.TongTien));
_searchKeys.Add(nameof(PhieuXuatManager.Properties.TrangThai));
_searchKeys.Add(nameof(DaiLyManager.Properties.TenDaiLy));
}
return _searchKeys;
}
public bool deleteDetail(int masosach)
{
foreach (ChiTietPhieuXuat ct in _chitiet)
{
if (ct.MaSoSach.Equals(masosach))
{
_chitiet.Remove(ct);
return true;
}
}
return false;
}
/// <summary>
/// Duyệt phiếu nhập
/// </summary>
/// <returns></returns>
public AcceptStatus accept()
{
if(Daily.TongTienNo > 10000000)
{
return AcceptStatus.Limited;
}
//Kiểm tra số lượng có thể duyệt không
foreach (ChiTietPhieuXuat ct in this.ChiTiet)
{
if(ct.Sach.Soluong < ct.SoLuong)
{
return AcceptStatus.ProductNotEnought;
}
}
//Duyệt từng chi tiết
foreach (ChiTietPhieuXuat ct in this.ChiTiet)
{
//Cập nhật thông tin sách
ct.Sach.Soluong -= ct.SoLuong;
if (!SachManager.edit(ct.Sach)) return AcceptStatus.UpdateProductFail;
//Ghi thẻ kho
var tk = new TheKho
{
MaSoSach = ct.MaSoSach,
SoLuong = ct.Sach.Soluong,
NgayGhi = DateTime.Now
};
if (TheKhoManager.add(tk) == 0) return AcceptStatus.UpdateStoreFail;
//Cập nhật công nợ
var congno = new CongNoDaiLy
{
MaSoDaiLy = this.MaSoDaiLy,
MaSoSach = ct.MaSoSach,
SoLuong = ct.SoLuong,
DonGia = ct.DonGia,
Thang = DateTime.Now
};
if (CongNoDaiLyManager.add(congno) == 0) return AcceptStatus.UpdateLiabilitiesFail;
ct.TrangThai = 1;
}
//Thay đổi trang thái phiếu nhập
this.TrangThai = 1;
if (PhieuXuatManager.edit(this))
{
return AcceptStatus.Success;
}
else
{
return AcceptStatus.Error;
}
}
public enum AcceptStatus
{
Success,
ProductNotEnought,
UpdateProductFail,
UpdateStoreFail,
UpdateLiabilitiesFail,
Error,
Limited
}
#endregion
#region Override Methods
public override string ToString()
{
return this.NgayLap.ToString();
}
public override bool Equals(object obj)
{
return MaSoPhieuXuat.Equals(((PhieuXuat)obj).MaSoPhieuXuat);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public enum Role
{
USER ,
ADMIN
}
public class User
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(100)]
[Index("Email_Index", IsUnique = true)]
public String Email { get; set; }
public String Password { get; set; }
public String RepeatPassword { get; set; }
public Role Role { get; set; }
public String Name { get; set; }
public virtual List<Vote> Votes { get; set; }
public virtual List<Answer> Answers{ get; set; }
public virtual List<Question> Questions { get; set; }
}
public class Question
{
[Key]
public int ID { get; set; }
public String QuestionText { get; set; }
[ForeignKey(nameof(User))]
public int? userId { get; set; }
public String Title { get; set; }
public virtual User User { get; set; }
public DateTime DateAndTime { get; set; }
public virtual List<Answer> Answers { get; set; }
}
public class Answer
{
[Key]
public int ID { get; set; }
public String AnswerText { get; set; }
[ForeignKey(nameof(User))]
public int? userId { get; set; }
public virtual User User { get; set; }
[ForeignKey(nameof(Question))]
public int? Question_id { get; set; }
public virtual Question Question { get; set; }
public DateTime DateAndTime { get; set; }
public bool CheckedByAdmin { get; set; }
public virtual List<Vote> Votes { get; set; }
}
public class Vote
{
[Key]
public int ID { get; set; }
public bool VoteType { get; set; }
public DateTime VoteDate { get; set; }
[ForeignKey(nameof (User))]
public int? UserID { get; set; }
public virtual User User { get; set; }
[ForeignKey(nameof(Answer))]
public int? AnswerId { get; set; }
public virtual Answer Answer { get; set; }
}
}
|
//#define WITH_DEBUG
using System;
using UnityEngine.Jobs;
using Unity.Jobs;
using Unity.Burst;
using Unity.Entities;
using Unity.Collections;
using Unity.Mathematics;
using static Unity.Mathematics.math;
namespace IzBone.PhysCloth.Core {
using Common;
using Common.Field;
[UpdateInGroup(typeof(IzBoneSystemGroup))]
[UpdateAfter(typeof(IzBCollider.Core.IzBColliderSystem))]
[AlwaysUpdateSystem]
public sealed partial class IzBPhysClothSystem
: PhysBone.Body.Core.BodySystemBase<Authoring.BaseAuthoring>
{
// フィッティングループのイテレーションカウント
const int ITERATION_NUM = 5;
/** 指定のAuthの物理状態をリセットする */
override public void reset(
Common.Entities8.EntityRegistererBase<Authoring.BaseAuthoring>.RegLink regLink
) {
var etp = _entityReg.etPacks;
for (int i=0; i<regLink.etpIdxs.Count; ++i) {
var etpIdx = regLink.etpIdxs[i];
var e = etp.Entities[ etpIdx ];
var t = etp.Transforms[ etpIdx ];
if (!HasComponent<Ptcl>(e)) continue;
var defTailLPos = GetComponent<Ptcl_DefaultTailLPos>(e).value;
var wPos = t.localToWorldMatrix.MultiplyPoint(defTailLPos);
SetComponent(e, new Ptcl_Velo());
SetComponent(e, new Ptcl_WPos{value = wPos});
}
}
/** デフォルト姿勢でのL2Wを転送する処理 */
[BurstCompile]
struct MngTrans2ECSJob : IJobParallelForTransform
{
[ReadOnly] public NativeArray<Entity> entities;
[ReadOnly] public ComponentDataFromEntity<Ptcl_InvM> invMs;
[ReadOnly] public ComponentDataFromEntity<Ptcl_Root> roots;
[ReadOnly] public ComponentDataFromEntity<Root_WithAnimation> withAnims;
[NativeDisableParallelForRestriction]
[WriteOnly] public ComponentDataFromEntity<Ptcl_DefaultHeadL2W> defHeadL2Ws;
[NativeDisableParallelForRestriction]
[WriteOnly] public ComponentDataFromEntity<Ptcl_DefaultHeadL2P> defHeadL2Ps;
// defTailLPosはWithAnimがTrueのときでも毎フレームは更新しない。
// [NativeDisableParallelForRestriction]
// [WriteOnly] public ComponentDataFromEntity<Ptcl_DefaultTailLPos> defTailLPoss;
[ReadOnly] public ComponentDataFromEntity<Ptcl_DefaultTailLPos> defTailLPoss;
[NativeDisableParallelForRestriction]
[WriteOnly] public ComponentDataFromEntity<Ptcl_DefaultTailWPos> defTailWPoss;
[NativeDisableParallelForRestriction]
[WriteOnly] public ComponentDataFromEntity<Ptcl_CurHeadTrans> curHeadTranss;
public void Execute(int index, TransformAccess transform) {
var entity = entities[index];
var withAnim = withAnims[ roots[entity].value ];
// デフォルト姿勢を毎フレーム初期化する必要がある場合は、ここで初期化
if (withAnim.value) {
defHeadL2Ps[entity] = new Ptcl_DefaultHeadL2P(transform);
// defTailLPoss[entity] =
}
// 現在のTransformをすべてのParticleに対して転送
curHeadTranss[entity] = new Ptcl_CurHeadTrans{
l2w = transform.localToWorldMatrix,
w2l = transform.worldToLocalMatrix,
lPos = transform.localPosition,
lRot = transform.localRotation,
};
// 固定パーティクルに対しては、DefaultL2Wを現在値に更新する
if (invMs[entity].value == 0) {
var headL2W = transform.localToWorldMatrix;
var tailLPos = defTailLPoss[entity].value;
defHeadL2Ws[entity] = new Ptcl_DefaultHeadL2W{value = headL2W};
defTailWPoss[entity] =
new Ptcl_DefaultTailWPos{value = Math8.trans(headL2W, tailLPos)};
}
}
public void Execute(int index, UnityEngine.Transform transform) {
var entity = entities[index];
var withAnim = withAnims[ roots[entity].value ];
// デフォルト姿勢を毎フレーム初期化する必要がある場合は、ここで初期化
if (withAnim.value) {
defHeadL2Ps[entity] = new Ptcl_DefaultHeadL2P(transform);
// defTailLPoss[entity] =
}
// 現在のTransformをすべてのParticleに対して転送
curHeadTranss[entity] = new Ptcl_CurHeadTrans{
l2w = transform.localToWorldMatrix,
w2l = transform.worldToLocalMatrix,
lPos = transform.localPosition,
lRot = transform.localRotation,
};
// 固定パーティクルに対しては、DefaultL2Wを現在値に更新する
if (invMs[entity].value == 0) {
var headL2W = transform.localToWorldMatrix;
var tailLPos = defTailLPoss[entity].value;
defHeadL2Ws[entity] = new Ptcl_DefaultHeadL2W{value = headL2W};
defTailWPoss[entity] =
new Ptcl_DefaultTailWPos{value = Math8.trans(headL2W, tailLPos)};
}
}
}
/** シミュレーション結果をボーンにフィードバックする */
[BurstCompile]
struct ApplyToBoneJob : IJobParallelForTransform
{
[ReadOnly] public NativeArray<Entity> entities;
[ReadOnly] public ComponentDataFromEntity<Ptcl_CurHeadTrans> curHeadTranss;
[ReadOnly] public ComponentDataFromEntity<Ptcl_InvM> invMs;
public void Execute(int index, TransformAccess transform)
{
var entity = entities[index];
var invM = invMs[entity].value;
if (invM != 0) {
var curTrans = curHeadTranss[entity];
transform.localPosition = curTrans.lPos;
transform.localRotation = curTrans.lRot;
}
}
}
protected override void OnCreate() {
_entityReg = new EntityRegisterer();
}
protected override void OnDestroy() {
_entityReg.Dispose();
}
override protected void OnUpdate() {
// var deltaTime = World.GetOrCreateSystem<Time8.TimeSystem>().DeltaTime;
var deltaTime = Time.DeltaTime;
if (deltaTime < 0.00001f) return; // とりあえずdt=0のときはやらないでおく。TODO: あとで何とかする
// 追加・削除されたAuthの情報をECSへ反映させる
_entityReg.apply(EntityManager);
var etp = _entityReg.etPacks;
#if UNITY_EDITOR
{// デバッグ用のバッファを更新
Entities.ForEach((
Entity entity,
in Ptcl_M2D ptclM2D,
in Ptcl_Velo ptclV,
in Ptcl_WPos ptclWPos
)=>{
ptclM2D.auth.DEBUG_curV = ptclV.value;
ptclM2D.auth.DEBUG_curPos = ptclWPos.value;
}).WithoutBurst().Run();
}
#endif
// TODO : 風・重力の処理は別システムへ一括して移す
{// 風の影響を決定する処理。
// TODO : これは今はWithoutBurstだが、後で何とかする
Entities.ForEach((
Entity entity,
in Root_M2D rootM2D
)=>{
SetComponent(entity, new Root_Air{
winSpd = rootM2D.auth.windSpeed,
airDrag = rootM2D.auth.airDrag,
});
}).WithoutBurst().Run();
}
{// 重力加速度を決定する
var defG = (float3)UnityEngine.Physics.gravity;
Dependency = Entities.ForEach((ref Root_G g)=>{
g.value = g.src.evaluate(defG);
}).Schedule( Dependency );
}
// 空気抵抗関係の値を事前計算しておく
#if WITH_DEBUG
Entities.ForEach((
#else
Dependency = Entities.ForEach((
#endif
Entity entity,
ref Root_Air air
)=>{
var airResRateIntegral =
HalfLifeDragAttribute.evaluateIntegral(air.airDrag, deltaTime);
air.winSpdIntegral = air.winSpd * (deltaTime - airResRateIntegral);
air.airResRateIntegral = airResRateIntegral;
#if WITH_DEBUG
}).WithoutBurst().Run();
#else
}).Schedule( Dependency );
#endif
{// デフォルト姿勢でのL2Wを計算しておく
// ルートのL2WをECSへ転送する
if (etp.Length != 0) {
#if WITH_DEBUG
var a = new MngTrans2ECSJob{
#else
Dependency = new MngTrans2ECSJob{
#endif
entities = etp.Entities,
invMs = GetComponentDataFromEntity<Ptcl_InvM>(true),
roots = GetComponentDataFromEntity<Ptcl_Root>(true),
withAnims = GetComponentDataFromEntity<Root_WithAnimation>(true),
defHeadL2Ws = GetComponentDataFromEntity<Ptcl_DefaultHeadL2W>(false),
defHeadL2Ps = GetComponentDataFromEntity<Ptcl_DefaultHeadL2P>(false),
defTailLPoss = GetComponentDataFromEntity<Ptcl_DefaultTailLPos>(true),
defTailWPoss = GetComponentDataFromEntity<Ptcl_DefaultTailWPos>(false),
curHeadTranss = GetComponentDataFromEntity<Ptcl_CurHeadTrans>(false),
#if WITH_DEBUG
};
for (int i=0; i<etp.Transforms.length; ++i) {
a.Execute( i, etp.Transforms[i] );
}
#else
}.Schedule( etp.Transforms, Dependency );
#endif
}
// ルート以外のL2Wを計算しておく
#if WITH_DEBUG
Entities.ForEach((Entity entity)=>{
#else
Dependency = Entities.ForEach((Entity entity)=>{
#endif
// これは上から順番に行う必要があるので、
// RootごとにRootから順番にParticleをたどって更新する
for (; entity!=Entity.Null; entity=GetComponent<Ptcl_Next>(entity).value) {
var invM = GetComponent<Ptcl_InvM>(entity).value;
if (invM == 0) {
// 固定パーティクルの場合はToChildWDistのみ更新する
var defHeadL2W = GetComponent<Ptcl_DefaultHeadL2W>(entity).value;
var defTailLPos = GetComponent<Ptcl_DefaultTailLPos>(entity).value;
var toChildDist =
length( mul((float3x3)defHeadL2W, defTailLPos) );
SetComponent(entity, new Ptcl_ToChildWDist{value = toChildDist});
} else {
// 固定パーティクル以外はL2W一式を更新
var parent = GetComponent<Ptcl_Parent>(entity).value;
var defHeadL2W = mul(
GetComponent<Ptcl_DefaultHeadL2W>(parent).value,
GetComponent<Ptcl_DefaultHeadL2P>(entity).l2p
);
var defTailLPos = GetComponent<Ptcl_DefaultTailLPos>(entity).value;
var defTailWPos = Math8.trans(defHeadL2W, defTailLPos);
SetComponent(entity, new Ptcl_DefaultHeadL2W{value = defHeadL2W});
SetComponent(entity, new Ptcl_DefaultTailWPos{value = defTailWPos});
var toChildDist = length(defTailWPos - defHeadL2W.c3.xyz);
SetComponent(entity, new Ptcl_ToChildWDist{value = toChildDist});
}
}
#if WITH_DEBUG
}).WithAll<Root>().WithoutBurst().Run();
#else
}).WithAll<Root>().Schedule( Dependency );
#endif
}
// 質点の位置を更新
#if WITH_DEBUG
Entities.ForEach((
#else
Dependency = Entities.ForEach((
#endif
Entity entity,
ref Ptcl_WPos wPos,
ref Ptcl_Velo v
#if WITH_DEBUG
,in Ptcl_M2D m2d
#endif
)=>{
var invM = GetComponent<Ptcl_InvM>(entity).value;
var defTailPos = GetComponent<Ptcl_DefaultTailWPos>(entity).value;
if (invM == 0) {
wPos.value = defTailPos;
} else {
var restoreHL = GetComponent<Ptcl_RestoreHL>(entity).value;
var root = GetComponent<Ptcl_Root>(entity).value;
var maxSpeed = GetComponent<Root_MaxSpd>(root).value;
var g = GetComponent<Root_G>(root).value;
var air = GetComponent<Root_Air>(root);
// 速度制限を適応
var v0 = clamp(v.value, -maxSpeed, maxSpeed);
// 更新前の位置をvに入れておく。これは後で参照するための一時的なキャッシュ用
v.value = wPos.value;
// 位置を物理で更新する。
// 空気抵抗の影響を与えるため、以下のようにしている。
// 一行目:
// dtは変動するので、空気抵抗の影響が解析的に正しく影響するように、
// vには積分結果のairResRateIntegralを掛ける。
// 空気抵抗がない場合は、gの影響は g*dt^2になるが、
// ここもいい感じになるようにg*dt*airResRateIntegralとしている。
// これは正しくはないが、いい感じに見える。
// 二行目:
// 1行目だけの場合は空気抵抗によって速度が0になるように遷移する。
// 風速の影響を与えたいため、空気抵抗による遷移先がwindSpeedになるようにしたい。
// airResRateIntegralは空気抵抗の初期値1の減速曲線がグラフ上に描く面積であるので,
// 減速が一切ない場合に描く面積1*dtとの差は、dt-airResRateIntegralとなる。
// したがってこれにwindSpeedを掛けて、風速に向かって空気抵抗がかかるようにする。
wPos.value +=
(v0 + g*deltaTime) * air.airResRateIntegral +
air.winSpdIntegral; // : windSpeed * (dt - airResRateIntegral)
// 初期位置に戻すようなフェードを掛ける
wPos.value = lerp(
defTailPos,
wPos.value,
HalfLifeDragAttribute.evaluate( restoreHL, deltaTime )
);
}
//UnityEngine.Debug.Log("ccc:"+(m2d.auth.transHead==null?"*":m2d.auth.transHead.name));
//UnityEngine.Debug.Log(sphere.value);
#if WITH_DEBUG
}).WithoutBurst().Run();
#else
}).ScheduleParallel( Dependency );
#endif
// λを初期化
#if WITH_DEBUG
Entities.ForEach((Entity entity)=>{
#else
Dependency = Entities.ForEach((Entity entity)=>{
#endif
SetComponent(entity, new Ptcl_CldCstLmd());
SetComponent(entity, new Ptcl_AglLmtLmd());
SetComponent(entity, new Ptcl_MvblRngLmd());
#if WITH_DEBUG
}).WithAll<Ptcl>().WithoutBurst().Run();
Entities.ForEach((Entity entity)=>{
#else
}).WithAll<Ptcl>().Schedule( Dependency );
Dependency = Entities.ForEach((Entity entity)=>{
#endif
SetComponent(entity, new Cstr_Lmd());
#if WITH_DEBUG
}).WithAll<DistCstr>().WithoutBurst().Run();
#else
}).WithAll<DistCstr>().Schedule( Dependency );
#endif
// XPBDによるフィッティング処理ループ
var sqDt = deltaTime*deltaTime/ITERATION_NUM/ITERATION_NUM;
for (int i=0; i<ITERATION_NUM; ++i) {
#if true
{// 角度制限の拘束条件を解決
var aglLmtLmds = GetComponentDataFromEntity<Ptcl_AglLmtLmd>();
var wPoss = GetComponentDataFromEntity<Ptcl_WPos>();
var dWRots = GetComponentDataFromEntity<Ptcl_DWRot>();
#if WITH_DEBUG
Entities.ForEach((Entity entity)=>{
#else
Dependency = Entities
.WithNativeDisableParallelForRestriction(aglLmtLmds)
.WithNativeDisableParallelForRestriction(wPoss)
.WithNativeDisableParallelForRestriction(dWRots)
.ForEach((Entity entity)=>{
#endif
// これは上から順番に行う必要があるので、
// RootごとにRootから順番にParticleをたどって更新する
for (var p3=entity; p3!=Entity.Null; p3=GetComponent<Ptcl_Next>(p3).value) {
var p2 = GetComponent<Ptcl_Parent>(p3).value;
if (p2 == Entity.Null) continue;
var p1 = GetComponent<Ptcl_Parent>(p2).value;
var p0 = p1==Entity.Null ? Entity.Null : GetComponent<Ptcl_Parent>(p1).value;
var p00 = p0==Entity.Null ? Entity.Null : GetComponent<Ptcl_Parent>(p0).value;
var spr0 = p0==Entity.Null ? default : wPoss[p0].value;
var spr1 = p1==Entity.Null ? default : wPoss[p1].value;
var spr2 = wPoss[p2].value;
var spr3 = wPoss[p3].value;
var defWPos0 = p0==Entity.Null ? default : GetComponent<Ptcl_DefaultTailWPos>(p0).value;
var defWPos1 = p1==Entity.Null ? default : GetComponent<Ptcl_DefaultTailWPos>(p1).value;
var defWPos2 = GetComponent<Ptcl_DefaultTailWPos>(p2).value;
var defWPos3 = GetComponent<Ptcl_DefaultTailWPos>(p3).value;
// 回転する元方向と先方向を計算する処理
static void getFromToDir(
float3 toWPos0, float3 toWPos1,
float3 fromWPos0, float3 fromWPos1,
quaternion q,
out float3 fromDir,
out float3 toDir
) {
var from = fromWPos1 - fromWPos0;
var to = toWPos1 - toWPos0;
fromDir = mul(q, from);
toDir = to;
}
// 拘束条件を適応
float3 from, to;
if (p1 != Entity.Null) {
getFromToDir(
spr2, spr3,
defWPos2, defWPos3,
dWRots[p1].value,
out from, out to
);
var constraint = new Constraint.AngleWithLimit{
aglCstr = new Constraint.Angle{
pos0 = spr1,
pos1 = spr2,
pos2 = spr3,
invM0 = GetComponent<Ptcl_InvM>(p1).value,
invM1 = GetComponent<Ptcl_InvM>(p2).value,
invM2 = GetComponent<Ptcl_InvM>(p3).value,
defChildPos = from + spr2
},
compliance_nutral = GetComponent<Ptcl_AngleCompliance>(p2).value,
compliance_limit = 0.0001f,
limitAngle = GetComponent<Ptcl_MaxAngle>(p2).value,
};
if (constraint.aglCstr.isValid()) {
var lmd2 = aglLmtLmds[p2].value;
var lmd3 = aglLmtLmds[p3].value;
constraint.solve(sqDt, ref lmd2, ref lmd3);
aglLmtLmds[p2] = new Ptcl_AglLmtLmd{value = lmd2};
aglLmtLmds[p3] = new Ptcl_AglLmtLmd{value = lmd3};
wPoss[p1] = new Ptcl_WPos{value = constraint.aglCstr.pos0};
wPoss[p2] = new Ptcl_WPos{value = constraint.aglCstr.pos1};
wPoss[p3] = new Ptcl_WPos{value = constraint.aglCstr.pos2};
}
/* var constraint = new Constraint.Angle{
parent = p1,
compliance = p2->angleCompliance,
self = p2,
child = p3,
defChildPos = from + p2->col.pos
};
*lmd2 += constraint.solve(sqDt, *lmd2);
*/ }
// 位置が変わったので、再度姿勢を計算
var initQ = quaternion(0,0,0,1);
if (p0 != Entity.Null) {
var q0 = p00==Entity.Null ? initQ : dWRots[p00].value;
getFromToDir(spr0, spr1, defWPos0, defWPos1, q0, out from, out to);
dWRots[p0]= new Ptcl_DWRot{value=mul( Math8.fromToRotation(from, to), q0 )};
}
if (p1 != Entity.Null) {
var q1 = p0==Entity.Null ? initQ : dWRots[p0].value;
getFromToDir(spr1, spr2, defWPos1, defWPos2, q1, out from, out to);
dWRots[p1]= new Ptcl_DWRot{value=mul( Math8.fromToRotation(from, to), q1 )};
}
var q2 = p1==Entity.Null ? initQ : dWRots[p1].value;
getFromToDir(spr2, spr3, defWPos2, defWPos3, q2, out from, out to);
dWRots[p2]= new Ptcl_DWRot{value=mul( Math8.fromToRotation(from, to), q2 )};
}
#if WITH_DEBUG
}).WithAll<Root>().WithoutBurst().Run();
#else
}).WithAll<Root>().ScheduleParallel( Dependency );
#endif
}
#endif
// デフォルト位置からの移動可能距離での拘束条件を解決
const float DefPosMovRngCompliance = 1e-10f;
#if WITH_DEBUG
Entities.ForEach((
#else
Dependency = Entities.ForEach((
#endif
Entity entity,
ref Ptcl_WPos wpos,
ref Ptcl_MvblRngLmd lambda
)=>{
// 固定Particleに対しては何もする必要なし
var invM = GetComponent<Ptcl_InvM>(entity).value;
if (invM == 0) return;
var maxMovableRange = GetComponent<Ptcl_MaxMovableRange>(entity).value;
if (maxMovableRange <= 0) return;
maxMovableRange *= GetComponent<Ptcl_ToChildWDist>(entity).value;
var cstr = new Constraint.MaxDistance{
compliance = DefPosMovRngCompliance,
srcPos = GetComponent<Ptcl_DefaultTailWPos>(entity).value,
pos = wpos.value,
invM = invM,
maxLen = maxMovableRange,
};
lambda.value += cstr.solve(sqDt, lambda.value);
wpos.value = cstr.pos;
#if WITH_DEBUG
}).WithoutBurst().Run();
#else
}).ScheduleParallel( Dependency );
#endif
// コライダとの衝突解決
const float ColResolveCompliance = 1e-10f;
#if WITH_DEBUG
Entities.ForEach((
#else
Dependency = Entities.ForEach((
#endif
Entity entity,
ref Ptcl_WPos wPos,
ref Ptcl_CldCstLmd lambda
)=>{
var mostParent = GetComponent<Ptcl_Root>(entity).value;
// コライダが未設定の場合は何もしない
var collider = GetComponent<Root_ColliderPack>(mostParent).value;
if (collider == Entity.Null) return;
// 固定Particleに対しては何もする必要なし
var invM = GetComponent<Ptcl_InvM>(entity).value;
if (invM == 0) return;
// パーティクル半径
var r = GetComponent<Ptcl_R>(entity).value;
r *= GetComponent<Ptcl_ToChildWDist>(entity).value;
// コライダとの衝突解決
var isCol = false;
var sp = new IzBCollider.RawCollider.Sphere{pos=wPos.value, r=r};
unsafe { do {
var bp = GetComponent<IzBCollider.Core.BodiesPack>(collider);
float3 n=0; float d=0;
for (
var e = bp.firstSphere;
e != Entity.Null;
e = GetComponent<IzBCollider.Core.Body_Next>(e).value
) {
var rc = GetComponent<IzBCollider.Core.Body_Raw_Sphere>(e);
if ( rc.value.solve(&sp,&n,&d) ) {
isCol |= true;
sp.pos += n * d;
}
}
for (
var e = bp.firstCapsule;
e != Entity.Null;
e = GetComponent<IzBCollider.Core.Body_Next>(e).value
) {
var rc = GetComponent<IzBCollider.Core.Body_Raw_Capsule>(e);
if ( rc.value.solve(&sp,&n,&d) ) {
isCol |= true;
sp.pos += n * d;
}
}
for (
var e = bp.firstBox;
e != Entity.Null;
e = GetComponent<IzBCollider.Core.Body_Next>(e).value
) {
var rc = GetComponent<IzBCollider.Core.Body_Raw_Box>(e);
if ( rc.value.solve(&sp,&n,&d) ) {
isCol |= true;
sp.pos += n * d;
}
}
for (
var e = bp.firstPlane;
e != Entity.Null;
e = GetComponent<IzBCollider.Core.Body_Next>(e).value
) {
var rc = GetComponent<IzBCollider.Core.Body_Raw_Plane>(e);
if ( rc.value.solve(&sp,&n,&d) ) {
isCol |= true;
sp.pos += n * d;
}
}
collider = bp.next;
} while(collider != Entity.Null); }
// 何かしらに衝突している場合は、引き離し用拘束条件を適応
if (isCol) {
var dPos = sp.pos - wPos.value;
var dPosLen = length(dPos);
var dPosN = dPos / (dPosLen + 0.0000001f);
var cstr = new Constraint.MinDistN{
compliance = ColResolveCompliance,
srcPos = wPos.value,
n = dPosN,
pos = wPos.value,
invM = invM,
minDist = dPosLen,
};
lambda.value += cstr.solve( sqDt, lambda.value );
wPos.value = cstr.pos;
} else {
lambda.value = 0;
}
#if WITH_DEBUG
}).WithoutBurst().Run();
#else
}).Schedule( Dependency );
#endif
// その他の拘束条件を解決
#if WITH_DEBUG
Entities.ForEach((
#else
Dependency = Entities.ForEach((
#endif
Entity entity,
ref Cstr_Lmd lambda
)=>{
var tgt = GetComponent<Cstr_Target>(entity);
var compliance = GetComponent<Cstr_Compliance>(entity).value;
var defaultLen = GetComponent<Cstr_DefaultLen>(entity).value;
defaultLen *= GetComponent<Ptcl_ToChildWDist>(tgt.src).value;
var wPos0 = GetComponent<Ptcl_WPos>(tgt.src);
var wPos1 = GetComponent<Ptcl_WPos>(tgt.dst);
var cstr = new Constraint.Distance{
compliance = compliance,
pos0 = wPos0.value,
pos1 = wPos1.value,
invM0 = GetComponent<Ptcl_InvM>(tgt.src).value,
invM1 = GetComponent<Ptcl_InvM>(tgt.dst).value,
defLen = defaultLen,
};
lambda.value += cstr.solve(sqDt, lambda.value);
wPos0.value = cstr.pos0;
wPos1.value = cstr.pos1;
SetComponent(tgt.src, wPos0);
SetComponent(tgt.dst, wPos1);
#if WITH_DEBUG
}).WithoutBurst().Run();
#else
}).Schedule( Dependency );
#endif
}
// 速度の保存
#if WITH_DEBUG
Entities.ForEach((
#else
Dependency = Entities.ForEach((
#endif
Entity entity,
ref Ptcl_Velo v,
in Ptcl_WPos wPos
)=>{
v.value = (wPos.value - v.value) / deltaTime;
#if WITH_DEBUG
}).WithoutBurst().Run();
#else
}).Schedule( Dependency );
#endif
// シミュレーション結果をボーンにフィードバックする
#if WITH_DEBUG
Entities.ForEach((
#else
Dependency = Entities.ForEach((
#endif
Entity entity
)=>{
// これは上から順番に行う必要があるので、
// RootごとにRootから順番にParticleをたどって更新する
for (; entity!=Entity.Null; entity=GetComponent<Ptcl_Next>(entity).value) {
// 最親Particleの場合はDefaultTransformをそのまま転写
var invM = GetComponent<Ptcl_InvM>(entity).value;
if (invM == 0) {
// var l2w = GetComponent<Ptcl_DefaultHeadL2W>(entity).value;
// SetComponent(
// entity, new Ptcl_CurHeadTrans{l2w=l2w, w2l=inverse(l2w)}
// );
continue;
}
var parent = GetComponent<Ptcl_Parent>(entity).value;
// 親のTransform
var parentTrans = GetComponent<Ptcl_CurHeadTrans>(parent);
var wPos = GetComponent<Ptcl_WPos>(entity);
var defHeadL2P = GetComponent<Ptcl_DefaultHeadL2P>(entity);
var defTailLPos = GetComponent<Ptcl_DefaultTailLPos>(entity).value;
// 回転する元方向と先方向
var defTailPPos = Math8.trans( defHeadL2P.l2p, defTailLPos );
var curTailPPos = Math8.trans( parentTrans.w2l, wPos.value );
var defHeadPPos = defHeadL2P.l2p.c3.xyz;
// 最大角度制限は制約条件のみだとどうしても完璧にはならず、
// コンプライアンス値をきつくし過ぎると暴走するので、
// 制約条件で緩く制御した上で、ここで強制的にクリッピングする。
var maxAngle = GetComponent<Ptcl_MaxAngle>(entity).value;
var q = Math8.fromToRotation(
defTailPPos - defHeadPPos,
curTailPPos - defHeadPPos,
maxAngle
);
// 初期姿勢を反映
var curTrans = GetComponent<Ptcl_CurHeadTrans>(entity);
curTrans.lRot = mul(q, defHeadL2P.rot);
curTrans.l2w = mul(
parentTrans.l2w,
Unity.Mathematics.float4x4.TRS(curTrans.lPos, curTrans.lRot, 1)
);
curTrans.w2l = inverse(curTrans.l2w);
SetComponent(entity, curTrans);
// 最大角度制限を反映させたので、パーティクルへ変更をフィードバックする
wPos.value = Math8.trans(curTrans.l2w, defTailLPos);
SetComponent(entity, wPos);
}
#if WITH_DEBUG
}).WithAll<Root>().WithoutBurst().Run();
#else
}).WithAll<Root>().Schedule( Dependency );
#endif
if (etp.Length != 0) {
Dependency = new ApplyToBoneJob{
entities = etp.Entities,
curHeadTranss = GetComponentDataFromEntity<Ptcl_CurHeadTrans>(true),
invMs = GetComponentDataFromEntity<Ptcl_InvM>(true),
}.Schedule( etp.Transforms, Dependency );
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DayNightCycle : MonoBehaviour {
public int _days; // Define naming convenction for the days
public int _hours; // Define naming convenction for the hours
public int _minutes; // Define naming convenction for the minutes
public int _seconds; // Define naming convenction for the seconds
public float _counter; // Define naming convenction for the counter
public int _years; // Define naming convenction for years counter
public int _leapYearsCounter; // Define naming convenction for leap years counter
public int _calendarDays; // Define naming convenction for days in the month
public bool _january; //Defines if we are in the month of January
public bool _february; //Defines if we are in the month of February
public bool _march; //Defines if we are in the month of March
public bool _april; //Defines if we are in the month of April
public bool _may; //Defines if we are in the month of May
public bool _june; //Defines if we are in the month of June
public bool _july; //Defines if we are in the month of July
public bool _august; //Defines if we are in the month of August
public bool _september; //Defines if we are in the month of September
public bool _october; //Defines if we are in the month of October
public bool _november; //Defines if we are in the month of November
public bool _december; //Defines if we are in the month of December
public bool _spring; //Defines if we are in Spring
public bool _summer; //Defines if we are in Summer
public bool _autumn; //Defines if we are in Autumn
public bool _winter; //Defines if we are in Winter
public int _dawnStartTime = 6; // Defines down start
public int _dayStartTime = 8; // Defines day start
public int _duskStartTime = 18; // Defines dusk start
public int _nightStartTime = 20; // Defines night start
public float _sunDimTime = 0.01f; // Speed at which sun dims
public float _dawnSunIntensity = 0.5f; // down sun strenght
public float _daySunIntensity = 1f; // day sun strenght
public float _duskSunIntensity = 0.25f; // dusk sun strenght
public float _nightSunIntensity = 0f; // night sun strenght
public float _ambientDimTime = 0.001f; // Defines the speed at which ambient light is adjusted
public float _dawnAmbientIntensity = 0.5f; // Defines the ambient intensity for dawn
public float _dayAmbientIntensity = 1f; // Defines the ambient intensity for day
public float _duskAmbientIntensity = 0.25f; // Defines the ambient intensity for dusk
public float _nightAmbientIntensity = 0f; // Defines the ambient intensity for night
public float _dawnSkyboxBlendFactor = 0.5f; // Defines dawn skybox blend value
public float _daySkyboxBlendFactor = 0.5f; // Defines day skybox blend value
public float _duskSkyboxBlendFactor = 0.5f; // Defines dusk skybox blend value
public float _nightSkyboxBlendFactor = 0.5f; // Defines night skybox blend value
public float _skyboxBlendFactor; // Defines the current skybox blend value
public float _skyboxBlendSpeed = 0.01f; // Defines speed at which the skybox will blend
public int _guiWidth = 100; // Defines GUI label width;
public int _guiHeight = 20; // Defines GUI label height;
public DayPhases _dayPhases; // Defines naming convection for the phases in the day
public enum DayPhases // enum for day phases
{
Dawn,Day,Dusk,Night
}
void Awake()
{
_dayPhases = DayPhases.Night; // Set up day phase on night on start up
RenderSettings.ambientIntensity = _nightAmbientIntensity; // Render settings is equal to night on start up
GetComponent<Light>().intensity = _nightSunIntensity; // Set sun intensity to night on start up
}
// Use this for initialization
void Start ()
{
StartCoroutine("TimeOfDayFiniteStateMachine"); // Starts TimeOfDayFiniteStateMachine on start up
_hours = 5; // Set up hours to 5 on start up
_minutes = 59; // Set up minutes to 59 on start up
_counter = 59; // Set up counter to 59 on start up
_days = 1; // Set up days to 1 on start up
_calendarDays = 1; // Calendar days equal to 1 on start up
_october = true; // Starts in the month of October on start up
_autumn = true; // Starts in the season of Autumn on start up
_years = 2016; // Year is equal to 2016 on start up
_leapYearsCounter = 4; // Leap year counter is equal to 4 on start up
}
// Update is called once per frame
void Update ()
{
SecondsCounter(); //Starts SecondCounter function
UpdateSkybox(); //Calls UpdateSkybox function
}
IEnumerator TimeOfDayFiniteStateMachine()
{
while(true)
{
switch(_dayPhases) {
case DayPhases.Dawn:
Dawn();
break;
case DayPhases.Day:
Day();
break;
case DayPhases.Dusk:
Dusk();
break;
case DayPhases.Night:
Night();
break;
}
yield return null;
}
}
void SecondsCounter()
{
Debug.Log("SecondsCounter");
if (_counter == 60) // If the counter is equals to 60
_counter = 0; // than make the counter equals to 0
_counter += Time.deltaTime; // counter plus time sync tp PC speed
_seconds = (int)_counter; // seconds equals to counter cast to an int
if (_counter < 60) // If the counter is less then 60
return; // then do nothing and return
if (_counter > 60) // if counter is greater then 60
_counter = 60; // then make counter equals to 60
if (_counter == 60) // If the counter is equals to 60
MinutesCounter(); // then call MinutesCounter function
}
void MinutesCounter()
{
Debug.Log("MinutesCounter");
_minutes++; // Increase minutes counter
if(_minutes == 60) // If minutes counter is equal to 60
{
HoursCounter(); // call HoursCounter function
_minutes = 0; // and then make minutes equal zero
}
}
void HoursCounter()
{
Debug.Log("HoursCounter");
_hours++; // Increase hours counter
if (_hours == 24) // If hours counter is equal to 60
{
DaysCounter(); // call HoursCounter function
_hours = 0; // and then make hours equal zero
}
}
void DaysCounter()
{
Debug.Log("DaysCounter");
_days++; // Increase hours counter
}
void UpdateCalendarMonth()
{
Debug.Log("UpdateCalendarMonth");
if (_january == true && _calendarDays > 31) // If we are in January and calendar days is greater than 31
{
_january = false; // then set January to false
_february = true; // and set February to true
_calendarDays = 1; // and make callendar day equal to 1 (the first day of February)
}
if (_leapYearsCounter == 4 && // If leap year counter is equal to 4
_february == true && _calendarDays > 29) // and February is equal to true and calendar days is greater than 29
{
_february = false; // then set February to false
_march = true; // and set March to true
_calendarDays = 1; // and make callendar day equal to 1 (the first day of March)
SeasonManager(); // Calls SeasonManager function
}
if (_leapYearsCounter < 4 && // If leap year counter is less than 4
_february == true && _calendarDays > 28) // and February is equal to true and calendar days is greater than 28
{
_february = false; // then set February to false
_march = true; // and set March to true
_calendarDays = 1; // and make callendar day equal to 1 (the first day of March
SeasonManager(); // Calls SeasonManager function
}
if (_march == true && _calendarDays > 31) // If we are in March and calendar days is greater than 31
{
_march = false; // then set March to false
_april = true; // and set April to true
_calendarDays = 1; // and make callendar day equal to 1 (the first day of April)
}
if (_april == true && _calendarDays > 30) // If we are in April and calendar days is greater than 30
{
_april = false; // then set April to false
_may = true; // and set May to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of May)
}
if (_may == true && _calendarDays > 31) // If we are in May and calendar days is greater than 31
{
_may = false; // then set March to false
_june = true; // and set June to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of June)
SeasonManager(); // Calls SeasonManagerfunction
}
if (_june == true && _calendarDays > 30) // If we are in June and calendar days is greater than 30
{
_june = false; // then set June to false
_july = true; // and set July to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of July)
}
if (_july == true && _calendarDays > 31) // If we are in July and calendar days is greater than 31
{
_july = false; // then set July to false
_august = true; // and set August to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of August)
}
if (_august == true && _calendarDays > 31) // If we are in August and calendar days is greater than 31
{
_august = false; // then set August to false
_september = true; // and set September to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of September)
SeasonManager(); // Calls SeasonManagerfunction
}
if (_september == true && _calendarDays > 30) // If we are in September and calendar days is greater than 30
{
_september = false; // then set September to false
_october = true; // and set October to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of October)
}
if (_october == true && _calendarDays > 31) // If we are in October and calendar days is greater than 31
{
_october = false; // then set October to false
_november = true; // and set November to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of November)
}
if (_november == true && _calendarDays > 30) // If we are in November and calendar days is greater than 30
{
_november = false; // then set November to false
_december = true; // and set December to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of December)
SeasonManager(); // Calls SeasonManagerfunction
}
if (_december == true && _calendarDays > 31) // If we are in December and calendar days is greater than 31
{
_december = false; // then set December to false
_january = true; // and set January to true
_calendarDays = 1; // and make calendar day equal to 1 (the first day of January)
}
YearCounter(); // Calls YearCounter function
}
void YearCounter()
{
Debug.Log("YearCounter");
_years++; // Increase years
_leapYearsCounter++; // Increase leap years
if (_leapYearsCounter > 4) // If leap year counter is greater than 4
_leapYearsCounter = 1; // then leap year counter is equal to 1
}
void SeasonManager()
{
Debug.Log("SeasonManager");
_spring = false; // Set spring to be equal to false
_summer = false; // Set summer to be equal to false
_autumn = false; // Set autumn to be equal to false
_winter = false; // Set winter to be equal to false
if (_march == true && _calendarDays == 1) // If we are in March and calendar days is 1
_spring = true; // then set Spring to true
if (_june == true && _calendarDays == 1) // If we are in June and calendar days is 1
_summer = true; // then set Summer to true
if (_september == true && _calendarDays == 1) // If we are in September and calendar days is 1
_autumn = true; // then set Autumn to true
if (_december == true && _calendarDays == 1) // If we are in December and calendar days is 1
_winter = true; // then set Winter to true
}
void Dawn()
{
Debug.Log("Dawn");
DawnSunLightManager(); // Call DawnSunLightManbager function
DawnLightAmbientManager(); // Call DawnLightAmbientManager function
if (-_hours == _dayStartTime && _hours < _duskStartTime)
{
_dayPhases = DayPhases.Day; // Set up day phase on day
}
}
void DawnSunLightManager()
{
Debug.Log("DawnSunLightManbager");
if (GetComponent<Light>().intensity == _dawnSunIntensity) // If light intensity is equal to dawn intensity
return; // then do nothing and return
if (GetComponent<Light>().intensity < _dawnSunIntensity) // If sun intensity is less than dawn
GetComponent<Light>().intensity += _sunDimTime * Time.deltaTime; // then increase sun intensity by the sun dim time
if (GetComponent<Light>().intensity > _dawnSunIntensity) // If sun intensity is greater than dawn
GetComponent<Light>().intensity = _dawnSunIntensity; // then make intensity equal to dawn
}
void DawnLightAmbientManager()
{
Debug.Log("DawnLightAmbientManager");
if (RenderSettings.ambientIntensity == _dayAmbientIntensity) // If ambient intensity is equal to dawn ambient intensity
return; // then do nothing and return
if (RenderSettings.ambientIntensity < _dawnAmbientIntensity) // If ambient intensity is less than dawn
RenderSettings.ambientIntensity += _ambientDimTime * Time.deltaTime; // then increase ambient intensity by the ambient dim time
if (RenderSettings.ambientIntensity > _dawnAmbientIntensity) // If ambient intensity is greater than dawn
RenderSettings.ambientIntensity = _dawnAmbientIntensity; // then make ambient intensity equal to dawn
}
void Day()
{
Debug.Log("Day");
DaySunLightManager(); // Call DaySunLightManager function
DayLightAmbientManager(); // Call DayLightAmbientManager function
if (-_hours == _duskStartTime && _hours < _nightStartTime)
{
_dayPhases = DayPhases.Dusk; // Set up day phase on dusk
}
}
void DaySunLightManager()
{
Debug.Log("DaySunLightManager");
if (GetComponent<Light>().intensity == _daySunIntensity) // If light intensity is equal to day intensity
return; // then do nothing and return
if (GetComponent<Light>().intensity < _dawnSunIntensity) // If sun intensity is less than dawn
GetComponent<Light>().intensity += _sunDimTime * Time.deltaTime; // then increase sun intensity by the sun dim time
if (GetComponent<Light>().intensity > _dawnSunIntensity) // If sun intensity is greater than dawn
GetComponent<Light>().intensity = _dawnSunIntensity; // then make intensity equal to dawn
}
void DayLightAmbientManager()
{
Debug.Log("DayLightAmbientManager");
if (RenderSettings.ambientIntensity == _dayAmbientIntensity) // If ambient intensity is equal to day ambient intensity
return; // then do nothing and return
if (RenderSettings.ambientIntensity < _dayAmbientIntensity) // If ambient intensity is less than day
RenderSettings.ambientIntensity += _ambientDimTime * Time.deltaTime; // then increase ambient intensity by the ambient dim time
if (RenderSettings.ambientIntensity > _dayAmbientIntensity) // If ambient intensity is greater than day
RenderSettings.ambientIntensity = _dayAmbientIntensity; // then make ambient intensity equal to day
}
void Dusk()
{
Debug.Log("Dusk");
DuskSunLightManager(); // Call DuskSunLightManager function
DuskLightAmbientManager(); // Call DuskLightAmbientManager function
if (-_hours == _nightStartTime)
{
_dayPhases = DayPhases.Night; // Set up day phase on night
}
}
void DuskSunLightManager()
{
Debug.Log("DuskSunLightManager");
if (GetComponent<Light>().intensity == _duskSunIntensity) // If light intensity is equal to dusk intensity
return; // then do nothing and return
if (GetComponent<Light>().intensity > _duskSunIntensity) // If sun intensity is grater than dusk
GetComponent<Light>().intensity -= _sunDimTime * Time.deltaTime; // then decrease sun intensity by the sun dim time
if (GetComponent<Light>().intensity < _duskSunIntensity) // If sun intensity is less than dusk
GetComponent<Light>().intensity = _duskSunIntensity; // then make intensity equal to dusk
}
void DuskLightAmbientManager()
{
Debug.Log("DayLightAmbientManager");
if (RenderSettings.ambientIntensity == _duskAmbientIntensity) // If ambient intensity is equal to dusk ambient intensity
return; // then do nothing and return
if (RenderSettings.ambientIntensity > _duskAmbientIntensity) // If ambient intensity is gtreater than dusk
RenderSettings.ambientIntensity -= _ambientDimTime * Time.deltaTime; // then decrease ambient intensity by the ambient dim time
if (RenderSettings.ambientIntensity < _duskAmbientIntensity) // If ambient intensity is less than dusk
RenderSettings.ambientIntensity = _duskAmbientIntensity; // then make ambient intensity equal to dusk
}
void Night()
{
Debug.Log("Night");
NightSunLightManager(); // Call NightSunLightManager function
NightLightAmbientManager(); // Call NightLightAmbientManager function
if (-_hours == _dawnStartTime && _hours < _duskStartTime)
{
_dayPhases = DayPhases.Dawn; // Set up day phase on dawn
}
}
void NightSunLightManager()
{
Debug.Log("NightSunLightManager");
if (GetComponent<Light>().intensity == _nightSunIntensity) // If light intensity is equal to night intensity
return; // then do nothing and return
if (GetComponent<Light>().intensity > _nightSunIntensity) // If sun intensity is grater than night
GetComponent<Light>().intensity -= _sunDimTime * Time.deltaTime; // then decrease sun intensity by the sun dim time
if (GetComponent<Light>().intensity < _nightSunIntensity) // If sun intensity is less than night
GetComponent<Light>().intensity = _nightSunIntensity; // then make intensity equal to night
}
void NightLightAmbientManager()
{
Debug.Log("NightLightAmbientManager");
if (RenderSettings.ambientIntensity == _duskAmbientIntensity) // If ambient intensity is equal to night ambient intensity
return; // then do nothing and return
if (RenderSettings.ambientIntensity < _nightAmbientIntensity) // If ambient intensity is less than night
RenderSettings.ambientIntensity += _ambientDimTime * Time.deltaTime; // then increase ambient intensity by the ambient dim time
if (RenderSettings.ambientIntensity > _nightAmbientIntensity) // If ambient intensity is greater than night
RenderSettings.ambientIntensity = _nightAmbientIntensity; // then make ambient intensity equal to night
}
void OnGUI()
{
// Create GUI Label to display numbers of days
GUI.Label(new Rect(Screen.width -50, 5, _guiWidth, _guiHeight), "Day " + _days);
// If minutes is less than 10 dysplay our clock with extra zero
if(_minutes < 10)
{
GUI.Label(new Rect(Screen.width - 50, 25, _guiWidth, _guiHeight), _hours + ":" + 0 + _minutes + ":" + _seconds);
}
// else just display our clock
else
GUI.Label(new Rect(Screen.width - 50, 25, _guiWidth, _guiHeight), _hours + ":" + _minutes + ":" + _seconds );
}
private void UpdateSkybox()
{
Debug.Log("UpdateSkybox");
if(_dayPhases == DayPhases.Dawn) // If day phase is equal to dawn
{
if (_skyboxBlendFactor == _dawnSkyboxBlendFactor) // If skybox blend value is equal to dawn
return; // then do nothing and return
_skyboxBlendFactor += _skyboxBlendSpeed * Time.deltaTime; // Increase skybox blend by blend speed
if (_skyboxBlendFactor > _dawnSkyboxBlendFactor) // If skybox blend value is greater to dawn
_skyboxBlendFactor = _dawnSkyboxBlendFactor; // then make skybox blend factor equal to dawn
}
if (_dayPhases == DayPhases.Day) // If day phase is equal to day
{
if (_skyboxBlendFactor == _daySkyboxBlendFactor) // If skybox blend value is equal to day
return; // then do nothing and return
_skyboxBlendFactor += _skyboxBlendSpeed * Time.deltaTime; // Increase skybox blend by blend speed
if (_skyboxBlendFactor > _daySkyboxBlendFactor) // If skybox blend value is greater to day
_skyboxBlendFactor = _daySkyboxBlendFactor; // then make skybox blend factor equal to day
}
if (_dayPhases == DayPhases.Dusk) // If day phase is equal to dusk
{
if (_skyboxBlendFactor == _duskSkyboxBlendFactor) // If skybox blend value is equal to dusk
return; // then do nothing and return
_skyboxBlendFactor -= _skyboxBlendSpeed * Time.deltaTime; // Decrease skybox blend by blend speed
if (_skyboxBlendFactor < _duskSkyboxBlendFactor) // If skybox blend value is less to day
_skyboxBlendFactor = _duskSkyboxBlendFactor; // then make skybox blend factor equal to day
}
if (_dayPhases == DayPhases.Night) // If day phase is equal to night
{
if (_skyboxBlendFactor == _nightSkyboxBlendFactor) // If skybox blend value is equal to night
return; // then do nothing and return
_skyboxBlendFactor -= _skyboxBlendSpeed * Time.deltaTime; // Decrease skybox blend by blend speed
if (_skyboxBlendFactor < _nightSkyboxBlendFactor) // If skybox blend value is less to night
_skyboxBlendFactor = _nightSkyboxBlendFactor; // then make skybox blend factor equal to night
}
RenderSettings.skybox.SetFloat("_Blend", _skyboxBlendFactor); // Get render for skybox and set float for the blend
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
namespace QLDSV
{
public partial class frmLop : DevExpress.XtraEditors.XtraForm
{
int vitri = 0;
String maKhoa = "";
bool kt;
public frmLop()
{
InitializeComponent();
}
private void lOPBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.bdsLop.EndEdit();
this.tableAdapterManager.UpdateAll(this.dS);
}
private void frmLop_Load(object sender, EventArgs e)
{
dS.EnforceConstraints = false;
//this.sINHVIENTableAdapter.Fill(this.DS.SINHVIEN); //gọi danh sách lớp vào trong table
this.lOPTableAdapter.Connection.ConnectionString = Program.connstr;
this.lOPTableAdapter.Fill(this.dS.LOP);
// TODO: This line of code loads data into the 'DS.SINHVIEN' table. You can move, or remove it, as needed.
this.sINHVIENTableAdapter.Connection.ConnectionString = Program.connstr;
this.sINHVIENTableAdapter.Fill(this.dS.SINHVIEN);
maKhoa = ((DataRowView)bdsLop[0])["MAKH"].ToString();
groupBox3.Enabled = false;
cmbKhoa.DataSource = Program.bds_dspm;
cmbKhoa.DisplayMember = "TENCN";
cmbKhoa.ValueMember = "TENSERVER";
cmbKhoa.SelectedIndex = Program.mKhoa;
if (Program.mGroup == "PGV")
{
cmbKhoa.Enabled = true;
btnPhucHoi.Enabled = false;
btnGhi.Enabled = false;
btnTaiLai.Enabled = true;
if (cmbKhoa.SelectedIndex.ToString() == "2")
{
cmbKhoa.SelectedIndex = Program.mKhoa;
}
}
else
{
cmbKhoa.Enabled = false;
}
if (Program.mGroup == "Khoa" || Program.mGroup == "PKeToan")
{
btnThem.Enabled = false;
btnXoa.Enabled = false;
btnPhucHoi.Enabled = false;
btnHieuChinh.Enabled = false;
btnGhi.Enabled = false;
}
}
private void lOPBindingNavigator_RefreshItems(object sender, EventArgs e)
{
}
private void cmbKhoa_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbKhoa.SelectedValue != null)
{
if (cmbKhoa.SelectedValue.ToString() == "System.Data.DataRowView")
return;
Program.servername = cmbKhoa.SelectedValue.ToString();
if (Program.mGroup == "PGV" && cmbKhoa.SelectedIndex == 2)
{
MessageBox.Show("Bạn không có quyền truy cập cái này", "", MessageBoxButtons.OK);
cmbKhoa.SelectedIndex = 1;
cmbKhoa.SelectedIndex = 0;
return;
}
if (cmbKhoa.SelectedIndex != Program.mKhoa)
{
Program.mlogin = Program.remotelogin;
Program.password = Program.remotepassword;
}
else
{
Program.mlogin = Program.mloginDN;
Program.password = Program.passwordDN;
}
if (Program.KetNoi() == 0)
MessageBox.Show("Lỗi kết nối về chi nhánh mới", "", MessageBoxButtons.OK);
else
{
this.lOPTableAdapter.Connection.ConnectionString = Program.connstr;
this.lOPTableAdapter.Fill(this.dS.LOP);
this.sINHVIENTableAdapter.Connection.ConnectionString = Program.connstr;
this.sINHVIENTableAdapter.Fill(this.dS.SINHVIEN);
}
}
}
private void btnThem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
vitri = bdsLop.Position;
groupBox3.Enabled = true;
bdsLop.AddNew();
txtMaLop.Focus();
txtMaKhoa.Text = ((DataRowView)bdsLop[0])["MAKH"].ToString();
txtMaKhoa.Enabled = false;
lOPGridControl.Enabled = false;
kt = false;
cmbKhoa.Enabled = false;
btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnTaiLai.Enabled = false;
btnGhi.Enabled = btnPhucHoi.Enabled = true;
}
private void btnHieuChinh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
vitri = bdsLop.Position;
groupBox3.Enabled = true;
cmbKhoa.Enabled = false;
kt = true;
lOPGridControl.Enabled = false;
btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnTaiLai.Enabled = false;
btnGhi.Enabled = btnPhucHoi.Enabled = true;
}
private void btnXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (bdsSV.Count != 0)
{
MessageBox.Show("Lớp đã có sinh viên không thể xóa \n", "",
MessageBoxButtons.OK);
return;
}
String malop = "";
if (MessageBox.Show("Bạn có thật sự muốn xóa lớp " + ((DataRowView)bdsLop[bdsLop.Position])["MALOP"].ToString() + " ?? ", "Xác nhận",
MessageBoxButtons.OKCancel) == DialogResult.OK)
{
try
{
malop = ((DataRowView)bdsLop[bdsLop.Position])["MALOP"].ToString();// giữ lại để khi xóa bị lỗi thì ta sẽ quay về lại
bdsLop.Position = bdsLop.Find("MALOP", malop);
bdsLop.RemoveCurrent();
this.lOPTableAdapter.Connection.ConnectionString = Program.connstr;
this.lOPTableAdapter.Update(this.dS.LOP);
MessageBox.Show("Đã xóa lớp" + malop);
}
catch (Exception ex)
{
MessageBox.Show("Lỗi không thể xóa \n" + ex.Message, "",
MessageBoxButtons.OK);
this.lOPTableAdapter.Fill(this.dS.LOP);
bdsLop.Position = bdsLop.Find("MALOP", malop);
return;
}
}
if (bdsLop.Count == 0) btnXoa.Enabled = false;
}
private void btnPhucHoi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
bdsLop.CancelEdit();
if (btnThem.Enabled == false) bdsLop.Position = vitri;
groupBox3.Enabled = false;
if (Program.mGroup == "PGV")
{
cmbKhoa.Enabled = true;
}
lOPGridControl.Enabled = true;
btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnTaiLai.Enabled = btnThoat.Enabled = true;
btnGhi.Enabled = btnPhucHoi.Enabled = false;
}
private void btnGhi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (txtMaKhoa.Text.Trim() == "")
{
MessageBox.Show("Mã khoa không được thiếu!", "", MessageBoxButtons.OK);
txtMaKhoa.Focus();
return;
}
if (txtMaLop.Text.Trim() == "")
{
MessageBox.Show("Mã lớp không được thiếu!", "", MessageBoxButtons.OK);
txtMaLop.Focus();
return;
}
try
{
string strLenh = "EXEC sp_KTraLop '" + txtMaLop.Text + "'";
Program.myReader = Program.ExecSqlDataReader(strLenh);
Program.myReader.Read();
int s = Program.myReader.GetInt32(0);
if (s == 1)
{
MessageBox.Show("Mã lớp đã bị trùng!", "", MessageBoxButtons.OK);
txtMaLop.Focus();
Program.myReader.Close();
return;
}
Program.myReader.Close();
}
catch (Exception ex)
{
Program.myReader.Close();
MessageBox.Show("Lỗi kiểm tra lớp!" + ex, "", MessageBoxButtons.OK);
txtTenLop.Focus();
return;
}
if (txtTenLop.Text.Trim() == "")
{
MessageBox.Show("Tên lớp không được thiếu!", "", MessageBoxButtons.OK);
txtTenLop.Focus();
return;
}
try
{
bdsLop.EndEdit();
bdsLop.ResetCurrentItem();
this.lOPTableAdapter.Connection.ConnectionString = Program.connstr;
this.lOPTableAdapter.Update(this.dS.LOP);
if (Program.mGroup == "PGV")
{
cmbKhoa.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi ghi lớp.\n" + ex.Message, "", MessageBoxButtons.OK);
return;
}
btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnTaiLai.Enabled = true;
btnGhi.Enabled = btnPhucHoi.Enabled = false;
lOPGridControl.Enabled = true;
groupBox3.Enabled = false;
}
private void btnTaiLai_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
try
{
this.lOPTableAdapter.Fill(this.dS.LOP);
this.sINHVIENTableAdapter.Fill(this.dS.SINHVIEN);
lOPGridControl.Enabled = true;
if (Program.mGroup == "PGV")
{
cmbKhoa.Enabled = true;
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi tải lại :" + ex.Message, "", MessageBoxButtons.OK);
return;
}
}
private void btnThoat_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
cmbKhoa.DataSource = null;
this.Close();
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace FSM_Application
{
//Stores all of the states that are to be written to a file
public class Fsm
{
public List<State> statesList = new List<State>();
public void Add(State state)
{
if (statesList.Count == 0)
{
current = state;
statesList.Add(state);
}
else
{
statesList.Add(state);
}
}
//Switches the current state to another. Mainly used for testing
public void Switch()
{
Dictionary<string, State> statesDictionary = new Dictionary<string, State>();
foreach (var state in statesList)
{
statesDictionary.Add(state.Name, state);
}
if(!statesDictionary.TryGetValue(current.destinationName, out current))
{
return;
}
else
{
return;
}
}
public State current;
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Thingy.Diagnostics.Api;
namespace Thingy.GraphicsPlus.SmdConverter
{
public class FileConverter : IFileConverter
{
private readonly IDiagnosticConsole diagnostics;
private readonly char[] itemSeparators = new char[] { ' ' };
public FileConverter(IDiagnosticConsole diagnostics)
{
this.diagnostics = diagnostics;
}
public string Convert(string inputFile)
{
string outputFile = Path.ChangeExtension(inputFile, ".STR");
Convert(inputFile, outputFile);
return outputFile;
}
public void Convert(string inputFile, string outputFile)
{
IDictionary<int, SkeletonNode> nodeTree = new Dictionary<int, SkeletonNode>();
IList<SmdTriangle> triangles = new List<SmdTriangle>();
using (StreamReader reader = new StreamReader(inputFile))
{
diagnostics.WriteMessage(this, "Convert(string,string)", DiagnosticLevels.Information, "Reading SMD File");
ParseSmdFile(reader, nodeTree, triangles);
}
using (StreamWriter writer = new StreamWriter(outputFile))
{
diagnostics.WriteMessage(this, "Convert(string,string)", DiagnosticLevels.Information, "Writing STR File");
foreach (int boneId in nodeTree.Keys)
{
string boneName = GetBoneName(nodeTree, boneId);
writer.WriteLine(string.IsNullOrEmpty(boneName) ? "Joint" : string.Format("Joint {0}", boneName));
writer.WriteLine(string.Format("{0},{1}", 256 * nodeTree[boneId].PosX, 256 * nodeTree[boneId].PosY));
writer.WriteLine(string.Format("{0}", 180 + nodeTree[boneId].RotZ * 57.295791433133264917914229473464));
writer.WriteLine(string.Format("{0}", nodeTree[boneId].PosZ));
writer.WriteLine("");
writer.WriteLine(string.IsNullOrEmpty(boneName) ? "Element dot" : string.Format("Element {0}.dot", boneName));
writer.WriteLine("Circle");
writer.WriteLine("0,0 1,0");
writer.WriteLine("Blue");
writer.WriteLine("10");
writer.WriteLine("");
}
int triangleNo = 1;
foreach(int boneId in nodeTree.Keys)
{
int parentBoneId = nodeTree[boneId].ParentNode;
string boneName = GetBoneName(nodeTree, boneId);
if (parentBoneId != -1)
{
string parentBoneName = GetBoneName(nodeTree, parentBoneId);
if (!string.IsNullOrEmpty(parentBoneName))
{
writer.WriteLine(string.Format("Triangle t{0}", triangleNo++));
writer.WriteLine(string.Format("{0} 0,0", boneName));
writer.WriteLine(string.Format("{0} 1,-1", parentBoneName));
writer.WriteLine(string.Format("{0} -1,1", parentBoneName));
writer.WriteLine("Black");
writer.WriteLine("0");
writer.WriteLine("");
}
}
}
////foreach (SmdTriangle triangle in triangles)
////{
//// triangleNo = CreateRegularTriangle(nodeTree, writer, triangleNo, triangle);
////}
}
}
private int CreateRegularTriangle(IDictionary<int, SkeletonNode> nodeTree, StreamWriter writer, int triangleNo, SmdTriangle triangle)
{
writer.WriteLine(string.Format("Triangle t{0}", triangleNo++));
int parentBoneId = triangle.Vertices[0].ParentBone;
string parentBoneName = GetBoneName(nodeTree, parentBoneId);
writer.WriteLine(string.Format("{0} {1},{2}", parentBoneName, 128 * triangle.Vertices[0].PosX, 128 * triangle.Vertices[0].PosY));
parentBoneId = triangle.Vertices[1].ParentBone;
parentBoneName = GetBoneName(nodeTree, parentBoneId);
writer.WriteLine(string.Format("{0} {1},{2}", parentBoneName, 128 * triangle.Vertices[1].PosX, 128 * triangle.Vertices[1].PosY));
parentBoneId = triangle.Vertices[2].ParentBone;
parentBoneName = GetBoneName(nodeTree, parentBoneId);
writer.WriteLine(string.Format("{0} {1},{2}", parentBoneName, 128 * triangle.Vertices[2].PosX, 128 * triangle.Vertices[2].PosY));
writer.WriteLine("Black");
writer.WriteLine(string.Format("{0}", triangle.Vertices[0].PosZ));
writer.WriteLine("");
return triangleNo;
}
private string GetBoneName(IDictionary<int, SkeletonNode> nodeTree, int boneId)
{
int parentBoneId = nodeTree[boneId].ParentNode;
if (parentBoneId == -1)
{
return string.Empty;
}
string parentBoneName = GetBoneName(nodeTree, parentBoneId);
return string.Format(string.IsNullOrEmpty(parentBoneName) ? "b{1}" : "{0}.b{1}", parentBoneName, boneId);
}
private void ParseSmdFile(StreamReader reader, IDictionary<int, SkeletonNode> nodeTree, IList<SmdTriangle> triangles)
{
ReadVersion(reader);
BuildNodeTree(reader, nodeTree);
BuildSkeleton(reader, nodeTree);
ReadTriangles(reader, triangles);
}
private void ReadTriangles(StreamReader reader, IList<SmdTriangle> triangles)
{
ReadTrianglesHeader(reader);
string line = reader.ReadLine();
while (line != "end")
{
SmdTriangle triangle = new SmdTriangle();
triangle.Material = line;
for (int i = 0; i < 3; i++)
{
triangle.Vertices.Add(CreateVertexFromLine(reader.ReadLine()));
}
triangles.Add(triangle);
line = reader.ReadLine();
}
}
private SmdVertex CreateVertexFromLine(string line)
{
SmdVertex vertex = new SmdVertex();
string[] items = line.Split(itemSeparators);
vertex.ParentBone = System.Convert.ToInt32(items[0]);
vertex.PosX = System.Convert.ToSingle(items[1]);
vertex.PosY = System.Convert.ToSingle(items[2]);
vertex.PosZ = System.Convert.ToSingle(items[3]);
vertex.NormX = System.Convert.ToSingle(items[4]);
vertex.NormY = System.Convert.ToSingle(items[5]);
vertex.NormZ = System.Convert.ToSingle(items[6]);
vertex.TextureU = System.Convert.ToSingle(items[7]);
vertex.TextureV = System.Convert.ToSingle(items[8]);
return vertex;
}
private void ReadTrianglesHeader(StreamReader reader)
{
string line = reader.ReadLine();
diagnostics.WriteMessage(GetType().Name, "ReadTrainglesHeader", DiagnosticLevels.Information, line);
if (line != "triangles")
{
throw new InvalidOperationException("triangles header expected");
}
}
private void BuildSkeleton(StreamReader reader, IDictionary<int, SkeletonNode> nodeTree)
{
ReadSkeletonHeader(reader);
ReadTimeIndex(reader);
string line = reader.ReadLine();
while (line != "end")
{
string[] items = line.Split(itemSeparators);
int boneId = System.Convert.ToInt32(items[0]);
nodeTree[boneId].PosX = System.Convert.ToSingle(items[1]);
nodeTree[boneId].PosY = System.Convert.ToSingle(items[2]);
nodeTree[boneId].PosZ = System.Convert.ToSingle(items[3]);
nodeTree[boneId].RotX = System.Convert.ToSingle(items[4]);
nodeTree[boneId].RotY = System.Convert.ToSingle(items[5]);
nodeTree[boneId].RotZ = System.Convert.ToSingle(items[6]);
line = reader.ReadLine();
}
}
private void ReadTimeIndex(StreamReader reader)
{
string line = reader.ReadLine();
diagnostics.WriteMessage(GetType().Name, "ReadTimeIndex", DiagnosticLevels.Information, line);
}
private void ReadSkeletonHeader(StreamReader reader)
{
string line = reader.ReadLine();
diagnostics.WriteMessage(GetType().Name, "ReadSkeletonHeader", DiagnosticLevels.Information, line);
if (line != "skeleton")
{
throw new InvalidOperationException("skeleton header expected");
}
}
private void BuildNodeTree(StreamReader reader, IDictionary<int, SkeletonNode> nodeTree)
{
ReadNodesHeader(reader);
string line = reader.ReadLine();
while (line != "end")
{
string[] items = line.Split(itemSeparators);
nodeTree[System.Convert.ToInt32(items[0])] = new SkeletonNode(System.Convert.ToInt32(items[2]));
line = reader.ReadLine();
}
}
private void ReadNodesHeader(StreamReader reader)
{
string line = reader.ReadLine();
diagnostics.WriteMessage(GetType().Name, "ReadNodesHeader", DiagnosticLevels.Information, line);
if (line != "nodes")
{
throw new InvalidOperationException("nodes header expected");
}
}
private void ReadVersion(StreamReader reader)
{
string line = reader.ReadLine();
diagnostics.WriteMessage(GetType().Name, "ReadVersion", DiagnosticLevels.Information, line);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LoowooTech.Stock.Rules
{
public class GHYTBaseTool
{
}
}
|
using System.Text;
namespace TagParsing.Tokens
{
public class ProcessingInstructionToken : ParseToken
{
private readonly string target;
private readonly string data;
public ProcessingInstructionToken(string target, string data)
{
this.target = target;
this.data = data;
}
public string Target
{
get { return target; }
}
public string Data
{
get { return data; }
}
public new string ToString()
{
StringBuilder result = new StringBuilder();
result.Append("PI: ").Append(target).Append(' ').Append(data);
return result.ToString();
}
public override string Render()
{
StringBuilder result = new StringBuilder();
result.Append("<?").Append(target).Append(' ').Append(data).Append("?>");
return result.ToString();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingBall : MonoBehaviour
{
public static MovingBall GetMovingBall;
GameObject currentBall;
void Awake()
{
GetMovingBall = this;
}
public void InitStartBall(GameObject ball)
{
//Записсь стартового шара и установка его скорости. На старте скорость равна 0, т.к. шар находится в покое
currentBall = ball;
currentBall.GetComponent<Ball>().ballSpeed = 0;
}
public void ChangeBall(GameObject ball)
{
//Предылущему шару задается скорость, равная 0, т.о. его движение останавливается. Стоит обратить внимание, что сам шар не прекращает движения! Он просто двигается со скоростью 0;
currentBall.GetComponent<Ball>().ballSpeed = 0;
//Текущий шар заменяется на новый, который подается в метод
currentBall = ball;
//Обновление значений скорости в UI
UI.GetUI.UpdateValue(currentBall.GetComponent<Ball>().ballSpeed);
}
//Обновление значения скорости шара на подающееся в метод значение
public void UpdateBallSpeed(float speed)
{
currentBall.GetComponent<Ball>().ballSpeed = speed;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Rendering;
using Unity.Transforms;
using Unity.Mathematics;
using Unity.Jobs;
using Unity.Collections;
using System;
public class DataComponent {
}
//标记用户 由于ECS查找的时候会找所有挂载的脚本,给主角添加单独的脚本区分
public struct PlayerComponent : IComponentData {
}
//添加接受输入
public struct InputComponent : IComponentData {
}
//记录输入数据
[Serializable]
public struct VelocityComponent : IComponentData {
public float3 moveVelicity;
}
//C# 作业系统
public struct MyJob : IJob
{
public float a;
public float b;
public NativeArray<float> result;
public void Execute() {
result[0] = a + b;
}
}
public struct MyJob1 : IJob {
public NativeArray<float> result;
public void Execute() {
result[0] = result[0] + 1;
}
}
//对批量的数据进行操作
public struct MyJobParallel : IJobParallelFor
{
[ReadOnly]
public NativeArray<float> a;
[ReadOnly]
public NativeArray<float> b;
public NativeArray<float> result;
public void Execute(int i)
{
result[i] = a[i] + b[i];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.