Beispiel #1
0
        protected override async Task <List <string> > SaveExecuteAsync(List <CurrencyForSave> entities, bool returnIds)
        {
            foreach (var(entity, index) in entities.Indexed())
            {
                // Ensure that Id is supplied
                if (string.IsNullOrEmpty(entity.Id))
                {
                    string path = $"[{index}].{nameof(entity.Id)}";
                    string msg  = _localizer[ErrorMessages.Error_Field0IsRequired, _localizer["Code"]];

                    ModelState.AddError(path, msg);
                }
                else if (entity.Id.Length > 3)
                {
                    string path = $"[{index}].{nameof(entity.Id)}";
                    string msg  = _localizer[ErrorMessages.Error_Field0LengthMaximumOf1, _localizer["Code"], 3];

                    ModelState.AddError(path, msg);
                }
            }

            // Save
            OperationOutput result = await _behavior.Repository.Currencies__Save(
                entities : entities,
                validateOnly : ModelState.IsError,
                top : ModelState.RemainingErrors,
                userId : UserId);

            AddErrorsAndThrowIfInvalid(result.Errors);

            // Return
            return(entities.Select(e => e.Id).ToList());
        }
Beispiel #2
0
        private async Task <EntitiesResult <AccountType> > SetIsActive(List <int> ids, ActionArguments args, bool isActive)
        {
            await Initialize();

            // Check user permissions
            var action       = "IsActive";
            var actionFilter = await UserPermissionsFilter(action, cancellation : default);

            ids = await CheckActionPermissionsBefore(actionFilter, ids);

            // Execute and return
            using var trx = TransactionFactory.ReadCommitted();
            OperationOutput output = await _behavior.Repository.AccountTypes__Activate(
                ids : ids,
                isActive : isActive,
                validateOnly : ModelState.IsError,
                top : ModelState.RemainingErrors,
                userId : UserId);

            AddErrorsAndThrowIfInvalid(output.Errors);

            var result = (args.ReturnEntities ?? false) ?
                         await GetByIds(ids, args, action, cancellation : default) :
                         EntitiesResult <AccountType> .Empty();

            // Check user permissions again
            await CheckActionPermissionsAfter(actionFilter, ids, result.Data);

            trx.Complete();
            return(result);
        }
Beispiel #3
0
    private IEnumerator PlayCor(OperationInput input, OperationOutput output, Action afterFinished)
    {
        yield return(PlayInput(input));

        foreach (var episode in output.episodes)
        {
            switch (episode.etype)
            {
            case OperationOutput.EpisodeType.ELIMINATION:
                yield return(PlayEminination(episode));

                break;

            case OperationOutput.EpisodeType.REFILL:
                yield return(PlayRefill(episode));

                break;

            case OperationOutput.EpisodeType.SHUFFLE:
                yield return(PlayShuffle(episode));

                break;

            default:
                break;
            }
        }

        afterFinished.Invoke();

        yield break;
    }
        public async Task <OperationOutput <UserDetails> > GetUserByHandle(string userHandle)
        {
            var user = await dbContext.UserDetails.FirstOrDefaultAsync(u => u.UserHandle.Equals(userHandle));

            if (user == null)
            {
                return(OperationOutput <UserDetails> .Failed("User with handle not found"));
            }
            return(OperationOutput <UserDetails> .Success(user));
        }
Beispiel #5
0
        public List <WSOperation> GetOperations()
        {
            List <WSOperation> lst = new List <WSOperation>();

            if (serviceDescription != null)
            {
                foreach (Service ser in serviceDescription.Services)
                {
                    String webServiceName = ser.Name.ToString();
                    foreach (Port port in ser.Ports)
                    {
                        string  portName = port.Name;
                        string  binding  = port.Binding.Name;
                        Binding bind     = bindColl[binding];

                        if (bind != null)
                        {
                            PortType portTyp = portTypColl[bind.Type.Name];

                            foreach (Operation op in portTyp.Operations)
                            {
                                WSOperation operObj = new WSOperation();
                                operObj.ClassName  = webServiceName;
                                operObj.MethodName = op.Name;

                                if (lst.Where(it => it.ClassName.Equals(operObj.ClassName) && it.MethodName.Equals(operObj.MethodName)).Count() == 0)
                                {
                                    OperationMessageCollection opMsgColl = op.Messages;
                                    OperationInput             opInput   = opMsgColl.Input;
                                    OperationOutput            opOutput  = opMsgColl.Output;
                                    string inputMsg  = opInput.Message.Name;
                                    string outputMsg = opOutput.Message.Name;

                                    Message            msgInput   = msgColl[inputMsg];
                                    List <WSParameter> InputParam = GetParameters(msgInput);

                                    Message            msgOutput    = msgColl[outputMsg];
                                    List <WSParameter> OutputParams = GetParameters(msgOutput);

                                    operObj.Parameters = InputParam;
                                    if (OutputParams != null && OutputParams.Count > 0)
                                    {
                                        operObj.ReturnType = OutputParams[0].TypeName;
                                    }

                                    lst.Add(operObj);
                                }
                            }
                        }
                    }
                }
            }
            return(lst);
        }
        public async Task <OperationOutput <UserDetails> > AddUserDetails(UserDetails userDetails)
        {
            if (dbContext.UserDetails.Any(ud => ud.UserHandle.Equals(userDetails.UserHandle)))
            {
                return(OperationOutput <UserDetails> .Failed("User exisist with the given handle"));
            }

            dbContext.UserDetails.Add(userDetails);
            await dbContext.SaveChangesAsync();

            return(OperationOutput <UserDetails> .Success(userDetails));
        }
Beispiel #7
0
        public static OperationBitcoinOutput ToBitcoinOutput(this OperationOutput output, IAddressValidator addressValidator)
        {
            var address = addressValidator.GetBitcoinAddress(output.Address);

            if (address == null)
            {
                throw new BusinessException("Invalid bitcoin address", ErrorCode.BadInputParameter);
            }
            return(new OperationBitcoinOutput
            {
                Address = address,
                Amount = new Money(output.Amount)
            });
        }
Beispiel #8
0
        internal ReturnValue(OperationOutput returnValue, TinyXdto.XdtoFactory factory)
        {
            Documentation   = returnValue.Documentation;
            MessagePartName = "";

            OutputParamNames = new List <string> ();

            var message = returnValue.Operation.PortType.ServiceDescription.Messages [returnValue.Message.Name];

            foreach (var oPart in message.Parts)
            {
                var returnPart = oPart as MessagePart;
                var package    = factory.Packages.Get(returnPart.Element.Namespace);
                if (package == null)
                {
                    continue;
                }

                var type = package.Get(returnPart.Element.Name);
                if (type == null)
                {
                    continue;
                }

                ResponseType = type as XdtoObjectType;

                if (ResponseType == null && Type == null)
                {
                    Type = type;
                    continue;
                }
                else
                {
                    foreach (var property in ResponseType.Properties)
                    {
                        if (property.LocalName == "return")
                        {
                            Type = property.Type;
                        }
                        else
                        {
                            OutputParamNames.Add(property.LocalName);
                        }
                    }
                }

                // Поддерживаем сообщения только из одной части
                break;
            }
        }
Beispiel #9
0
        private async Task <EntitiesResult <Currency> > SetIsActive(List <string> ids, ActionArguments args, bool isActive)
        {
            await Initialize();

            // Check user permissions
            var action       = "IsActive";
            var actionFilter = await UserPermissionsFilter(action, cancellation : default);

            ids = await CheckActionPermissionsBefore(actionFilter, ids);

            var settings = await _behavior.Settings();

            foreach (var(id, index) in ids.Indexed())
            {
                if (ids.Any(id => id != null && id == settings.FunctionalCurrencyId))
                {
                    string path = $"[{index}]";
                    string msg  = _localizer["Error_CannotDeactivateTheFunctionalCurrency"];

                    ModelState.AddError(path, msg);
                }
            }

            // Execute and return
            using var trx = TransactionFactory.ReadCommitted();
            OperationOutput output = await _behavior.Repository.Currencies__Activate(
                ids : ids,
                isActive : isActive,
                validateOnly : ModelState.IsError,
                top : ModelState.RemainingErrors,
                userId : UserId);

            AddErrorsAndThrowIfInvalid(output.Errors);

            var result = (args.ReturnEntities ?? false) ?
                         await GetByIds(ids, args, action, cancellation : default) :
                         EntitiesResult <Currency> .Empty();

            // Check user permissions again
            await CheckActionPermissionsAfter(actionFilter, ids, result.Data);

            trx.Complete();
            return(result);
        }
        public async Task <EntitiesResult <ResourceDefinition> > UpdateState(List <int> ids, UpdateStateArguments args)
        {
            await Initialize();

            // Check user permissions
            var action       = "State";
            var actionFilter = await UserPermissionsFilter(action, cancellation : default);

            ids = await CheckActionPermissionsBefore(actionFilter, ids);

            // C# Validation
            if (string.IsNullOrWhiteSpace(args.State))
            {
                throw new ServiceException(_localizer[ErrorMessages.Error_Field0IsRequired, _localizer["State"]]);
            }

            if (!DefStates.All.Contains(args.State))
            {
                string validStates = string.Join(", ", DefStates.All);
                throw new ServiceException($"'{args.State}' is not a valid definition state, valid states are: {validStates}");
            }

            // Execute and return
            using var trx = TransactionFactory.ReadCommitted();
            OperationOutput output = await _behavior.Repository.ResourceDefinitions__UpdateState(
                ids : ids,
                state : args.State,
                validateOnly : ModelState.IsError,
                top : ModelState.RemainingErrors,
                userId : UserId);

            AddErrorsAndThrowIfInvalid(output.Errors);

            // Prepare result
            var result = (args.ReturnEntities ?? false) ?
                         await GetByIds(ids, args, action, cancellation : default) :
                         EntitiesResult <ResourceDefinition> .Empty();

            // Check user permissions again
            await CheckActionPermissionsAfter(actionFilter, ids, result.Data);

            trx.Complete();
            return(result);
        }
Beispiel #11
0
        /// <summary>
        /// Add a new user to the system
        /// </summary>
        /// <param name="userModel"> user data</param>
        /// <returns>Added user</returns>
        public async Task <OperationOutput <ApplicationUser> > AddUser(ApplicationUserModel userModel)
        {
            if (userModel == null)
            {
                return(OperationOutput <ApplicationUser> .Failed("Arguments Null"));
            }

            if (String.IsNullOrWhiteSpace(userModel.Email) || String.IsNullOrWhiteSpace(userModel.UserName))
            {
                return(OperationOutput <ApplicationUser> .Failed("Arguments Invalid"));
            }

            try
            {
                if (dbContext.Users.Any(u => u.Email.Equals(userModel.Email)))
                {
                    return(OperationOutput <ApplicationUser> .Failed("User Exists"));
                }

                var user = new ApplicationUser
                {
                    Id             = Guid.NewGuid(),
                    UserName       = userModel.UserName,
                    Email          = userModel.Email,
                    PasswordHash   = Encoding.UTF8.GetString(MySHA256.ComputeHash(Encoding.UTF8.GetBytes(userModel.Password + "MySecret"))),
                    Gender         = userModel.Gender,
                    ProfilePicture = new Image
                    {
                        Id  = Guid.NewGuid(),
                        Url = userModel.Gender == Gender.Male ? "/images/profile_m.png" : "/images/profile_f.png"
                    }
                };

                dbContext.Users.Add(user);
                await dbContext.SaveChangesAsync();

                return(OperationOutput <ApplicationUser> .Success(user));
            }
            catch (Exception ex)
            {
                return(OperationOutput <ApplicationUser> .Failed("Internal Server Error", ex.Message));
            }
        }
        private List <ServiceDefinition> GetServices(ServiceDescription serviceDescription, WsdlHandlerConfiguration wsdlHandlerConfiguration)
        {
            var services = new List <ServiceDefinition>();

            foreach (PortType portType in serviceDescription.PortTypes)
            {
                foreach (Operation operation in portType.Operations)
                {
                    ServiceDefinition serviceDefinition = new ServiceDefinition(wsdlHandlerConfiguration)
                    {
                        ServiceName = operation.Name
                    };

                    foreach (OperationMessage message in operation.Messages)
                    {
                        var parameter = serviceDescription.Messages.Cast <Message>().FirstOrDefault(x => x.Name == message.Message.Name);

                        OperationInput operationInput = message as OperationInput;
                        if (operationInput != null)
                        {
                            serviceDefinition.InputType          = parameter != null && parameter.Parts.Count > 0 ? parameter.Parts[0].Type.Name : String.Empty;
                            serviceDefinition.InputParameterName = parameter != null && parameter.Parts.Count > 0 ? parameter.Parts[0].Name : String.Empty;
                        }
                        OperationOutput operationOutput = message as OperationOutput;
                        if (operationOutput != null)
                        {
                            serviceDefinition.OutputType          = parameter != null && parameter.Parts.Count > 0 ? parameter.Parts[0].Type.Name : String.Empty;
                            serviceDefinition.OutputParameterName = parameter != null && parameter.Parts.Count > 0 ? parameter.Parts[0].Name : String.Empty;
                        }
                    }
                    serviceDefinition.Input  = GetTypeDefinition(serviceDefinition.InputType);
                    serviceDefinition.Output = GetTypeDefinition(serviceDefinition.OutputType);
                    services.Add(serviceDefinition);
                }
            }
            return(services);
        }
        private static PortType ConstructPortTypes(InterfaceContract serviceInterfaceContract, System.Web.Services.Description.ServiceDescription desc, string portTypeName)
        {
            PortTypeCollection portTypes = desc.PortTypes;
            PortType           portType  = new PortType();

            portType.Name          = portTypeName;
            portType.Documentation = serviceInterfaceContract.ServiceDocumentation;

            // Add each operation and it's corresponding in/out messages to the WSDL Port Type.
            foreach (Operation op in serviceInterfaceContract.Operations)
            {
                FxOperation tempOperation = new FxOperation();
                tempOperation.Name          = op.Name;
                tempOperation.Documentation = op.Documentation;
                int i = 0;

                OperationInput operationInput = new OperationInput();
                operationInput.Message = new XmlQualifiedName(op.MessagesCollection[i].Name, desc.TargetNamespace);

                tempOperation.Messages.Add(operationInput);

                if (op.Mep == Mep.RequestResponse)
                {
                    OperationOutput operationOutput = new OperationOutput();
                    operationOutput.Message = new XmlQualifiedName(op.MessagesCollection[i + 1].Name, desc.TargetNamespace);

                    tempOperation.Messages.Add(operationOutput);
                }

                portType.Operations.Add(tempOperation);
                i++;
            }

            portTypes.Add(portType);
            return(portType);
        }
Beispiel #14
0
	private IEnumerator PlayRefill(OperationOutput.Episode ep)
	{
		foreach (var f in ep.refillFlow.NonFillMovements)
		{
			MoveCell(f.src.x, f.src.y, f.dst.x, f.dst.y);
		}
		foreach (var f in ep.refillFlow.FillMovements)
		{
			InsertCell(ep.refillSlots[f.dst.y, f.dst.x], new Pos2D(f.dst.x, f.dst.y));
		}
		foreach (var f in ep.refillFlow.OnSpotList)
		{
			InsertCell(ep.refillSlots[f.y, f.x], new Pos2D(f.x, f.y));
		}

		if (ep.refillFlow.OnSpotList.Count > 0)
		{
			var start = Time.time;
			yield return PlayDuration(start, start + eliminationTime, (now)=>{
				var alpha = Mathf.Min(1, (now - start) / eliminationTime);
				foreach (var p in ep.refillFlow.OnSpotList)
				{
					cells[p.y, p.x].SetAlpha(alpha);
				}
			});
		}

		var moves = new List<MoveCellHelper>();
		foreach (var f in ep.refillFlow.FillMovements)
		{
			moves.Add(CreateMoveCellHelper(Time.time, cells[f.dst.y, f.dst.x], f.movements));
		}
		foreach (var f in ep.refillFlow.NonFillMovements)
		{
			moves.Add(CreateMoveCellHelper(Time.time, cells[f.dst.y, f.dst.x], f.movements));
		}

		yield return PlayMovements(moves);

		yield break;
	}
    public static void Main()
    {
        try
        {
            ServiceDescription myDescription =
                ServiceDescription.Read("AddNumbersIn_cs.wsdl");

            // Add the ServiceHttpPost binding.
            Binding myBinding = new Binding();
            myBinding.Name = "ServiceHttpPost";
            XmlQualifiedName myXmlQualifiedName =
                new XmlQualifiedName("s0:ServiceHttpPost");
            myBinding.Type = myXmlQualifiedName;
            HttpBinding myHttpBinding = new HttpBinding();
            myHttpBinding.Verb = "POST";
            myBinding.Extensions.Add(myHttpBinding);

            // Add the operation name AddNumbers.
            OperationBinding myOperationBinding = new OperationBinding();
            myOperationBinding.Name = "AddNumbers";
            HttpOperationBinding myOperation = new HttpOperationBinding();
            myOperation.Location = "/AddNumbers";
            myOperationBinding.Extensions.Add(myOperation);

            // Add the input binding.
            InputBinding       myInput = new InputBinding();
            MimeContentBinding postMimeContentbinding =
                new MimeContentBinding();
            postMimeContentbinding.Type = "application/x-www-form-urlencoded";
            myInput.Extensions.Add(postMimeContentbinding);

            // Add the InputBinding to the OperationBinding.
            myOperationBinding.Input = myInput;

            // Add the ouput binding.
            OutputBinding  myOutput           = new OutputBinding();
            MimeXmlBinding postMimeXmlbinding = new MimeXmlBinding();
            postMimeXmlbinding.Part = "Body";
            myOutput.Extensions.Add(postMimeXmlbinding);

            // Add the OutPutBinding to the OperationBinding.
            myOperationBinding.Output = myOutput;

            myBinding.Operations.Add(myOperationBinding);
            myDescription.Bindings.Add(myBinding);

            // Add the port definition.
            Port postPort = new Port();
            postPort.Name    = "ServiceHttpPost";
            postPort.Binding = new XmlQualifiedName("s0:ServiceHttpPost");
            HttpAddressBinding postAddressBinding = new HttpAddressBinding();
            postAddressBinding.Location = "http://localhost/Service_cs.asmx";
            postPort.Extensions.Add(postAddressBinding);
            myDescription.Services[0].Ports.Add(postPort);

            // Add the post port type definition.
            PortType postPortType = new PortType();
            postPortType.Name = "ServiceHttpPost";
            Operation postOperation = new Operation();
            postOperation.Name = "AddNumbers";
            OperationMessage postInput =
                (OperationMessage) new OperationInput();
            postInput.Message =
                new XmlQualifiedName("s0:AddNumbersHttpPostIn");
// <Snippet2>
            OperationOutput postOutput = new OperationOutput();
            postOutput.Message =
                new XmlQualifiedName("s0:AddNumbersHttpPostOut");

            postOperation.Messages.Add(postInput);
            postOperation.Messages.Add(postOutput);
            postPortType.Operations.Add(postOperation);
// </Snippet2>
            myDescription.PortTypes.Add(postPortType);

            // Add the first message information.
            Message postMessage1 = new Message();
            postMessage1.Name = "AddNumbersHttpPostIn";
            MessagePart postMessagePart1 = new MessagePart();
            postMessagePart1.Name = "firstnumber";
            postMessagePart1.Type = new XmlQualifiedName("s:string");

            // Add the second message information.
            MessagePart postMessagePart2 = new MessagePart();
            postMessagePart2.Name = "secondnumber";
            postMessagePart2.Type = new XmlQualifiedName("s:string");
            postMessage1.Parts.Add(postMessagePart1);
            postMessage1.Parts.Add(postMessagePart2);
            Message postMessage2 = new Message();
            postMessage2.Name = "AddNumbersHttpPostOut";

            // Add the third message information.
            MessagePart postMessagePart3 = new MessagePart();
            postMessagePart3.Name    = "Body";
            postMessagePart3.Element = new XmlQualifiedName("s0:int");
            postMessage2.Parts.Add(postMessagePart3);

            myDescription.Messages.Add(postMessage1);
            myDescription.Messages.Add(postMessage2);

            // Write the ServiceDescription as a WSDL file.
            myDescription.Write("AddNumbersOut_cs.wsdl");
            Console.WriteLine("WSDL file named AddNumbersOut_cs.Wsdl" +
                              " created successfully.");
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception caught!!!");
            Console.WriteLine("Source : " + e.Source);
            Console.WriteLine("Message : " + e.Message);
        }
    }
Beispiel #16
0
        ContractExportMap ExportContractInternal(ContractDescription contract)
        {
            if (ExportedContracts.ContainsKey(contract))
            {
                return(ExportedContracts [contract]);
            }

            QName qname = new QName(contract.Name, contract.Namespace);

            if (ExportedContracts.Any(m => m.Value.QName == qname))
            {
                throw new ArgumentException(String.Format(
                                                "A ContractDescription with Namespace : {0} and Name : {1} has already been exported.",
                                                contract.Namespace, contract.Name));
            }

            WSServiceDescription sd = GetServiceDescription(contract.Namespace);

            List <IWsdlExportExtension> extensions = new List <IWsdlExportExtension> ();

            foreach (IWsdlExportExtension extn in contract.Behaviors.FindAll <IWsdlExportExtension> ())
            {
                extensions.Add(extn);
            }

            XmlDocument xdoc = new XmlDocument();

            PortType ws_port = new PortType();

            ws_port.Name = contract.Name;

            foreach (OperationDescription sm_op in contract.Operations)
            {
                Operation ws_op = new Operation();
                ws_op.Name = sm_op.Name;

                foreach (MessageDescription sm_md in sm_op.Messages)
                {
                    //OperationMessage
                    OperationMessage ws_opmsg;
                    WSMessage        ws_msg = new WSMessage();
                    MessagePart      ws_msgpart;
                    if (sm_md.Direction == MessageDirection.Input)
                    {
                        ws_opmsg    = new OperationInput();
                        ws_msg.Name = String.Concat(ws_port.Name, "_", ws_op.Name, "_", "InputMessage");
                        ws_msgpart  = ExportMessageBodyDescription(sm_md.Body, ws_op.Name, sd.TargetNamespace);
                    }
                    else
                    {
                        ws_opmsg    = new OperationOutput();
                        ws_msg.Name = String.Concat(ws_port.Name, "_", ws_op.Name, "_", "OutputMessage");
                        ws_msgpart  = ExportMessageBodyDescription(sm_md.Body, ws_op.Name + "Response", sd.TargetNamespace);
                    }
                    ws_msg.Parts.Add(ws_msgpart);

                    /* FIXME: Faults */

                    //Action
                    XmlAttribute attr = xdoc.CreateAttribute("wsaw", "Action", "http://www.w3.org/2006/05/addressing/wsdl");
                    attr.Value = sm_md.Action;
                    ws_opmsg.ExtensibleAttributes = new XmlAttribute [] { attr };

                    //FIXME: Set .Input & .Output

                    ws_opmsg.Message = new QName(ws_msg.Name, sd.TargetNamespace);
                    ws_op.Messages.Add(ws_opmsg);
                    sd.Messages.Add(ws_msg);
                }

                ws_port.Operations.Add(ws_op);

                foreach (IWsdlExportExtension extn in sm_op.Behaviors.FindAll <IWsdlExportExtension> ())
                {
                    extensions.Add(extn);
                }
            }

            //Add Imports for <types
            XmlSchema xs_import = new XmlSchema();

            xs_import.TargetNamespace = String.Concat(
                contract.Namespace,
                contract.Namespace.EndsWith("/") ? "" : "/",
                "Imports");
            foreach (XmlSchema schema in GeneratedXmlSchemas.Schemas())
            {
                XmlSchemaImport imp = new XmlSchemaImport();
                imp.Namespace = schema.TargetNamespace;
                xs_import.Includes.Add(imp);
            }
            sd.Types.Schemas.Add(xs_import);

            sd.PortTypes.Add(ws_port);
            var map = new ContractExportMap(qname, contract, extensions);

            ExportedContracts.Add(contract, map);

            WsdlContractConversionContext context = new WsdlContractConversionContext(contract, ws_port);

            foreach (IWsdlExportExtension extn in extensions)
            {
                extn.ExportContract(this, context);
            }

            return(map);
        }
Beispiel #17
0
 public void Play(OperationInput input, OperationOutput output, Action afterFinished)
 {
     StartCoroutine(RecursiveCoroutine.Recursion(PlayCor(input, output, afterFinished)));
 }
Beispiel #18
0
	private IEnumerator PlayShuffle(OperationOutput.Episode ep)
	{
		var start = Time.time;
		var middle = start + shuffleTime / 2;
		var end = start + shuffleTime;
		yield return PlayDuration(start, middle, (now)=>{
			var gray = Math.Max(0, (middle - now) / (middle - start));
			var color = new Color(gray, gray, gray);
			for (int y = 0; y < ep.shuffle.GetLength(0); y++)
			{
				for (int x = 0; x < ep.shuffle.GetLength(1); x++)
				{
					if (ep.shuffle[y, x].category == SlotAttribute.Category.TARGET)
					{
						cells[y, x].SetColor(color);
					}
				}
			}
		});

		for (int y = 0; y < ep.shuffle.GetLength(0); y++)
		{
			for (int x = 0; x < ep.shuffle.GetLength(1); x++)
			{
				if (ep.shuffle[y, x].category == SlotAttribute.Category.TARGET)
				{
					cells[y, x].Sync(ep.shuffle[y, x]);
				}
			}
		}

		yield return PlayDuration(middle, end, (now)=>{
			var gray = Math.Min(1, (now - middle) / (end - middle));
			var color = new Color(gray, gray, gray);
			for (int y = 0; y < ep.shuffle.GetLength(0); y++)
			{
				for (int x = 0; x < ep.shuffle.GetLength(1); x++)
				{
					if (ep.shuffle[y, x].category == SlotAttribute.Category.TARGET)
					{
						cells[y, x].SetColor(color);
					}
				}
			}
		});

		yield break;
	}
        public async Task <IBuiltTransaction> GetTransferTransactionAsync(OperationInput fromAddress, OperationOutput toAddress, bool includeFee)
        {
            var input  = fromAddress.ToBitcoinInput(_addressValidator);
            var output = toAddress.ToBitcoinOutput(_addressValidator);

            var builder = new TransactionBuilder();

            var coins = await GetUnspentCoins(input);

            builder.AddCoins(coins);

            var addressBalance = coins.Sum(o => o.Amount);

            if (addressBalance < input.Amount)
            {
                throw new BusinessException($"The sum of total applicable outputs is less than the required : {input.Amount.Satoshi} satoshis.",
                                            ErrorCode.NotEnoughFundsAvailable);
            }

            var sentFees = Money.Zero;

            var change = addressBalance - input.Amount;

            if (change < new TxOut(Money.Zero, input.Address).GetDustThreshold(builder.StandardTransactionPolicy.MinRelayTxFee).Satoshi)
            {
                builder.SendFees(change);
                sentFees = change;
            }

            builder.Send(output.Address, input.Amount)
            .SetChange(input.Address);

            var calculatedFee = await _feeService.CalcFeeForTransactionAsync(builder) - sentFees;

            var requiredBalance = input.Amount + (includeFee ? Money.Zero : calculatedFee);

            if (addressBalance < requiredBalance)
            {
                throw new BusinessException(
                          $"The sum of total applicable outputs is less than the required : {requiredBalance} satoshis.",
                          ErrorCode.NotEnoughFundsAvailable);
            }

            if (includeFee)
            {
                if (calculatedFee > input.Amount)
                {
                    throw new BusinessException(
                              $"The sum of total applicable outputs is less than the required fee:{calculatedFee} satoshis.",
                              ErrorCode.BalanceIsLessThanFee);
                }
                builder.SubtractFees();
            }

            if (calculatedFee > 0)
            {
                builder.SendFees(calculatedFee);
            }
            var tx = builder.BuildTransaction(false);

            var usedCoins = builder.FindSpentCoins(tx).ToArray();

            return(BuiltTransaction.Create(tx, tx.GetFee(usedCoins), usedCoins.Cast <Coin>()));
        }
Beispiel #20
0
	public void Play(OperationInput input, OperationOutput output, Action afterFinished)
	{
		StartCoroutine(RecursiveCoroutine.Recursion(PlayCor(input, output, afterFinished)));
	}
Beispiel #21
0
        public void importWSDL(String filename, EA.Repository repository, EA.Diagram diagram)
        {
            logger.log("Importing: " + filename);

            EA.Package package = repository.GetPackageByID(diagram.PackageID);

            XmlTextReader reader = new XmlTextReader(filename);

            ServiceDescription wsdl = ServiceDescription.Read(reader);

            foreach (PortType pt in wsdl.PortTypes)
            {
                //logger.log("PortType: "+ pt.Name);

                EA.Element clazz = package.Elements.AddNew(pt.Name, APIAddinClass.EA_TYPE_CLASS);
                clazz.Notes   = wsdl.Documentation;
                clazz.Version = wsdl.TargetNamespace;
                package.Update();

                EA.DiagramObject diaObj = diagram.DiagramObjects.AddNew(pt.Name, "");
                diagram.Update();

                diaObj.ElementID = clazz.ElementID;

                diaObj.Update();


                foreach (Operation op in pt.Operations)
                {
                    //logger.log("\tOperation: "+ op.Name);

                    EA.Method method = clazz.Methods.AddNew(op.Name, "");

                    method.Name = op.Name;

                    method.Update();

                    clazz.Update();

                    clazz.Methods.Refresh();

                    OperationInput  oi = null;
                    OperationOutput oo = null;
                    foreach (OperationMessage msg in op.Messages)
                    {
                        if (msg is OperationInput)
                        {
                            oi = msg as OperationInput;
                        }

                        else if (msg is OperationOutput)
                        {
                            oo = msg as OperationOutput;
                        }
                        else
                        {
                        }
                    }

                    if (oi == null || oo == null)
                    {
                        return;
                    }

                    foreach (Message m in wsdl.Messages)
                    {
                        //logger.log("\n\tMessage: " + m.Name);
                        //logger.log("\tOperationInput: " + oi.Message.Name);

                        if (m.Name.Equals(oi.Message.Name))
                        {
                            foreach (MessagePart p in m.Parts)
                            {
                                if (!p.Name.Equals("Header"))
                                {
                                    addParameter(repository, method, p.Element, wsdl);
                                }
                            }
                        }
                        else if (m.Name.Equals(oo.Message.Name))
                        {
                            foreach (MessagePart p in m.Parts)
                            {
                                if (!p.Name.Equals("Header"))
                                {
                                    addReturn(repository, method, p.Element, wsdl);
                                }
                            }
                        }
                    }
                }
            }
            diagram.DiagramObjects.Refresh();
        }
        public async Task <EntitiesResult <DocumentDefinition> > UpdateState(List <int> ids, UpdateStateArguments args)
        {
            await Initialize();

            // Check user permissions
            var action       = "State";
            var actionFilter = await UserPermissionsFilter(action, cancellation : default);

            ids = await CheckActionPermissionsBefore(actionFilter, ids);

            // Validation
            if (string.IsNullOrWhiteSpace(args.State))
            {
                throw new ServiceException(_localizer[ErrorMessages.Error_Field0IsRequired, _localizer["State"]]);
            }

            if (!DefStates.All.Contains(args.State))
            {
                string validStates = string.Join(", ", DefStates.All);
                throw new ServiceException($"'{args.State}' is not a valid definition state, valid states are: {validStates}.");
            }

            var defs = await _behavior.Definitions();

            int jvDefId = defs.ManualJournalVouchersDefinitionId;

            int index = 0;

            ids.ForEach(id =>
            {
                if (id == jvDefId)
                {
                    string path = $"[{index}]";
                    string msg  = _localizer["Error_CannotModifySystemItem"];

                    ModelState.AddError(path, msg);
                }

                index++;
            });

            // Execute
            using var trx = TransactionFactory.ReadCommitted();
            OperationOutput output = await _behavior.Repository.DocumentDefinitions__UpdateState(
                ids : ids,
                state : args.State,
                validateOnly : ModelState.IsError,
                top : ModelState.RemainingErrors,
                userId : UserId);

            AddErrorsAndThrowIfInvalid(output.Errors);

            // Prepare result
            var result = (args.ReturnEntities ?? false) ?
                         await GetByIds(ids, args, action, cancellation : default) :
                         EntitiesResult <DocumentDefinition> .Empty();

            // Check user permissions again
            await CheckActionPermissionsAfter(actionFilter, ids, result.Data);

            trx.Complete();
            return(result);
        }
// <Snippet1>
    public static void MyMethod(
        ServiceDescriptionBaseCollection myServiceCollection)
    {
        Type myType = myServiceCollection.GetType();

        if (myType.Equals(
                typeof(System.Web.Services.Description.ServiceCollection)))
        {
            // Remove the services at index 0 of the collection.
            ((ServiceCollection)myServiceCollection).Remove(
                myServiceDescription.Services[0]);

            // Build a new Service.
            Service myService = new Service();
            myService.Name = "MathService";
            XmlQualifiedName myXmlQualifiedName =
                new XmlQualifiedName("s0:MathServiceSoap");

            // Build a new Port for SOAP.
            Port mySoapPort = new Port();
            mySoapPort.Name    = "MathServiceSoap";
            mySoapPort.Binding = myXmlQualifiedName;
            SoapAddressBinding mySoapAddressBinding = new SoapAddressBinding();
            mySoapAddressBinding.Location = "http://localhost/" +
                                            "ServiceDescriptionBaseCollection/AddSubtractService.CS.asmx";
            mySoapPort.Extensions.Add(mySoapAddressBinding);

            // Build a new Port for HTTP-GET.
            XmlQualifiedName myXmlQualifiedName2 =
                new XmlQualifiedName("s0:MathServiceHttpGet");
            Port myHttpGetPort = new Port();
            myHttpGetPort.Name    = "MathServiceHttpGet";
            myHttpGetPort.Binding = myXmlQualifiedName2;
            HttpAddressBinding myHttpAddressBinding = new HttpAddressBinding();
            myHttpAddressBinding.Location = "http://localhost/" +
                                            "ServiceDescriptionBaseCollection/AddSubtractService.CS.asmx";
            myHttpGetPort.Extensions.Add(myHttpAddressBinding);

            // Add the ports to the Service.
            myService.Ports.Add(myHttpGetPort);
            myService.Ports.Add(mySoapPort);

            // Add the Service to the ServiceCollection.
            myServiceDescription.Services.Add(myService);
        }
        else if (myType.Equals(
                     typeof(System.Web.Services.Description.BindingCollection)))
        {
            // Remove the Binding in the BindingCollection at index 0.
            ((BindingCollection)myServiceCollection).Remove(
                myServiceDescription.Bindings[0]);

            // Build a new Binding.
            Binding myBinding = new Binding();
            myBinding.Name = "MathServiceSoap";
            XmlQualifiedName myXmlQualifiedName =
                new XmlQualifiedName("s0:MathServiceSoap");
            myBinding.Type = myXmlQualifiedName;
            SoapBinding mySoapBinding = new SoapBinding();
            mySoapBinding.Transport = "http://schemas.xmlsoap.org/soap/http";
            mySoapBinding.Style     = SoapBindingStyle.Document;

            // Create the operations for the binding.
            OperationBinding addOperationBinding = CreateOperationBinding(
                "Add", myServiceDescription.TargetNamespace);
            OperationBinding subtractOperationBinding = CreateOperationBinding(
                "Subtract", myServiceDescription.TargetNamespace);

            // Add the operations to the Binding.
            myBinding.Operations.Add(subtractOperationBinding);
            myBinding.Operations.Add(addOperationBinding);
            myBinding.Extensions.Add(mySoapBinding);

            // Add the Binding to the Bindings collection.
            myServiceDescription.Bindings.Add(myBinding);
        }
        else if (myType.Equals(
                     typeof(System.Web.Services.Description.PortTypeCollection)))
        {
            // Remove the PortType at index 0.
            ((PortTypeCollection)myServiceCollection).Remove(
                myServiceDescription.PortTypes[0]);

            // Build a new PortType.
            PortType myPortType = new PortType();
            myPortType.Name = "MathServiceSoap";

            // Build an Add Operation for the PortType.
            Operation myAddOperation = new Operation();
            myAddOperation.Name = "Add";

            // Build the Input and Output messages for the Operations.
            OperationInput   myOperationInputMessage1 = new OperationInput();
            XmlQualifiedName myXmlQualifiedName1      =
                new XmlQualifiedName("s0:AddSoapIn");
            myOperationInputMessage1.Message = myXmlQualifiedName1;

            OperationOutput  myOperationOutputMessage1 = new OperationOutput();
            XmlQualifiedName myXmlQualifiedName2       =
                new XmlQualifiedName("s0:AddSoapOut");
            myOperationOutputMessage1.Message = myXmlQualifiedName2;

            // Add the messages to the operations.
            myAddOperation.Messages.Add(myOperationInputMessage1);
            myAddOperation.Messages.Add(myOperationOutputMessage1);

            // Build an Add Operation for the PortType.
            Operation mySubtractOperation = new Operation();
            mySubtractOperation.Name = "Subtract";

            // Build the Input and Output messages for the operations.
            OperationInput   myOperationInputMessage2 = new OperationInput();
            XmlQualifiedName myXmlQualifiedName3      =
                new XmlQualifiedName("s0:SubtractSoapIn");
            myOperationInputMessage2.Message = myXmlQualifiedName3;
            OperationOutput  myOperationOutputMessage2 = new OperationOutput();
            XmlQualifiedName myXmlQualifiedName4       =
                new XmlQualifiedName("s0:SubtractSoapOut");
            myOperationOutputMessage2.Message = myXmlQualifiedName4;

            // Add the messages to the operations.
            mySubtractOperation.Messages.Add(myOperationInputMessage2);
            mySubtractOperation.Messages.Add(myOperationOutputMessage2);

            // Add the operations to the PortType.
            myPortType.Operations.Add(myAddOperation);
            myPortType.Operations.Add(mySubtractOperation);

            // Add the PortType to the collection.
            myServiceDescription.PortTypes.Add(myPortType);
        }
    }
Beispiel #24
0
        public ServiceDescription exportWSDL(EA.Repository repository, EA.Element component)
        {
            string faultnamespace = "http://www.iag.co.nz/soa/iagiaa/fault";
            string iaaNamespace   = "http://www.iag.co.nz/soa/iagiaa/v2";

            string wsdlNamespace = component.Version;

            ServiceDescription service = new ServiceDescription();

            service.TargetNamespace = wsdlNamespace;
            service.Name            = component.Name;

            service.Namespaces.Add("iaa", iaaNamespace);
            service.Namespaces.Add("fault", faultnamespace);
            service.Namespaces.Add("soa", wsdlNamespace);

            XmlSchema schema = new XmlSchema();

            service.Documentation = component.Notes;
            {
                schema.ElementFormDefault = XmlSchemaForm.Qualified;
                schema.TargetNamespace    = component.Version;

                {
                    XmlSchemaImport si = new XmlSchemaImport();
                    si.SchemaLocation = "iagiaa_.xsd";
                    si.Namespace      = iaaNamespace;
                    schema.Includes.Add(si);
                }
                {
                    XmlSchemaImport si = new XmlSchemaImport();
                    si.SchemaLocation = "iagiaa_fault.xsd";
                    si.Namespace      = faultnamespace;
                    schema.Includes.Add(si);
                }
                service.Types.Schemas.Add(schema);
            }

            Message faultMessage = new Message();
            {
                faultMessage.Name = "ErrorInfo";
                service.Messages.Add(faultMessage);

                MessagePart mp = new MessagePart();
                mp.Name = "ErrorInfo";
                XmlQualifiedName qn = new XmlQualifiedName("ErrorInfo", faultnamespace);
                mp.Element = qn;
                faultMessage.Parts.Add(mp);
            }



            Binding binding = new Binding();

            service.Bindings.Add(binding);
            binding.Name = component.Name;
            binding.Type = new XmlQualifiedName(component.Name, wsdlNamespace);

            Soap12Binding soapBinding = new Soap12Binding();

            binding.Extensions.Add(soapBinding);
            soapBinding.Transport = "http://schemas.xmlsoap.org/soap/http";

            PortType portType = new PortType();

            portType.Name = component.Name;
            service.PortTypes.Add(portType);

            foreach (EA.Method m in component.Methods)
            {
                {
                }

                {
                    Message inMessage = new Message();
                    inMessage.Name = m.Name + "SoapIn";
                    service.Messages.Add(inMessage);

                    MessagePart mp = new MessagePart();
                    mp.Name = "Header";
                    XmlQualifiedName qn = new XmlQualifiedName("ApplicationContext", iaaNamespace);
                    mp.Element = qn;
                    inMessage.Parts.Add(mp);

                    MessagePart ip = new MessagePart();
                    ip.Name = m.Name + "Part";
                    XmlQualifiedName iqn = new XmlQualifiedName(m.Name, wsdlNamespace);
                    ip.Element = iqn;
                    inMessage.Parts.Add(ip);
                }
                {
                    Message outMessage = new Message();
                    outMessage.Name = m.Name + "SoapOut";
                    service.Messages.Add(outMessage);

                    MessagePart ip = new MessagePart();
                    ip.Name = m.Name + "ResponsePart";
                    XmlQualifiedName iqn = new XmlQualifiedName(m.Name + "Response", wsdlNamespace);
                    ip.Element = iqn;
                    outMessage.Parts.Add(ip);
                }

                {
                    Operation operation = new Operation();
                    portType.Operations.Add(operation);
                    operation.Name = m.Name;

                    OperationInput oi = new OperationInput();
                    oi.Message = new XmlQualifiedName(component.Name + "SoapIn", component.Version);
                    operation.Messages.Add(oi);


                    OperationOutput oo = new OperationOutput();
                    oo.Message = new XmlQualifiedName(component.Name + "SoapOut", component.Version);
                    operation.Messages.Add(oo);

                    OperationFault of = new OperationFault();
                    of.Name    = faultMessage.Name;
                    of.Message = new XmlQualifiedName("ErrorInfo", component.Version);
                    operation.Faults.Add(of);
                }

                {
                    OperationBinding opBinding = new OperationBinding();
                    binding.Operations.Add(opBinding);
                    opBinding.Input  = new InputBinding();
                    opBinding.Output = new OutputBinding();
                    FaultBinding faultBinding = new FaultBinding();
                    opBinding.Faults.Add(faultBinding);

                    SoapHeaderBinding headerBinding = new SoapHeaderBinding();
                    opBinding.Input.Extensions.Add(headerBinding);
                    headerBinding.Message = new XmlQualifiedName(m.Name + "SoapIn", wsdlNamespace);
                    headerBinding.Part    = "Header";
                    headerBinding.Use     = SoapBindingUse.Literal;

                    SoapBodyBinding bodyBinding = new SoapBodyBinding();
                    opBinding.Input.Extensions.Add(bodyBinding);
                    bodyBinding.PartsString = m.Name + "Part";


                    SoapBodyBinding outBinding = new SoapBodyBinding();
                    opBinding.Output.Extensions.Add(outBinding);
                    outBinding.Use = SoapBindingUse.Literal;

                    faultBinding.Name = "ErrorResponseType";
                    SoapFaultBinding soapFaultBinding = new SoapFaultBinding();
                    faultBinding.Extensions.Add(soapFaultBinding);
                    soapFaultBinding.Use = SoapBindingUse.Literal;
                }
            }
            return(service);
        }
Beispiel #25
0
        /// <summary>
        /// CreateSourceFiles - Parse Wsdl Schema and generate DataContract, DataContractSerializer types,
        /// HostedServices and Client Proxies.
        /// </summary>
        /// <remarks>Currently only generates C# source files.</remarks>
        /// <param name="contractFilename">The name of a contract source code (.cs) file.</param>
        /// <param name="hostedServiceFilename">The name of a hosted service source code (.cs) file.</param>
        /// <param name="clientProxyFilename">The name of a client proxy source code (.cs) file.</param>
        /// <param name="targetPlatform">Specifies the target runtime platform.</param>
        public void CreateSourceFiles(string contractFilename, string hostedServiceFilename, string clientProxyFilename, TargetPlatform targetPlatform)
        {
            m_platform = targetPlatform;

            Logger.WriteLine("", LogLevel.Normal);
            Logger.WriteLine("Generating contract source: " + contractFilename + "...", LogLevel.Normal);

            if (contractFilename == null)
            {
                throw new ArgumentNullException("codeFilename", "You must pass a valid code filename.");
            }

            if (m_svcDesc.Types == null)
            {
                throw new Exception("No wsdl types found.");
            }

            string path = Path.GetDirectoryName(contractFilename).Trim();

            if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // Create code file stream
            FileStream   dcStream       = new FileStream(contractFilename, FileMode.Create, FileAccess.Write, FileShare.None);
            StreamWriter dcStreamWriter = new StreamWriter(dcStream);

            // Write the auto generated header
            dcStreamWriter.Write(AutoGenTextHeader.Message);

            try
            {
                // Set up data contract code generator
                CSharpCodeProvider   cSharpCP       = new CSharpCodeProvider();
                ICodeGenerator       codeGen        = cSharpCP.CreateGenerator(dcStreamWriter);
                CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions();
                codeGenOptions.BracingStyle = "C";

                // Cobble up a valid .net namespace. Turn any progression that's not a-z or A-Z to a single '.'
                string targetNamespaceName = CodeGenUtils.GenerateDotNetNamespace(m_svcDesc.TargetNamespace);

                // For some reason we have to force schemas to compile. Though it was suppose to automatically. Huh!
                foreach (XmlSchema schema in m_svcDesc.Types.Schemas)
                {
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    schemaSet.Add(schema);
                    schemaSet.Compile();
                }

                // Create new code namespace
                CodeNamespace targetNamespace = new CodeNamespace(targetNamespaceName);

                // Add data contract using directives
                CodeSnippetCompileUnit compileUnit = new CodeSnippetCompileUnit("using System;");
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using System.Xml;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                if (m_platform == TargetPlatform.MicroFramework)
                {
                    compileUnit.Value = "using System.Ext;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                    compileUnit.Value = "using System.Ext.Xml;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                }
                compileUnit.Value = "using Ws.ServiceModel;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Mtom;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Serialization;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlElement = Ws.Services.Xml.WsXmlNode;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlAttribute = Ws.Services.Xml.WsXmlAttribute;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlConvert = Ws.Services.Serialization.WsXmlConvert;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Namespaces.Add(targetNamespace);
                m_dcCodeGen.CodeNamespaces = compileUnit.Namespaces;

                Logger.WriteLine("", LogLevel.Normal);

                // Create HostedServices and ClientProxies collections
                HostedServices hostedServices = new HostedServices(targetNamespaceName);
                ClientProxies  clientProxies  = new ClientProxies(targetNamespaceName);

                // For each PortType process
                foreach (PortType portType in m_svcDesc.PortTypes)
                {
                    // For each operation in the port type:
                    // Get input and output message parts.
                    // If the message part is a simple type:
                    //   Build HostedService operation.
                    // Else if the message part is an element:
                    //   Find elements in Schema
                    //   If element type is native xml type:
                    //     Build HostedService operation.
                    //   Else if element references a simple or complex type:
                    //     If simpleType is base xml type with restrictions:
                    //       Build HostedService operation.
                    //     Else
                    //       Build DataContract and DataContractSerializer.
                    //       Build HostedService Operation.
                    //

                    // Create instance of a HostedService to hold the port type details
                    HostedService hostedService = new HostedService(portType.Name, m_svcDesc.TargetNamespace, m_platform);

                    // Create instance of ClientProxyGenerator
                    ClientProxy clientProxy = new ClientProxy(portType.Name, m_platform);

                    // Create service contract interface
                    CodeTypeDeclaration      serviceCodeType = new CodeTypeDeclaration("I" + portType.Name);
                    CodeAttributeArgument    codeAttr        = new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(m_svcDesc.TargetNamespace));
                    CodeAttributeDeclaration codeAttrDecl    = new CodeAttributeDeclaration("ServiceContract", codeAttr);
                    serviceCodeType.CustomAttributes.Add(codeAttrDecl);

                    // Check for Policy assertions. If found add policy assertion attributes. Policy assertion attributes
                    // are required to regenerate policy assertions when converting a service to Wsdl.
                    List <PolicyAssertion> policyAssertions = GetPolicyAssertions();
                    bool OptimizedMimeEncoded = false;
                    foreach (PolicyAssertion assert in policyAssertions)
                    {
                        serviceCodeType.CustomAttributes.Add(CreatePolicyAssertions(assert.Name, assert.Namespace.ToString(), assert.PolicyID));

                        // if Optimized Mime assertion id found set a processing flag
                        if (assert.Name == "OptimizedMimeSerialization")
                        {
                            OptimizedMimeEncoded = true;
                        }
                    }

                    // Add type declaration
                    serviceCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCodeType.IsInterface    = true;

                    // Create service contract callback client interface
                    CodeTypeDeclaration serviceCallbackCodeType = new CodeTypeDeclaration("I" + portType.Name + "Callback");

                    // Add type declaration
                    serviceCallbackCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCallbackCodeType.IsInterface    = true;

                    // If the binding contains a ref to Mtom encoding type set the Mtom flag
                    if (OptimizedMimeEncoded)
                    {
                        m_dcCodeGen.EncodingType   = MessageEncodingType.Mtom;
                        hostedService.EncodingType = MessageEncodingType.Mtom;
                        clientProxy.EncodingType   = MessageEncodingType.Mtom;
                    }

                    // Step through port operations, get method names and parse elements.
                    for (int pt_index = 0; pt_index < portType.Operations.Count; ++pt_index)
                    {
                        Operation operation     = portType.Operations[pt_index];
                        string    operationName = operation.Name;

                        string inputMessageName  = null;
                        string outputMessageName = null;
                        MessagePartCollection inputMessageParts  = null;
                        MessagePartCollection outputMessageParts = null;
                        string inAction  = null;
                        string outAction = null;
                        GetAction(portType, operation, m_svcDesc.TargetNamespace, ref inAction, ref outAction);

                        // Oneway request port type
                        if (operation.Messages.Flow == OperationFlow.OneWay)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Twoway request/response pattern
                        else if (operation.Messages.Flow == OperationFlow.RequestResponse)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Event pattern
                        else if (operation.Messages.Flow == OperationFlow.Notification)
                        {
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }

                        // Find input and output message parts collection in messages collection
                        // and store for later.
                        foreach (Message message in m_svcDesc.Messages)
                        {
                            if (inputMessageName != null)
                            {
                                if (message.Name == inputMessageName)
                                {
                                    inputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                            }

                            if (outputMessageName != null)
                            {
                                if (message.Name == outputMessageName)
                                {
                                    outputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                            }
                        }

                        try
                        {
                            // Try to generate Data Contracts and DataContractSerializers
                            GenerateTypeContracts(operation, inputMessageParts, outputMessageParts);

                            // If operation flow is notification (event) add OperationContract to ServiceContractCallback
                            // else add OperationContract to ServiceContract
                            if (operation.Messages.Flow == OperationFlow.Notification)
                            {
                                AddServiceOperationToInterface(operation, outAction, serviceCallbackCodeType);
                            }
                            else
                            {
                                AddServiceOperationToInterface(operation, inAction, serviceCodeType);
                            }
                        }
                        catch (Exception e)
                        {
                            dcStreamWriter.Close();
                            File.Delete(contractFilename);
                            Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                            return;
                        }
                    }

                    // Add serviceCodeType Service Contract interface to namespace
                    // A serviceCodeType is added even if the wsdl only contains notifications. In that case
                    // the contract will be empty but the ServiceContract attribute and CallbackContract argument
                    // will be used to point to the notification or callback contract interace
                    targetNamespace.Types.Add(serviceCodeType);

                    // If service contract callback type contains members add callback contract to namespace
                    // and add CallbackContract reference attribute to serviceCodeType contract.
                    if (serviceCallbackCodeType.Members.Count > 0)
                    {
                        // Add the callback argument to the service description attribute
                        CodeAttributeArgument callbackArg = new CodeAttributeArgument("CallbackContract",
                                                                                      new CodeTypeOfExpression(serviceCallbackCodeType.Name)
                                                                                      );
                        serviceCodeType.CustomAttributes[0].Arguments.Add(callbackArg);

                        // Add the callback interface to namespace
                        targetNamespace.Types.Add(serviceCallbackCodeType);
                    }

                    // If the hosted service has opeations add to Hosted Services collection for Code Gen
                    if (hostedService.ServiceOperations.Count > 0)
                    {
                        hostedServices.Add(hostedService);
                    }

                    // If the client Proxy service has opeations add to client proxy collection for Code Gen
                    if (clientProxy.ServiceOperations.Count > 0)
                    {
                        clientProxies.Add(clientProxy);
                    }
                }

                // MOD: 12-02-08 Added code to handle multiple type namespaces
                // Generate contract source file
                foreach (CodeNamespace codeNamespace in compileUnit.Namespaces)
                {
                    codeGen.GenerateCodeFromNamespace(codeNamespace, dcStreamWriter, codeGenOptions);
                }
                dcStreamWriter.Flush();
                dcStreamWriter.Close();

                // Generate Hosted Service code
                Logger.WriteLine("Generating Hosted Service source: " + hostedServiceFilename + "...", LogLevel.Normal);
                HostedServiceGenerator hsGen = new HostedServiceGenerator();
                hsGen.GenerateCode(hostedServiceFilename, hostedServices);

                // Generate Client proxy code
                Logger.WriteLine("Generating Client Proxy source: " + clientProxyFilename + "...", LogLevel.Normal);
                ClientProxyGenerator cpGen = new ClientProxyGenerator();
                cpGen.GenerateCode(clientProxyFilename, clientProxies);
            }
            catch (Exception e)
            {
                dcStreamWriter.Close();
                File.Delete(contractFilename);
                Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                throw new Exception("Failed to generate service code. ", e);
            }
        }
Beispiel #26
0
        private void CheckSoap()
        {
            bool signatureValid = true;

            this.Compiled();
            if (this._inputDocument == null)
            {
                return;
            }
            if (this._inputDocument.GetElementsByTagName("ds:Signature") != null)
            {
                this._validator = new SignatureValidator(this);
            }
            signatureValid = this._validator.Valid;
            object invokedObject = new object();

            object[] parameters = null;
            string   response;

            if (this._serviceDescription == null)
            {
                EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs("There is no Web Service Description available", this, NotificationLevel.Error));
            }
            else
            {
                if (!signatureValid)
                {
                    EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs("Signature validation failed", this, NotificationLevel.Error));
                    goto Abort;
                }

                Types types = this._serviceDescription.Types;
                PortTypeCollection   portTypes         = this._serviceDescription.PortTypes;
                MessageCollection    messages          = this._serviceDescription.Messages;
                PortType             porttype          = portTypes[0];
                Operation            operation         = porttype.Operations[0];
                OperationOutput      output            = operation.Messages[0].Operation.Messages.Output;
                OperationInput       input             = operation.Messages[0].Operation.Messages.Input;
                Message              messageOutput     = messages[output.Message.Name];
                Message              messageInput      = messages[input.Message.Name];
                MessagePart          messageOutputPart = messageOutput.Parts[0];
                MessagePart          messageInputPart  = messageInput.Parts[0];
                XmlSchema            xmlSchema         = types.Schemas[0];
                XmlSchemaElement     outputSchema      = (XmlSchemaElement)xmlSchema.Elements[messageOutputPart.Element];
                XmlSchemaElement     inputSchema       = (XmlSchemaElement)xmlSchema.Elements[messageInputPart.Element];
                XmlSchemaComplexType complexTypeOutput = (XmlSchemaComplexType)outputSchema.SchemaType;
                XmlSchemaSequence    sequenzTypeOutput = (XmlSchemaSequence)complexTypeOutput.Particle;
                XmlSchemaComplexType complexTypeInput  = (XmlSchemaComplexType)inputSchema.SchemaType;
                XmlSchemaSequence    sequenzTypeInput  = (XmlSchemaSequence)complexTypeInput.Particle;
                Hashtable            paramTypesTable   = new Hashtable();
                StringWriter         xmlStringWriter   = new StringWriter();
                xmlSchema.Write(xmlStringWriter);
                this._set = new DataSet();
                StringReader  sreader   = new StringReader(xmlStringWriter.ToString());
                XmlTextReader xmlreader = new XmlTextReader(sreader);
                this._set.ReadXmlSchema(xmlreader);
                if (sequenzTypeInput != null)
                {
                    foreach (XmlSchemaElement inputParam in sequenzTypeInput.Items)
                    {
                        XmlQualifiedName schemaName = inputParam.SchemaTypeName;
                        paramTypesTable.Add(inputParam.QualifiedName.Name, schemaName.Name);
                    }

                    XmlNamespaceManager manager = new XmlNamespaceManager(this._modifiedInputDocument.NameTable);
                    XmlElement          body    = (XmlElement)this._inputDocument.GetElementsByTagName("s:Body")[0];
                    manager.AddNamespace("s", body.NamespaceURI);
                    manager.AddNamespace("tns", "http://tempuri.org/");
                    XmlNode    node         = this._modifiedInputDocument.SelectSingleNode("s:Envelope/s:Body/" + "tns:" + this._set.Tables[0].TableName, manager);
                    XmlElement ele          = (XmlElement)node;
                    int        paramCounter = new Int32();
                    try
                    {
                        paramCounter = ele.ChildNodes.Count;
                    }

                    catch
                    {
                        EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs("Some params are missing", this, NotificationLevel.Error));
                    }
                    if (paramCounter != 0)
                    {
                        parameters = new Object[paramCounter];

                        for (int i = 0; i < paramCounter; i++)
                        {
                            string param     = ele.ChildNodes[i].InnerText;
                            Object paramType = paramTypesTable[ele.ChildNodes[i].LocalName];
                            if (paramType.ToString().Equals("int"))
                            {
                                if (!ele.ChildNodes[i].InnerText.Equals(""))
                                {
                                    try
                                    {
                                        parameters[i] = Convert.ToInt32((Object)ele.ChildNodes[i].InnerText);
                                    }
                                    catch (Exception e)
                                    {
                                        EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(e.Message, this, NotificationLevel.Error));
                                        goto Abort;
                                    }
                                }
                                else
                                {
                                    if (ele.ChildNodes[i].Name != null)
                                    {
                                        EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs("Parameter " + ele.ChildNodes[i].Name + " is missing", this, NotificationLevel.Error));
                                    }
                                    goto Abort;
                                }
                            }
                            if (paramType.ToString().Equals("string"))
                            {
                                if (!ele.ChildNodes[i].InnerText.Equals(""))
                                {
                                    try
                                    {
                                        parameters[i] = Convert.ToString((Object)ele.ChildNodes[i].InnerText);
                                    }
                                    catch (Exception e)
                                    {
                                        EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(e.Message, this, NotificationLevel.Error));
                                        goto Abort;
                                    }
                                }
                                else
                                {
                                    if (ele.ChildNodes[i].Name != null)
                                    {
                                        EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs("Parameter " + ele.ChildNodes[i].Name + " is missing", this, NotificationLevel.Error));
                                    }
                                    goto Abort;
                                }
                            }
                            if (paramType.ToString().Equals("double"))
                            {
                                if (!ele.ChildNodes[i].InnerText.Equals(""))
                                {
                                    try
                                    {
                                        parameters[i] = Convert.ToDouble((Object)ele.ChildNodes[i].InnerText);
                                    }
                                    catch (Exception e)
                                    {
                                        EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(e.Message, this, NotificationLevel.Error));
                                        goto Abort;
                                    }
                                }
                                else
                                {
                                    if (ele.ChildNodes[i].Name != null)
                                    {
                                        EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs("Parameter " + ele.ChildNodes[i].Name + " is missing", this, NotificationLevel.Error));
                                    }
                                    goto Abort;
                                }
                            }
                        }
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            if (parameters[i] == null)
                            {
                                goto Abort;
                            }
                        }
                        try
                        {
                            Type   typ        = this._service.GetType().GetMethod(operation.Name).ReturnType;
                            string returnType = typ.ToString();
                            if (!returnType.Equals("System.Void"))
                            {
                                invokedObject = this._service.GetType().GetMethod(operation.Name).Invoke(this._service, parameters).ToString();
                            }
                            else
                            {
                                this._service.GetType().GetMethod(operation.Name).Invoke(this._service, parameters).ToString();
                            }
                        }
                        catch (Exception e)
                        {
                            EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(e.Message, this, NotificationLevel.Error));
                            goto Abort;
                        }
                    }
                    else
                    {
                        if (sequenzTypeOutput != null)
                        {
                            try
                            {
                                invokedObject = this._service.GetType().GetMethod(operation.Name).Invoke(this._service, null).ToString();
                            }
                            catch (Exception e)
                            {
                                EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(e.Message, this, NotificationLevel.Error));
                                goto Abort;
                            }
                        }
                        else
                        {
                            this._service.GetType().GetMethod(operation.Name).Invoke(this._service, parameters);
                        }
                    }
                    response = invokedObject.ToString();
                    this.CreateResponse(response);
                }
            }
            Abort :;
        }
Beispiel #27
0
    public OperationOutput PerformOperation(OperationInput op)
    {
        var ret = new OperationOutput();

        ret.IsRejected = true;
        foreach (var plm in plmRecords)
        {
            if ((plm.x1 == op.x1 && plm.y1 == op.y1 && plm.x2 == op.x2 && plm.y2 == op.y2) ||
                (plm.x1 == op.x2 && plm.y1 == op.y2 && plm.x2 == op.x1 && plm.y2 == op.y1))
            {
                ret.IsRejected = false;
                break;
            }
        }
        if (ret.IsRejected)
        {
            return(ret);
        }
        else
        {
            ret.episodes = new List <OperationOutput.Episode>();
        }

        foreground.SwapSlot(op.x1, op.y1, op.x2, op.y2);

        var lmRecords = new List <LMRecord2D_Retangular>();

        lmRecords = SeekContainerLM(foreground);

        do
        {
            var elimination = new OperationOutput.Episode(OperationOutput.EpisodeType.ELIMINATION);
            elimination.elimination = new List <Pos2D>();
            var sandbox = CollectContainerEliminate(foreground, lmRecords);
            foreground.ForeachSlot((x, y, slot) => {
                if (sandbox[y, x])
                {
                    elimination.elimination.Add(new Pos2D(x, y));
                    foreground.ClearSlot(x, y);
                }
            });
            ret.episodes.Add(elimination);

            foreach (var sc in scoreRules)
            {
                sc.Apply(sandbox);
            }

            ret.episodes.Add(DoRefill());

            lmRecords = SeekContainerLM(foreground);
            if (0 == lmRecords.Count)
            {
                plmRecords = SeekContainerPLM(foreground);
                if (plmRecords.Count >= minimalPlayablePLM)
                {
                    break;
                }
                else
                {
                    foreground.RecreateSubjects(true);
                    MakeContainerStable(foreground);
                    MakeContainerPlayable(foreground);
                    var shuffle = new OperationOutput.Episode(OperationOutput.EpisodeType.SHUFFLE);
                    shuffle.shuffle = new SlotAttribute[foreground.Height, foreground.Width];
                    foreground.ForeachSlot((x, y, slot) => {
                        shuffle.shuffle[y, x] = slot.slotAttribute;
                    });
                    ret.episodes.Add(shuffle);
                    plmRecords = SeekContainerPLM(foreground);
                    break;
                }
            }
        }while (true);

        return(ret);
    }
Beispiel #28
0
	private IEnumerator PlayEminination(OperationOutput.Episode ep)
	{
		var start = Time.time;
		var end = start + eliminationTime;
		yield return PlayDuration(start, end, (now)=>{
			var alpha = Mathf.Max(0, (end - now) / eliminationTime);
			foreach (var p in ep.elimination)
			{
				cells[p.y, p.x].SetAlpha(alpha);
			}
		});

		foreach (var p in ep.elimination)
		{
			GameObject.Destroy(cells[p.y, p.x].gameObject);
			cells[p.y, p.x] = null;
		}

		yield break;
	}
Beispiel #29
0
	private IEnumerator PlayCor(OperationInput input, OperationOutput output, Action afterFinished)
	{
		yield return PlayInput(input);

		foreach (var episode in output.episodes)
		{
			switch (episode.etype)
			{
			case OperationOutput.EpisodeType.ELIMINATION:
				yield return PlayEminination(episode);
				break;
			case OperationOutput.EpisodeType.REFILL:
				yield return PlayRefill(episode);
				break;
			case OperationOutput.EpisodeType.SHUFFLE:
				yield return PlayShuffle(episode);
				break;
			default:
				break;
			}
		}

		afterFinished.Invoke();

		yield break;
	}
 public static TransactionOutputValueType ToDomain(this OperationOutput source)
 {
     return(new TransactionOutputValueType(source.Address, source.Amount));
 }
        public async Task <IBuiltTransaction> GetManyInputsTransferTransactionAsync(IList <OperationInput> fromAddresses, OperationOutput toAddress)
        {
            var inputs = fromAddresses.Select(o => o.ToBitcoinInput(_addressValidator)).ToList();
            var output = toAddress.ToBitcoinOutput(_addressValidator);

            var builder = new TransactionBuilder();

            var totalBalance = Money.Zero;
            var sendAmount   = inputs.Sum(o => o.Amount);
            var sentFees     = Money.Zero;

            foreach (var operationBitcoinInput in inputs)
            {
                var coins = await GetUnspentCoins(operationBitcoinInput);

                builder.AddCoins(coins);

                var addressBalance = coins.Sum(o => o.Amount);

                if (addressBalance < operationBitcoinInput.Amount)
                {
                    throw new BusinessException($"The sum of total applicable outputs is less than the required : {operationBitcoinInput.Amount.Satoshi} satoshis.",
                                                ErrorCode.NotEnoughFundsAvailable);
                }

                // send change to source address
                var change = addressBalance - operationBitcoinInput.Amount;
                if (change < new TxOut(Money.Zero, operationBitcoinInput.Address).GetDustThreshold(builder.StandardTransactionPolicy.MinRelayTxFee))
                {
                    builder.SendFees(change);
                    sentFees += change;
                }
                else
                {
                    builder.Send(operationBitcoinInput.Address, change);
                }
                totalBalance += addressBalance;
            }
            builder.Send(output.Address, sendAmount);

            var calculatedFee = await _feeService.CalcFeeForTransactionAsync(builder) - sentFees;

            var requiredBalance = sendAmount;

            if (totalBalance < requiredBalance)
            {
                throw new BusinessException(
                          $"The sum of total applicable outputs is less than the required : {requiredBalance} satoshis.",
                          ErrorCode.NotEnoughFundsAvailable);
            }

            if (calculatedFee > sendAmount)
            {
                throw new BusinessException(
                          $"The sum of total applicable outputs is less than the required fee:{calculatedFee} satoshis.",
                          ErrorCode.BalanceIsLessThanFee);
            }
            if (calculatedFee > 0)
            {
                builder.SubtractFees();
                builder.SendFees(calculatedFee);
            }

            var tx = builder.BuildTransaction(false);

            var usedCoins = builder.FindSpentCoins(tx).ToArray();

            return(BuiltTransaction.Create(tx, tx.GetFee(usedCoins), usedCoins.Cast <Coin>()));
        }