Example #1
0
 public SharedModel(IPostable parentForm, IExportStrategy exportStrategy)
 {
     Utils.CheckNotNull(parentForm, "parentForm");
     Utils.CheckNotNull(exportStrategy, "exportStrategy");
     m_ParentForm   = parentForm;
     ExportStrategy = exportStrategy;
 }
Example #2
0
        /// <summary>
        /// returns all post's likes/dislikes depends on {opinionType}
        /// </summary>
        /// <param name="opinionType">like or dislike</param>
        /// <param name="postType">story or comment</param>
        /// <param name="userName">author of the story</param>
        /// <param name="title">title of the story</param>
        /// <param name="id">id of the comment if {postType} is comment</param>
        /// <returns>a list of likes/dislikes</returns>
        public async Task <ICollection <Opinion> > GetAllOpinionsAsync(string opinionType,
                                                                       string postType,
                                                                       string userName,
                                                                       string title,
                                                                       int id)
        {
            try
            {
                IPostable post = await GetPostWithGivenType(postType, userName, title, id);

                if (post != null)
                {
                    switch (opinionType)
                    {
                    case LIKE:
                        return(post.Likes);

                    case DISLIKE:
                        return(post.Dislikes);

                    default:
                        _logger.LogDebug("Invalid type of the opinions");
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"Error while getting all opinions\n {e.Message}");
            }

            return(null);
        }
Example #3
0
        private bool CanPost(IPostable receipt, IShift shift, decimal money, out string message)
        {
            foreach (var item in receipt.Items)
            {
                if (!item.IsEnough(out float diff))
                {
                    message = $"Товара \"{item.ItemName}\" не хватает на складе ({diff} шт.)";
                    return(false);
                }
            }

            if ((money >= receipt.TotalPrice) && (receipt.GetItemsCount() > 0) && ((money - receipt.TotalPrice) <= shift.Balance))
            {
                message = $"Сдача: {money - receipt.TotalPrice} руб.";
                return(true);
            }
            else if (money < receipt.TotalPrice)
            {
                message = $"к оплате предоставлено недостаточно средств ({receipt.TotalPrice - money})";
                return(false);
            }
            else if (receipt.GetItemsCount() < 1)
            {
                message = $"список товаров пуст";
                return(false);
            }
            else
            {
                message = $"недостаточно средств для выдачи сдачи " +
                          $"({(money - receipt.TotalPrice) - shift.Balance}).\n" +
                          $"(В кассе: {shift.Balance} руб)";
                return(false);
            }
        }
Example #4
0
        // private const string urlUpdate = "https://api.twitter.com/1.1/statuses/update.json";

        /// <summary>
        /// The content to tweet, limited to the requisite 140 chars
        /// </summary>
        /// <param name="o">The IPostable object</param>
        /// <param name="szHost">host to use, branding used if null</param>
        /// <returns>The content of the tweet</returns>
        public static string TweetContent(IPostable o, string szHost)
        {
            if (o == null)
            {
                throw new ArgumentNullException(nameof(o));
            }

            if (!o.CanPost)
            {
                return(string.Empty);
            }

            Uri    uriItem = o.SocialMediaItemUri(szHost);
            string szUri   = uriItem == null ? string.Empty : uriItem.AbsoluteUri;

            int           cch = 140;
            StringBuilder sb  = new StringBuilder(cch);

            cch -= szUri.Length + 1;
            sb.Append(o.SocialMediaComment.LimitTo(cch));
            if (szUri.Length > 0)
            {
                sb.AppendFormat(CultureInfo.CurrentCulture, " {0}", szUri);
            }

            return(sb.ToString());
        }
Example #5
0
 public bool TryPost(IPostable receipt, IShift shift, out string message, decimal money = 0)
 {
     if ((receipt as Receipt != null) && (shift as Shift != null))
     {
         if (this.CanPost(receipt, shift, out string innerMessage))
         {
             using (CashRegisterContext ctx = new CashRegisterContext())
             {
                 using (var transaction = ctx.Database.BeginTransaction())
                 {
                     try
                     {
                         receipt.AssignShiftAndDate(shift);
                         shift.ChangeReturnsStats(receipt.TotalPrice);
                         var s = shift as Shift;
                         var r = receipt as Receipt;
                         s.Receipts.Clear();
                         s.Receipts.Add(r);
                         foreach (var i in s.Receipts[s.Receipts.Count - 1].Items)
                         {
                             i.Receipt        = null;
                             i.Item.Quantity += i.Quantity;
                             ctx.Update(i);
                         }
                         ctx.Shifts.Update(shift as Shift);
                         ctx.SaveChanges();
                         transaction.Commit();
                         foreach (var i in s.Receipts[s.Receipts.Count - 1].Items)
                         {
                             i.Item = null;
                         }
                         message = innerMessage;
                         return(true);
                     }
                     catch (Exception ex)
                     {
                         transaction.Rollback();
                         message = ex.Message;
                         return(false);
                     }
                 }
             }
         }
         else
         {
             message = innerMessage;
             return(false);
         }
     }
     else
     {
         message = "не удалось получить ссылку на экземпляр смены, либо чека";
         return(false);
     }
 }
Example #6
0
        /// <summary>
        /// method to like or dislike post
        /// </summary>
        /// <param name="opinionType">like or dislike</param>
        /// <param name="postType">story or comment</param>
        /// <param name="userName">author of the story</param>
        /// <param name="title">title of the story</param>
        /// <param name="id">id if {postType} is comment</param>
        /// <param name="author">author of the opinion</param>
        /// <returns>if the opinion was added</returns>
        public async Task <bool> AddOpinionAsync(string opinionType,
                                                 string postType,
                                                 string userName,
                                                 string title,
                                                 int id,
                                                 string author)
        {
            try
            {
                Opinion opinion = new Opinion(author);
                opinion.Date = DateTime.Now;

                // first we need to delete user's like/dislike if he did it before
                await DeleteOpinionAsync(opinionType == LIKE?DISLIKE : LIKE,
                                         postType, userName, title, id, opinion.Author);

                IPostable post = await GetPostWithGivenType(postType, userName, title, id);

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

                switch (opinionType)
                {
                case LIKE:
                    if (post.Likes.FindIndex(op => op.Author == opinion.Author) == -1)
                    {
                        post.Likes.Add(opinion);
                    }
                    break;

                case DISLIKE:
                    if (post.Dislikes.FindIndex(op => op.Author == opinion.Author) == -1)
                    {
                        post.Dislikes.Add(opinion);
                    }
                    break;

                default:
                    _logger.LogDebug($"invalid type of the opinion");
                    break;
                }

                return(await UpdatePostWithGivenType(postType, userName, title, post));
            }
            catch (Exception e)
            {
                _logger.LogError($"Error while adding opinion\n {e.Message}");
            }

            return(false);
        }
    /// <summary>
    /// Posts the flight to facebook, setting up authorization as needed.
    /// </summary>
    /// <param name="le">The flight to post</param>
    /// <returns>The Facebook result, empty if not posted or error</returns>
    public void PostFlight(IPostable le)
    {
        if (le == null)
        {
            throw new ArgumentNullException("le");
        }

        Profile pf = MyFlightbook.Profile.GetUser(Page.User.Identity.Name);

        if (pf.CanPostFacebook())
        {
            FDefaultFacebookCheckboxState = true;
            new FacebookPoster().PostToSocialMedia(le, Page.User.Identity.Name, Request.Url.Host);
        }
        else
        {
            MFBFacebook.NotifyFacebookNotSetUp(pf.UserName);
        }
    }
Example #8
0
 private bool CanPost(IPostable receipt, IShift shift, out string message)
 {
     if ((receipt.GetItemsCount() > 0) && (receipt.TotalPrice <= shift.Balance))
     {
         message = $"К возврату: {receipt.TotalPrice} руб";
         return(true);
     }
     else if (receipt.GetItemsCount() < 1)
     {
         message = $"список товаров пуст";
         return(false);
     }
     else
     {
         message = $"недостаточно средств в кассе для выдачи сдачи " +
                   $"({receipt.TotalPrice - shift.Balance}).\n " +
                   $"В кассе: {shift.Balance} руб)";
         return(false);
     }
 }
Example #9
0
        public bool PostToSocialMedia(IPostable o, string szUser, string szHost = null)
        {
            if (o == null)
            {
                throw new ArgumentNullException("o");
            }

            if (!o.CanPost)
            {
                return(false);
            }

            if (String.IsNullOrEmpty(szUser))
            {
                throw new ArgumentNullException("szUser");
            }

            if (String.IsNullOrEmpty(szHost))
            {
                szHost = Branding.CurrentBrand.HostName;
            }

            Profile pf = Profile.GetUser(szUser);

            // Check for user not configured
            if (pf.TwitterAccessToken == null || String.IsNullOrEmpty(pf.TwitterAccessToken))
            {
                return(false);
            }

            oAuthTwitter oAuth = new oAuthTwitter()
            {
                Token = pf.TwitterAccessToken, TokenSecret = pf.TwitterAccessSecret
            };
            string result = oAuth.oAuthWebRequest(oAuthTwitter.Method.POST, urlUpdate, "status=" + HttpUtility.UrlEncode(TweetContent(o, szHost).ToString()));

            return(result.Contains("created_at"));
        }
Example #10
0
        /// <summary>
        /// updates story or comment depends on {postType}
        /// </summary>
        /// <param name="postType">story or comment</param>
        /// <param name="userName">author of the story</param>
        /// <param name="title">title of the story</param>
        /// <param name="post">changed story or comment</param>
        /// <returns>if the post was updated</returns>
        private async Task <bool> UpdatePostWithGivenType(string postType,
                                                          string userName,
                                                          string title,
                                                          IPostable post)
        {
            try
            {
                switch (postType)
                {
                case STORY:
                    return(await _storiesRepository.UpdateStoryAsync(userName, title, (Story)post));

                case COMMENT:
                    return(await _commentsRepository.UpdateCommentAsync(userName, title, (Comment)post));
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"Error while updating post with given type\n {e.Message}");
            }

            return(false);
        }
Example #11
0
        public bool PostToSocialMedia(IPostable o, string szUser, string szHost = null)
        {
            if (o == null)
            {
                throw new ArgumentNullException("o");
            }

            if (!o.CanPost)
            {
                return(false);
            }

            if (String.IsNullOrEmpty(szUser))
            {
                throw new ArgumentNullException("szUser");
            }

            if (String.IsNullOrEmpty(szHost))
            {
                szHost = Branding.CurrentBrand.HostName;
            }

            Profile pf = Profile.GetUser(szUser);

            // Check for user not configured
            if (pf.FacebookAccessToken == null || String.IsNullOrEmpty(pf.FacebookAccessToken.AccessToken))
            {
                return(false);
            }

            // NOTE: We need to update the version code below periodically as the API updates
            const string szUrl = "https://graph.facebook.com/v2.10/me/feed";

            MultipartFormDataContent form = new MultipartFormDataContent();

            Uri uriItem = o.SocialMediaItemUri(szHost);

            MyFlightbook.Image.MFBImageInfo img = o.SocialMediaImage(szHost);

            // Add in the main parameters:
            Dictionary <string, string> dictParams = new Dictionary <string, string>()
            {
                { "access_token", pf.FacebookAccessToken.AccessToken },
                { "message", string.Empty }
            };

            if (uriItem != null)
            {
                dictParams.Add("link", uriItem.AbsoluteUri);
            }

            if (img != null)
            {
                dictParams.Add("picture", img.URLFullImage.ToAbsoluteURL("http", Branding.CurrentBrand.HostName).ToString());
            }

            foreach (string key in dictParams.Keys)
            {
                StringContent sc = new StringContent(dictParams[key]);
                sc.Headers.ContentDisposition = (new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                {
                    Name = key
                });
                sc.Headers.ContentType        = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain")
                {
                    CharSet = "ISO-8859-1"
                };
                form.Add(sc);
            }

            // The remainder can run on a background thread, since we don't do anything that requires a result from here.
            new System.Threading.Thread(() =>
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    try
                    {
                        HttpResponseMessage response = httpClient.PostAsync(new Uri(szUrl), form).Result;
                        string szResult = response.Content.ReadAsStringAsync().Result;

                        if (response.IsSuccessStatusCode)
                        {
                            // do a refresh, to extend as much as possible
                            if (MFBFacebook.ExchangeToken(pf.FacebookAccessToken))
                            {
                                pf.FCommit();
                            }
                        }
                        else
                        {
                            HandleFBFailure(szUser, szResult);
                        }
                    }
                    catch (MyFlightbookException) { }
                    catch (System.ArgumentNullException) { }
                    finally
                    {
                        form.Dispose();
                    }
                }
            }).Start();

            return(true);
        }