void DMcreatedCallback(TwitterDirectMessage incomingDM) { if (DMReceived != null) { DMReceived(incomingDM, privOAuth); } }
private void getUserMessages(string username) { getWaitCursor(); TwitterResponse <TwitterDirectMessageCollection> timeline = TwitterDirectMessage.DirectMessages(_authToken); if (timeline.Result == RequestResult.Success) { listboxMentionsTimeline.Items.Clear(); try { //MessageBox.Show(timeline.ResponseObject); for (int i = 0; i < timeline.ResponseObject.Count; i++) { var result = timeline.ResponseObject[i]; ListBoxItem itm = new ListBoxItem(); itm.Name = result.Sender.ScreenName; itm.Content = result.Sender.ScreenName + ": " + result.Text + result.CreatedDate; listboxMessagesTimeline.Items.Add(itm); } } catch (TwitterizerException) { MessageBox.Show("Erro"); } } else { MessageBox.Show(timeline.ErrorMessage); } getDefaultCursor(); }
public void InsertDM(FlowLayoutPanel panel, TwitterDirectMessage dm) { this.Invoke(new Action(delegate { // insert new DM in list TweetControl tc = new TweetControl(); Global.DownloadImageToPictureBox(tc.picAvatar, dm.Sender.ProfileImageSecureLocation, this); tc.labelFollowers.Text = dm.Sender.NumberOfFollowers.Value.ToString(); tc.labelName.Text = dm.Sender.ScreenName; tc.labelDate.Text = FormatDate(dm.CreatedDate); tc.labelVia.Text = "via Direct Message"; tc.labelInReplyTo.Text = ""; //tc.labelText.Text = dm.Text; tc.rtText.Text = dm.Text; FindAlternativeLinks(tc.rtText); tc.Width = panel.Width - 8 - panel.Padding.Right; tc.DM = dm; panel.Controls.Add(tc); panel.Controls.SetChildIndex(tc, 0); // limit amount of tweets in list if (panel.Controls.Count > 100) { // delete anything after 100 for (int i = 101; i < panel.Controls.Count; i++) { panel.Controls.RemoveAt(101); // index should always be 101... o___o // this loop looks weird. } } })); }
public static TwitterItem writeDirectMessage(AccountTwitter account, string receiver, string text) { try { SendDirectMessageOptions options = new SendDirectMessageOptions(); options.Text = text; options.ScreenName = receiver; TwitterDirectMessage status = account.twitterService.SendDirectMessage(options); if (status != null) { return(API.TweetSharpConverter.getItemFromDirectMessage(status, account)); } else { System.Windows.MessageBox.Show("Failed", "Sending of dm failed"); return(null); } } catch (Exception exp) { System.Windows.MessageBox.Show(exp.Message, "Sending of dm failed"); return(null); } }
public JsonResult TwitterSendDirectMessage() { bool result = false; string _consumerKey = System.Configuration.ConfigurationManager.AppSettings["consumerKeyLogin"]; string _consumerSecret = System.Configuration.ConfigurationManager.AppSettings["consumerSecretLogin"]; TwitterService service = new TwitterService(_consumerKey, _consumerSecret); service.AuthenticateWith(Session[Sessionvars.TwitterRequestToken].ToString(), Session[Sessionvars.TwitterRequestTokenSecert].ToString()); string TwitterDirectMessage = Request.Params["TwitterDM"]; string ListSelectUserDM = Convert.ToString(Request.Params["SelectedUserForDM"]); char[] splitchars = { ',' }; string[] DirectMessageUserId = ListSelectUserDM.Split(splitchars, StringSplitOptions.RemoveEmptyEntries); if (DirectMessageUserId.Count() > 0) { foreach (var list in DirectMessageUserId) { TwitterDirectMessage Ds = service.SendDirectMessage(Convert.ToInt32(list), TwitterDirectMessage); } result = true; } return(Json(result, JsonRequestBehavior.AllowGet)); }
protected virtual void Dispose(bool disposing) { if (disposing) { AtNameLabel = null; datelabel = null; replyBtn = null; TweetBlock = null; tweetImg = null; contextmenu = null; dbUser = null; ID = null; imageborder = null; label1 = null; messagePolygon = null; name = null; NameLabel = null; parent = null; polyOpacity = 0; replyBtn = null; replyimageborder = null; Status = null; tweetelementgrid = null; DM_Element = null; } }
static void NewDirectMessage(TwitterDirectMessage message) { if (!jsonView) { Console.WriteLine(string.Format("New message from {0}", message.SenderScreenName)); } }
/// <summary> /// ダイレクトメッセージの追加に際しての処理 /// </summary> private static TweetViewModel RegisterDirectMessage(TwitterDirectMessage dmsg) { UserStorage.Register(dmsg.Sender); UserStorage.Register(dmsg.Recipient); var vm = RegisterCore(dmsg); EventStorage.OnDirectMessage(vm); return(vm); }
public void InsertDMIn(TwitterDirectMessage dm, ColumnType colType) { for (int i = 0; i < flowColumns.Controls.Count; i++) { ColumnControl cc = (ColumnControl)flowColumns.Controls[i]; if (cc.ColType == colType) { cc.InsertDM(cc.flowColumn, dm); } } }
public static string GetPairName(this TwitterDirectMessage msg, UserToken user) { if (msg.SenderId == user.Id) { return(msg.RecipientScreenName); } else { return(msg.SenderScreenName); } }
/// <summary> /// Get direct messages /// </summary> private static IEnumerable <TwitterDirectMessage> GetDirectMessages(this CredentialProvider provider, string partialUri, IEnumerable <KeyValuePair <string, string> > param) { var doc = provider.RequestAPIv1(partialUri, CredentialProvider.RequestMethod.GET, param); if (doc == null) { return(null); } List <TwitterStatus> statuses = new List <TwitterStatus>(); HashSet <string> hashes = new HashSet <string>(); return(doc.Root.Elements().Select(n => TwitterDirectMessage.FromNode(n)).Where(d => d != null)); }
private static void writeTwitterDMS() { Requester requester = new Requester(); string response = requester.makeGetHttpRequest("https://api.twitter.com/1.1/followers/ids.json"); SendDirectMessageOptions options = new SendDirectMessageOptions(); //options.UserId = J options.Text = "dm messages"; TwitterService service = new TwitterService(ConsumerKey, ConsumerKeySecret, AccessToken, AccessTokenSecret); TwitterDirectMessage dm = service.SendDirectMessage(options); }
public static bool SendDmMessage(string SenderScreenName, string ReciverScreenName, string Message, out RequestResult Result) { var vUser = GetUser(SenderScreenName); if (vUser == null) { Result = RequestResult.Unknown; return(false); } if (!Classes.AppSetting.UseProxy || string.IsNullOrWhiteSpace(vUser.ProxyAddress)) { OAuthTokens Oa = GetUserOAuthTokens(SenderScreenName); if (!CanSendMessage(AppSetting.Username, AppSetting.Password, ReciverScreenName, Message, SenderScreenName)) { Result = RequestResult.Unauthorized; return(false); } var omRes = TwitterDirectMessage.Send(Oa, ReciverScreenName, Message); if (omRes.Result == RequestResult.Unauthorized) { if (LoginUser(vUser.ScreenName, vUser.Name, vUser.ProxyAddress)) { return(SendDmMessage(SenderScreenName, ReciverScreenName, Message, out Result)); } else { DeleteUser(vUser); Result = RequestResult.NotAcceptable; return(false); } } Result = omRes.Result; return(Result == RequestResult.Success); } else { var Proxy = vUser.ProxyAddress; var option = new OptionalProperties(); option.Proxy = GetProxy(Proxy); OAuthTokens Oa = GetUserOAuthTokens(SenderScreenName); if (!CanSendMessage(AppSetting.Username, AppSetting.Password, ReciverScreenName, Message, SenderScreenName)) { Result = RequestResult.Unauthorized; return(false); } var omRes = TwitterDirectMessage.Send(Oa, ReciverScreenName, Message, null); Result = omRes.Result; return(Result == RequestResult.Success); } }
/// <summary> /// Delete a direct message which you sent /// </summary> /// <param name="provider">credential provider</param> /// <param name="id">destroy id</param> public static TwitterDirectMessage DestroyDirectMessage(this CredentialProvider provider, long id) { List <KeyValuePair <string, string> > para = new List <KeyValuePair <string, string> >(); para.Add(new KeyValuePair <string, string>("id", id.ToString())); var xmlDoc = provider.RequestAPIv1("direct_messages/destroy.json", CredentialProvider.RequestMethod.POST, para); if (xmlDoc == null) { return(null); } return(TwitterDirectMessage.FromNode(xmlDoc.Root)); }
public DMElement(MainWindow1 prnt, TwitterDirectMessage status, UserDatabase.User usr, ImageSource Imagesource, bool MoreThanOneUser = false) { InitializeComponent(); dbUser = usr; moreusers = MoreThanOneUser; name = status.Sender.ScreenName; tweetImg.Source = Imagesource; ID = status.Id.ToString(); Status = status; parent = prnt; SolidColorBrush gBrush = new SolidColorBrush(Color.FromArgb((byte)(polyOpacity * 255), 0, 0, 0)); messagePolygon.Fill = gBrush; }
/// <summary> /// Send new direct message /// </summary> /// <param name="provider">credential provider</param> /// <param name="user">target user id or name</param> /// <param name="text">send body</param> public static TwitterDirectMessage SendDirectMessage(this CredentialProvider provider, string screenName, string text) { List <KeyValuePair <string, string> > para = new List <KeyValuePair <string, string> >(); para.Add(new KeyValuePair <string, string>("text", HttpUtility.UrlEncodeStrict(text, Encoding.UTF8, true))); para.Add(new KeyValuePair <string, string>("screen_name", screenName)); var xmlDoc = provider.RequestAPIv1("direct_messages/new.json", CredentialProvider.RequestMethod.POST, para); if (xmlDoc == null) { return(null); } return(TwitterDirectMessage.FromNode(xmlDoc.Root)); }
public TwitterMessageBuilder Append(TwitterDirectMessage status, ContactModel sender, bool isHighlight) { if (status == null) { throw new ArgumentNullException("status"); } if (sender == null) { throw new ArgumentNullException("sender"); } // MessageModel serializer expects UTC values TimeStamp = status.CreatedDate.ToUniversalTime(); AppendSenderPrefix(sender, isHighlight); AppendMessage(status.Text); return(this); }
public DirectMessage(TwitterDirectMessage message, DirectMessageRenderingStyle style) { Id = message.Id; if (style == DirectMessageRenderingStyle.Recieved) { ScreenName = message.SenderScreenName; ProfileImageUrlNormal = message.Sender.ProfileImageUrl; ProfileImageUrlBigger = message.Sender.ProfileImageUrl.Replace("_normal.", "_bigger."); } else { ScreenName = message.RecipientScreenName; ProfileImageUrlNormal = message.Recipient.ProfileImageUrl; ProfileImageUrlBigger = message.Recipient.ProfileImageUrl.Replace("_normal.", "_bigger."); } Text = StatusFormattingHelper.FormatLinksAndMentions(message.Text); CreatedDate = StatusFormattingHelper.FormatPrettyDate(message.CreatedDate); }
void o3o_NewDM(TwitterDirectMessage DM, UserDatabase.User _usr) // PLZ CHECK IF WORK { DMElement element; if (UsrDB.Users.Count > 1) { element = new DMElement(this, DM, _usr, ImageCache.GetImage(DM.Sender.Id, DM.Sender.ProfileImageLocation), true); } else { element = new DMElement(this, DM, _usr, ImageCache.GetImage(DM.Sender.Id, DM.Sender.ProfileImageLocation)); } element.polyOpacity = polygonOpacity; this.TweetMessages.Items.Add(element); if (this.TweetMessages.Items.Count > o3o.Properties.Settings.Default.amountOfTWeetsToDisplay) { TweetElement el = (TweetElement)this.TweetMessages.Items[this.TweetMessages.Items.Count - 1]; this.TweetMessages.Items.Remove(el); el.Dispose(); } }
void ReceiveDM(TwitterDirectMessage DM, TwitterResponse response) { IsLoading = false; BarText = ""; if (response.StatusCode == HttpStatusCode.Forbidden) { MessageService.ShowError(Resources.ErrorDuplicateTweet); } else if (response.StatusCode != HttpStatusCode.OK) { MessageService.ShowError(Resources.ErrorMessage); } else { TweetText = ""; DataTransfer.Text = ""; GoBack(); DataTransfer.ReplyingDM = false; } }
private void lsMessage_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index < 0) { return; } var item = lsMessage.Items[e.Index]; var dmUser = item as TwitterUserAddition; e.Graphics.DrawLine(new Pen(Color.FromArgb(100, 100, 100), 3), new Point(0, e.Bounds.Bottom), new Point(e.Bounds.Width, e.Bounds.Bottom)); e.Graphics.DrawImage(dmUser.UserImage, new Rectangle(10 + e.Bounds.Left, 10 + e.Bounds.Top, 50, 50)); e.Graphics.DrawString(dmUser.TwitterUser.ScreenName, new Font(this.Font.FontFamily, 14, FontStyle.Bold, GraphicsUnit.Pixel), new SolidBrush(Color.Gray), new PointF(70 + e.Bounds.Left, 20 + e.Bounds.Top)); TwitterDirectMessage firstMessage = GetFirstMessage(dmUser); e.Graphics.DrawString(firstMessage.Text, new Font(this.Font.FontFamily, 14, FontStyle.Bold, GraphicsUnit.Pixel), new SolidBrush(Color.Gray), new PointF(70 + e.Bounds.Left, 40 + e.Bounds.Top)); e.Graphics.DrawString(firstMessage.CreatedDate.ToShortDateString(), new Font(this.Font.FontFamily, 14, FontStyle.Bold, GraphicsUnit.Pixel), new SolidBrush(Color.Gray), new PointF(e.Bounds.Right, e.Bounds.Top + 5), new StringFormat() { Alignment = StringAlignment.Far }); }
private DirectMessage GetTOBDMFromTSDM(TwitterDirectMessage tdm) { DirectMessage dm = new DirectMessage(); dm.AccountId = Acc.Id; dm.AccountsId = Acc.Id; //dm.Account = Acc; dm.CreationTime = DateTime.Now; dm.SenderId = tdm.SenderId; dm.UserScreenName = tdm.SenderScreenName; dm.UserProfileId = tdm.Sender.Id; //dm.RecipientUserProfileId = tdm.Recipient.Id; dm.Text = tdm.Text; dm.TwitterId = tdm.Id; dm.TwitterCreatedDate = tdm.CreatedDate; dm.SortableColumn = tdm.CreatedDate; UserProfile tup = GetUserProfile(tdm.Sender); if (tup != null) { dm.UserProfileId = tup.Id; } tup = GetUserProfile(tdm.Recipient); if (tup != null) { //dm.RecipientUserProfileId = tup.Id; dm.SearchableString = (dm.Text + " " + tdm.Sender.ScreenName + " " + tdm.Sender.Name).ToLower(); } if (MarkAsRead.Instance.IsMinimized == true || MarkAsRead.Instance.IsNotActive == true) { dm.IsMarkAsRead = false; } else { dm.IsMarkAsRead = true; } return dm; }
void ReceiveDM(TwitterDirectMessage DM, TwitterResponse response) { IsLoading = false; BarText = ""; if (response.StatusCode == HttpStatusCode.Forbidden) MessageService.ShowError(Resources.ErrorDuplicateTweet); else if (response.StatusCode != HttpStatusCode.OK) MessageService.ShowError(Resources.ErrorMessage); else { TweetText = ""; DataTransfer.Text = ""; GoBack(); DataTransfer.ReplyingDM = false; } }
private void ParseDirectMessage(XElement node) { Kind = ElementKind.DirectMessage; Status = TwitterDirectMessage.FromNode(node.Element("direct_message")); }
public void NotifyDirectMessage(TwitterDirectMessage dm) { ShowBalloon( String.Format(MessageDMReceivedFormat, dm.Sender.Name), dm.Text, ToolTipIcon.Info ); if (NotifySoundDMReceivedPlayer != null) NotifySoundDMReceivedPlayer.Play(); }
private void DirectMessageCreated(TwitterDirectMessage status) { }
public GroupedDM(TwitterDirectMessage element, UserToken mainUser) : this(mainUser) { Messages.Add(element); }
public static TwitterItem getItemFromDirectMessage(TwitterDirectMessage directMessage, AccountTwitter account) { TwitterItem item = new TwitterItem(); item.RetrievingAccount = account; string text = Functions.decodeHtml(directMessage.Text); item.Author = getPersonFromUser(directMessage.Sender, account); item.Id = directMessage.Id; item.Source.Name = "Direct message"; item.CreatedAt = directMessage.CreatedDate.ToLocalTime(); item.DMReceipient = getPersonFromUser(directMessage.Recipient, account); if (item.Author.ProfileBackgroundColorString != "") { //item.BackgroundColor = "#" + item.Author.ProfileBackgroundColorString; } try { if (AppController.Current.AllTwitterAccounts.Where(a => a.Login.Id == item.Author.Id).Count() > 0) { Nymphicus.Model.AccountTwitter ownaccount = AppController.Current.AllTwitterAccounts.Where(a => a.Login.Id == item.Author.Id).First(); item.OwnAccountHavingWrittenThisTweet = ownaccount; } } catch { } item.isDirectMessage = true; item.Entities = directMessage.Entities; if (item.Entities != null) { if (item.Entities.Urls != null) { foreach (TwitterUrl urlEntity in item.Entities.Urls) { if (!string.IsNullOrEmpty(urlEntity.ExpandedValue)) { text = text.Replace(urlEntity.Value, urlEntity.ExpandedValue); if (!AppController.Current.AllShortenedLinksInItems.ContainsKey(urlEntity.Value)) { try { AppController.Current.AllShortenedLinksInItems.Add(urlEntity.Value, urlEntity.ExpandedValue); } catch { // as we are asynchron there might be another thread having added it already... } } } } } if (item.Entities.Media != null) { foreach (TwitterMedia mediaEntity in item.Entities.Media) { if (mediaEntity.MediaType == TwitterMediaType.Photo) { if (!string.IsNullOrEmpty(mediaEntity.ExpandedUrl)) { text = text.Replace(mediaEntity.Url, mediaEntity.ExpandedUrl); TwitterItem.embedded_image image = new TwitterItem.embedded_image(); image.url = mediaEntity.ExpandedUrl; image.thumbnail_url = mediaEntity.MediaUrl; item.imagesInPost.Add(image); if (!AppController.Current.AllImagesInItems.ContainsKey(mediaEntity.ExpandedUrl)) { AppController.Current.AllImagesInItems.Add(mediaEntity.ExpandedUrl, mediaEntity.MediaUrl); } } } } } if (item.Entities.HashTags != null) { foreach (TwitterHashTag hashEntity in item.Entities.HashTags) { if (hashEntity != null) { if (!AppController.Current.AllKnownHashtags.Contains("#" + hashEntity.Text)) { AppController.Current.AllKnownHashtags.Add("#" + hashEntity.Text); } } } } } item.Text = text; if (string.IsNullOrEmpty(text)) { return(null); } return(item); }
/// <summary> /// If your twitter account received a direct message /// </summary> /// <param name="message"></param> /// <remarks>Example override: string result = string.Format("New message from {0}", message.SenderScreenName);</remarks> public virtual void NewDirectMessage(TwitterDirectMessage message) { string result = string.Format("New message from {0}", message.SenderScreenName); }
public TwitterDirectMessageCollection GetMessages() { return(TwitterDirectMessage.DirectMessages(privOAuth.GetOAuthToken()).ResponseObject); }
public void DMreply(TwitterDirectMessage Status) { Process.Start("https://twitter.com/messages"); }
/// <summary> /// Converts a raw DM into an InteractiveTweet object /// </summary> private InteractiveTweet ConvertDM(TwitterDirectMessage message) { TweetIdentification create = new TweetIdentification(); if (message.Author.ScreenName != GetUpdates.userScreenName) { try { SoundPlayer notification = new SoundPlayer(); notification.SoundLocation = Environment.CurrentDirectory + "/notification.wav"; notification.Play(); } catch (Exception) { } } InteractiveTweet dm = new InteractiveTweet(); dm.AuthorScreenName = message.Author.ScreenName; dm.Contents = message.Text; dm.ID = message.Id; dm.IsDirectMessage = true; dm.TimePosted = message.CreatedDate; dm.TweetIdentification = create.GenerateIdentification(); return dm; }
/// <summary> /// Create StreamingEvent /// </summary> public StreamingEvent(TwitterDirectMessage dmsg) { this.Kind = ElementKind.DirectMessage; this.Status = dmsg; this.SourceUser = dmsg.User; }
private void CreateDirectMessagesFromJson(TwitterDirectMessage[] item, MyCommon.WORKERTYPE gType, bool read) { foreach (var message in item) { var post = new PostClass(); try { post.StatusId = message.Id; if (gType != MyCommon.WORKERTYPE.UserStream) { if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv) { if (minDirectmessage > post.StatusId) minDirectmessage = post.StatusId; } else { if (minDirectmessageSent > post.StatusId) minDirectmessageSent = post.StatusId; } } //二重取得回避 lock (LockObj) { if (TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage).Contains(post.StatusId)) continue; } //sender_id //recipient_id post.CreatedAt = MyCommon.DateTimeParse(message.CreatedAt); //本文 var textFromApi = message.Text; //HTMLに整形 post.Text = CreateHtmlAnchor(textFromApi, post.ReplyToList, message.Entities, post.Media); post.TextFromApi = this.ReplaceTextFromApi(textFromApi, message.Entities); post.TextFromApi = WebUtility.HtmlDecode(post.TextFromApi); post.TextFromApi = post.TextFromApi.Replace("<3", "\u2661"); post.AccessibleText = this.CreateAccessibleText(textFromApi, message.Entities, quoteStatus: null); post.AccessibleText = WebUtility.HtmlDecode(post.AccessibleText); post.AccessibleText = post.AccessibleText.Replace("<3", "\u2661"); post.IsFav = false; post.QuoteStatusIds = GetQuoteTweetStatusIds(message.Entities).Distinct().ToArray(); post.ExpandedUrls = message.Entities.OfType<TwitterEntityUrl>() .Select(x => new PostClass.ExpandedUrlInfo(x.Url, x.ExpandedUrl)) .ToArray(); //以下、ユーザー情報 TwitterUser user; if (gType == MyCommon.WORKERTYPE.UserStream) { if (this.Api.CurrentUserId == message.Recipient.Id) { user = message.Sender; post.IsMe = false; post.IsOwl = true; } else { user = message.Recipient; post.IsMe = true; post.IsOwl = false; } } else { if (gType == MyCommon.WORKERTYPE.DirectMessegeRcv) { user = message.Sender; post.IsMe = false; post.IsOwl = true; } else { user = message.Recipient; post.IsMe = true; post.IsOwl = false; } } post.UserId = user.Id; post.ScreenName = user.ScreenName; post.Nickname = user.Name.Trim(); post.ImageUrl = user.ProfileImageUrlHttps; post.IsProtect = user.Protected; // メモリ使用量削減 (同一のテキストであれば同一の string インスタンスを参照させる) if (post.Text == post.TextFromApi) post.Text = post.TextFromApi; if (post.AccessibleText == post.TextFromApi) post.AccessibleText = post.TextFromApi; // 他の発言と重複しやすい (共通化できる) 文字列は string.Intern を通す post.ScreenName = string.Intern(post.ScreenName); post.Nickname = string.Intern(post.Nickname); post.ImageUrl = string.Intern(post.ImageUrl); } catch(Exception ex) { MyCommon.TraceOut(ex, MethodBase.GetCurrentMethod().Name); MessageBox.Show("Parse Error(CreateDirectMessagesFromJson)"); continue; } post.IsRead = read; if (post.IsMe && !read && _readOwnPost) post.IsRead = true; post.IsReply = false; post.IsExcludeReply = false; post.IsDm = true; var dmTab = TabInformations.GetInstance().GetTabByType(MyCommon.TabUsageType.DirectMessage); dmTab.AddPostQueue(post); } }
internal void DirectMessageReceived(TwitterDirectMessage directmessage) { this.ResetStopped(); Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object) directmessage), (object) this.MultiAccountifyToken((Enum) ViewModelMessages.StreamingDirectMessage)); }
private UIElement CreateDMPanel(TwitterDirectMessage dm, bool isme) { ListViewItem lvi = new ListViewItem(); lvi.HorizontalContentAlignment = HorizontalAlignment.Right; lvi.Margin = new Thickness(2); var s = new StackPanel(); s.Orientation = Orientation.Horizontal; var so = new StackPanel(); if (isme) { s.HorizontalAlignment = HorizontalAlignment.Right; lvi.HorizontalContentAlignment = HorizontalAlignment.Right; lvi.Background = Brushes.LightCyan; var tb = new TextBlock(); tb.Text = dm.Text; tb.TextWrapping = TextWrapping.Wrap; Image im2 = new Image(); BitmapImage bi = new BitmapImage(new Uri(CurrentUser.ProfileImageUrlHttps)); im2.Source = bi; im2.Width = 36; im2.Height = 36; s.Children.Add(tb); s.Children.Add(im2); var l = new TextBlock { FontSize = 10 }; l.Text = dm.CreatedDate.AddHours(9).ToString(); l.TextAlignment = TextAlignment.Right; so.Children.Add(s); so.Children.Add(l); } else { s.HorizontalAlignment = HorizontalAlignment.Left; lvi.HorizontalContentAlignment = HorizontalAlignment.Left; lvi.Background = Brushes.Honeydew; var tb = new TextBlock(); tb.Text = dm.Text; tb.TextWrapping = TextWrapping.Wrap; Image im2 = new Image(); BitmapImage bi = new BitmapImage(new Uri(TargetUser.ProfileImageUrlHttps)); im2.Source = bi; im2.Width = 36; im2.Height = 36; s.Children.Add(im2); s.Children.Add(tb); var l = new TextBlock { FontSize = 10 }; l.TextAlignment = TextAlignment.Left; l.Text = dm.CreatedDate.AddHours(9).ToString(); so.Children.Add(s); so.Children.Add(l); } lvi.Content = so; return lvi; }