Esempio n. 1
0
 /// <summary>
 /// Creates a StatusType. Delegates can be null.
 /// </summary>
 /// <param name="apply"></param>
 /// <param name="reset"></param>
 /// <param name="specialEffectPath"></param>
 /// <param name="specialEffectAttachmentPoint"></param>
 internal TimedType(StatusFunction apply, StatusFunction reset, StatusFunction onRemove, String specialEffectPath, String specialEffectAttachmentPoint)
 {
     Id         = ++Count;
     Apply      = apply;
     Reset      = reset;
     OnRemove   = onRemove;
     Effectpath = specialEffectPath;
     Attachment = specialEffectAttachmentPoint;
 }
 public void ResultReceived(IPendingServiceCall call)
 {
     //Unwrap flex messages
     if (call.Result is ErrorMessage)
     {
         StatusFunction statusFunction = _responder.GetType().GetProperty("Status").GetValue(_responder, null) as StatusFunction;
         if (statusFunction != null)
         {
             statusFunction(new Fault(call.Result as ErrorMessage));
         }
     }
     else if (call.Result is AcknowledgeMessage)
     {
         AcknowledgeMessage ack            = call.Result as AcknowledgeMessage;
         Delegate           resultFunction = _responder.GetType().GetProperty("Result").GetValue(_responder, null) as Delegate;
         if (resultFunction != null)
         {
             ParameterInfo[] arguments = resultFunction.Method.GetParameters();
             object          result    = TypeHelper.ChangeType(ack.body, arguments[0].ParameterType);
             resultFunction.DynamicInvoke(result);
         }
     }
     else if (call.IsSuccess)
     {
         Delegate resultFunction = _responder.GetType().GetProperty("Result").GetValue(_responder, null) as Delegate;
         if (resultFunction != null)
         {
             ParameterInfo[] arguments = resultFunction.Method.GetParameters();
             object          result    = TypeHelper.ChangeType(call.Result, arguments[0].ParameterType);
             resultFunction.DynamicInvoke(result);
         }
     }
     else
     {
         StatusFunction statusFunction = _responder.GetType().GetProperty("Status").GetValue(_responder, null) as StatusFunction;
         if (statusFunction != null)
         {
             statusFunction(new Fault(call.Result));
         }
     }
 }
Esempio n. 3
0
        public void DefineBoolTag(
            StatusFunction function,
            TagAddressMaskType masktype = TagAddressMaskType.None,
            bool mask = false,
            TagAddressMergeType mergetype = TagAddressMergeType.OrMerge)
        {
            if (InnerTag != null)
            {
                return;
            }
            BoolTag innertag = new BoolTag(function)
            {
                MaskType  = masktype,
                Mask      = mask,
                MergeType = mergetype
            };

            InnerTag = innertag;
            InnerTag.TagValueChangedEvent += delegate(ITagType tag)
            {
                TagStatusChanged?.Invoke(this, EventArgs.Empty);
            };
        }
Esempio n. 4
0
 public StackingStatusType(StatusFunction apply, StatusFunction reset, StatusFunction onRemove, string specialEffectAttachmentPoint, string specialEffectPath, int stackLimit = 0, int initialStacks = 1) : base(apply, reset, onRemove, specialEffectPath, specialEffectAttachmentPoint)
 {
     StackLimit    = stackLimit;
     InitialStacks = initialStacks;
 }
Esempio n. 5
0
 private void BeginResponseFlexCall(IAsyncResult ar)
 {
     try
     {
         AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData;
         if (amfRequestData != null)
         {
             HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar);
             if (response != null)
             {
                 //Get response and deserialize
                 Stream responseStream = response.GetResponseStream();
                 if (responseStream != null)
                 {
                     AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream);
                     AMFMessage responseMessage = amfDeserializer.ReadAMFMessage();
                     AMFBody responseBody = responseMessage.GetBodyAt(0);
                     for (int i = 0; i < responseMessage.HeaderCount; i++)
                     {
                         AMFHeader header = responseMessage.GetHeaderAt(i);
                         if (header.Name == AMFHeader.RequestPersistentHeader)
                             _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content);
                     }
                     object message = responseBody.Content;
                     if (message is ErrorMessage)
                     {
                         /*
                         ASObject status = new ASObject();
                         status["level"] = "error";
                         status["code"] = "NetConnection.Call.Failed";
                         status["description"] = (result as ErrorMessage).faultString;
                         status["details"] = result;
                         _netConnection.RaiseNetStatus(status);
                         */
                         if (amfRequestData.Call != null)
                         {
                             PendingCall call = amfRequestData.Call;
                             call.Result = message;
                             call.Status = Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION;
                             amfRequestData.Callback.ResultReceived(call);
                         }
                         if (amfRequestData.Responder != null)
                         {
                             StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction;
                             if (statusFunction != null)
                                 statusFunction(new Fault(message as ErrorMessage));
                         }
                     }
                     else if (message is AcknowledgeMessage)
                     {
                         AcknowledgeMessage ack = message as AcknowledgeMessage;
                         if (_netConnection.ClientId == null && ack.HeaderExists(MessageBase.FlexClientIdHeader))
                             _netConnection.SetClientId(ack.GetHeader(MessageBase.FlexClientIdHeader) as string);
                         if (amfRequestData.Call != null)
                         {
                             PendingCall call = amfRequestData.Call;
                             call.Result = ack.body;
                             call.Status = Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT;
                             amfRequestData.Callback.ResultReceived(call);
                         }
                         if (amfRequestData.Responder != null)
                         {
                             Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate;
                             if (resultFunction != null)
                             {
                                 ParameterInfo[] arguments = resultFunction.Method.GetParameters();
                                 object result = TypeHelper.ChangeType(ack.body, arguments[0].ParameterType);
                                 resultFunction.DynamicInvoke(result);
                             }
                         }
                     }
                 }
                 else
                     _netConnection.RaiseNetStatus("Could not aquire ResponseStream");
             }
             else
                 _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse");
         }
     }
     catch (Exception ex)
     {
         _netConnection.RaiseNetStatus(ex);
     }
 }
Esempio n. 6
0
 private void BeginResponseFlashCall(IAsyncResult ar)
 {
     try
     {
         AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData;
         if (amfRequestData != null)
         {
             HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar);
             if (response != null)
             {
                 //Get response and deserialize
                 Stream responseStream = response.GetResponseStream();
                 if (responseStream != null)
                 {
                     AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream);
                     AMFMessage responseMessage = amfDeserializer.ReadAMFMessage();
                     AMFBody responseBody = responseMessage.GetBodyAt(0);
                     for (int i = 0; i < responseMessage.HeaderCount; i++)
                     {
                         AMFHeader header = responseMessage.GetHeaderAt(i);
                         if (header.Name == AMFHeader.RequestPersistentHeader)
                             _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content);
                     }
                     if (amfRequestData.Call != null)
                     {
                         PendingCall call = amfRequestData.Call;
                         call.Result = responseBody.Content;
                         call.Status = responseBody.Target.EndsWith(AMFBody.OnStatus) ? Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION : Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT;
                         amfRequestData.Callback.ResultReceived(call);
                     }
                     if (amfRequestData.Responder != null)
                     {
                         if (responseBody.Target.EndsWith(AMFBody.OnStatus))
                         {
                             StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction;
                             if (statusFunction != null)
                                 statusFunction(new Fault(responseBody.Content));
                         }
                         else
                         {
                             Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate;
                             if (resultFunction != null)
                             {
                                 ParameterInfo[] arguments = resultFunction.Method.GetParameters();
                                 object result = TypeHelper.ChangeType(responseBody.Content, arguments[0].ParameterType);
                                 resultFunction.DynamicInvoke(result);
                             }
                         }
                     }
                 }
                 else
                     _netConnection.RaiseNetStatus("Could not aquire ResponseStream");
             }
             else
                 _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse");
         }
     }
     catch (Exception ex)
     {
         _netConnection.RaiseNetStatus(ex);
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Responder&lt;T&gt;"/> class.
 /// You pass a Responder object to NetConnection.call() to handle return values from the server. You may pass null for either or both parameters.
 /// </summary>
 /// <param name="result">The function invoked if the call to the server succeeds and returns a result.</param>
 /// <param name="status">The function invoked if the server returns an error.</param>
 public Responder(ResultFunction <T> result, StatusFunction status)
 {
     _result = result;
     _status = status;
 }
Esempio n. 8
0
        public override async Task ExecuteFunction(IAsyncStreamReader <BundledRows> requestStream,
                                                   IServerStreamWriter <BundledRows> responseStream,
                                                   ServerCallContext context)
        {
            var response = new QlikResponse();

            try
            {
                logger.Debug("The method 'ExecuteFunction' is called...");

                //Read function header
                var functionHeader = context.RequestHeaders.ParseIMessageFirstOrDefault <FunctionRequestHeader>();

                //Read common header
                var commonHeader = context.RequestHeaders.ParseIMessageFirstOrDefault <CommonRequestHeader>();

                //Set appid
                logger.Info($"The Qlik app id '{commonHeader?.AppId}' in header found.");
                var qlikAppId = commonHeader?.AppId;

                //Set qlik user
                logger.Info($"The Qlik user '{commonHeader?.UserId}' in header found.");
                var domainUser = new DomainUser(commonHeader?.UserId);

                //Very important code line
                await context.WriteResponseHeadersAsync(new Metadata { { "qlik-cache", "no-store" } });

                //Read parameter from qlik
                var row      = GetParameter(requestStream);
                var userJson = GetParameterValue(0, row);

                //Parse request from qlik script
                logger.Debug("Parse user request...");
                var request = QlikRequest.Parse(domainUser, qlikAppId, userJson);

                var functionCall = (ConnectorFunction)functionHeader.FunctionId;
                logger.Debug($"Call Function id: '{functionCall}' from client '{context?.Peer}'.");

                if (functionCall == ConnectorFunction.START)
                {
                    #region Switch qlik user to app owner
                    if (domainUser?.UserId == "sa_scheduler" && domainUser?.UserDirectory == "INTERNAL")
                    {
                        try
                        {
                            var oldUser = domainUser.ToString();
                            domainUser = new DomainUser("INTERNAL\\ser_scheduler");
                            logger.Debug($"Change Qlik user '{oldUser}' to task service user '{domainUser}'.");
                            var connection = RuntimeOptions.Config.Connection;
                            var tmpsession = RuntimeOptions.SessionHelper.Manager.CreateNewSession(connection, domainUser, qlikAppId);
                            if (tmpsession == null)
                            {
                                throw new Exception("No session cookie generated. (Qlik Task)");
                            }
                            var qrsHub = new QlikQrsHub(RuntimeOptions.Config.Connection.ServerUri, tmpsession.Cookie);
                            qrsHub.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                            domainUser = request.GetAppOwner(qrsHub, qlikAppId);
                            if (domainUser == null)
                            {
                                throw new Exception("The owner of the App could not found.");
                            }
                            logger.Debug($"App owner '{domainUser}' found.");
                            request.QlikUser = domainUser;
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex, "Could not switch the task user to real qlik user.");
                        }
                    }
                    #endregion

                    #region Function call SER.START
                    logger.Debug("Function call SER.START...");
                    var newManagedTask = new ManagedTask()
                    {
                        StartTime    = DateTime.Now,
                        Message      = "Create new report job...",
                        Cancellation = new CancellationTokenSource(),
                        Status       = 0
                    };
                    RuntimeOptions.TaskPool.ManagedTasks.TryAdd(newManagedTask.Id, newManagedTask);
                    var startFunction = new StartFunction(RuntimeOptions);
                    startFunction.StartReportJob(request, newManagedTask);
                    response.TaskId = newManagedTask.Id.ToString();
                    #endregion
                }
                else if (functionCall == ConnectorFunction.STOP)
                {
                    #region Function call SER.STOP
                    logger.Debug("Function call SER.STOP...");
                    var stopFunction = new StopFunction(RuntimeOptions);
                    stopFunction.StopReportJobs(request);
                    if (request.ManagedTaskId == "all")
                    {
                        response.Log = "All report jobs is stopping...";
                    }
                    else
                    {
                        response.Log = $"Report job '{request.ManagedTaskId}' is stopping...";
                    }
                    response.Status = 4;
                    #endregion
                }
                else if (functionCall == ConnectorFunction.RESULT)
                {
                    #region Function call SER.RESULT
                    logger.Debug("Function call SER.RESULT...");
                    var resultFunction = new ResultFunction(RuntimeOptions);
                    response = resultFunction.FormatJobResult(request);
                    #endregion
                }
                else if (functionCall == ConnectorFunction.STATUS)
                {
                    #region Function call SER.STATUS
                    logger.Debug("Function call SER.STATUS...");
                    var statusFunction = new StatusFunction(RuntimeOptions);
                    response = statusFunction.GetStatusResponse(request);
                    #endregion
                }
                else
                {
                    throw new Exception($"The id '{functionCall}' of the function call was unknown.");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"The method 'ExecuteFunction' failed with error '{ex.Message}'.");
                response.Status = -1;
                response.SetErrorMessage(ex);
            }
            finally
            {
                logger.Trace($"Qlik status result: {JsonConvert.SerializeObject(response)}");
                await responseStream.WriteAsync(GetResult(response));

                LogManager.Flush();
            }
        }
Esempio n. 9
0
        // public bool PeriodicEffect;

        public PeriodicType(StatusFunction apply, StatusFunction onRemove, string specialEffectPath, string specialEffectAttachmentPoint, float periodicTimeoutTime = 1) : base(apply, null, onRemove, specialEffectPath, specialEffectAttachmentPoint)
        {
            // PeriodicEffect = periodicEffect;
            PeriodicTimeoutTime = periodicTimeoutTime;
        }
Esempio n. 10
0
 public TimedStackingType(StatusFunction apply, StatusFunction reset, StatusFunction onRemove, string specialEffectPath, string specialEffectAttachmentPoint) : base(apply, reset, onRemove, specialEffectPath, specialEffectAttachmentPoint)
 {
 }