public override Location GetLocation(ActivityContext context)
 {
     Location location;
     if (context == null)
     {
         throw FxTrace.Exception.ArgumentNull("context");
     }
     this.ThrowIfNotInTree();
     if (!context.AllowChainedEnvironmentAccess)
     {
         if (this.IsPublic || !object.ReferenceEquals(this.Owner, context.Activity))
         {
             throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.VariableOnlyAccessibleAtScopeOfDeclaration(context.Activity, this.Owner)));
         }
         if (!context.Environment.TryGetLocation(base.Id, out location))
         {
             throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.VariableDoesNotExist(this.Name)));
         }
         return location;
     }
     if (!context.Environment.TryGetLocation(base.Id, this.Owner, out location))
     {
         throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.VariableDoesNotExist(this.Name)));
     }
     return location;
 }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var user = workflowContext.Content.As<IUserRoles>();

            // if the current workflow subject is not a user, use current user
            if (user == null) {
                user = _workContextAccessor.GetContext().CurrentUser.As<IUserRoles>();
            }

            var roles = GetRoles(activityContext);

            if (user != null) {
                foreach (var role in roles) {
                    if (!user.Roles.Contains(role)) {
                        var roleRecord = _roleService.GetRoleByName(role);
                        if (roleRecord != null) {
                            _repository.Create(new UserRolesPartRecord {UserId = user.Id, Role = roleRecord});
                        }
                        else {
                            Logger.Debug("Role not found: {0}", role);
                        }
                    }
                }
            }

            yield return T("Done");
        }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var userName = activityContext.GetState<string>("UserName");
            var email = activityContext.GetState<string>("Email");
            var password = activityContext.GetState<string>("Password");
            var approved = activityContext.GetState<bool>("Approved");

            if (String.IsNullOrWhiteSpace(userName) || String.IsNullOrWhiteSpace(email)) {
                yield return T("InvalidUserNameOrEmail");
                yield break;
            }

            if (String.IsNullOrWhiteSpace(password)) {
                yield return T("InvalidPassword");
                yield break;
            }

            if (!_userService.VerifyUserUnicity(userName, email)) {
                yield return T("UserNameOrEmailNotUnique");
                yield break;
            }

            var user = _membershipService.CreateUser(
                new CreateUserParams(
                    userName,
                    password,
                    email,
                    isApproved: approved,
                    passwordQuestion: null,
                    passwordAnswer: null));

            workflowContext.Content = user;

            yield return T("Done");
        }
 private bool UserIsApproved(ActivityContext context) {
     // checking if user is in an accepted role
     var workContext = _workContextAccessor.GetContext();
     var user = workContext.CurrentUser;
     if (user == null) return false;
     return user.As<UserPart>().RegistrationStatus == UserStatus.Approved;
 }
Example #5
0
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var body = activityContext.GetState<string>("Body");
            var subject = activityContext.GetState<string>("Subject");
            var recipients = activityContext.GetState<string>("Recipients");
            var replyTo = activityContext.GetState<string>("ReplyTo");
            var bcc = activityContext.GetState<string>("Bcc");
            var cc = activityContext.GetState<string>("CC");

            var parameters = new Dictionary<string, object> {
                {"Subject", subject},
                {"Body", body},
                {"Recipients", recipients},
                {"ReplyTo", replyTo},
                {"Bcc", bcc},
                {"CC", cc}
            };

            var queued = activityContext.GetState<bool>("Queued");

            if (!queued) {
                _messageService.Send(SmtpMessageChannel.MessageType, parameters);
            }
            else {
                var priority = activityContext.GetState<int>("Priority");
                _jobsQueueService.Enqueue("IMessageService.Send", new { type = SmtpMessageChannel.MessageType, parameters = parameters }, priority);
            }

            yield return T("Done");
        }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            if (UserIsApproved(activityContext)) {
                yield return T("Yes");
            }

            yield return T("No");
        }
        public override void OnActivityExecuted(WorkflowContext workflowContext, ActivityContext activityContext) {

            // for blocking activities only
            if (!activityContext.Activity.IsEvent) {
                return;
            }

            // activity records pointing to the executed activity
            var inboundActivities = workflowContext.GetInboundTransitions(activityContext.Record);


            // if a direct target of a Branch Activity is executed, then suppress all other direct waiting activities
            var parentBranchActivities = inboundActivities
                .Where(x => x.SourceActivityRecord.Name == this.Name)
                .Select(x => x.SourceActivityRecord)
                .ToList();

            if (parentBranchActivities.Any()) {
                foreach (var parentBranch in parentBranchActivities) {
                    // remove all other waiting activities after the parent branch

                    var siblings = workflowContext.GetOutboundTransitions(parentBranch).Select(x => x.DestinationActivityRecord).ToList();
                    var awaitings = workflowContext.Record.AwaitingActivities.Where(x => siblings.Contains(x.ActivityRecord));
                    foreach (var awaiting in awaitings) {
                        workflowContext.Record.AwaitingActivities.Remove(awaiting);
                    }
                }
            }
        }
Example #8
0
        public override bool CanExecute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            try {

                var contentTypesState = activityContext.GetState<string>("ContentTypes");

                // "" means 'any'
                if (String.IsNullOrEmpty(contentTypesState)) {
                    return true;
                }

                string[] contentTypes = contentTypesState.Split(',');

                var content = workflowContext.Content;

                if (content == null) {
                    return false;
                }

                return contentTypes.Any(contentType => content.ContentItem.TypeDefinition.Name == contentType);
            }
            catch {
                return false;
            }
        }
        public override bool CanExecute(WorkflowContext workflowContext, ActivityContext activityContext) {
            try {

                var state = activityContext.GetState<string>("CustomForms");

                // "" means 'any'
                if (String.IsNullOrEmpty(state)) {
                    return true;
                }

                var content = workflowContext.Tokens["CustomForm"] as ContentItem;

                if (content == null) {
                    return false;
                }

                var contentManager = content.ContentManager;
                var identities = state.Split(',').Select(x => new ContentIdentity(x));
                var customForms = identities.Select(contentManager.ResolveIdentity);

                return customForms.Any(x => x == content);

            }
            catch {
                return false;
            }
        }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var part = workflowContext.Content.As<WXMsgPart>();
            var apiUrl = activityContext.GetState<string>("api_url");
            var apiToken = activityContext.GetState<string>("api_token");
            var timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            var nonce = HttpContext.Current.Request.QueryString["nonce"];

            string[] arr = { apiToken, timestamp, nonce };
            Array.Sort(arr);     //字典排序
            string tmpStr = string.Join("", arr);
            var signature = _winXinService.GetSHA1(tmpStr);
            signature = signature.ToLower();

            var client = new System.Net.WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            var url = string.Format("{0}?timestamp={1}&nonce={2}&signature={3}"
                    , apiUrl, timestamp, nonce, signature);
            string postData = part.XML;
            //using (var stream = HttpContext.Current.Request.InputStream)
            //{
            //    var reader = new StreamReader(stream);
            //    postData = reader.ReadToEnd();
            //}

            string result = null;
            try
            {
                result = client.UploadString(url, postData);
            }
            catch (System.Net.WebException ex)
            {
                string msg = null;
                using (var stream = ex.Response.GetResponseStream())
                {
                    var reader = new StreamReader(stream);
                    msg = reader.ReadToEnd();
                }
                Logger.Warning(ex, ex.Message);
            }
            catch (Exception ex)
            {
                var innerEx = ex;
                while (innerEx.InnerException != null)
                    innerEx = innerEx.InnerException;
                Logger.Warning(ex, innerEx.Message);
            }

            if (result == null)
            {
                yield return T("Error");
            }
            else
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Write(result);
                HttpContext.Current.Response.End();
                yield return T("Success");
            }
        }
 public object Get(ActivityContext context)
 {
     if (context == null)
     {
         throw FxTrace.Exception.ArgumentNull("context");
     }
     return context.GetValue<object>((LocationReference) this);
 }
 public override IEnumerable<LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext, ActivityContext activityContext) {
     return new[] {
         T("InvalidUserNameOrEmail"),
         T("InvalidPassword"),
         T("UserNameOrEmailNotUnique"),
         T("Done")
     };
 }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var user = workflowContext.Content.As<UserPart>();

            user.RegistrationStatus = UserStatus.Approved;
            user.EmailStatus = UserStatus.Approved;
            _userEventHandlers.Approved(user);

            yield return T("Done");
        }
Example #14
0
        private IEnumerable<string> GetBranches(ActivityContext context) {
            var branches = context.GetState<string>("Branches");

            if (String.IsNullOrEmpty(branches)) {
                return Enumerable.Empty<string>();
            }

            return branches.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();
        }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var key = activityContext.GetState<string>("Key");
            var message = activityContext.GetState<string>("ErrorMessage");
            var updater = (IUpdateModel) workflowContext.Tokens["Updater"];

            updater.AddModelError(key, T(message));

            return new[] { T("Done") };
        }
 internal override Location GetLocationForWrite(ActivityContext context)
 {
     ValidateAccessor(context);
     if (!this.allowWrites)
     {
         throw FxTrace.Exception.AsError(new InvalidOperationException(SR.WriteAccessToReadOnlyPublicReference(context.Activity)));
     }
     return GetLocationCore(context);
 }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var notification = activityContext.GetState<string>("Notification");
            var message = activityContext.GetState<string>("Message");

            var notificationType = (NotifyType)Enum.Parse(typeof(NotifyType), notification);
            _notifier.Add(notificationType, T(message));

            yield return T("Done");
        }
Example #18
0
        private bool UserIsInRole(ActivityContext context) {

            // checking if user is in an accepted role
            var workContext = _workContextAccessor.GetContext();
            var user = workContext.CurrentUser;
            var roles = GetRoles(context);

            return UserIsInRole(user, roles);
        }
Example #19
0
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var levelString = activityContext.GetState<string>("Level");
            var message = activityContext.GetState<string>("Message");

            LogLevel level;
            Enum.TryParse(levelString, true, out level);
            Logger.Log(level, null, message);

            yield return T("Done");
        }
        void ValidateAccessor(ActivityContext context)
        {
            // We need to call ThrowIfDisposed explicitly since
            // context.Activity does not check isDisposed
            context.ThrowIfDisposed();

            if (!object.ReferenceEquals(context.Activity, this.validAccessor))
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.InlinedLocationReferenceOnlyAccessibleByOwner(context.Activity, this.validAccessor)));
            }
        }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var userName = activityContext.GetState<string>("UserName");
            var email = activityContext.GetState<string>("Email");

            if (_userService.VerifyUserUnicity(userName, email)) {
                yield return T("Unique");
            }
            else {
                yield return T("NotUnique");
            }
        }
Example #22
0
        private bool ActionIsValid(WorkflowContext workflowContext, ActivityContext activityContext) {
            
            // checking if user has triggered an accepted action

            // triggered action
            var userAction = workflowContext.Tokens["UserTask.Action"];

            var actions = GetActions(activityContext);
            bool isValidAction = actions.Contains(userAction);

            return isValidAction;    
        }
Example #23
0
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var content = workflowContext.Content;

            if (content != null) {
                var comments = content.As<CommentsPart>();
                if (comments != null) {
                    comments.CommentsActive = false;
                }
            }

            yield return T("Done");
        }
 public override Location GetLocation(ActivityContext context)
 {
     if (context == null)
     {
         throw FxTrace.Exception.ArgumentNull("context");
     }
     ValidateAccessor(context);
     if (!this.allowGetLocation)
     {
         throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetLocationOnPublicAccessReference(context.Activity)));
     }
     return GetLocationCore(context);
 }
Example #25
0
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var script = activityContext.GetState<string>("Script");
            object outcome = null;

            _csharpService.SetParameter("Services", _orchardServices);
            _csharpService.SetParameter("ContentItem", (dynamic)workflowContext.Content.ContentItem);
            _csharpService.SetParameter("WorkContext", _workContextAccessor.GetContext());
            _csharpService.SetFunction("T", (Func<string, string>)(x => T(x).Text));
            _csharpService.SetFunction("SetOutcome", (Action<object>)(x => outcome = x));

            _csharpService.Run(script);

            yield return T(Convert.ToString(outcome));
        }
Example #26
0
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var properties = new Dictionary<string, string> {
                {"Script", activityContext.GetState<string>("Script")} 
            };

            _csharpService.SetParameter("Services", _orchardServices);
            _csharpService.SetParameter("ContentItem", (dynamic)workflowContext.Content.ContentItem);
            _csharpService.SetParameter("WorkContext", _workContextAccessor.GetContext());
            _csharpService.SetFunction("T", (Func<string, string>)(x => T(x).Text));

            var scriptResult = _csharpService.Evaluate(properties["Script"]).ToString();

            yield return T(scriptResult);
        }
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var nextUserId = PopNextWatcherId(workflowContext, activityContext);

            if (nextUserId != 0)
            {
                workflowContext.Tokens["User"] = _contentManager.Get(nextUserId).As<IUser>();
                yield return T("Run for the next watcher");
            }
            else
            {
                yield return T("Done");
            }
        }
Example #28
0
        private bool IsExpired(WorkflowContext workflowContext, ActivityContext activityContext) {
            DateTime started;

            if (!workflowContext.HasStateFor(activityContext.Record, "StartedUtc")) {
                workflowContext.SetStateFor(activityContext.Record, "StartedUtc", started = _clock.UtcNow);
            }
            else {
                started = workflowContext.GetStateFor<DateTime>(activityContext.Record, "StartedUtc");
            }

            var amount = activityContext.GetState<int>("Amount");
            var type = activityContext.GetState<string>("Unity");

            return _clock.UtcNow > When(started, amount, type);
        }
Example #29
0
 private MailMessage CreateMessage(ActivityContext context)
 {
     var message = EmailHelper.CreateMessage
         (
             Subject.Get(context),
             Body.Get(context),
             From.Get(context),
             To.Get(context)
         );
     if (Cc.Get(context).ContainsCharacters())
         message.CC.Add(Cc.Get(context));
     if (AttachmentFilePath.Get(context).ContainsCharacters())
         message.Attachments.Add(new Attachment(AttachmentFilePath.Get(context)));
     return message;
 }
Example #30
0
        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var url = activityContext.GetState<string>("Url");
            var verb = (activityContext.GetState<string>("Verb") ?? "GET").ToUpper();
            var headers = activityContext.GetState<string>("Headers");
            var formValues = activityContext.GetState<string>("FormValues") ?? "";

            using (var httpClient = new HttpClient {BaseAddress = new Uri(url)}) {
                HttpResponseMessage response;

                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                if (!String.IsNullOrWhiteSpace(headers)) {
                    foreach (var header in ParseKeyValueString(headers)) {
                        httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                switch (verb) {
                    default:
                    case "GET":
                        response = httpClient.GetAsync("").Result;
                        break;
                    case "POST":
                        var format = activityContext.GetState<string>("FormFormat");

                        switch (format) {
                            default:
                            case "KeyValue":
                                var form = ParseKeyValueString(formValues);
                                response = httpClient.PostAsync("", new FormUrlEncodedContent(form)).Result;
                                break;
                            case "Json":
                                var json = formValues.Replace("((", "{").Replace("))", "}");
                                response = httpClient.PostAsync("", new StringContent(json, Encoding.UTF8, "application/json")).Result;
                                break;
                        }
                        
                        break;
                }
                
                workflowContext.SetState("WebRequestResponse", response.Content.ReadAsStringAsync().Result);

                if (response.IsSuccessStatusCode)
                    yield return T("Success");
                else
                    yield return T("Error");
            }
        }
Example #31
0
        public override bool Execute(ActivityContext context)
        {
            var folderPath = context.Get(this.FolderPath);

            return(Directory.Exists(folderPath));
        }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var part    = workflowContext.Content.As <WXMsgPart>();
            var content = part.Content;
            var op      = activityContext.GetState <string>("operator");
            var value   = activityContext.GetState <string>("textValue");

            switch (op)
            {
            case "Equals":
                if (content == value)
                {
                    yield return(T("条件满足"));

                    yield break;
                }
                break;

            case "NotEquals":
                if (content != value)
                {
                    yield return(T("条件满足"));

                    yield break;
                }
                break;

            case "Contains":
                if (content.Contains(value))
                {
                    yield return(T("条件满足"));

                    yield break;
                }
                break;

            case "NotContains":
                if (!content.Contains(value))
                {
                    yield return(T("条件满足"));

                    yield break;
                }
                break;

            case "Starts":
                if (content.StartsWith(value))
                {
                    yield return(T("条件满足"));

                    yield break;
                }
                break;

            case "NotStarts":
                if (!content.StartsWith(value))
                {
                    yield return(T("条件满足"));

                    yield break;
                }
                break;

            case "Ends":
                if (content.EndsWith(value))
                {
                    yield return(T("条件满足"));

                    yield break;
                }
                break;

            case "NotEnds":
                if (!content.EndsWith(value))
                {
                    yield return(T("条件满足"));

                    yield break;
                }
                break;
            }


            yield return(T("条件不满足"));
        }
        /**********************************************************************************/

        public async Task Configure(ActivityContext activityContext)
        {
            InitializeInternalState(activityContext, null);
            var  configurationType   = GetConfigurationRequestType();
            bool afterConfigureFails = false;

            try
            {
                if (!await CheckAuthentication())
                {
                    AddAuthenticationCrate(false);
                    return;
                }

                if (!await BeforeConfigure(configurationType))
                {
                    return;
                }

                switch (configurationType)
                {
                case ConfigurationRequestType.Initial:
                    await Initialize();

                    break;

                case ConfigurationRequestType.Followup:
                    await FollowUp();

                    break;

                default:
                    throw new ArgumentOutOfRangeException($"Unsupported configuration type: {configurationType}");
                }
                try
                {
                    await AfterConfigure(configurationType, null);
                }
                catch
                {
                    afterConfigureFails = true;
                    throw;
                }
            }
            catch (AuthorizationTokenExpiredOrInvalidException)
            {
                AddAuthenticationCrate(true);
            }
            catch (Exception ex)
            {
                if (IsInvalidTokenException(ex))
                {
                    AddAuthenticationCrate(true);
                    return;
                }
                else if (!afterConfigureFails)
                {
                    await AfterConfigure(configurationType, ex);
                }

                throw;
            }
        }
Example #34
0
        //Download
        private void Download_icon_Click(object sender, EventArgs e)
        {
            try
            {
                if (Download_icon.Tag.ToString() == "false")
                {
                    Download_icon.SetImageDrawable(ActivityContext.GetDrawable(Resource.Drawable.ic_action_download_stop));
                    Download_icon.Tag = "true";

                    string urlVideo = string.Empty;
                    if (Videodata.source.Contains("youtube") || Videodata.source.Contains("Youtube") || Videodata.source.Contains("youtu"))
                    {
                        urlVideo = VideoInfoRetriever.VideoDownloadstring;
                        if (!string.IsNullOrEmpty(urlVideo))
                        {
                            VideoControler = new VideoDownloadAsyncControler(urlVideo, Videodata.source, ActivityContext);
                            if (!VideoControler.CheckDownloadLinkIfExits())
                            {
                                VideoControler.StartDownloadManager(Videodata.name, Videodata);
                            }
                        }
                        else
                        {
                            IMethods.DialogPopup.InvokeAndShowDialog(ActivityContext, ActivityContext.GetString(Resource.String.Lbl_Error), ActivityContext.GetString(Resource.String.Lbl_You_can_not_Download_video), ActivityContext.GetString(Resource.String.Lbl_Ok));
                        }
                    }
                    else
                    {
                        urlVideo = Videodata.source;

                        VideoControler = new VideoDownloadAsyncControler(urlVideo, Videodata.id, ActivityContext);
                        if (!VideoControler.CheckDownloadLinkIfExits())
                        {
                            VideoControler.StartDownloadManager(Videodata.name, Videodata);
                        }
                    }
                }
                else if (Download_icon.Tag.ToString() == "Downloaded")
                {
                    try
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(ActivityContext);
                        builder.SetTitle(ActivityContext.GetString(Resource.String.Lbl_Delete_video));
                        builder.SetMessage(ActivityContext.GetString(Resource.String.Lbl_Do_You_want_to_remove_video));

                        builder.SetPositiveButton(ActivityContext.GetString(Resource.String.Lbl_Yes), delegate(object o, DialogClickEventArgs args)
                        {
                            try
                            {
                                VideoDownloadAsyncControler.RemoveDiskVideoFile(Videodata.id + ".mp4");
                                Download_icon.SetImageDrawable(ActivityContext.GetDrawable(Resource.Drawable.ic_action_download));
                                Download_icon.Tag = "false";
                            }
                            catch (Exception exception)
                            {
                                Crashes.TrackError(exception);
                            }
                        });

                        builder.SetNegativeButton(ActivityContext.GetString(Resource.String.Lbl_No), delegate(object o, DialogClickEventArgs args)
                        {
                        });

                        var alert = builder.Create();
                        alert.Show();
                    }
                    catch (System.Exception exception)
                    {
                        Crashes.TrackError(exception);
                    }
                }
                else
                {
                    Download_icon.SetImageDrawable(ActivityContext.GetDrawable(Resource.Drawable.ic_action_download));
                    Download_icon.Tag = "false";
                    VideoControler.StopDownloadManager();
                }
            }
            catch (System.Exception exception)
            {
                Crashes.TrackError(exception);
            }
        }
Example #35
0
        public void Initialize()
        {
            try
            {
                PlayerLitsener = new Player_Events(ActivityContext, controlView);

                if (ActivityName != "FullScreen")
                {
                    simpleExoPlayerView = ActivityContext.FindViewById <PlayerView>(Resource.Id.player_view);
                    simpleExoPlayerView.SetControllerVisibilityListener(PlayerLitsener);
                    simpleExoPlayerView.RequestFocus();

                    //Player initialize
                    controlView    = simpleExoPlayerView.FindViewById <PlaybackControlView>(Resource.Id.exo_controller);
                    PlayerLitsener = new Player_Events(ActivityContext, controlView);

                    Exo_topLayout     = controlView.FindViewById <LinearLayout>(Resource.Id.topLayout);
                    Exo_back_button   = controlView.FindViewById <ImageView>(Resource.Id.backIcon);
                    Download_icon     = controlView.FindViewById <ImageView>(Resource.Id.Download_icon);
                    mFullScreenIcon   = controlView.FindViewById <ImageView>(Resource.Id.exo_fullscreen_icon);
                    mFullScreenButton = controlView.FindViewById <FrameLayout>(Resource.Id.exo_fullscreen_button);
                    ShareIcon         = controlView.FindViewById <ImageView>(Resource.Id.share_icon);
                    Menue_button      = controlView.FindViewById <FrameLayout>(Resource.Id.exo_menue_button);
                    videoPlayButton   = controlView.FindViewById <ImageButton>(Resource.Id.exo_play);
                    videoResumeButton = controlView.FindViewById <ImageButton>(Resource.Id.exo_pause);

                    MainvideoFrameLayout = ActivityContext.FindViewById <FrameLayout>(Resource.Id.root);
                    MainvideoFrameLayout.SetOnClickListener(this);

                    Loadingprogress_bar = ActivityContext.FindViewById <ProgressBar>(Resource.Id.progress_bar);

                    QualityiconView             = ActivityContext.FindViewById <TextView>(Resource.Id.Qualityicon);
                    ViewsiconView               = ActivityContext.FindViewById <TextView>(Resource.Id.Viewsicon);
                    ShareiconView               = ActivityContext.FindViewById <TextView>(Resource.Id.Shareicon);
                    MoreiconView                = ActivityContext.FindViewById <TextView>(Resource.Id.Moreicon);
                    ShowMoreDiscriptioniconView = ActivityContext.FindViewById <TextView>(Resource.Id.video_ShowDiscription);
                    videoDescriptionLayout      = ActivityContext.FindViewById <LinearLayout>(Resource.Id.videoDescriptionLayout);


                    Share_Button        = ActivityContext.FindViewById <LinearLayout>(Resource.Id.ShareButton);
                    Share_Button.Click += ShareIcon_Click;

                    More_Button        = ActivityContext.FindViewById <LinearLayout>(Resource.Id.moreButton);
                    More_Button.Click += MoreButton_OnClick;

                    Video_Titile           = ActivityContext.FindViewById <TextView>(Resource.Id.video_Titile);
                    Video_QualityTextView  = ActivityContext.FindViewById <TextView>(Resource.Id.QualityTextView);
                    Video_ViewsNumber      = ActivityContext.FindViewById <TextView>(Resource.Id.ViewsNumber);
                    Video_videoDate        = ActivityContext.FindViewById <TextView>(Resource.Id.videoDate);
                    Video_videoDescription = ActivityContext.FindViewById <AutoLinkTextView>(Resource.Id.videoDescriptionTextview);
                    Video_videoCategory    = ActivityContext.FindViewById <TextView>(Resource.Id.videoCategorytextview);

                    Video_Stars = ActivityContext.FindViewById <TextView>(Resource.Id.videoStarstextview);
                    Video_Tag   = ActivityContext.FindViewById <TextView>(Resource.Id.videoTagtextview);

                    TextSanitizerAutoLink = new TextSanitizer(Video_videoDescription, ActivityContext);

                    IMethods.Set_TextViewIcon("1", QualityiconView, IonIcons_Fonts.RibbonA);
                    IMethods.Set_TextViewIcon("1", ViewsiconView, IonIcons_Fonts.Eye);
                    IMethods.Set_TextViewIcon("1", ShareiconView, IonIcons_Fonts.ReplyAll);
                    IMethods.Set_TextViewIcon("1", MoreiconView, IonIcons_Fonts.PlusCircled);
                    IMethods.Set_TextViewIcon("1", ShowMoreDiscriptioniconView, IonIcons_Fonts.ArrowDownB);

                    ShowMoreDiscriptioniconView.Visibility = ViewStates.Gone;

                    videoDescriptionLayout.Visibility = ViewStates.Visible;

                    if (!mFullScreenButton.HasOnClickListeners)
                    {
                        mFullScreenButton.SetOnClickListener(this);
                    }

                    if (!Exo_back_button.HasOnClickListeners)
                    {
                        Exo_back_button.Click += BackIcon_Click;
                        Download_icon.Click   += Download_icon_Click;
                        ShareIcon.Click       += ShareIcon_Click;
                        //Menue_button.Click += Menue_button_Click;

                        Menue_button.Visibility = ViewStates.Gone;
                    }
                }
                else
                {
                    FullscreenplayerView = ActivityContext.FindViewById <PlayerView>(Resource.Id.player_view2);
                    controlView          = FullscreenplayerView.FindViewById <PlaybackControlView>(Resource.Id.exo_controller);
                    PlayerLitsener       = new Player_Events(ActivityContext, controlView);

                    Exo_topLayout     = controlView.FindViewById <LinearLayout>(Resource.Id.topLayout);
                    Exo_back_button   = controlView.FindViewById <ImageView>(Resource.Id.backIcon);
                    Download_icon     = controlView.FindViewById <ImageView>(Resource.Id.Download_icon);
                    mFullScreenIcon   = controlView.FindViewById <ImageView>(Resource.Id.exo_fullscreen_icon);
                    mFullScreenButton = controlView.FindViewById <FrameLayout>(Resource.Id.exo_fullscreen_button);
                    ShareIcon         = controlView.FindViewById <ImageView>(Resource.Id.share_icon);
                    Menue_button      = controlView.FindViewById <FrameLayout>(Resource.Id.exo_menue_button);
                    videoPlayButton   = controlView.FindViewById <ImageButton>(Resource.Id.exo_play);
                    videoResumeButton = controlView.FindViewById <ImageButton>(Resource.Id.exo_pause);

                    if (!mFullScreenButton.HasOnClickListeners)
                    {
                        mFullScreenButton.SetOnClickListener(this);
                    }

                    if (!Exo_back_button.HasOnClickListeners)
                    {
                        Exo_back_button.Click += BackIcon_Click;
                        Download_icon.Click   += Download_icon_Click;
                        ShareIcon.Click       += ShareIcon_Click;
                        //Menue_button.Click += Menue_button_Click;

                        Menue_button.Visibility = ViewStates.Gone;
                    }
                }
            }
            catch (Exception exception)
            {
                Crashes.TrackError(exception);
            }
        }
Example #36
0
 public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
 {
     _contentManager.Remove(workflowContext.Content.ContentItem);
     yield return(T("Deleted"));
 }
Example #37
0
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            string inspectionTypeString = activityContext.GetState <string>("InspectionType");
            var    inspectionType       = InspectionType.DeviceBrand;

            Enum.TryParse(inspectionTypeString, out inspectionType);
            if (inspectionType == InspectionType.DeviceBrand)
            {
                var brand = _commonServices.GetDeviceBrandByUserAgent().ToString();
                yield return(T(brand));
            }
            else
            {
                yield return(T("Unknown"));
            }
        }
Example #38
0
        public void TracerProviderSdkInvokesSamplingWithCorrectParameters()
        {
            var testSampler = new TestSampler();

            using var activitySource = new ActivitySource(ActivitySourceName);
            using var tracerProvider = Sdk.CreateTracerProviderBuilder()
                                       .AddSource(ActivitySourceName)
                                       .SetSampler(testSampler)
                                       .Build();

            // OpenTelemetry Sdk is expected to set default to W3C.
            Assert.True(Activity.DefaultIdFormat == ActivityIdFormat.W3C);

            using (var rootActivity = activitySource.StartActivity("root"))
            {
                Assert.NotNull(rootActivity);
                Assert.True(rootActivity.ParentSpanId == default);

                // Validate that the TraceId seen by Sampler is same as the
                // Activity when it got created.
                Assert.Equal(rootActivity.TraceId, testSampler.LatestSamplingParameters.TraceId);
            }

            using (var parent = activitySource.StartActivity("parent", ActivityKind.Client))
            {
                Assert.Equal(parent.TraceId, testSampler.LatestSamplingParameters.TraceId);
                using (var child = activitySource.StartActivity("child"))
                {
                    Assert.Equal(child.TraceId, testSampler.LatestSamplingParameters.TraceId);
                    Assert.Equal(parent.TraceId, child.TraceId);
                    Assert.Equal(parent.SpanId, child.ParentSpanId);
                }
            }

            var customContext = new ActivityContext(
                ActivityTraceId.CreateRandom(),
                ActivitySpanId.CreateRandom(),
                ActivityTraceFlags.None);

            using (var fromCustomContext =
                       activitySource.StartActivity("customContext", ActivityKind.Client, customContext))
            {
                Assert.Equal(fromCustomContext.TraceId, testSampler.LatestSamplingParameters.TraceId);
                Assert.Equal(customContext.TraceId, fromCustomContext.TraceId);
                Assert.Equal(customContext.SpanId, fromCustomContext.ParentSpanId);
                Assert.NotEqual(customContext.SpanId, fromCustomContext.SpanId);
            }

            // Validate that when StartActivity is called using Parent as string,
            // Sampling is called correctly.
            var act = new Activity("anything").Start();

            act.Stop();
            var customContextAsString = act.Id;
            var expectedTraceId       = act.TraceId;
            var expectedParentSpanId  = act.SpanId;

            using (var fromCustomContextAsString =
                       activitySource.StartActivity("customContext", ActivityKind.Client, customContextAsString))
            {
                Assert.Equal(fromCustomContextAsString.TraceId, testSampler.LatestSamplingParameters.TraceId);
                Assert.Equal(expectedTraceId, fromCustomContextAsString.TraceId);
                Assert.Equal(expectedParentSpanId, fromCustomContextAsString.ParentSpanId);
            }

            using (var fromInvalidW3CIdParent =
                       activitySource.StartActivity("customContext", ActivityKind.Client, "InvalidW3CIdParent"))
            {
                // OpenTelemetry ActivityContext does not support
                // non W3C Ids. Starting activity with non W3C Ids
                // will result in no activity being created.
                Assert.Null(fromInvalidW3CIdParent);
            }
        }
Example #39
0
 public ActivityController(ActivityContext context)
 {
     _context = context;
 }
Example #40
0
 public virtual Task <bool> CanExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
 {
     return(Task.FromResult(CanExecute(workflowContext, activityContext)));
 }
Example #41
0
 public abstract IEnumerable <Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext);
Example #42
0
 public virtual bool CanExecute(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
 {
     return(true);
 }
Example #43
0
 public virtual Task <ActivityExecutionResult> ResumeAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
 {
     return(Task.FromResult(Resume(workflowContext, activityContext)));
 }
Example #44
0
 public virtual ActivityExecutionResult Resume(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
 {
     return(Noop());
 }
Example #45
0
 public virtual Task OnActivityExecutingAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Task.CompletedTask);
 }
        public override bool CanExecute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var part = workflowContext.Content.As <WXMsgPart>();

            return(part.MsgType == "text");
        }
        internal static bool TryParseXRayTraceHeader(string rawHeader, out ActivityContext activityContext)
        {
            // from https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader
            // rawHeader format: Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1

            activityContext = default;
            ReadOnlySpan <char> traceId  = default;
            ReadOnlySpan <char> parentId = default;
            char traceOptions            = default;

            if (string.IsNullOrEmpty(rawHeader))
            {
                return(false);
            }

            ReadOnlySpan <char> header = rawHeader.AsSpan();

            while (header.Length > 0)
            {
                int delimiterIndex = header.IndexOf(TraceHeaderDelimiter);
                ReadOnlySpan <char> part;
                if (delimiterIndex >= 0)
                {
                    part   = header.Slice(0, delimiterIndex);
                    header = header.Slice(delimiterIndex + 1);
                }
                else
                {
                    part   = header.Slice(0);
                    header = header.Slice(header.Length);
                }

                ReadOnlySpan <char> trimmedPart = part.Trim();
                int equalsIndex = trimmedPart.IndexOf(KeyValueDelimiter);
                if (equalsIndex < 0)
                {
                    return(false);
                }

                ReadOnlySpan <char> value = trimmedPart.Slice(equalsIndex + 1);
                if (trimmedPart.StartsWith(RootKey.AsSpan()))
                {
                    if (!TryParseOTFormatTraceId(value, out var otFormatTraceId))
                    {
                        return(false);
                    }

                    traceId = otFormatTraceId;
                }
                else if (trimmedPart.StartsWith(ParentKey.AsSpan()))
                {
                    if (!IsParentIdValid(value))
                    {
                        return(false);
                    }

                    parentId = value;
                }
                else if (trimmedPart.StartsWith(SampledKey.AsSpan()))
                {
                    if (!TryParseSampleDecision(value, out var sampleDecision))
                    {
                        return(false);
                    }

                    traceOptions = sampleDecision;
                }
            }

            if (traceId == default || parentId == default || traceOptions == default)
            {
                return(false);
            }

            var activityTraceId      = ActivityTraceId.CreateFromString(traceId);
            var activityParentId     = ActivitySpanId.CreateFromString(parentId);
            var activityTraceOptions = traceOptions == SampledValue ? ActivityTraceFlags.Recorded : ActivityTraceFlags.None;

            activityContext = new ActivityContext(activityTraceId, activityParentId, activityTraceOptions, isRemote: true);

            return(true);
        }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            TicketPart                ticketPart      = workflowContext.Content.As <TicketPart>();
            CRMCommentPart            commentPart     = workflowContext.Content.As <CRMCommentPart>();
            ContentItemPermissionPart permissionsPart = workflowContext.Content.As <ContentItemPermissionPart>();

            if (ticketPart == null)
            {
                if (commentPart == null)
                {
                    this.Logger.Debug("ContentItem mismatch: Expexting TicketPart");
                    return(new[] { T("Failed") });
                }
                else
                {
                    var contentPart = this.contentManager.Get(commentPart.Record.CRMCommentsPartRecord.ContentItemRecord.Id);
                    ticketPart      = contentPart.As <TicketPart>();
                    permissionsPart = contentPart.As <ContentItemPermissionPart>();
                }
            }

            if (permissionsPart == null)
            {
                this.Logger.Debug("ContentItem mismatch: Expexting ContentItemPermissionPart ");
                return(new[] { T("Failed") });
            }

            // setup tokenizer
            Dictionary <string, object> temp = new Dictionary <string, object>();

            temp.Add("Content", workflowContext.Content);
            var titlePart = ticketPart.As <TitlePart>();

            // read email template Id
            string emailTemplateIdString = activityContext.GetState <string>(EmailTemplateActivityForm.EmailTemplateIdFieldName);
            int    emailTemplateId;

            if (!int.TryParse(emailTemplateIdString, out emailTemplateId))
            {
                this.Logger.Debug("There is no email Template for new Tickets");
                return(new[] { T("Failed") });
            }

            bool sendToRequestingUser  = this.GetBooleanValue(activityContext, EmailTemplateActivityForm.SentToRequestingUserFieldName);
            bool sendToOwner           = this.GetBooleanValue(activityContext, EmailTemplateActivityForm.SentToOwnerFieldName);
            bool sendToSharedWithUsers = this.GetBooleanValue(activityContext, EmailTemplateActivityForm.SentToSharedUsersFieldName);

            var ticketEmailTemplate = this.emailTemplateRepository.Table.First(c => c.Id == emailTemplateId);

            if (ticketEmailTemplate == null)
            {
                this.Logger.Debug("There is no email Template for new Tickets");
                return(new[] { T("Failed") });
            }

            var queued   = activityContext.GetState <bool>("Queued");
            var priority = activityContext.GetState <int>("Priority");

            List <UserPartRecord> recipients = new List <UserPartRecord>();

            if (permissionsPart.Record.Items != null)
            {
                foreach (var permission in permissionsPart.Record.Items)
                {
                    if (permission.AccessType == ContentItemPermissionAccessTypes.Assignee && sendToOwner)
                    {
                        recipients.AddRange(this.GetRecipients(permission));
                    }
                    else if (sendToSharedWithUsers)
                    {
                        recipients.AddRange(this.GetRecipients(permission));
                    }
                }
            }

            if (sendToRequestingUser)
            {
                var record = ticketPart.Record;
                if (record.RequestingUser != null)
                {
                    recipients.Add(record.RequestingUser);
                }
                else if (record.SourceId == TicketSourceTypes.Email &&
                         !string.IsNullOrEmpty(record.SourceData))
                {
                    dynamic sender = JObject.Parse(record.SourceData);
                    string  email  = sender.Email;
                    string  name   = sender.Name;
                    recipients.Add(new UserPartRecord {
                        Email = email, UserName = name
                    });
                }
            }

            // filter the redundent items
            recipients = recipients.GroupBy(c => c.Id).Select(c => c.First()).ToList();

            foreach (var recipient in recipients.Where(c => !string.IsNullOrEmpty(c.Email)))
            {
                temp[ActivityTokenProvider.UserKey] = recipient;
                string body    = this.tokenizer.Replace(ticketEmailTemplate.Body, temp);
                string subject = this.tokenizer.Replace(ticketEmailTemplate.Subject, temp);
                this.SendEmail(subject, body, recipient.Email, queued, priority);
            }

            return(new[] { T("Done") });
        }
 public override IEnumerable <LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext, ActivityContext activityContext)
 {
     return(new[] { T("Done"), T("Failed") });
 }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            ContentItem contentItem = null;

            if (workflowContext != null && workflowContext.Content != null)
            {
                contentItem = workflowContext.Content.ContentItem;
            }

            var  device      = activityContext.GetState <string>("allDevice");
            var  PushMessage = activityContext.GetState <string>("PushMessage");
            bool produzione  = activityContext.GetState <string>("Produzione") == "Produzione";
            var  usersList   = activityContext.GetState <string>("userId") ?? "";
            int  iUser       = 0;

            string users = "";

            string[] userList;
            if (device == "UserId")
            {
                int.TryParse(usersList, out iUser);
                userList = usersList.Split(',', ' ');
                List <int> iUserList = new List <int>();
                foreach (string uId in userList)
                {
                    if (int.TryParse(uId, out iUser))
                    {
                        iUserList.Add(iUser);
                    }
                }
                users = string.Join(",", iUserList);
            }
            else if (device.Equals("UserEmail"))
            {
                userList = usersList.Split(',', ' ');
                List <string> neUserList = new List <string>();
                foreach (string neUser in userList)
                {
                    neUserList.Add("'" + GetSafeSqlString(neUser) + "'");
                }
                users = string.Join(",", neUserList);
            }
            else if (device.Equals("UserName"))
            {
                userList = usersList.Split(',', ' ');
                List <string> neUserList = new List <string>();
                foreach (string neUser in userList)
                {
                    neUserList.Add("'" + GetSafeSqlString(neUser) + "'");
                }
                users = string.Join(",", neUserList);
            }

            int    idRelated      = 0;
            string stateIdRelated = activityContext.GetState <string>("idRelated");

            if (stateIdRelated == "idRelated" && contentItem != null)   //caso necessario per il pregresso
            {
                idRelated = contentItem.Id;
            }
            else
            {
                int.TryParse(stateIdRelated, out idRelated);
            }
            string language    = activityContext.GetState <string>("allLanguage");
            string querydevice = "";

            if (contentItem == null && (device == "ContentOwner" || device == "ContentCreator" || device == "ContentLastModifier"))
            {
                querydevice = " SELECT  distinct P.* " +
                              " FROM  Laser_Orchard_Mobile_PushNotificationRecord AS P " +
                              " Where 0 = 1";       //necessario per non spedire le push a tutti
                device = "All";
            }
            else
            {
                if (device == "ContentOwner")
                {
                    querydevice = " SELECT  distinct P.* " +
                                  " FROM  Laser_Orchard_Mobile_PushNotificationRecord AS P " +
                                  " LEFT OUTER JOIN Laser_Orchard_Mobile_UserDeviceRecord AS U ON P.UUIdentifier = U.UUIdentifier " +
                                  " Where U.UserPartRecord_Id=" + contentItem.As <CommonPart>().Owner.Id.ToString();
                    device = "All";
                }
                if (device == "ContentCreator")
                {
                    querydevice = " SELECT  distinct P.* " +
                                  " FROM  Laser_Orchard_Mobile_PushNotificationRecord AS P " +
                                  " LEFT OUTER JOIN Laser_Orchard_Mobile_UserDeviceRecord AS U ON P.UUIdentifier = U.UUIdentifier " +
                                  " Where U.UserPartRecord_Id=" + ((dynamic)contentItem.As <CommonPart>()).Creator.Value.ToString();

                    device = "All";
                }
                if (device == "ContentLastModifier")
                {
                    querydevice = " SELECT  distinct P.* " +
                                  " FROM  Laser_Orchard_Mobile_PushNotificationRecord AS P " +
                                  " LEFT OUTER JOIN Laser_Orchard_Mobile_UserDeviceRecord AS U ON P.UUIdentifier = U.UUIdentifier " +
                                  " Where U.UserPartRecord_Id=" + ((dynamic)contentItem.As <CommonPart>()).LastModifier.Value.ToString();

                    device = "All";
                }
                if (device == "UserId")
                {
                    querydevice = " SELECT  distinct P.* " +
                                  " FROM  Laser_Orchard_Mobile_PushNotificationRecord AS P " +
                                  " LEFT OUTER JOIN Laser_Orchard_Mobile_UserDeviceRecord AS U ON P.UUIdentifier = U.UUIdentifier " +
                                  " Where U.UserPartRecord_Id in (" + users + ")";

                    device = "All";
                }
                if (device == "UserEmail")
                {
                    querydevice = " SELECT  distinct P.* " +
                                  " FROM  Laser_Orchard_Mobile_PushNotificationRecord AS P " +
                                  " LEFT OUTER JOIN Laser_Orchard_Mobile_UserDeviceRecord AS U ON P.UUIdentifier = U.UUIdentifier " +
                                  " INNER JOIN Orchard_Users_UserPartRecord AS Ou ON Ou.Id = U.UserPartRecord_Id " +
                                  " Where Ou.Email in (" + users + ")";

                    device = "All";
                }
                if (device == "UserName")
                {
                    querydevice = " SELECT  distinct P.* " +
                                  " FROM  Laser_Orchard_Mobile_PushNotificationRecord AS P " +
                                  " LEFT OUTER JOIN Laser_Orchard_Mobile_UserDeviceRecord AS U ON P.UUIdentifier = U.UUIdentifier " +
                                  " INNER JOIN Orchard_Users_UserPartRecord AS Ou ON Ou.Id = U.UserPartRecord_Id " +
                                  " Where Ou.UserName in (" + users + ")";

                    device = "All";
                }
            }

            // schedule the sending of the push notification
            try {
                var ci   = _orchardServices.ContentManager.Create("BackgroundPush");
                var part = ci.As <MobilePushPart>();
                part.DevicePush       = device;
                part.PushSent         = false;
                part.TestPush         = !produzione;
                part.TestPushToDevice = false;
                part.TextPush         = PushMessage;
                part.ToPush           = true;
                part.UseRecipientList = false;
                var relatedContentField = part.Fields.FirstOrDefault(x => x.Name == "RelatedContent");
                if (relatedContentField != null)
                {
                    (relatedContentField as ContentPickerField).Ids = new int[] { idRelated };
                }
                // we cannot use part settings to specify this queryDevice value because it can change for each BackgroundPush item
                // so we use a dedicated field on this content item
                var queryField = ci.Parts.FirstOrDefault(x => x.PartDefinition.Name == "BackgroundPush").Fields.FirstOrDefault(x => x.Name == "QueryDevice");
                (queryField as TextField).Value = querydevice;
                // force publish of content item to manage the content picker field the right way (field index)
                // and to start scheduled task that will send push notifications
                ci.VersionRecord.Published = false;
                _orchardServices.ContentManager.Publish(ci);
            } catch (Exception ex) {
                Logger.Error(ex, "PushTask - Error starting asynchronous thread to send push notifications.");
            }
            yield return(T("Sent"));
        }
Example #51
0
 public override bool CanExecute(WorkflowContext workflowContext, ActivityContext activityContext)
 {
     return(true);
 }
 public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
 {
     yield return(T("Done"));
 }
Example #53
0
        public override IEnumerable <LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            string inspectionTypeString = activityContext.GetState <string>("InspectionType");

            return(_activityServices.RequestInspectorWokflowOutcomes(inspectionTypeString));
        }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var url = activityContext.GetState <string>("Url");

            // Redirect is going to terminate the request, which will cause any pending updates to get rolled back,
            // so we force a commit in case anything has changed
            _tm.RequireNew();

            _wca.GetContext().HttpContext.Response.Redirect(url);
            yield return(T("Done"));
        }
Example #55
0
        public void PlayVideo(string videoUrL, Get_Movies_Object.Movie videoObject)
        {
            try
            {
                if (videoObject != null)
                {
                    Videodata = videoObject;

                    LoadVideo_Data(videoObject);

                    ReleaseVideo();

                    if (Settings.Allow_Offline_Download == false)
                    {
                        Download_icon.Visibility = ViewStates.Gone;
                    }

                    mFullScreenIcon.SetImageDrawable(ActivityContext.GetDrawable(Resource.Drawable.ic_action_ic_fullscreen_expand));

                    Android.Net.Uri videoURL;
                    if (!string.IsNullOrEmpty(videoUrL))
                    {
                        videoURL = Android.Net.Uri.Parse(videoUrL);
                    }
                    else
                    {
                        videoURL = Android.Net.Uri.Parse(Videodata.source);
                    }

                    mainHandler = new Handler();

                    AdaptiveTrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
                    DefaultTrackSelector           trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);

                    Player = ExoPlayerFactory.NewSimpleInstance(ActivityContext, trackSelector);
                    DefaultDatamediaFactory = new DefaultDataSourceFactory(ActivityContext, Util.GetUserAgent(ActivityContext, Settings.Application_Name), BANDWIDTH_METER);

                    // Produces DataSource instances through which media data is loaded.
                    ExtractorMediaSource DefaultSource = new ExtractorMediaSource(videoURL, DefaultDatamediaFactory, new DefaultExtractorsFactory(), mainHandler, eventLogger);

                    videoSource = null;

                    //Set Interactive Media Ads
                    if (Player_Settings.ShowInteractiveMediaAds)
                    {
                        videoSource = CreateAdsMediaSource(DefaultSource, Player_Settings.IMAdsUri);
                    }

                    if (simpleExoPlayerView == null)
                    {
                        Initialize();
                    }

                    //Set Cache Media Load
                    if (Player_Settings.EnableOfflineMode)
                    {
                        videoSource = videoSource == null?CreateCacheMediaSource(DefaultSource, videoURL) : CreateCacheMediaSource(videoSource, videoURL);

                        if (videoSource != null)
                        {
                            Download_icon.SetImageDrawable(ActivityContext.GetDrawable(Resource.Drawable.ic_checked_red));
                            Download_icon.Tag = "Downloaded";

                            simpleExoPlayerView.Player = Player;
                            Player.Prepare(videoSource);
                            Player.AddListener(PlayerLitsener);
                            Player.PlayWhenReady = true;

                            bool haveResumePosition = resumeWindow != C.IndexUnset;
                            if (haveResumePosition)
                            {
                                Player.SeekTo(resumeWindow, resumePosition);
                            }

                            return;
                        }
                    }

                    if (videoSource == null)
                    {
                        if (!string.IsNullOrEmpty(videoUrL))
                        {
                            if (videoUrL.Contains("youtube") || videoUrL.Contains("Youtube") || videoUrL.Contains("youtu"))
                            {
                                Task.Run(async() =>
                                {
                                    var newurl  = await VideoInfoRetriever.GetEmbededVideo(Videodata.source);
                                    videoSource = CreateDefaultMediaSource(Android.Net.Uri.Parse(newurl));
                                });
                            }
                            else
                            {
                                videoSource = CreateDefaultMediaSource(Android.Net.Uri.Parse(videoUrL));

                                simpleExoPlayerView.Player = Player;
                                Player.Prepare(videoSource);
                                Player.AddListener(PlayerLitsener);
                                Player.PlayWhenReady = true;

                                bool haveResumePosition = resumeWindow != C.IndexUnset;
                                if (haveResumePosition)
                                {
                                    Player.SeekTo(resumeWindow, resumePosition);
                                }
                            }
                        }
                    }
                    else
                    {
                        simpleExoPlayerView.Player = Player;
                        Player.Prepare(videoSource);
                        Player.AddListener(PlayerLitsener);
                        Player.PlayWhenReady = true;

                        bool haveResumePosition = resumeWindow != C.IndexUnset;
                        if (haveResumePosition)
                        {
                            Player.SeekTo(resumeWindow, resumePosition);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Crashes.TrackError(exception);
            }
        }
 public override IEnumerable <LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext, ActivityContext activityContext)
 {
     yield return(T("Done"));
 }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var            records     = this.GetData().ToList();
            TicketPart     ticketPart  = workflowContext.Content.As <TicketPart>();
            CRMCommentPart commentPart = workflowContext.Content.As <CRMCommentPart>();

            if (ticketPart == null)
            {
                if (commentPart == null)
                {
                    this.Logger.Debug("ContentItem mismatch: Expexting TicketPart");
                    return(new[] { T("Failed") });
                }
                else
                {
                    var contentPart = this.contentManager.Get(commentPart.Record.CRMCommentsPartRecord.ContentItemRecord.Id);
                    ticketPart = contentPart.As <TicketPart>();
                }
            }

            var record = this.GetFromTicket(ticketPart);

            if (record == null)
            {
                this.Logger.Debug("TicketPart doesn't have any " + BasicDataRecordName);
                return(new[] { T(this.UnknownValue) });
            }

            return(new[] { this.T(record.Name) });
        }
        public override bool CanExecute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var url = activityContext.GetState <string>("Url");

            return(!string.IsNullOrWhiteSpace(url));
        }
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            double lat1 = 0, lng1 = 0, distance = 0, distance1 = 0;
            bool   flag = true;
            var    part = workflowContext.Content.As <WXMsgPart>();

            try
            {
                lat1      = activityContext.GetState <double>("lat1");
                lng1      = activityContext.GetState <double>("lng1");
                distance  = activityContext.GetState <double>("distance");
                distance1 = _winXinService.GetDistance(lat1, lng1, part.Location_X, part.Location_Y);
            }
            catch { flag = false; }

            if (lat1 + lat1 + distance == 0 || !flag)
            {
                yield return(T("缺省"));

                yield break;
            }

            if (distance1 <= distance)
            {
                yield return(T("在范围内"));

                yield break;
            }
            else
            {
                yield return(T("在范围外"));

                yield break;
            }
        }
Example #60
0
 public virtual Task OnActivityExecutedAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
 {
     return(Task.CompletedTask);
 }