public void getNewItem() { m_itemView = InstanceFactory.instance.getRandomItemView(GetComponent<Transform>().position, Quaternion.identity); m_itemView.GetComponent<Transform>().SetParent(this.GetComponent<Transform>()); m_itemView.GetComponent<Transform>().localScale = Vector3.one; m_itemName = m_itemView.m_itemName; m_effectType = m_itemView.m_effectType; }
public void accessShared() { ServicePointManager.ServerCertificateValidationCallback = m_UrlBack.CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // Get the information of the account. service.Credentials = new WebCredentials(EMAIL_ACCOUNT, EMAIL_PWD); // Set the url of server. if (!AutodiscoverUrl(service, EMAIL_ACCOUNT)) { return; } var mb = new Mailbox(SHARED_MAILBOX); var fid1 = new FolderId(WellKnownFolderName.Inbox, mb); // Add a search filter that searches on the body or subject. List<SearchFilter> searchFilterCollection = new List<SearchFilter>(); searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, SUBJECT_KEY_WORD)); SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray()); // Create a view with a page size of 10. var view = new ItemView(10); // Identify the Subject and DateTimeReceived properties to return. // Indicate that the base property will be the item identifier view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived); // Order the search results by the DateTimeReceived in descending order. view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending); // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.) view.Traversal = ItemTraversal.Shallow; String[] invalidStings = { "\\", ",", ":", "*", "?", "\"", "<", ">", "|" }; PropertySet itemPorpertySet = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.MimeContent); FindItemsResults<Item> findResults = service.FindItems(fid1, searchFilter, view); foreach (Item item in findResults.Items) { EmailMessage email = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); email.Load(itemPorpertySet); string emailBody = email.Body.ToString(); } }
public override IEnumerable GetEvaluationBlock() { var info = this.info as PickUpItemStateInfo; var timer = new StepTimer( info.duration ); while ( timer.ValueNormalized < 1f ) { timer.Step( deltaTime ); yield return null; } target.NotifyPickUp( character ); character.inventory.AddItem( target.item ); target = null; }
protected override void InitializeViews() { creationTextView = ItemView.FindViewById <TextView>(Resource.Id.CreationLabel); }
protected override void InitializeViews() { sourceName = ItemView.FindViewById <TextView>(Resource.Id.CalendarSource); }
public Controller(ItemView view) { this.View = view; AttachEvent(); }
protected override void InitializeViews() { textView = ItemView.FindViewById <TextView>(Resource.Id.Text); }
private static int GetItemConst(ItemView item) { return(item.AttackBonus + item.DefenceBonus * 2); }
public void SetView(IView view) { this.view = (ItemView)view; }
protected override void InitializeViews() { mainLogHeaderTitle = ItemView.FindViewById <TextView>(Resource.Id.MainLogHeaderTitle); mainLogHeaderDuration = ItemView.FindViewById <TextView>(Resource.Id.MainLogHeaderDuration); }
void LayoutCover(ItemView aCover, int selectedIndex, bool animated) { int coverNumber = aCover.Number; MonoTouch.CoreAnimation.CATransform3D newTransform; float newZPosition = sideCoverPosition; System.Drawing.PointF newPosition = new System.Drawing.PointF(_halfScreenWidth + aCover.HorizontalPosition, _halfScreenHeight + aCover.VerticalPosition); if (coverNumber < selectedIndex) { newPosition.X -= centerCoverOffset; newTransform = _leftTransform; } else if (coverNumber > selectedIndex) { newPosition.X += centerCoverOffset; newTransform = _rightTransform; } else { newZPosition = 0; newTransform = MonoTouch.CoreAnimation.CATransform3D.Identity; } if (animated) { BeginAnimations(null); SetAnimationCurve(MonoTouch.UIKit.UIViewAnimationCurve.EaseOut); SetAnimationBeginsFromCurrentState(true); } aCover.Layer.Transform = newTransform; aCover.Layer.ZPosition = newZPosition; aCover.Layer.Position = newPosition; if (animated) CommitAnimations(); }
/// <summary> /// カバーフローを初期化する。 /// </summary> private void Initialize() { _coverImages = new System.Collections.Generic.Dictionary<int, CoverImage>(); _onscreenCovers = new System.Collections.Generic.Dictionary<int, ItemView>(); _offscreenCovers = new System.Collections.Generic.Stack<ItemView>(); #if false // デフォルト画像の作成 _defaultImage = new CoverImage(_dataSource.RequestDefaultImage(this)); #endif // スクロールビューの作成 _scrollView = new MonoTouch.UIKit.UIScrollView(Frame) { UserInteractionEnabled = false, MultipleTouchEnabled = false, AutoresizingMask = MonoTouch.UIKit.UIViewAutoresizing.FlexibleHeight | MonoTouch.UIKit.UIViewAutoresizing.FlexibleWidth }; AddSubview(_scrollView); MultipleTouchEnabled = false; UserInteractionEnabled = true; AutosizesSubviews = true; //Layer.Position = new System.Drawing.PointF((float)(Frame.Size.Width / 2), (float)(Frame.Height / 2)); Layer.Position = new System.Drawing.PointF((float)(Frame.Left + Frame.Size.Width / 2), (float)(Frame.Top + Frame.Height / 2)); // Initialize the visible and selected cover range. _lowerVisibleCover = _upperVisibleCover = -1; _selectedCoverView = null; // Set up transforms UpdateTransforms(); // Set some perspective var sublayerTransform = MonoTouch.CoreAnimation.CATransform3D.Identity; sublayerTransform.m34 = -0.01f; _scrollView.Layer.SublayerTransform = sublayerTransform; Bounds = Frame; }
ItemView CoverForIndex(int index) { var coverView = DequeueReusableCover(); if (coverView == null) coverView = new ItemView(this, System.Drawing.RectangleF.Empty); coverView.Number = index; return coverView; }
public void SetSelectedCover(int newSelectedCover) { if (_selectedCoverView != null && (newSelectedCover == _selectedCoverView.Number)) return; int newLowerBound = System.Math.Max(0, newSelectedCover - kCoverBuffer); int newUpperBound = System.Math.Min(_numberOfImages - 1, newSelectedCover + kCoverBuffer); if (_selectedCoverView == null) { // Allocate and display covers from newLower to newUYpper bounds. for (int i = newLowerBound; i <= newUpperBound; i++) { var cover = CoverForIndex(i); _onscreenCovers[i] = cover; UpdateCoverImage(cover); _scrollView.Layer.AddSublayer(cover.Layer); LayoutCover(cover, newSelectedCover, false); } _lowerVisibleCover = newLowerBound; _upperVisibleCover = newUpperBound; _selectedCoverView = _onscreenCovers[newSelectedCover]; return; } // Check to see if the new and current ranges overlap if ((newLowerBound > _upperVisibleCover) || (newUpperBound < _lowerVisibleCover)) { // They do not overlap at all // This does not animate -- assuming it's programmatically set from view controller. // Recycle all onscreen covers. for (int i = _lowerVisibleCover; i <= _upperVisibleCover; i++) { var cover = _onscreenCovers[i]; _offscreenCovers.Push(cover); cover.RemoveFromSuperview(); _onscreenCovers.Remove(i); } // Move all available covers to new location for (int i = newLowerBound; i <= newUpperBound; i++) { var cover = CoverForIndex(i); _onscreenCovers[i] = cover; UpdateCoverImage(cover); _scrollView.Layer.AddSublayer(cover.Layer); } _lowerVisibleCover = newLowerBound; _upperVisibleCover = newUpperBound; _selectedCoverView = _onscreenCovers[newSelectedCover]; LayoutCovers(newSelectedCover, newLowerBound, newUpperBound); return; } else if (newSelectedCover > _selectedCoverView.Number) { for (int i = _lowerVisibleCover; i < newLowerBound; i++) { var cover = _onscreenCovers[i]; if (_upperVisibleCover < newUpperBound) { // Tack it on right side _upperVisibleCover++; cover.Number = _upperVisibleCover; UpdateCoverImage(cover); _onscreenCovers[cover.Number] = cover; LayoutCover(cover, newSelectedCover, false); } else { // Recycle this cover _offscreenCovers.Push(cover); cover.RemoveFromSuperview(); } _onscreenCovers.Remove(i); } _lowerVisibleCover = newLowerBound; // Add in any missing covers on the right up to the newUpperBound. for (int i = _upperVisibleCover + 1; i <= newUpperBound; i++) { var cover = CoverForIndex(i); _onscreenCovers[i] = cover; UpdateCoverImage(cover); _scrollView.Layer.AddSublayer(cover.Layer); LayoutCover(cover, newSelectedCover, false); } _upperVisibleCover = newUpperBound; } else { // Move covers that are now out of range on the right to the left side. // but only if appropriate (within the range set by newLoweBound). for (int i = _upperVisibleCover; i > newUpperBound; i--) { var cover = _onscreenCovers[i]; if (_lowerVisibleCover > newLowerBound) { // Tack it on the left _lowerVisibleCover--; cover.Number = _lowerVisibleCover; UpdateCoverImage(cover); _onscreenCovers[_lowerVisibleCover] = cover; LayoutCover(cover, newSelectedCover, false); } else { // Recycle this cover _offscreenCovers.Push(cover); cover.RemoveFromSuperview(); } } _upperVisibleCover = newUpperBound; // Add in any missing covers on the left down to the newLowerBound for (int i = _lowerVisibleCover - 1; i >= newLowerBound; i--) { var cover = CoverForIndex(i); _onscreenCovers[i] = cover; UpdateCoverImage(cover); _scrollView.Layer.AddSublayer(cover.Layer); LayoutCover(cover, newSelectedCover, false); } _lowerVisibleCover = newLowerBound; } if (_selectedCoverView.Number > newSelectedCover) LayoutCovers(newSelectedCover, newSelectedCover, _selectedCoverView.Number); else if (newSelectedCover > _selectedCoverView.Number) LayoutCovers(newSelectedCover, _selectedCoverView.Number, newSelectedCover); _selectedCoverView = _onscreenCovers[newSelectedCover]; }
private void SetTarget( ItemView target ) { this.target = target; }
private bool IsItemBetterThanEquiped(ItemView item) { return(!Self.equippedItem.HasValue || PlayerBot.ItemValue(item) > PlayerBot.ItemValue(Self.equippedItem)); }
public void Start(object o) { string logpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Roomerror.log"); if (File.Exists(logpath)) { File.Delete(logpath); } StreamWriter sr = new StreamWriter(logpath); try { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); if (string.IsNullOrEmpty(Properties.Settings.Default.Domain)) { service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword); } else { service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword, Properties.Settings.Default.Domain); } if (string.IsNullOrEmpty(Properties.Settings.Default.ExchangeUri)) { service.AutodiscoverUrl(Properties.Settings.Default.EXIMPUser, RedirectionUrlValidationCallback); } else { service.Url = new Uri(Properties.Settings.Default.ExchangeUri + "/ews/exchange.asmx"); } Terms terms = new Terms(); room = o as List <Room>; if (Initialized != null) { Initialized(room.Count); } List <Appointment> Appointments = new List <Appointment>(); XmlDocument doc2 = new XmlDocument(); doc2.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "roommapping.xml")); foreach (Room r in room) { try { if (doc2.SelectSingleNode("/RoomMaps/Room[@name=\"" + r.Name + "\"]") != null) { this.Current = "Removing previous appointments for " + r.Name; if (Updated != null) { Updated(); } service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, doc2.SelectSingleNode("/RoomMaps/Room[@name=\"" + r.Name + "\"]").Attributes["email"].Value); SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection(); searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, terms[0].StartDate)); searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "Lesson:")); bool removecompleted = false; while (!removecompleted) { ItemView view = new ItemView(1000); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view); this.Current = "Found Existing" + findResults.TotalCount + " out of " + findResults.Items.Count + " for " + r.Name; if (Updated != null) { Updated(); } var appsids = new List <ItemId>(); foreach (Item item in findResults.Items) { Appointment appt = item as Appointment; if (appt.AppointmentType == AppointmentType.RecurringMaster) { appsids.Add(appt.Id); } } this.Current = "Removing previous appointments for " + r.Name + " " + appsids.Count; if (Updated != null) { Updated(); } try { if (appsids.Count > 0) { service.DeleteItems(appsids, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences, true); } } catch (Exception e1) { sr.WriteLine(e1.Message); sr.WriteLine(e1.Source); sr.WriteLine(e1); sr.Flush(); System.Threading.Thread.Sleep(1000); } var c = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view).TotalCount; removecompleted = c == 0; if (!removecompleted) { removecompleted = c == 1; } if (!removecompleted) { this.Current = "Remove not completed, still " + c + " to remove for " + r.Name; if (Updated != null) { Updated(); } System.Threading.Thread.Sleep(2000); } } this.Current = "Creating appointments for " + r.Name; if (Updated != null) { Updated(); } var apps = new List <Appointment>(); foreach (Lesson l in r) { this.Current = "Creating appointments for " + r.Name + " - " + l.Class + " on Day " + l.Day; if (Updated != null) { Updated(); } foreach (Term t in terms) { try { if (t.HalfTerm.HasValue) { DateTime hts = t.HalfTerm.Value.StartDate; if (hts.DayOfWeek == DayOfWeek.Monday) { hts = hts.AddDays(-3); } DateTime hte = t.HalfTerm.Value.EndDate; if (hte.DayOfWeek == DayOfWeek.Friday) { hte = hte.AddDays(3); } if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, hts))) == 0) { apps.Add(CreateApp(l, t.StartDate, hts, t.StartWeekNum == 2, service)); } if (hte < t.EndDate) { if (apps.Count(f => f.Body.Text.Contains(GenBody(l, hte, t.EndDate))) == 0) { apps.Add(CreateApp(l, hte, t.EndDate, t.WeekNum(hte) == 2, service)); } } } else if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, t.EndDate))) == 0) { apps.Add(CreateApp(l, t.StartDate, t.EndDate, t.StartWeekNum == 2, service)); } } catch (Exception ex1) { sr.WriteLine(ex1.Message); sr.WriteLine(ex1.Source); sr.WriteLine(ex1); sr.WriteLine(r.Name); sr.Flush(); } } } this.Current = "Creating " + apps.Count + " appointments for " + r.Name; if (Updated != null) { Updated(); } service.CreateItems(apps, null, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone); } } catch (Exception ex) { sr.WriteLine(ex.Message); sr.WriteLine(ex.Source); sr.WriteLine(ex); } this.Progress++; if (Updated != null) { Updated(); } } } catch (Exception e) { sr.WriteLine(e.Message); sr.WriteLine(e.Source); sr.WriteLine(e); } finally { sr.Close(); } if (Done != null) { Done(); } }
/// <summary> /// カバー用画像を更新する。 /// </summary> /// <param name="aCover"></param> void UpdateCoverImage(ItemView aCover) { if (_coverImages.ContainsKey(aCover.Number)) { // リスト内から割り当て aCover.SetImage(_coverImages[aCover.Number].Image, _coverImages[aCover.Number].Height, kReflectionFraction); } else { // データソースに要求 if (null != _dataSource) { MonoTouch.UIKit.UIImage image = _dataSource.RequestImage(this, aCover.Number); if (null != image) { _coverImages.Add(aCover.Number, new CoverImage(image)); aCover.SetImage(_coverImages[aCover.Number].Image, _coverImages[aCover.Number].Height, kReflectionFraction); } else { if (null == _defaultImage) { _defaultImage = new CoverImage(_dataSource.RequestDefaultImage(this)); } aCover.SetImage(_defaultImage.Image, _defaultImage.Height, kReflectionFraction); } } } }
} // End Sub SendMailWithAttachment public static void FindUnreadEmail(ExchangeService service) { try { Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox); } catch (System.Exception e) { System.Console.WriteLine(e); } // The search filter to get unread email. SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And , new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); ItemView view = new ItemView(1); // https://stackoverflow.com/questions/20662855/fetching-all-mails-in-inbox-from-exchange-web-services-managed-api-and-storing-t FindItemsResults <Item> findResults = null; do { // Fire the query for the unread items. // This method call results in a FindItem call to EWS. findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view); System.Console.WriteLine(findResults.TotalCount); foreach (Item item in findResults) { if (item is EmailMessage) { EmailMessage em = item as EmailMessage; System.Console.WriteLine("Subject: \"{0}\"", em.Subject); // https://msdn.microsoft.com/en-us/library/office/dn726695(v=exchg.150).aspx if (em.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, item.Id , new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { System.Console.WriteLine(attachment.Name); if (attachment is FileAttachment) { FileAttachment fa = attachment as FileAttachment; fa.Load(); // System.Console.WriteLine(fa.Content); // System.IO.File.WriteAllBytes(@"d:\" + attachment.Name, fa.Content); // System.Console.WriteLine(fa.ContentType); // System.Console.WriteLine(fa.Content.Length); } // End if (attachment is FileAttachment) else if (attachment is ItemAttachment) { ItemAttachment itemAttachment = attachment as ItemAttachment; itemAttachment.Load(ItemSchema.MimeContent); string fileName = @"C:\Temp\" + itemAttachment.Item.Subject + @".eml"; // Write the bytes of the attachment into a file. // System.IO.File.WriteAllBytes(fileName, itemAttachment.Item.MimeContent.Content); System.Console.WriteLine("Email attachment name: " + itemAttachment.Item.Subject + ".eml"); } // End else if (attachment is ItemAttachment) } // Next attachment } // End if (em.HasAttachments) } // End if (item is EmailMessage) else if (item is MeetingRequest) { MeetingRequest mr = item as MeetingRequest; System.Console.WriteLine("Subject: \"{0}\"", mr.Subject); } else { // we can handle other item types } } // Next item //any more batches? if (findResults.NextPageOffset.HasValue) { view.Offset = findResults.NextPageOffset.Value; } // End if (findResults.NextPageOffset.HasValue) } while (findResults.MoreAvailable); } // End Sub FindUnreadEmail
void SetupInitialState() { //if (_dataSource != null) // _defaultImage = _dataSource.GetDefaultImage(); _scrollView = new MonoTouch.UIKit.UIScrollView(Frame) { UserInteractionEnabled = false, MultipleTouchEnabled = false, AutoresizingMask = MonoTouch.UIKit.UIViewAutoresizing.FlexibleHeight | MonoTouch.UIKit.UIViewAutoresizing.FlexibleWidth }; AddSubview(_scrollView); MultipleTouchEnabled = false; UserInteractionEnabled = true; AutosizesSubviews = true; Layer.Position = new System.Drawing.PointF((float)(Frame.Size.Width / 2), (float)(Frame.Height / 2)); // Initialize the visible and selected cover range. _lowerVisibleCover = _upperVisibleCover = -1; _selectedCoverView = null; // Set up transforms UpdateTransforms(); // Set some perspective var sublayerTransform = MonoTouch.CoreAnimation.CATransform3D.Identity; sublayerTransform.m34 = -0.01f; _scrollView.Layer.SublayerTransform = sublayerTransform; Bounds = Frame; }
public void freeItemView(ItemView itemView) { ObjectPoolManager.Destroy(itemView.gameObject); }
public FeedViewHolder(View itemView, Action <ActionType, Post> postAction, Action <string> tagAction, int height) : base(itemView) { Context = itemView.Context; PhotoPagerType = PostPagerType.Feed; _avatar = itemView.FindViewById <CircleImageView>(Resource.Id.profile_image); _author = itemView.FindViewById <TextView>(Resource.Id.author_name); _gallery = itemView.FindViewById <ImageView>(Resource.Id.gallery); _photosViewPager = itemView.FindViewById <ViewPager>(Resource.Id.post_photos_pager); _pagerTabLayout = ItemView.FindViewById <TabLayout>(Resource.Id.dot_selector); _pagerTabLayout.SetupWithViewPager(_photosViewPager, true); var parameters = _photosViewPager.LayoutParameters; parameters.Height = height; _photosViewPager.LayoutParameters = parameters; _photosViewPager.Adapter = new PostPhotosPagerAdapter(Context, _photosViewPager.LayoutParameters, (post) => postAction.Invoke(PhotoPagerType == PostPagerType.Feed ? ActionType.Photo : ActionType.Preview, post)); _title = itemView.FindViewById <PostCustomTextView>(Resource.Id.first_comment); _commentSubtitle = itemView.FindViewById <TextView>(Resource.Id.comment_subtitle); _time = itemView.FindViewById <TextView>(Resource.Id.time); _likes = itemView.FindViewById <TextView>(Resource.Id.likes); _flags = itemView.FindViewById <TextView>(Resource.Id.flags); _flagsIcon = itemView.FindViewById <ImageView>(Resource.Id.flagIcon); _cost = itemView.FindViewById <TextView>(Resource.Id.cost); _likeOrFlag = itemView.FindViewById <ImageButton>(Resource.Id.btn_like); More = itemView.FindViewById <ImageButton>(Resource.Id.more); _topLikers = itemView.FindViewById <LinearLayout>(Resource.Id.top_likers); NsfwMask = itemView.FindViewById <RelativeLayout>(Resource.Id.nsfw_mask); _nsfwMaskMessage = NsfwMask.FindViewById <TextView>(Resource.Id.mask_message); NsfwMaskSubMessage = NsfwMask.FindViewById <TextView>(Resource.Id.mask_submessage); _nsfwMaskCloseButton = NsfwMask.FindViewById <ImageButton>(Resource.Id.mask_close); _nsfwMaskActionButton = NsfwMask.FindViewById <Button>(Resource.Id.nsfw_mask_button); _author.Typeface = Style.Semibold; _time.Typeface = Style.Regular; _likes.Typeface = Style.Semibold; _flags.Typeface = Style.Semibold; _cost.Typeface = Style.Semibold; _title.Typeface = Style.Regular; _commentSubtitle.Typeface = Style.Regular; _nsfwMaskMessage.Typeface = Style.Light; NsfwMaskSubMessage.Typeface = Style.Light; _moreActionsDialog = new BottomSheetDialog(Context); _moreActionsDialog.Window.RequestFeature(WindowFeatures.NoTitle); _title.MovementMethod = new LinkMovementMethod(); _title.SetHighlightColor(Color.Transparent); _postAction = postAction; _tagAction = tagAction; _likeOrFlag.Click += DoLikeAction; _avatar.Click += DoUserAction; _author.Click += DoUserAction; _cost.Click += DoUserAction; _commentSubtitle.Click += DoCommentAction; _likes.Click += DoLikersAction; _topLikers.Click += DoLikersAction; _flags.Click += DoFlagersAction; _flagsIcon.Click += DoFlagersAction; _nsfwMaskCloseButton.Click += NsfwMaskCloseButtonOnClick; _nsfwMaskActionButton.Click += NsfwMaskActionButtonOnClick; More.Click += DoMoreAction; More.Visibility = BasePresenter.User.IsAuthenticated ? ViewStates.Visible : ViewStates.Invisible; _title.Click += OnTitleOnClick; _title.TagAction += _tagAction; if (_title.OnMeasureInvoked == null) { _title.OnMeasureInvoked += OnTitleOnMeasureInvoked; } }
/// <summary> /// 获取ItemView /// </summary> private ItemView FindItemView(ItemContainer container) { ItemView result = container.view; if (result == null) { bool hasChild = container.trans.childCount > 0; GameObject child = null; if (hasChild) child = container.trans.GetChild(0).gameObject; for (int i = 0, len = viewList.Count; i < len; i++) { ItemView item = viewList[i]; if (hasChild) { // 让子节点为我所用 if (item.View == child) { result = item; break; } } else { // 从缓存列表中查找到一个可用的视图项 if (item.View != null && item.Container == null) { result = item; break; } } } } if (result == null) { // 第二步,如果缓存中没有就构建一个视图项出来 result = new ItemView(); viewList.Add(result); } // 和container互相绑定 container.view = result; result.Container = container; return result; }
public bool SetConversation(ref string kom) { try { string folderToSync = string.Empty; string days = string.Empty; FolderView view = new FolderView(100); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.PropertySet.Add(FolderSchema.DisplayName); view.Traversal = FolderTraversal.Deep; if (service != null) { List <string> lstDirsToChoose = new List <string>(); List <string> lstDirsToDisplay = new List <string>(); //find specific folder lstDirsToChoose.Add(WellKnownFolderName.Inbox.ToString()); lstDirsToChoose.Add(WellKnownFolderName.SentItems.ToString()); lstDirsToDisplay.Add(WellKnownFolderName.Inbox.ToString()); lstDirsToDisplay.Add(WellKnownFolderName.SentItems.ToString()); FolderDecision fd = new FolderDecision(lstDirsToDisplay, true); fd.SelectedFolder = lstDirsToChoose.FirstOrDefault(); fd.ShowDialog(); if (!Directory.Exists(mailDir + "\\" + fd.SelectedFolder.Replace(" ", ""))) { Directory.CreateDirectory(mailDir + "\\" + fd.SelectedFolder.Replace(" ", "")); } mailDir = mailDir + "\\" + fd.SelectedFolder.Replace(" ", ""); folderToSync = lstDirsToChoose.Where(q => q == fd.SelectedFolder).FirstOrDefault(); days = fd.SelectedTime; SearchFilter sfs = new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-int.Parse(days))); int offset = 0; int pageSize = 50; bool more = true; ItemView viewItem = new ItemView(pageSize, offset, OffsetBasePoint.Beginning); FindItemsResults <Item> findResults; List <EmailMessage> emails = new List <EmailMessage>(); while (more) { WellKnownFolderName folderName = WellKnownFolderName.Inbox; if (folderToSync == WellKnownFolderName.Inbox.ToString()) { folderName = WellKnownFolderName.Inbox; } if (folderToSync == WellKnownFolderName.SentItems.ToString()) { folderName = WellKnownFolderName.SentItems; } findResults = service.FindItems(folderName, sfs, viewItem); foreach (var item in findResults.Items) { emails.Add((EmailMessage)item); } more = findResults.MoreAvailable; if (more) { viewItem.Offset += pageSize; } } PropertySet properties = (BasePropertySet.FirstClassProperties); //A PropertySet with the explicit properties you want goes here service.LoadPropertiesForItems(emails, properties); int index = 1; foreach (EmailMessage em in emails) { em.Load(new PropertySet(ItemSchema.MimeContent)); MimeContent mc = em.MimeContent; string nazwa = BitConverter.ToString(MD5.Create().ComputeHash(ASCIIEncoding.ASCII.GetBytes(em.Id.UniqueId))); if (!File.Exists(mailDir + "\\" + nazwa + ".eml")) { File.WriteAllBytes(mailDir + "\\" + nazwa + ".eml", em.MimeContent.Content); OnNewFilesNumberEvent(string.Format("{0} {1}", index, _rm.GetString("strNewEmailsInsideOutlookDirRes"))); index++; } } } return(true); } catch (Exception ex) { kom = _rm.GetString("lblTotalGenericErrorRes") + " " + ex.Message; return(false); } }
private static double GetItemValue(ItemView item) { return(item.AttackBonus + item.DefenceBonus); }
/// <summary> /// Bindet sich den öffentlichen Ordner uns startet eine Schleife über alle internen Kontakte ("Arges Intern"). /// Danach wird der Geburtstag oder Jahrestag auf NULL überprüft (ist NULL zb. bei Meetingraum) und ausgelesen. /// Ist ein Geburtstag oder Jahrestag da, wird nun das Alter berechnet. /// <h3>DIESES JAHR</h3> /// <ul> /// <li>Erstellt neuen Termin</li> /// <li>Setzt die Eigenschaften für den Termin (zb. Subject, Start, Ende, AllDayEvent...)</li> /// <li>Fpgt die Kategorie "autogenerated by Arges IT" hinzu</li> /// <li>Prüft ob der Termin in der übergebenen Liste schon vorhanden ist</li> /// <li>Fügt den Termin zum Kalender falls er noch nicht vorhanden ist und der Start >= Heute ist</li> /// </ul> /// <h3>NÄCHSTES JAHR</h3> /// Wiederholt die Schritte von diesem Jahr nur mit age+1 /// </summary> /// <param name="mailboxList">Liste mit allen Terminen die aus getMailboxAppointments() zurück kommen</param> /// <param name="BirthdayOrAnniversary">0 => Geburtstag 1 => Jahrestag</param> void addAppointment(List <string> mailboxList, int BirthdayOrAnniversary) // 0 => Geburtstag 1 => Jahrestag { var PublicRoot = Folder.Bind(service, WellKnownFolderName.PublicFoldersRoot); SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, ContactFolderName); FindFoldersResults FindPublicContactFolder = service.FindFolders(PublicRoot.Id, filter, new FolderView(1)); var ContactFolder = FindPublicContactFolder.Folders[0]; ItemView view = new ItemView(int.MaxValue); FindItemsResults <Item> findResults; var count = 0; do { findResults = service.FindItems(ContactFolder.Id, view); // Läuft über alle Kontakte im PublicFolder foreach (Item item in findResults.Items) { //Prüft ob Birthday / Jahrestag ungleich NULL ist (zb bei Kontakt Meetingraum) DateTime BirthDayValue = new DateTime(); bool check = BirthdayOrAnniversary == 0 ? check = item.TryGetProperty(ContactSchema.Birthday, out BirthDayValue) : check = item.TryGetProperty(ContactSchema.WeddingAnniversary, out BirthDayValue); if (check) { //Berechne Geburtsdatum und Alter int age = DateTime.Now.Year - BirthDayValue.Year; BirthDayValue = BirthDayValue.AddYears(age); //if (DateTime.Now.CompareTo(BirthDayValue) < 0) { age--; } // #### DIESES JAHR // Erstelle Appointment Objekt Appointment appo = new Appointment(service); //Setze Appointment Eigenschaften appo.Subject = BirthdayOrAnniversary == 0 ? age + ". Geburtstag von " + item.Subject : age + ". Jahrestag von " + item.Subject; appo.Start = BirthDayValue; appo.End = appo.Start.AddHours(1); appo.IsAllDayEvent = true; appo.IsReminderSet = false; appo.LegacyFreeBusyStatus = 0; // Setze Categorie an der Objekte erkannt werden, die hier mit diesem Script erstellt worden sind appo.Categories.Add("autogenerated by Arges IT"); // Prüft ob Appointment schon vorhanden ist var match = mailboxList.FirstOrDefault(stringToCheck => stringToCheck.Contains(appo.Subject)); if (match == null && appo.Start >= DateTime.Now) { count++; appo.Save(); } else { mailboxList.Remove(appo.Subject); } // #### NÄCHSTES JAHR // Erstelle Appointment Objekt appo = new Appointment(service); //Setze Appointment Eigenschaften appo.Subject = BirthdayOrAnniversary == 0 ? age + 1 + ". Geburtstag von " + item.Subject : age + 1 + ". Jahrestag von " + item.Subject; appo.Start = BirthDayValue.AddYears(1); appo.End = appo.Start.AddHours(1); appo.IsAllDayEvent = true; appo.IsReminderSet = false; appo.LegacyFreeBusyStatus = 0; // Setze Categorie an der Objekte erkannt werden, die hier mit diesem Script erstellt worden sind appo.Categories.Add("autogenerated by Arges IT"); // Prüft ob Appointment schon vorhanden ist match = mailboxList.FirstOrDefault(stringToCheck => stringToCheck.Contains(appo.Subject)); if (match == null && appo.Start >= DateTime.Now) { count++; appo.Save(); } else { mailboxList.Remove(appo.Subject); } } } view.Offset += findResults.Items.Count; } while (findResults.MoreAvailable == true); var e = BirthdayOrAnniversary == 0 ? " Geburtstage" : " Jahrestag"; if (mailboxList.Count > 0) { foreach (var subject in mailboxList) { deleteBySubject(subject); } ExchangeSync.writeLog(SMTPAdresse + " - " + mailboxList.Count + e + " gelöscht"); } if (count > 0) { ExchangeSync.writeLog(SMTPAdresse + " - " + count + e + " hinzugefügt"); } else { ExchangeSync.writeLog(SMTPAdresse + " - Keine" + e + " hinzugefügt"); } }
/// <summary> /// Reads emails from an Exchange server. Can be used only on legacy (Windows) agents. /// </summary> /// <param name="settings">Settings to use</param> /// <param name="options">Options to use</param> /// <returns> /// List of /// { /// string Id. /// string To. /// string Cc. /// string From. /// DateTime Date. /// string Subject. /// string BodyText. /// string BodyHtml. /// List(string) AttachmentSaveDirs /// } /// </returns> public static List <EmailMessageResult> ReadEmailFromExchangeServer([PropertyTab] ExchangeSettings settings, [PropertyTab] ExchangeOptions options) { #if NET471 if (!options.IgnoreAttachments) { // Check that save directory is given if (options.AttachmentSaveDirectory == "") { throw new ArgumentException("No save directory given. ", nameof(options.AttachmentSaveDirectory)); } // Check that save directory exists if (!Directory.Exists(options.AttachmentSaveDirectory)) { throw new ArgumentException("Could not find or access attachment save directory. ", nameof(options.AttachmentSaveDirectory)); } } // Connect, create view and search filter ExchangeService exchangeService = Services.ConnectToExchangeService(settings); ItemView view = new ItemView(options.MaxEmails); var searchFilter = BuildFilterCollection(options); FindItemsResults <Item> exchangeResults; if (!string.IsNullOrEmpty(settings.Mailbox)) { var mb = new Mailbox(settings.Mailbox); var fid = new FolderId(WellKnownFolderName.Inbox, mb); var inbox = Folder.Bind(exchangeService, fid); exchangeResults = searchFilter.Count == 0 ? inbox.FindItems(view) : inbox.FindItems(searchFilter, view); } else { exchangeResults = searchFilter.Count == 0 ? exchangeService.FindItems(WellKnownFolderName.Inbox, view) : exchangeService.FindItems(WellKnownFolderName.Inbox, searchFilter, view); } // Get email items List <EmailMessage> emails = exchangeResults.Where(msg => msg is EmailMessage).Cast <EmailMessage>().ToList(); // Check if list is empty and if an error needs to be thrown. if (emails.Count == 0 && options.ThrowErrorIfNoMessagesFound) { // If not, return a result with a notification of no found messages. throw new ArgumentException("No messages matching the search filter found. ", nameof(options.ThrowErrorIfNoMessagesFound)); } // Load properties for each email and process attachments var result = ReadEmails(emails, exchangeService, options); // should delete mails? if (options.DeleteReadEmails) { emails.ForEach(msg => msg.Delete(DeleteMode.HardDelete)); } // should mark mails as read? if (!options.DeleteReadEmails && options.MarkEmailsAsRead) { foreach (EmailMessage msg in emails) { msg.IsRead = true; msg.Update(ConflictResolutionMode.AutoResolve); } } return(result); #else throw new Exception("Only supported on .NET Framework (i.e. on Windows)."); #endif }
public bool DownloadFromExchange(string PathDownload, string Subject, string Filter, string Sender) { //cargar credenciales string Asunto; string _stage = ""; bool _isRead; bool _attachmentFound = false; EmailMessage _message; if (pExchange != null) { //El filtro de búsqueda para obtener correos electrónicos no leídos SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); ItemView view = new ItemView(50); // Se Activa la consulta de los elementos no leídos // Este método obtiene el resultado de la llamada FindItem a EWS. Con los correos sin leer FindItemsResults <Item> findResults = pExchange.FindItems(WellKnownFolderName.Inbox, sf, view); // Recorremos los correos no leídos foreach (Item item in findResults) { try { // Recorrer los mensajes _stage = "Find in messages"; _message = EmailMessage.Bind(pExchange, item.Id); // se carga el "message" busca por Id Asunto = _message.Subject.ToString(); // sacamos el Subject } catch (Exception ex) { //Console.WriteLine($"[cExchangeTools/DownloadFromExchange#{_stage}]: {ex.Message}"); //continue; throw new Exception($"[cExchangeTools/DownloadFromExchange#{_stage}]: {ex.Message}"); } try { if (Regex.IsMatch(_message.From.ToString(), Sender) || Sender == "") { Console.WriteLine($"-> Checking sender: {_message.From}"); if (Asunto.Contains(Subject) || Subject == "") // se comprueba en los correos no leídos el asunto { Console.WriteLine($" -> Checking subject: {Asunto}"); _isRead = false; // foreach (Attachment att in _message.Attachments) { // Recorrer los adjuntos _stage = "Find in messages"; if (att is FileAttachment) { FileAttachment fileAttachment = att as FileAttachment; // Carga el archivo adjunto en un archivo //if (Filter == fileAttachment.Name.Substring((fileAttachment.Name.ToString().Length - 3), 3)) if (Regex.IsMatch(fileAttachment.Name.ToString(), Filter) || Filter == "") { Console.Write($" -> Checking attachment: {fileAttachment.Name} ..."); // Que guarda en la dirección indicada _stage = "Save File"; fileAttachment.Load(PathDownload + fileAttachment.Name); Console.WriteLine($" Downloaded OK!!"); _attachmentFound = true; pBody += $"- File {fileAttachment.Name.ToString()} found and stored.<br>"; if (!_isRead) { _stage = "Message update is read"; _message.IsRead = true; // lo marcamos como leído _message.Update(ConflictResolutionMode.AutoResolve); // Se envía al servidor el cambio realizado _isRead = true; Console.WriteLine($" -> Marked as read."); } } } } } } else { Console.WriteLine("-> No matches"); } } catch (Exception ex) { //Console.WriteLine($"[{_stage}]: {ex.Message}"); //continue; throw new Exception($"[cExchangeTools/DownloadFromExchange#{_stage}]: {ex.Message}"); } } } return(_attachmentFound); }
static void Main(string[] args) { if (args.Length < 14) { ShowUsage(); Environment.Exit(0); } ExchangeService service = null; if ((args[0] != "-CerValidation")) { ShowUsage(); Environment.Exit(0); } if ((args[1] == "No")) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return(true); }; } Console.WriteLine("[+]CerValidation:{0}", args[1]); if ((args[2] != "-ExchangeVersion")) { ShowUsage(); Environment.Exit(0); } if ((args[3] == "Exchange2007_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); } else if ((args[3] == "Exchange2010")) { service = new ExchangeService(ExchangeVersion.Exchange2010); } else if ((args[3] == "Exchange2010_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); } else if ((args[3] == "Exchange2010_SP2")) { service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); } else if ((args[3] == "Exchange2013")) { service = new ExchangeService(ExchangeVersion.Exchange2013); } else if ((args[3] == "Exchange2013_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); } else { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]ExchangeVersion:{0}", args[3]); if (args[4] == "-u") { UserString = args[5]; Console.WriteLine("[+]User:{0}", args[5]); if ((args[6] != "-p")) { ShowUsage(); Environment.Exit(0); } PwdString = args[7]; Console.WriteLine("[+]Password:{0}", args[7]); service.Credentials = new WebCredentials(UserString, PwdString); } else if (args[4] == "-use") { if (args[5] == "the") { if (args[6] == "default") { if (args[7] == "credentials") { service.UseDefaultCredentials = true; Console.WriteLine("[+]Use the default credentials"); } } } else { ShowUsage(); Environment.Exit(0); } } else { ShowUsage(); Environment.Exit(0); } if ((args[8] == "-ewsPath")) { Console.WriteLine("[+]ewsPath:{0}", args[9]); ewsPathString = args[9]; try { service.Url = new Uri(ewsPathString); } catch (Exception e) { Console.WriteLine("{0}", e.Message); Environment.Exit(0); } } else if ((args[8] == "-AutodiscoverUrl")) { Console.WriteLine("[+]AutodiscoverUrl:{0}", args[9]); AutodiscoverUrlString = args[9]; try { service.AutodiscoverUrl(AutodiscoverUrlString, RedirectionUrlValidationCallback); } catch (Exception e) { Console.WriteLine("{0}", e.Message); Environment.Exit(0); } } else { ShowUsage(); Environment.Exit(0); } if ((args[10] != "-Mode")) { ShowUsage(); Environment.Exit(0); } if ((args[11] == "ListMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FindItemsResults <Item> findResults = null; FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); if (args[13] == "Inbox") { findResults = service.FindItems(WellKnownFolderName.Inbox, view); } else if (args[13] == "Outbox") { findResults = service.FindItems(WellKnownFolderName.Outbox, view); } else if (args[13] == "DeletedItems") { findResults = service.FindItems(WellKnownFolderName.DeletedItems, view); } else if (args[13] == "Drafts") { findResults = service.FindItems(WellKnownFolderName.Drafts, view); } else if (args[13] == "SentItems") { findResults = service.FindItems(WellKnownFolderName.SentItems, view); } else if (args[13] == "JunkEmail") { findResults = service.FindItems(WellKnownFolderName.JunkEmail, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); if (item.Subject != null) { Console.WriteLine("[*]Subject:{0}", item.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", item.HasAttachments); if (item.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", item.Id); Console.WriteLine("[*]DateTimeCreated:{0}", item.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", item.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", item.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", item.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", item.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", item.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); item.Load(itempropertyset); if (item.Body.ToString().Length > 100) { item.Body = item.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", item.Body); } else { Console.WriteLine("[*]MessageBody:{0}", item.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListUnreadMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FindItemsResults <Item> findResults = null; FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); if (args[13] == "Inbox") { findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view); } else if (args[13] == "Outbox") { findResults = service.FindItems(WellKnownFolderName.Outbox, sf, view); } else if (args[13] == "DeletedItems") { findResults = service.FindItems(WellKnownFolderName.DeletedItems, sf, view); } else if (args[13] == "Drafts") { findResults = service.FindItems(WellKnownFolderName.Drafts, sf, view); } else if (args[13] == "SentItems") { findResults = service.FindItems(WellKnownFolderName.SentItems, sf, view); } else if (args[13] == "JunkEmail") { findResults = service.FindItems(WellKnownFolderName.JunkEmail, sf, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); EmailMessage email = EmailMessage.Bind(service, item.Id); if (email.Subject != null) { Console.WriteLine("[*]Subject:{0}", email.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", email.HasAttachments); if (email.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", email.Id); Console.WriteLine("[*]DateTimeCreated:{0}", email.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", email.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", email.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", email.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", email.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", email.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); email.Load(itempropertyset); if (email.Body.ToString().Length > 100) { email.Body = email.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", email.Body); } else { Console.WriteLine("[*]MessageBody:{0}", email.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } if ((args[11] == "ListFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); FindFoldersResults findResults = null; FolderView view = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep }; if (args[13] == "Inbox") { findResults = service.FindFolders(WellKnownFolderName.Inbox, view); } else if (args[13] == "Outbox") { findResults = service.FindFolders(WellKnownFolderName.Outbox, view); } else if (args[13] == "DeletedItems") { findResults = service.FindFolders(WellKnownFolderName.DeletedItems, view); } else if (args[13] == "Drafts") { findResults = service.FindFolders(WellKnownFolderName.Drafts, view); } else if (args[13] == "SentItems") { findResults = service.FindFolders(WellKnownFolderName.SentItems, view); } else if (args[13] == "JunkEmail") { findResults = service.FindFolders(WellKnownFolderName.JunkEmail, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Folder folder in findResults.Folders) { Console.WriteLine("\r\n"); Console.WriteLine("[*]DisplayName:{0}", folder.DisplayName); Console.WriteLine("[*]Id:{0}", folder.Id); Console.WriteLine("[*]TotalCount:{0}", folder.TotalCount); } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListMailofFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); Folder Folders = Folder.Bind(service, IdString); FindItemsResults <Item> findResults = null; ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; findResults = Folders.FindItems(view); foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); if (item.Subject != null) { Console.WriteLine("[*]Subject:{0}", item.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", item.HasAttachments); if (item.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", item.Id); Console.WriteLine("[*]DateTimeCreated:{0}", item.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", item.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", item.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", item.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", item.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", item.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); item.Load(itempropertyset); if (item.Body.ToString().Length > 100) { item.Body = item.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", item.Body); } else { Console.WriteLine("[*]MessageBody:{0}", item.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListUnreadMailofFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); Folder Folders = Folder.Bind(service, IdString); FindItemsResults <Item> findResults = null; ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; findResults = Folders.FindItems(sf, view); foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); EmailMessage email = EmailMessage.Bind(service, item.Id); if (email.Subject != null) { Console.WriteLine("[*]Subject:{0}", email.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", email.HasAttachments); if (email.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", email.Id); Console.WriteLine("[*]DateTimeCreated:{0}", email.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", email.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", email.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", email.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", email.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", email.InReplyTo); Console.WriteLine("[*]Size:{0}", email.Size); email.Load(itempropertyset); if (email.Body.ToString().Length > 100) { email.Body = email.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", email.Body); } else { Console.WriteLine("[*]MessageBody:{0}", email.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "SaveAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; Console.WriteLine("[+]Attachments:{0}", fileAttachment.Name); fileAttachment.Load(fileAttachment.Name); Console.WriteLine("\r\n[+]SaveAttachment success"); } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "AddAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); if ((args[14] != "-AttachmentFile")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]AttachmentFile:{0}", args[15]); EmailMessage message = EmailMessage.Bind(service, IdString); message.Attachments.AddFileAttachment(args[15]); message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]AddAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ClearAllAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); message.Attachments.Clear(); message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]ClearAllAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "DeleteAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); if ((args[14] != "-AttachmentFile")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]AttachmentFile:{0}", args[15]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { if (attachment.Name == args[15]) { message.Attachments.Remove(attachment); break; } } message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]DeleteAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "DeleteMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString); message.Delete(DeleteMode.SoftDelete); Console.WriteLine("\r\n[+]DeleteMail success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "SearchMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-String")) { ShowUsage(); Environment.Exit(0); } SearchString = args[13]; Console.WriteLine("[+]SearchString:{0}", args[13]); SearchMail(service, WellKnownFolderName.Inbox, SearchString); SearchMail(service, WellKnownFolderName.Outbox, SearchString); SearchMail(service, WellKnownFolderName.DeletedItems, SearchString); SearchMail(service, WellKnownFolderName.Drafts, SearchString); SearchMail(service, WellKnownFolderName.SentItems, SearchString); SearchMail(service, WellKnownFolderName.JunkEmail, SearchString); Console.WriteLine("\r\n[+]SearchMail done"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ExportMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); Console.WriteLine("[+]SavePath:{0}.eml", args[13]); Folder inbox = null; if (args[13] == "Inbox") { inbox = Folder.Bind(service, WellKnownFolderName.Inbox); } else if (args[13] == "Outbox") { inbox = Folder.Bind(service, WellKnownFolderName.Outbox); } else if (args[13] == "DeletedItems") { inbox = Folder.Bind(service, WellKnownFolderName.DeletedItems); } else if (args[13] == "Drafts") { inbox = Folder.Bind(service, WellKnownFolderName.Drafts); } else if (args[13] == "SentItems") { inbox = Folder.Bind(service, WellKnownFolderName.SentItems); } else if (args[13] == "JunkEmail") { inbox = Folder.Bind(service, WellKnownFolderName.JunkEmail); } else { Console.WriteLine("[!]Don't support this folder"); Environment.Exit(0); } ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); FindItemsResults <Item> results = inbox.FindItems(view); int i = 0; foreach (var item in results) { i++; PropertySet props = new PropertySet(EmailMessageSchema.MimeContent); var email = EmailMessage.Bind(service, item.Id, props); string emlFileName = args[13] + ".eml"; using (FileStream fs = new FileStream(emlFileName, FileMode.Append, FileAccess.Write)) { fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length); } } Console.WriteLine("\r\n[+]ExportMail done,total number:{0}", i); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ViewMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); ViewMail(service, WellKnownFolderName.Inbox, IdString); ViewMail(service, WellKnownFolderName.Outbox, IdString); ViewMail(service, WellKnownFolderName.DeletedItems, IdString); ViewMail(service, WellKnownFolderName.Drafts, IdString); ViewMail(service, WellKnownFolderName.SentItems, IdString); ViewMail(service, WellKnownFolderName.JunkEmail, IdString); Console.WriteLine("\r\n[+]ViewMail done"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ReadXML")) { Console.WriteLine("[+]Mode:{0}", args[11]); if ((args[12] != "-Path")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]XML path:{0}", args[13]); Console.WriteLine("[+]Out path:out.xml"); StreamReader sendData = new StreamReader(args[13], Encoding.Default); byte[] sendDataByte = Encoding.UTF8.GetBytes(sendData.ReadToEnd()); sendData.Close(); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(service.Url); request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = sendDataByte.Length; request.AllowAutoRedirect = false; if (args[4] == "-use") { request.Credentials = CredentialCache.DefaultCredentials; } else { request.Credentials = new NetworkCredential(UserString, PwdString); } Stream requestStream = request.GetRequestStream(); requestStream.Write(sendDataByte, 0, sendDataByte.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new WebException(response.StatusDescription); } Stream receiveStream = response.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); String receiveString = readStream.ReadToEnd(); response.Close(); readStream.Close(); StreamWriter receiveData = new StreamWriter("out.xml"); receiveData.Write(receiveString); receiveData.Close(); } catch (WebException e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } Console.WriteLine("\r\n[+]ReadXML done"); } }
protected override void InitializeViews() { colorCircle = ItemView.FindViewById <CircleView>(Resource.Id.EditProjectColorCircle); selectionCircle = ItemView.FindViewById <ImageView>(Resource.Id.EditProjectColorSelectionCircle); }
private void button8_Click(object sender, EventArgs e) { lstMsg.Visible = false; if (textBox3.Text == "" || textBox2.Text == "") { MessageBox.Show("Lütfen mail adresi ve şifrenizi giriniz."); } else { if (Regex.IsMatch(textBox3.Text, @"(@)")) { this.Size = new Size(1454, 664); this.Location = new Point(50, 50); username = textBox3.Text.Split('@')[0]; domain = textBox3.Text.Split('@')[1]; lblMsg.Visible = true; i = 0; lstMsg.Items.Clear(); if (domain == "hotmail.com" || domain == "std.yildiz.edu.tr") { ConnectToExchangeServer(); TimeSpan ts = new TimeSpan(0, -24, 0, 0); DateTime date = DateTime.Now.Add(ts); SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date); if (exchange != null) { PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; ItemView itemview = new ItemView(1000); itemview.PropertySet = itempropertyset; //FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, "subject:TODO", itemview); lstMsg.Width = 1170; lstMsg.Height = 450; button8.Text = "Yenile"; try { FindItemsResults <Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(100)); foreach (Item item in findResults) { lstMsg.Visible = true; item.Load(itempropertyset); String content = item.Body; icerikler[i] = content; var input = new Input { Text = content }; var prediction = predictor.Predict(input); double skor = Cast(prediction.Probability, typeof(double)); String durum; if ((Convert.ToBoolean(prediction.Prediction) ? "Spam" : "Not spam") == "Spam") { durum = "YES"; } else { durum = "NO"; } EmailMessage message = EmailMessage.Bind(exchange, item.Id); basliklar[i] = message.Subject; i++; ListViewItem listitem = new ListViewItem(new[] { message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject, content, durum, skor.ToString("N2") }); lstMsg.Items.Add(listitem); } if (findResults.Items.Count <= 0) { lstMsg.Items.Add("Yeni Mail Bulunamadı.!!"); } colorListcolor(lstMsg); } catch { MessageBox.Show("Mail adresi veya şifre yanlış."); textBox3.Text = ""; textBox2.Text = ""; lblMsg.Text = ""; lblMsg.Visible = false; button8.Text = "Giriş"; Screen screen = Screen.FromControl(this); Rectangle workingArea = screen.WorkingArea; this.Location = new Point() { X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2), Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2) }; } } } else if (domain == "gmail.com") { lblMsg.Text = "IMAP Server'a bağlanılıyor...."; lblMsg.Refresh(); try { IC = new ImapClient("imap.gmail.com", textBox3.Text, textBox2.Text, AuthMethods.Login, 993, true); lblMsg.Text = "IMAP Server'a bağlandı.\nGünlük Mailler Gösteriliyor."; lblMsg.Refresh(); IC.SelectMailbox("INBOX"); int mailCount = IC.GetMessageCount(); mailCount--; var Email = IC.GetMessage(mailCount); DateTime localDate = DateTime.Now; TimeSpan baseInterval = new TimeSpan(24, 0, 0); var value = localDate.Subtract(Email.Date); lstMsg.Visible = true; lstMsg.Width = 1170; lstMsg.Height = 450; button8.Text = "Yenile"; while (TimeSpan.Compare(baseInterval, value) == 1) { basliklar[i] = Email.Subject.ToString(); icerikler[i] = Email.Body.ToString(); i++; var input = new Input { Text = Email.Body }; var prediction = predictor.Predict(input); double skor = Cast(prediction.Probability, typeof(double)); String durum; if ((Convert.ToBoolean(prediction.Prediction) ? "Spam" : "Not spam") == "Spam") { durum = "YES"; } else { durum = "NO"; } var content = Email.Body.ToString(); ListViewItem listitem = new ListViewItem(new[] { Email.Date.ToString(), Email.From.Address.ToString(), Email.Subject.ToString(), content, durum, skor.ToString("N2") }); lstMsg.Items.Add(listitem); //MessageBox.Show(Email.Subject.ToString()); mailCount--; Email = IC.GetMessage(mailCount); value = localDate.Subtract(Email.Date); } colorListcolor(lstMsg); } catch { MessageBox.Show("Lütfen email güvenlik ayarlarından Daha az güvenli uygulamalara izin ver: AÇIK yapınız."); } } else { MessageBox.Show("Geçersiz bir domain ismi girdiniz.Lütfen kontrol edin!"); } } else { MessageBox.Show("Lütfen doğru bir mail formatı giriniz."); } } }
protected void Page_Load(object sender, EventArgs e) { // access master page from nested master page Protected.ClaimRuler masterPage = Master.Master as Protected.ClaimRuler; // check user permission //masterPage.checkPermission(); clientID = SessionHelper.getClientId(); // get current lead leadID = SessionHelper.getLeadId(); // get current lead id claimID = SessionHelper.getClaimID(); // get current user userID = SessionHelper.getUserId(); // set directory where client can upload pictures for signature txtSignature.UploadedFilesDirectory = appPath + "/clientLogo/" + clientID; if (!Page.IsPostBack) { bindData(); userID = SessionHelper.getUserId(); CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID); string email = secUser.Email; string password = SecurityManager.Decrypt(secUser.emailPassword); string url = "https://" + secUser.emailHost + "/EWS/Exchange.asmx"; try { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); service.Credentials = new WebCredentials(email, password); service.Url = new Uri(url); ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts); int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50; ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName); FindItemsResults <Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view); DataTable table = new DataTable(); table.Columns.Add("FirstName", typeof(string)); table.Columns.Add("LastName", typeof(string)); table.Columns.Add("CompanyName", typeof(string)); table.Columns.Add("Email", typeof(string)); table.Columns.Add("ContactType", typeof(string)); foreach (GridRecord crow in contractGrid.Rows) { DataRow row = table.NewRow(); row[0] = crow.Items[0].Text; row[1] = crow.Items[1].Text; //row[2] = crow.Cells[2].Text; row[3] = crow.Items[3].Text; row[4] = crow.Items[4].Text; table.Rows.Add(row); } foreach (Item item in contactItems) { if (item is Microsoft.Exchange.WebServices.Data.Contact) { item.Load(); Microsoft.Exchange.WebServices.Data.Contact contact = item as Microsoft.Exchange.WebServices.Data.Contact; DataRow row = table.NewRow(); row[0] = contact.GivenName; row[1] = contact.Surname; row[3] = contact.EmailAddresses[0].Address; row[4] = "Outlook"; table.Rows.Add(row); } } contractGrid.DataSourceID = null; contractGrid.Columns.Clear(); contractGrid.DataBind(); contractGrid.DataSource = table; contractGrid.DataBind(); } catch (Exception ex) { } } }
//thread to get all emails public static void _getMails(object param) { helpers.addLog("_getMails() started..."); ews _ews = (ews)param; //need an instance _ews.OnStateChanged(new StatusEventArgs(StatusType.busy, "_getMails() started...")); const int chunkSize = 50; try { PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body //blocking call ItemView view = new ItemView(chunkSize); view.PropertySet = itempropertyset; view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending); /* * private static void GetAttachments(ExchangeService service) * { * // Return a single item. * ItemView view = new ItemView(1); * * string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email"; * * // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS. * FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view); * * if (results.TotalCount > 0) * { * EmailMessage email = results.Items[0] as EmailMessage; */ FindItemsResults <Item> findResults; do { //findResults = service.FindItems(WellKnownFolderName.Inbox, view); SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And); filterCollection.Add(new SearchFilter.Not(new SearchFilter.ContainsSubstring(ItemSchema.Subject, sMailHasAlreadyProcessed))); filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, helpers.filterSubject)); filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Attachments, helpers.filterAttachement)); findResults = _ews._service.FindItems(WellKnownFolderName.Inbox, filterCollection, view); _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: found " + findResults.Items.Count + " items in inbox")); foreach (Item item in findResults.Items) { helpers.addLog("found item..."); if (item is EmailMessage) { EmailMessage mailmessage = item as EmailMessage; mailmessage.Load(itempropertyset); //load data from server helpers.addLog("\t is email ..."); // If the item is an e-mail message, write the sender's name. helpers.addLog(mailmessage.Sender.Name + ": " + mailmessage.Subject); _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: processing eMail " + mailmessage.Subject)); MailMsg myMailMsg = new MailMsg(mailmessage, _ews._userData.sUser); // Bind to an existing message using its unique identifier. //EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId)); int iRet = _ews._licenseMail.processMail(myMailMsg); //change subject? // Bind to the existing item, using the ItemId. This method call results in a GetItem call to EWS. Item myItem = Item.Bind(_ews._service, item.Id as ItemId); myItem.Load(); // Update the Subject of the email. myItem.Subject += "[processed]"; // Save the updated email. This method call results in an UpdateItem call to EWS. myItem.Update(ConflictResolutionMode.AlwaysOverwrite); _ews.OnStateChanged(new StatusEventArgs(StatusType.license_mail, "processed " + iRet.ToString())); } } view.Offset += chunkSize; } while (findResults.MoreAvailable && _ews._bRunThread); _ews.OnStateChanged(new StatusEventArgs(StatusType.idle, "readmail done")); } catch (ThreadAbortException ex) { helpers.addLog("ThreadAbortException: " + ex.Message); } catch (Exception ex) { helpers.addLog("Exception: " + ex.Message); _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "readmail exception: " + ex.Message)); } helpers.addLog("_getMails() ended"); _ews.startPull(); }
private void DownloadEmails() { _logger.AddLogEntry(_serviceName, "INPROGRESS", "Downloading emails", "DownloadEmails"); using (var _setting = new AppSettingService()) { var appSettings = _setting.Get(); ServicePointManager.ServerCertificateValidationCallback = (s, certificate, chain, sslPolicyErrors) => true; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.Credentials = new WebCredentials(appSettings.aps_rapids_email, appSettings.aps_rapids_password); service.Url = new Uri(appSettings.aps_rapids_service); service.PreAuthenticate = true; _logger.AddLogEntry(_serviceName, "INPROGRESS", "Reading O365 mailbox", "DownloadEmails"); ItemView view = new ItemView(int.MaxValue); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, SetFilter(), view); _logger.AddLogEntry(_serviceName, "INFO", $"There are {findResults.Items?.Count} emails to process", "DownloadEmails"); // in case if deployed different location as background job string rapidsDirectoryUrl = System.Configuration.ConfigurationManager.AppSettings.Get("RapidsDirectoryUrl"); using (var _rapidsService = new RapidsService()) { foreach (Item item in findResults.Items) { _logger.AddLogEntry(_serviceName, "INPROGRESS", $"Processing email with Subject = {item.Subject}", "DownloadEmails"); var mailMessage = (EmailMessage)item; // format internalMessageId to be used as Id string messageID = mailMessage.InternetMessageId.Replace("<", "").Replace(">", ""); Model.rapids_mailbox newEmail = null; if (_rapidsService.FindByUID(messageID)) { service.DeleteItems(new List <ItemId> { new ItemId(mailMessage.Id.UniqueId) }, DeleteMode.MoveToDeletedItems, null, null); continue; } // load details item.Load(); try { newEmail = new Model.rapids_mailbox { rpd_attachments = item.Attachments.Count, rpd_body = item.Body, rpd_date = item.DateTimeReceived, rpd_created_by = "Import Service", rpd_created_date = DateTime.Now.ToEST(), rpd_from = string.Format("{0} <{1}>", mailMessage.From.Name, mailMessage.From.Address), rpd_subject = item.Subject, rpd_to = item.DisplayTo, rpd_uid = messageID, }; // save email into database _rapidsService.Create(newEmail); newEmail.rpd_body = newEmail.rpd_body.Replace("cid:", $"{rapidsDirectoryUrl}/RapidsAttachments/{newEmail.rpd_key}/"); #region ----- Save Attachments ----- // check if there are any attachments if (item.Attachments != null && item.Attachments.Count > 0) { _logger.AddLogEntry(_serviceName, "INPROGRESS", $"Processing attachments with Subject = {item.Subject}", "DownloadEmails"); string parentDirectory = System.Configuration.ConfigurationManager.AppSettings.Get("RapidsDirectory"); string attachmentDirectory = Path.Combine(parentDirectory, Convert.ToString(newEmail.rpd_key)); string attachmentDirectoryOthers = Path.Combine(attachmentDirectory, "Others"); // create directory if (!Directory.Exists(attachmentDirectory)) { Directory.CreateDirectory(attachmentDirectory); } if (!Directory.Exists(attachmentDirectoryOthers)) { Directory.CreateDirectory(attachmentDirectoryOthers); } // save attachments foreach (Attachment attach in item.Attachments) { if (attach.IsInline) { ((FileAttachment)attach).Load(Path.Combine(attachmentDirectory, attach.Name)); newEmail.rpd_body = newEmail.rpd_body.Replace(attach.ContentId, attach.Name); } else { ((FileAttachment)attach).Load(Path.Combine(attachmentDirectoryOthers, attach.Name)); string htmlForAttachment = "<div style=\"text-align: center; display: block; padding: 10px; \">"; string attachmentLink = $"{rapidsDirectoryUrl}/RapidsAttachments/{newEmail.rpd_key}/Others/{attach.Name}"; if (attach.Name.EndsWith(".txt") || attach.Name.EndsWith(".doc") || attach.Name.EndsWith(".docx")) { htmlForAttachment += $"<a href=\"{attachmentLink}\" target=\"_blank\">{attach.Name}</a>"; } else { htmlForAttachment += $"<img src=\"{attachmentLink}\" alt=\"{attach.Name}\" />"; } htmlForAttachment += "</div>"; if (string.IsNullOrEmpty(newEmail.rpd_attachment_html)) { newEmail.rpd_attachment_html = ""; } newEmail.rpd_attachment_html = newEmail.rpd_attachment_html + htmlForAttachment; if (!string.IsNullOrEmpty(attach.ContentId)) { newEmail.rpd_attachment_html = newEmail.rpd_attachment_html.Replace(attach.ContentId, attach.Name); } } } } #endregion // delete email once saved into database service.DeleteItems(new List <ItemId> { new ItemId(mailMessage.InternetMessageId) }, DeleteMode.MoveToDeletedItems, null, null); } catch (Exception ex) { if (newEmail != null) { newEmail.rpd_logs += ex.ToString(); } } finally { // save email attachments name changes, if any _rapidsService.Edit(newEmail); } } } } }
internal static double ItemValue(ItemView item) { return(item.AttackBonus * 1.2 + item.DefenceBonus); }
/// <summary> /// Iterate through folder to get read/unread flags. /// </summary> /// <returns>Returns integer array with two elements : read and unread count.</returns> public int[] GetMailCountDetails() { try { int[] mailCounts = new int[2]; int unReadCount = 0; int readCount = 0; // Declare folder and item view. FolderView viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) }; ItemView viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) }; //Create read and unread email items filters SearchFilter unreadFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); SearchFilter readFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true); // Create folder filter. SearchFilter folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "AllItems"); //Find the AllItems folder FindFoldersResults inboxFolders = service.FindFolders(WellKnownFolderName.MsgFolderRoot, folderFilter, viewFolders); // If user does not have an AllItems folder then search the Inbox and Inbox sub-folders. if (inboxFolders.Count() == 0) { // Search all items in Inbox for read and unread email. FindItemsResults <Item> findUnreadResults = service.FindItems(WellKnownFolderName.Inbox, unreadFilter, viewEmails); FindItemsResults <Item> findReadResults = service.FindItems(WellKnownFolderName.Inbox, readFilter, viewEmails); unReadCount += findUnreadResults.Count(); readCount += findReadResults.Count(); //Get all Inbox sub-folders inboxFolders = service.FindFolders(WellKnownFolderName.Inbox, viewFolders); //Look for read and unread email in each Inbox sub folder foreach (Folder folder in inboxFolders.Folders) { findUnreadResults = service.FindItems(folder.Id, unreadFilter, viewEmails); findReadResults = service.FindItems(folder.Id, readFilter, viewEmails); unReadCount += findUnreadResults.Count(); readCount += findReadResults.Count(); } } // AllItems folder is avilable. else { foreach (Folder folder in inboxFolders.Folders) { FindItemsResults <Item> findUnreadResults = service.FindItems(folder.Id, unreadFilter, viewEmails); FindItemsResults <Item> findReadResults = service.FindItems(folder.Id, readFilter, viewEmails); unReadCount += findUnreadResults.Count(); readCount += findReadResults.Count(); } } // Fill count to the integer array. mailCounts[0] = readCount; mailCounts[1] = unReadCount; return(mailCounts); } catch (Exception) { throw; } }
public static List <OutLookEmails> ReadMailItems() { List <OutLookEmails> listEmailDetails = new List <OutLookEmails>(); OutLookEmails emailsDetails; ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1); try { exchange.Credentials = new WebCredentials("email", "password"); // exchange.Url = new Uri("https://outlook.office365.com/owa/bridgetree.com/ews/exchange.asmx"); exchange.AutodiscoverUrl("email", RedirectionUrlValidationCallback); TimeSpan ts = new TimeSpan(0, -1, 0, 0); DateTime date = DateTime.Today.AddDays(-1); //DateTime.Now.Add(ts); // new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date) SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date), new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); if (exchange != null) { PropertySet FindItemPropertySet = new PropertySet(BasePropertySet.IdOnly); ItemView view = new ItemView(999); view.PropertySet = FindItemPropertySet; PropertySet GetItemsPropertySet = new PropertySet(BasePropertySet.FirstClassProperties); GetItemsPropertySet.RequestedBodyType = BodyType.Text; FindItemsResults <Item> emailMessages = null; emailMessages = exchange.FindItems(WellKnownFolderName.Inbox, searchFilter, view); if (emailMessages.Items.Count > 0) { exchange.LoadPropertiesForItems(emailMessages.Items, GetItemsPropertySet); foreach (EmailMessage message in emailMessages.Items) { if (message.IsRead == false && emailMessages.Items.Count > 0) { emailsDetails = new OutLookEmails(); emailsDetails.EmailFrom = message.From.ToString(); emailsDetails.EmailSubject = message.Subject; emailsDetails.EmailBody = message.Body.Text; listEmailDetails.Add(emailsDetails); message.IsRead = true; message.Update(ConflictResolutionMode.AlwaysOverwrite); } else { } } } } } catch (Exception ex) { throw (ex); } return(listEmailDetails); }
public ICollection <T> GetRequests() { ICollection <T> ret = new List <T>(); Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", "Lettura mail...")); // Inizializziamo il filtro di ricerca per scaricare le nuove mail SearchFilter sf = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false) /*, * new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, "jarvis", ContainmentMode.Prefixed, ComparisonMode.IgnoreCase * * )*/); ItemView view = new ItemView(20); // Lanciamo la query FindItemsResults <Item> findResults = this.service.FindItems(WellKnownFolderName.Inbox, sf, view); Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", string.Format("Trovate {0} nuove mail", findResults.TotalCount))); if (findResults.TotalCount > 0) { List <Item> items = new List <Item>(); foreach (EmailMessage emsg in findResults) { Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", string.Format("Elaboro {0}", emsg.Id))); items.Add(emsg); emsg.IsRead = true; emsg.Update(ConflictResolutionMode.AutoResolve); } if (items.Count == 0) { return(ret); } // si caricano le proprietà dei messaggi da leggere Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", "Caricamento proprieta' mail e creazione MailRequest")); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent); itempropertyset.RequestedBodyType = BodyType.HTML; this.service.LoadPropertiesForItems(items, itempropertyset); // si crea la Jarvis Request. NB: questa operazione va fatta dopo che le proprieta' // del messaggio sono state caricate foreach (EmailMessage mail in items) { Logger.Debug(new LogInfo(MethodBase.GetCurrentMethod(), "DEB", string.Format("MailRequest: {0}", mail.Subject))); var ctr = typeof(T).GetConstructor(new Type[] { typeof(EmailMessage) }); if (ctr == null) { throw new Exception("Impossibile trovare un costruttore per soddisfare la richiesta"); } //T request = new MailRequest(i.From.Address, i.ToRecipients.First().Address, i.Subject, i.Body); T request = (T)ctr.Invoke(new object[] { mail }); ret.Add(request); } } return(ret); }
public void CreateView() { this.view = new ItemView(); }
protected override void InitializeViews() { checkedImage = ItemView.FindViewById <ImageView>(Resource.Id.SettingsWorkspaceCellCheckedImageView); workspaceName = ItemView.FindViewById <TextView>(Resource.Id.SettingsWorkspaceCellWorkspaceNameTextView); }
protected override void InitializeViews() { descriptionLabel = ItemView.FindViewById <TextView>(Resource.Id.DescriptionLabel); projectLabel = ItemView.FindViewById <TextView>(Resource.Id.ProjectLabel); clientLabel = ItemView.FindViewById <TextView>(Resource.Id.ClientLabel); }
public void Deactivate() { if (mEditButton != null) { mToolBarLayer.Remove(mEditButton); mEditButton.Dispose(); mEditButton = null; } if (mTitle != null) { mToolBarLayer.Remove(mTitle); mTitle.Dispose(); mTitle = null; } if (mLayoutButton != null) { mToolBarLayer.Remove(mLayoutButton); mLayoutButton.Dispose(); mLayoutButton = null; } if (mToolBarLayer != null) { mRootView.Remove(mToolBarLayer); mToolBarLayer.Dispose(); mToolBarLayer = null; } if (mReplaceButton != null) { mReplaceButton.GetParent().Remove(mReplaceButton); mReplaceButton.Dispose(); mReplaceButton = null; } if (mInsertButton != null) { mInsertButton.GetParent().Remove(mInsertButton); mInsertButton.Dispose(); mInsertButton = null; } if (mDeleteButton != null) { mDeleteButton.GetParent().Remove(mDeleteButton); mDeleteButton.Dispose(); mDeleteButton = null; } if (mItemView != null) { mContentView.Remove(mItemView); mItemView.Dispose(); mItemView = null; } if (mContentView != null) { mRootView.Remove(mContentView); mContentView.Dispose(); mContentView = null; } if (mRootView != null) { mDefaultLayer.Remove(mRootView); mRootView.Dispose(); mRootView = null; } NUIApplication.GetDefaultWindow().GetDefaultLayer().Behavior = Layer.LayerBehavior.LayerUI; }