public void Copy() { PropertySet original = new PropertySet(); original.Add("abc", "123"); original.Add("def", ""); PropertySet copy = original.Copy(); Assert.AreNotSame(original, copy); AssertAreEqual(original, copy); }
internal void ExportItem() { if (this.ItemToExport.GetType().Name.ToString() != "EmailMessage") throw new InvalidOperationException("Please provide item typeof EmailMessage."); ExchangeService ewsSession = this.GetSessionVariable(); PropertySet propertySet = new PropertySet(EmailMessageSchema.MimeContent); propertySet.Add(EmailMessageSchema.ConversationTopic); EmailMessage emailMessage = EmailMessage.Bind(ewsSession, this.ItemToExport.Id, propertySet); Random rNumber = new Random(); string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "EmailExport"); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); if (string.IsNullOrEmpty(this.fileName)) { int subjectLenght = emailMessage.ConversationTopic.Length > 10 ? 10 : emailMessage.ConversationTopic.Length; fileName = String.Format( "Email-{0}-{1}" , emailMessage.ConversationTopic.Substring( 0 , subjectLenght ) , rNumber.Next( 1 , 10 ) ); } fileName = Path.Combine(directory, string.Format("{0}.eml", fileName)); using (FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { fileStream.Write(emailMessage.MimeContent.Content, 0, emailMessage.MimeContent.Content.Length); } }
public void SerializeToXml(string expectedXml, string[] keyValuePairs) { PropertySet map = new PropertySet(); for (int i = 0; i < keyValuePairs.Length; i += 2) map.Add(keyValuePairs[i], keyValuePairs[i + 1]); StringWriter writer = new StringWriter(); serializer.Serialize(writer, map); Assert.AreEqual(expectedXml, writer.ToString()); }
private OutlookAppointment GetOutlookAppointment(Microsoft.Exchange.WebServices.Data.Appointment appointment, ExchangeService service) { OutlookAppointment newAppointment = new OutlookAppointment(); PropertySet props = new PropertySet(); props.Add(AppointmentSchema.Body); props.Add(AppointmentSchema.Subject); newAppointment.IsEWS = true; newAppointment.Service = service; newAppointment.Id = appointment.Id.UniqueId; newAppointment.Subject = appointment.Subject; newAppointment.Start = appointment.Start; newAppointment.End = appointment.End; newAppointment.AllDayEvent = appointment.IsAllDayEvent; newAppointment.Location = appointment.Location; newAppointment.Organizer = appointment.Organizer.ToString(); newAppointment.ReminderMinutesBeforeStart = appointment.ReminderMinutesBeforeStart; newAppointment.ReminderSet = appointment.IsReminderSet; return newAppointment; }
/// <summary> /// Get the MimeContent of each Item specified in itemIds and write it /// to the destination folder. /// </summary> /// <param name="itemIds">ItemIds to retrieve</param> /// <param name="destinationFolderPath">Folder to save messages to</param> /// <param name="service">ExchangeService to use to make EWS calls</param> public static void DumpMIME( List<ItemId> itemIds, string destinationFolderPath, ExchangeService service) { DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count)); PropertySet mimeSet = new PropertySet(BasePropertySet.IdOnly); mimeSet.Add(EmailMessageSchema.MimeContent); mimeSet.Add(EmailMessageSchema.Subject); //mimeSet.Add(AppointmentSchema.MimeContent); //mimeSet.Add(AppointmentSchema.Subject); //mimeSet.Add(AppointmentSchema.RequiredAttendees); //mimeSet.Add(AppointmentSchema.OptionalAttendees); ServiceResponseCollection<GetItemResponse> responses = service.BindToItems(itemIds, mimeSet); DebugLog.WriteVerbose("Finished getting items."); foreach (GetItemResponse response in responses) { switch (response.Result) { case ServiceResult.Success: DumpMIME(response.Item, destinationFolderPath); break; case ServiceResult.Error: DumpErrorResponseXML(response, destinationFolderPath); break; case ServiceResult.Warning: throw new NotImplementedException("DumpMIME doesn't handle ServiceResult.Warning."); default: throw new NotImplementedException("DumpMIME encountered an unexpected ServiceResult."); } } DebugLog.WriteVerbose("Finished dumping MimeContents for each item."); }
public EGLSurface CreateSurface(SwapChainPanel panel, Size?renderSurfaceSize, float?resolutionScale) { if (panel == null) { throw new ArgumentNullException("SwapChainPanel parameter is invalid"); } EGLSurface surface = Egl.EGL_NO_SURFACE; EGLint[] surfaceAttributes = new[] { // EGL_ANGLE_SURFACE_RENDER_TO_BACK_BUFFER is part of the same optimization as EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER (see above). // If you have compilation issues with it then please update your Visual Studio templates. Egl.EGL_ANGLE_SURFACE_RENDER_TO_BACK_BUFFER, Egl.EGL_TRUE, Egl.EGL_NONE }; // Create a PropertySet and initialize with the EGLNativeWindowType. PropertySet surfaceCreationProperties = new PropertySet(); surfaceCreationProperties.Add(Egl.EGLNativeWindowTypeProperty, panel); // If a render surface size is specified, add it to the surface creation properties if (renderSurfaceSize.HasValue) { PropertySetExtensions.AddSize(surfaceCreationProperties, Egl.EGLRenderSurfaceSizeProperty, renderSurfaceSize.Value); } // If a resolution scale is specified, add it to the surface creation properties if (resolutionScale.HasValue) { PropertySetExtensions.AddSingle(surfaceCreationProperties, Egl.EGLRenderResolutionScaleProperty, resolutionScale.Value); } surface = Egl.eglCreateWindowSurface(mEglDisplay, mEglConfig, surfaceCreationProperties, surfaceAttributes); if (surface == Egl.EGL_NO_SURFACE) { throw new Exception("Failed to create EGL surface"); } return(surface); }
private async void EffectButton_Tapped(object sender, TappedRoutedEventArgs e) { //VideoStabilizationEffectDefinition vsed = new VideoStabilizationEffectDefinition(); //VideoEffectDefinition ved = new VideoEffectDefinition(vsed.ActivatableClassId, vsed.Properties); // 创建一个属性集,并添加一个属性/值对 PropertySet echoProperties = new PropertySet(); echoProperties.Add("Mix", 0.5f); PropertySet properties = new PropertySet(); properties.Add("FadeValue", 5); VideoTransformEffectDefinition van = new VideoTransformEffectDefinition(); VideoEffectDefinition effect = new VideoEffectDefinition(van.ActivatableClassId, van.Properties); // VideoEffectDefinition effect = new VideoEffectDefinition(typeof(ExampleVideoEffect).FullName); if (App.Model.Current != null) { try { App.Model.Current.VideoEffectDefinitions.Add(effect); } catch (Exception exception) { await new MessageDialog(exception.Message).ShowAsync(); } } else if (App.Model.OverlayCurrent != null) { try { App.Model.OverlayCurrent.Clip.VideoEffectDefinitions.Add(new VideoEffectDefinition(typeof(ExampleVideoEffect).FullName)); } catch (Exception exception) { await new MessageDialog(exception.Message).ShowAsync(); } } }
private static PropertySet CollectProperties(object target) { //var targetType = target.GetType(); PropertySet result; if (!Properties.TryGetValue(target, out result)) { result = new PropertySet(); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(target, PropertyFilter)) { result.Add(descriptor.Name, new PropertyData(descriptor)); CollectAttributes(target, descriptor); } Properties.Add(target, result); } return(result); }
/// <summary> /// Sets a value in the property set. If the property doesn't exist, it is created. /// </summary> /// <param name="propertySet"> /// The <see cref="PropertySet"/> instance that this extension method affects.</param> /// <param name="key">The property's key.</param> /// <param name="value">The property's value.</param> /// <returns>The property.</returns> /// <exception cref="ArgumentNullException"><paramref name="propertySet"/> is <c>null</c>.</exception> public static Property SetValue(this PropertySet propertySet, string key, object value) { if (propertySet == null) { throw new ArgumentNullException(nameof(propertySet)); } var property = propertySet.TryGetValue(key); if (property == null) { property = propertySet.Add(value, key); } else { property.Value = value; } return(property); }
public static void GetMessageBodyAsHtml(Item oItem, ref string MessageBodyHtml) { string sRet = string.Empty; PropertySet oPropSet = new PropertySet(PropertySet.FirstClassProperties); oItem.Load(PropertySet.FirstClassProperties); PropertySet oPropSetForBodyText = new PropertySet(PropertySet.FirstClassProperties); oPropSetForBodyText.RequestedBodyType = BodyType.HTML; oPropSetForBodyText.Add(ItemSchema.Body); oItem.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID Item oItemForBodyText = Item.Bind((ExchangeService)oItem.Service, oItem.Id, (PropertySet)oPropSetForBodyText); oItem.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID oItem.Load(oPropSetForBodyText); sRet = oItem.Body.Text; MessageBodyHtml = sRet; }
/// <summary> /// Enables direct posting data to the timeline. /// </summary> /// <param name="title">Title of the post.</param> /// <param name="message">Message of the post.</param> /// <param name="description">Description of the post.</param> /// <param name="link">Link contained as part of the post. Cannot be null</param> /// <param name="pictureUrl">URL of a picture attached to this post. Can be null</param> /// <returns>Task to support await of async call.</returns> public async Task <bool> PostToFeedAsync(string title, string message, string description, string link, string pictureUrl = null) { if (Provider.LoggedIn) { var parameters = new PropertySet { { "title", title }, { "message", link }, { "description", description }, { "link", link } }; if (!string.IsNullOrEmpty(pictureUrl)) { parameters.Add(new KeyValuePair <string, object>("picture", pictureUrl)); } string path = FBSession.ActiveSession.User.Id + "/feed"; var factory = new FBJsonClassFactory(JsonConvert.DeserializeObject <FacebookPost>); var singleValue = new FBSingleValue(path, parameters, factory); var result = await singleValue.PostAsync(); if (result.Succeeded) { var postResponse = result.Object as FacebookPost; if (postResponse != null) { return(true); } } Debug.WriteLine(string.Format("Could not post. {0}", result.ErrorInfo?.ErrorUserMessage)); return(false); } var isLoggedIn = await LoginAsync(); if (isLoggedIn) { return(await PostToFeedAsync(title, message, description, link, pictureUrl)); } return(false); }
/*Method keeps sending get requets to facebook api using paging, untill all pictures have been added */ private async void GetAllFbPic(PicturePlaceObject results, PropertySet parameters, string endpoint, PicturePlaceDb db) { Boolean addedAllPics = false; do //only do this while there is a next page and all pics have not been added { addedAllPics = SortPictures(results, db); //Add Results to a list if (addedAllPics == false) { parameters.Remove("after"); //Remove previous parameters parameters.Add("after", results.paging.cursors.after); //the next page to send the request too FBSingleValue value = new FBSingleValue(endpoint, parameters, DeserializeJson.FromJson); //send the request and get back a JSON responce FBResult graphResult = await value.GetAsync(); //check to see if the Requets Succeeded results = graphResult.Object as PicturePlaceObject; } } while ((results.paging != null || results.data.Count() != 0) && addedAllPics == false); PaintPins(db); }
private LearningModelBinding Evaluate(LearningModelSession session, object input, object output, bool wait = false) { // Create the binding var binding = new LearningModelBinding(session); // Bind inputs and outputs string inputName = session.Model.InputFeatures[0].Name; string outputName = session.Model.OutputFeatures[0].Name; binding.Bind(inputName, input); var outputBindProperties = new PropertySet(); outputBindProperties.Add("DisableTensorCpuSync", PropertyValue.CreateBoolean(true)); binding.Bind(outputName, output, outputBindProperties); // Evaluate EvaluateInternal(session, binding, wait); return(binding); }
private void Button1_Click(object sender, EventArgs e) { if (TextBox1.Text.Length > 0) { PartDocument oDoc = (PartDocument)mApp.Documents.Add(DocumentTypeEnum.kPartDocumentObject, mApp.FileManager.GetTemplateFile(DocumentTypeEnum.kPartDocumentObject), true); //Author property is contained in "Inventor Summary Information" Set PropertySet oPropertySet = oDoc.PropertySets["{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"]; //Using Inventor.Property to avoid confusion Inventor.Property oProperty = oPropertySet["Author"]; oProperty.Value = TextBox1.Text; //Get "Inventor User Defined Properties" set oPropertySet = oDoc.PropertySets["{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"]; //Create new property oProperty = oPropertySet.Add("Parts R Us", "Supplier", null); //Save document, prompt user for filename FileDialog oDLG = null; mApp.CreateFileDialog(out oDLG); oDLG.FileName = @"C:\Temp\NewPart.ipt"; oDLG.Filter = "Inventor Files (*.ipt)|*.ipt"; oDLG.DialogTitle = "Save Part"; oDLG.ShowSave(); if (oDLG.FileName != "") { oDoc.SaveAs(oDLG.FileName, false); oDoc.Close(true); } } }
public void CreateSurface(SwapChainPanel panel, Size?renderSurfaceSize, float?resolutionScale) { if (panel == null) { throw new ArgumentNullException("SwapChainPanel parameter is invalid"); } EGLSurface surface = Egl.EGL_NO_SURFACE; int[] surfaceAttributes = new[] { Egl.EGL_NONE }; // Create a PropertySet and initialize with the EGLNativeWindowType. PropertySet surfaceCreationProperties = new PropertySet(); surfaceCreationProperties.Add(Egl.EGLNativeWindowTypeProperty, panel); // If a render surface size is specified, add it to the surface creation properties if (renderSurfaceSize.HasValue) { PropertySetExtensions.AddSize(surfaceCreationProperties, Egl.EGLRenderSurfaceSizeProperty, renderSurfaceSize.Value); } // If a resolution scale is specified, add it to the surface creation properties if (resolutionScale.HasValue) { PropertySetExtensions.AddSingle(surfaceCreationProperties, Egl.EGLRenderResolutionScaleProperty, resolutionScale.Value); } surface = Egl.eglCreateWindowSurface(eglDisplay, eglConfig, surfaceCreationProperties, surfaceAttributes); if (surface == Egl.EGL_NO_SURFACE) { throw new Exception("Failed to create EGL surface"); } eglSurface = surface; }
private IEnumerable <Item> GetAllMessages(Folder folder) { DateTime?datetimeReceived = null; var items = new List <Item>(); string lastModName = ""; string subject = ""; var from = ""; DateTime?lastModTime = null; var headers = Enumerable.Empty <dynamic>().Select(e => new { Name = "", Value = "" }); var iv = new ItemView(1000); var ps = new PropertySet(BasePropertySet.FirstClassProperties); ps.Add(EmailMessageSchema.From); iv.OrderBy.Add(EWSProperties.PR_Last_Modification_Time, SortDirection.Descending); FindItemsResults <Item> f; f = folder.FindItems(iv); if (f.Count() > 0) { var latest = f.MaxBy(i => i.LastModifiedTime); datetimeReceived = latest.DateTimeReceived; lastModName = latest.LastModifiedName; lastModTime = latest.LastModifiedTime; subject = latest.Subject; latest.TryGetProperty(EmailMessageSchema.From, out EmailAddress emailAddress); from = emailAddress?.Address; } var moreAvailable = f.MoreAvailable; while (moreAvailable) { moreAvailable = f.MoreAvailable; items.AddRange(folder.FindItems(new ItemView(1000, f.NextPageOffset.GetValueOrDefault()))); } return(f); }
// 修改文件的属性 private async void btnModifyProperty_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // 用户选中的文件 string fileName = (string)listBox.SelectedItem; StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary); StorageFile storageFile = await picturesFolder.GetFileAsync(fileName); // 在 System.FileAttributes 中保存有文件是否是“只读”的信息 string[] retrieveList = new string[] { "System.FileAttributes" }; StorageItemContentProperties storageItemContentProperties = storageFile.Properties; IDictionary <string, object> extraProperties = await storageItemContentProperties.RetrievePropertiesAsync(retrieveList); uint FILE_ATTRIBUTES_READONLY = 1; if (extraProperties != null && extraProperties.ContainsKey("System.FileAttributes")) { // 切换文件的只读属性 uint temp = (UInt32)extraProperties["System.FileAttributes"] ^ FILE_ATTRIBUTES_READONLY; // 设置文件的只读属性为 true // uint temp = (UInt32)extraProperties["System.FileAttributes"] | 1; // 设置文件的只读属性为 false // uint temp = (UInt32)extraProperties["System.FileAttributes"] & 0; extraProperties["System.FileAttributes"] = temp; } else { // 设置文件的只读属性为 true extraProperties = new PropertySet(); extraProperties.Add("System.FileAttributes", FILE_ATTRIBUTES_READONLY); } // 保存修改后的属性(用这种方法可以修改部分属性,大部分属性都是无权限修改的) await storageFile.Properties.SavePropertiesAsync(extraProperties); }
/// <summary> /// Gets the group memberships. /// </summary> /// <param name="userEmailAddress">The user email address.</param> /// <returns></returns> public Collection <Membership> GetGroupMemberships(string userEmailAddress) { Logger.LogDebug("Getting group memberships for " + userEmailAddress); var result = new Collection <Membership>(); PropertyList pl = new PropertyList(); pl.Set(PropID.TokenType, TokenType.Email); pl.Set(PropID.TokenId, userEmailAddress); PropertySet psToken = new PropertySet(); psToken.Add(pl); PropertySet memberOf = this._server.GetMemberOf(psToken); var doc = this.formatXmlPropertyList(memberOf.Xml); var nodes = doc.SelectNodes("//prMembers"); Logger.LogDebug(string.Format("Converting {0} to membership objects", nodes.Count)); foreach (XmlNode node in nodes) { try { var propNode = node.SelectSingleNode("PropertyList"); var member = new Membership() { Guid = propNode.SelectSingleNode("prGUID").InnerText, Name = propNode.SelectSingleNode("prName").InnerText, DistinguishedName = propNode.SelectSingleNode("prDistinguishedName").InnerText, }; result.Add(member); } catch (Exception ex) { throw ex; } } return(result); }
private void LinkControlToProperty() { string pn = "DEPARTMENT"; if (!Properties.Settings.Default.Testing) { pn = "DEPTID"; } string dept; if (PropertySet.Contains(pn)) { PropertySet.GetProperty(pn).Ctl = cbDepartment; dept = PropertySet.GetProperty(pn).Value; int tp = 1; if (int.TryParse(dept, out tp)) { OpType = tp; } else { OpType = PropertySet.cutlistData.GetOpTypeIDByName(dept); } dept = tp.ToString(); } else { SolidWorks.Interop.swconst.swCustomInfoType_e t = SolidWorks.Interop.swconst.swCustomInfoType_e.swCustomInfoNumber; SwProperty p = new SwProperty(pn, t, "1", true); p.SwApp = SwApp; p.Ctl = cbDepartment; PropertySet.Add(p); OpType = 1; } }
private Tuple <int, int, int> GetRules(Folder folder) { var iv = new ItemView(1000); iv.Traversal = ItemTraversal.Associated; var ruleCount = 0; var enableCount = 0; var disabledCount = 0; foreach (var item in folder.FindItems(iv).ToList()) { if (item.ItemClass == "IPM.Rule.Version2.Message") { PropertySet propset; propset = new PropertySet(BasePropertySet.FirstClassProperties); propset.Add(EWSProperties.PR_RULE_MSG_STATE); item.Load(propset); item.TryGetProperty(EWSProperties.PR_RULE_MSG_STATE, out int state); ruleCount++; if (state == 1) { enableCount++; } else { disabledCount++; } } } return(Tuple.Create(ruleCount, enableCount, disabledCount)); }
private static LearningModelEvaluationResult Evaluate(LearningModelSession session, object input) { // Create the binding var binding = new LearningModelBinding(session); // Create an empty output, that will keep the output resources on the GPU // It will be chained into a the post processing on the GPU as well var output = TensorFloat.Create(); // Bind inputs and outputs // For squeezenet these evaluate to "data", and "squeezenet0_flatten0_reshape0" string inputName = session.Model.InputFeatures[0].Name; string outputName = session.Model.OutputFeatures[0].Name; binding.Bind(inputName, input); var outputBindProperties = new PropertySet(); outputBindProperties.Add("DisableTensorCpuSync", PropertyValue.CreateBoolean(true)); binding.Bind(outputName, output, outputBindProperties); // Evaluate return(session.Evaluate(binding, "")); }
/*On Successful login, send GET request to FB endpoint with params and DeserializeJson the results into objects/Dictonary */ private async void OnSuccessLogin() { string endpoint = "/me/photos";//where the url starts from PropertySet parameters = new PropertySet(); parameters.Add("fields", "source,place"); //Required fields needed FBSingleValue value = new FBSingleValue(endpoint, parameters, DeserializeJson.FromJson); //send the request and get back a JSON responce FBResult graphResult = await value.GetAsync(); if (graphResult.Succeeded)//check to see if the Request Succeeded { PicturePlaceObject results = graphResult.Object as PicturePlaceObject; var db = new PicturePlaceDb(); GetAllFbPic(results, parameters, endpoint, db); } else { MessageDialog dialog = new MessageDialog("Try Again Later!"); await dialog.ShowAsync(); } }
public static int Main(string[] args) { // Create a class ManagementClass dummyClass = new ManagementClass("root/default", "", null); dummyClass.SystemProperties["__CLASS"].Value = "TestDelClassSync"; PropertySet mykeyprop = dummyClass.Properties; mykeyprop.Add("MydelKey", "delHello"); dummyClass.Put(); // Get the Class TestDelClassSync ManagementClass dummyDeleteCheck = new ManagementClass("root/default", "TestDelClassSync", null); dummyDeleteCheck.Get(); // Set the Delete Options on the Class TestDelClassSync //int Capacity = 8; CaseInsensitiveHashtable MyHash = new CaseInsensitiveHashtable(); DeleteOptions Options = new DeleteOptions(MyHash); dummyDeleteCheck.Delete(Options); return(0); }
public void DeserializeFromXml(string xml, string[] expectedKeyValuePairs) { PropertySet expectedMap = new PropertySet(); for (int i = 0; i < expectedKeyValuePairs.Length; i += 2) expectedMap.Add(expectedKeyValuePairs[i], expectedKeyValuePairs[i + 1]); PropertySet actualMap = (PropertySet) serializer.Deserialize(new StringReader(xml)); AssertAreEqual(expectedMap, actualMap); }
/// Don't use - not sure what its tring to pull - its not pulling the shared calendars /// //EWS - Access All Shared Calendars //http://stackoverflow.com/questions/23766747/ews-access-all-shared-calendars // http://stackoverflow.com/questions/23766747/ews-access-all-shared-calendars public static Dictionary <string, Folder> GetSharedCalendarFolders(ExchangeService service, String mbMailboxname) { Dictionary <String, Folder> rtList = new System.Collections.Generic.Dictionary <string, Folder>(); FolderId rfRootFolderid = new FolderId(WellKnownFolderName.Root, mbMailboxname); FolderView fvFolderView = new FolderView(1000); SearchFilter sfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Common Views"); service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. FindFoldersResults ffoldres = service.FindFolders(rfRootFolderid, sfSearchFilter, fvFolderView); if (ffoldres.Folders.Count == 1) { PropertySet psPropset = new PropertySet(BasePropertySet.FirstClassProperties); ExtendedPropertyDefinition PidTagWlinkAddressBookEID = new ExtendedPropertyDefinition(0x6854, MapiPropertyType.Binary); ExtendedPropertyDefinition PidTagWlinkFolderType = new ExtendedPropertyDefinition(0x684F, MapiPropertyType.Binary); ExtendedPropertyDefinition PidTagWlinkGroupName = new ExtendedPropertyDefinition(0x6851, MapiPropertyType.String); psPropset.Add(PidTagWlinkAddressBookEID); psPropset.Add(PidTagWlinkFolderType); ItemView iv = new ItemView(1000); iv.PropertySet = psPropset; iv.Traversal = ItemTraversal.Associated; SearchFilter cntSearch = new SearchFilter.IsEqualTo(PidTagWlinkGroupName, "Other Calendars"); service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. FindItemsResults <Item> fiResults = ffoldres.Folders[0].FindItems(cntSearch, iv); foreach (Item itItem in fiResults.Items) { try { //object GroupName = null; object WlinkAddressBookEID = null; if (itItem.TryGetProperty(PidTagWlinkAddressBookEID, out WlinkAddressBookEID)) { byte[] ssStoreID = (byte[])WlinkAddressBookEID; int leLegDnStart = 0; String lnLegDN = ""; for (int ssArraynum = (ssStoreID.Length - 2); ssArraynum != 0; ssArraynum--) { if (ssStoreID[ssArraynum] == 0) { leLegDnStart = ssArraynum; lnLegDN = System.Text.ASCIIEncoding.ASCII.GetString(ssStoreID, leLegDnStart + 1, (ssStoreID.Length - (leLegDnStart + 2))); ssArraynum = 1; } } NameResolutionCollection ncCol = service.ResolveName(lnLegDN, ResolveNameSearchLocation.DirectoryOnly, true); if (ncCol.Count > 0) { FolderId SharedCalendarId = new FolderId(WellKnownFolderName.Calendar, ncCol[0].Mailbox.Address); service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. Folder SharedCalendaFolder = Folder.Bind(service, SharedCalendarId); rtList.Add(ncCol[0].Mailbox.Address, SharedCalendaFolder); } } } catch (Exception exception) { Console.WriteLine(exception.Message); } } } return(rtList); }
private static PropertySet CanonicalizePropertiesToLowerCase(PropertySet properties) { PropertySet result = new PropertySet(); foreach (KeyValuePair<string, string> property in properties) result.Add(CanonicalizePropertyKey(property.Key), property.Value); return result; }
public void AddMore() { _ps.Add("NewProperty", "New property value"); _ps.Add("AnotherProperty", "A property value"); }
async Task StartMediaCapture() { Debug.WriteLine("Starting MediaCapture"); app.MediaCapture = new MediaCapture(); var selectedDevice = _devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back); if (selectedDevice == null) { selectedDevice = _devices.First(); } await app.MediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = selectedDevice.Id }); app.PreviewElement.Source = app.MediaCapture; _encodingPreviewProperties = app.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview); _encodingRecorderProperties = app.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoRecord); ListAllResolutionDetails(); var selectedPreviewProperties = _encodingPreviewProperties.First(x => ((VideoEncodingProperties)x).Width == 800); ListResolutionDetails((VideoEncodingProperties)selectedPreviewProperties); await app.MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, selectedPreviewProperties); var selectedRecordingProperties = _encodingRecorderProperties.First(x => ((VideoEncodingProperties)x).Width == _encodingRecorderProperties.Max(y => ((VideoEncodingProperties)y).Width)); ListResolutionDetails((VideoEncodingProperties)selectedRecordingProperties); await app.MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, selectedRecordingProperties); PropertySet testSet = new PropertySet(); FilterEffect effect = new FilterEffect(); //LomoFilter lomoFilter = new LomoFilter(); //VignettingFilter vignettingFilter = new VignettingFilter(); //effect.Filters = new IFilter[] { lomoFilter, vignettingFilter }; HdrEffect hdrEffect = new HdrEffect(effect); List <IImageProvider> providers = new List <IImageProvider>(); providers.Add(effect); providers.Add(hdrEffect); testSet.Add(new KeyValuePair <string, object>("IImageProviders", providers)); await app.MediaCapture.AddEffectAsync(MediaStreamType.VideoPreview, "ImagingEffects.ImagingEffect", testSet); //app.MediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees); //need this if portrait mode or landscapeflipped. app.IsPreviewing = true; await app.MediaCapture.StartPreviewAsync(); if (app.MediaCapture.VideoDeviceController.FocusControl.Supported) //.SetPresetAsync(Windows.Media.Devices.FocusPreset.Manual); { await app.MediaCapture.VideoDeviceController.FocusControl.SetPresetAsync(Windows.Media.Devices.FocusPreset.Manual); } else { app.MediaCapture.VideoDeviceController.Focus.TrySetAuto(false); } }
protected override void ProcessRecord() { ItemView itemView = new ItemView(30); if (this.CustomProperty != null) { PropertySet propertySet = new PropertySet(BasePropertySet.FirstClassProperties); foreach (PropertyDefinitionBase customProp in this.CustomProperty) propertySet.Add(customProp); itemView.PropertySet = propertySet; } EwsItem ewsItems = new EwsItem(this.EwsSession, this.FolderRoot, itemView, this.SearchFilter); ewsItems.SearchResultFound += OnSearchResultFound; ewsItems.FindItem(this.FolderRoot); }
private PropertySet EnsurePropertyCache(Record record) { var columns = record.Columns; if (null != columns) { PropertySet properties; if (!this.cache.TryGetValue(columns.QueryString, out properties)) { properties = new PropertySet(); for (int i = 0; i < columns.Count; ++i) { var column = columns[i]; properties.Add(new PSAdaptedProperty(column.Key, column)); } // Format a suitable type name if only a single table was selected. if (null != columns.TableNames && 1 == columns.TableNames.Length) { properties.TypeName = typeof(Record).FullName + "#" + columns.TableNames[0]; } this.cache.Add(columns.QueryString, properties); } return properties; } return null; }
/// <summary> /// Get the MimeContent of each Item specified in itemIds and write it /// to a string. /// </summary> /// <param name="itemIds">ItemIds to retrieve</param> /// <param name="destinationFolderPath">Folder to save messages to</param> /// <param name="service">ExchangeService to use to make EWS calls</param> /// <param name="TheMime">MIME string to set</param> public static void DumpMIMEToString( List<ItemId> itemIds, ExchangeService service, ref string TheMime) { DebugLog.WriteVerbose(String.Format("Getting {0} items by ItemId.", itemIds.Count)); string MimeToReturn = string.Empty; PropertySet mimeSet = new PropertySet(BasePropertySet.IdOnly); mimeSet.Add(EmailMessageSchema.MimeContent); mimeSet.Add(EmailMessageSchema.Subject); ServiceResponseCollection<GetItemResponse> responses = service.BindToItems(itemIds, mimeSet); DebugLog.WriteVerbose("Finished getting items."); foreach (GetItemResponse response in responses) { switch (response.Result) { case ServiceResult.Success: if (response.Item.MimeContent == null) { throw new ApplicationException("No MIME content to write"); } UTF8Encoding oUTF8Encoding = new UTF8Encoding(); MimeToReturn = oUTF8Encoding.GetString(response.Item.MimeContent.Content); break; case ServiceResult.Error: MimeToReturn = "ErrorCode: " + response.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + response.ErrorMessage + "\r\n"; break; case ServiceResult.Warning: throw new NotImplementedException("DumpMIMEToString doesn't handle ServiceResult.Warning."); default: throw new NotImplementedException("DumpMIMEToString encountered an unexpected ServiceResult."); } } TheMime = MimeToReturn; DebugLog.WriteVerbose("Finished dumping MimeContents for each item."); }
public static bool LoadLvContacts(ExchangeService oExchangeService, ref ListView oListView, FolderTag oFolderTag) { bool bRet = true; // Configure ListView before adding data. //oListView.Dock = DockStyle.None; oListView.Clear(); oListView.View = View.Details; oListView.GridLines = true; oListView.Dock = DockStyle.Fill; oListView.Columns.Add("Type", 150, HorizontalAlignment.Left); oListView.Columns.Add("DisplayName", 150, HorizontalAlignment.Left); oListView.Columns.Add("Department", 50, HorizontalAlignment.Left); oListView.Columns.Add("Manager", 50, HorizontalAlignment.Left); oListView.Columns.Add("Business Street", 50, HorizontalAlignment.Left); oListView.Columns.Add("Business City", 50, HorizontalAlignment.Left); oListView.Columns.Add("Business State", 50, HorizontalAlignment.Left); oListView.Columns.Add("Business Zip", 50, HorizontalAlignment.Left); oListView.Columns.Add("Business CountryOrRegion", 50, HorizontalAlignment.Left); oListView.Columns.Add("Business Phone", 50, HorizontalAlignment.Left); oListView.Columns.Add("Home Street", 50, HorizontalAlignment.Left); oListView.Columns.Add("Home City", 50, HorizontalAlignment.Left); oListView.Columns.Add("Home State", 50, HorizontalAlignment.Left); oListView.Columns.Add("Home Zip", 50, HorizontalAlignment.Left); oListView.Columns.Add("Home CountryOrRegion", 50, HorizontalAlignment.Left); oListView.Columns.Add("Home Phone", 50, HorizontalAlignment.Left); FolderId oFolder; oFolder = oFolderTag.Id; PropertySet oPropSet = new PropertySet(PropertySet.FirstClassProperties); oPropSet.Add(ContactSchema.ItemClass); oPropSet.Add(ContactSchema.DisplayName); oPropSet.Add(ContactSchema.Department); oPropSet.Add(ContactSchema.Manager); oPropSet.Add(ContactSchema.BusinessAddressStreet); oPropSet.Add(ContactSchema.BusinessAddressCity); oPropSet.Add(ContactSchema.BusinessAddressState); oPropSet.Add(ContactSchema.BusinessAddressPostalCode); oPropSet.Add(ContactSchema.BusinessPhone); oPropSet.Add(ContactSchema.HomeAddressStreet); oPropSet.Add(ContactSchema.HomeAddressCity); oPropSet.Add(ContactSchema.HomeAddressState); oPropSet.Add(ContactSchema.HomeAddressPostalCode); oPropSet.Add(ContactSchema.HomePhone); ItemView oView = new ItemView(9999); oExchangeService.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. Folder folder = Folder.Bind(oExchangeService, oFolder, oPropSet); folder.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. FindItemsResults <Microsoft.Exchange.WebServices.Data.Item> oResults = folder.FindItems(oView); ListViewItem oListItem = null; //Contact contact = Contact.Bind(service, new ItemId("AAMkA=")); string sAddress = string.Empty; PhysicalAddressEntry oAddress = null; string sPhone = string.Empty; foreach (Item o in oResults) { Contact oContact = o as Contact; ContactGroup oContactGroup = o as ContactGroup; if (oContact != null) { oListItem = new ListViewItem("Contact", 0); oListItem.SubItems.Add(oContact.DisplayName); oListItem.SubItems.Add(oContact.Department); oListItem.SubItems.Add(oContact.Manager); if (oContact.PhysicalAddresses.TryGetValue(PhysicalAddressKey.Business, out oAddress)) { oListItem.SubItems.Add(oAddress.Street); oListItem.SubItems.Add(oAddress.City); oListItem.SubItems.Add(oAddress.State); oListItem.SubItems.Add(oAddress.PostalCode); oListItem.SubItems.Add(oAddress.CountryOrRegion); //sAddress = oAddress.Street; } else { oListItem.SubItems.Add(""); oListItem.SubItems.Add(""); oListItem.SubItems.Add(""); oListItem.SubItems.Add(""); oListItem.SubItems.Add(""); } sPhone = string.Empty; if (oContact.PhoneNumbers.TryGetValue(PhoneNumberKey.BusinessPhone, out sPhone)) { oListItem.SubItems.Add(sPhone); } else { oListItem.SubItems.Add(""); } if (oContact.PhysicalAddresses.TryGetValue(PhysicalAddressKey.Home, out oAddress)) { oListItem.SubItems.Add(oAddress.Street); oListItem.SubItems.Add(oAddress.State); oListItem.SubItems.Add(oAddress.City); oListItem.SubItems.Add(oAddress.PostalCode); oListItem.SubItems.Add(oAddress.CountryOrRegion); sAddress = oAddress.Street; } else { oListItem.SubItems.Add(""); oListItem.SubItems.Add(""); oListItem.SubItems.Add(""); oListItem.SubItems.Add(""); oListItem.SubItems.Add(""); } sPhone = string.Empty; if (oContact.PhoneNumbers.TryGetValue(PhoneNumberKey.HomePhone, out sPhone)) { oListItem.SubItems.Add(sPhone); } else { oListItem.SubItems.Add(""); } oListItem.Tag = new ItemTag(o.Id, o.ItemClass); oListView.Items.AddRange(new ListViewItem[] { oListItem }); oContact = null; oContactGroup = null; oListItem = null; oAddress = null; } } return(bRet); }
// LoadItem // This will load an item by ID. // Test code to load a folder object with many properties - modify as needed for your code. bool LoadItem(ExchangeService oService, ItemId oItemId, out Item oItem) { bool bRet = true; ExtendedPropertyDefinition Prop_IsHidden = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean); // PR_ARCHIVE_TAG 0x3018 ExtendedPropertyDefinition Prop_PidTagPolicyTag = new ExtendedPropertyDefinition(0x66B1, MapiPropertyType.Long); // PR_POLICY_TAG 0x3019 Data type: PtypBinary, 0x0102 ExtendedPropertyDefinition Prop_PR_POLICY_TAG = new ExtendedPropertyDefinition(0x3019, MapiPropertyType.Binary); // PR_RETENTION_FLAGS 0x301D (12317) PtypInteger32 ExtendedPropertyDefinition Prop_Retention_Flags = new ExtendedPropertyDefinition(0x301D, MapiPropertyType.Integer); // PR_RETENTION_PERIOD 0x301A (12314) PtypInteger32, 0x0003 ExtendedPropertyDefinition Prop_Retention_Period = new ExtendedPropertyDefinition(0x301A, MapiPropertyType.Integer); Item oReturnItem = null; oItem = null; List <ItemId> oItems = new List <ItemId>(); oItems.Add(oItemId); PropertySet oPropertySet = new PropertySet( BasePropertySet.IdOnly, EmailMessageSchema.ItemClass, EmailMessageSchema.Subject); // Add more properties? oPropertySet.Add(Prop_IsHidden); oPropertySet.Add(EmailMessageSchema.DateTimeCreated); oPropertySet.Add(EmailMessageSchema.DateTimeReceived); oPropertySet.Add(EmailMessageSchema.DateTimeSent); //oPropertySet.Add(EmailMessageSchema.RetentionDate); oPropertySet.Add(EmailMessageSchema.ToRecipients); oPropertySet.Add(EmailMessageSchema.MimeContent); //oPropertySet.Add(EmailMessageSchema.StoreEntryId); oPropertySet.Add(EmailMessageSchema.Size); oPropertySet.Add(Prop_Retention_Period); oPropertySet.Add(Prop_PR_POLICY_TAG); oPropertySet.Add(Prop_Retention_Flags); int iVal = 0; long lVal = 0; object oVal = null; bool boolVal = false; ServiceResponseCollection <GetItemResponse> oGetItemResponses = oService.BindToItems(oItems, oPropertySet); StringBuilder oSB = new StringBuilder(); foreach (GetItemResponse oGetItemResponse in oGetItemResponses) { switch (oGetItemResponse.Result) { case ServiceResult.Success: oReturnItem = oGetItemResponse.Item; oSB.AppendFormat("Subject: {0}\r\n", oReturnItem.Subject); oSB.AppendFormat("Class: {0}\r\n", oReturnItem.ItemClass); oSB.AppendFormat("DateTimeCreated: {0}\r\n", oReturnItem.DateTimeCreated.ToString()); oSB.AppendFormat("Size: {0}\r\n", oReturnItem.Size.ToString()); if (oReturnItem.TryGetProperty(Prop_IsHidden, out boolVal)) { oSB.AppendFormat("PR_IS_HIDDEN: {0}\r\n", boolVal); } else { oSB.AppendLine("PR_IS_HIDDEN: Not found."); } if (oReturnItem.TryGetProperty(Prop_PR_POLICY_TAG, out oVal)) { oSB.AppendFormat("PR_POLICY_TAG: {0}\r\n", oVal); } //else // oSB.AppendLine("PR_RETENTION_TAG: Not found."); if (oReturnItem.TryGetProperty(Prop_Retention_Flags, out iVal)) { oSB.AppendFormat("PR_RETENTION_FLAGS: {0}\r\n", iVal); } //else // oSB.AppendLine("PR_RETENTION_FLAGS: Not found."); if (oReturnItem.TryGetProperty(Prop_Retention_Period, out iVal)) { oSB.AppendFormat("PR_RETENTION_PERIOD: {0}\r\n", iVal); } //else // oSB.AppendLine("PR_RETENTION_PERIOD: Not found."); //// The following is for geting the MIME string //if (oGetItemResponse.Item.MimeContent == null) //{ // // Do something //} //UTF8Encoding oUTF8Encoding = new UTF8Encoding(); //string sMIME = oUTF8Encoding.GetString(oGetItemResponse.Item.MimeContent.Content); MessageBox.Show(oSB.ToString(), "ServiceResult.Success"); break; case ServiceResult.Error: string sError = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sError, "ServiceResult.Error"); break; case ServiceResult.Warning: string sWarning = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sWarning, "ServiceResult.Warning"); break; //default: // // Should never get here. // string sSomeError = // "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + // "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; // MessageBox.Show(sSomeError, "Some sort of error"); // break; } } oItem = oReturnItem; return(bRet); }
//private string DeNullString(string s) //{ // if (s == null) // return ""; // else // return s; //} // LoadItem // This will load an item by ID. // Test code to load a folder object with many properties - modify as needed for your code. bool LoadItem(ExchangeService oService, ItemId oItemId, out Item oItem) { bool bRet = true; ExtendedPropertyDefinition Prop_IsHidden = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean); Item oReturnItem = null; oItem = null; List <ItemId> oItems = new List <ItemId>(); oItems.Add(oItemId); PropertySet oPropertySet = new PropertySet( BasePropertySet.IdOnly, EmailMessageSchema.ItemClass, EmailMessageSchema.Subject); // Add more properties? oPropertySet.Add(Prop_IsHidden); oPropertySet.Add(EmailMessageSchema.DateTimeCreated); oPropertySet.Add(EmailMessageSchema.DateTimeReceived); oPropertySet.Add(EmailMessageSchema.DateTimeSent); //oPropertySet.Add(EmailMessageSchema.RetentionDate); oPropertySet.Add(EmailMessageSchema.ToRecipients); oPropertySet.Add(EmailMessageSchema.MimeContent); oPropertySet.Add(EmailMessageSchema.StoreEntryId); oPropertySet.Add(EmailMessageSchema.Size); oService.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. ServiceResponseCollection <GetItemResponse> oGetItemResponses = oService.BindToItems(oItems, oPropertySet); foreach (GetItemResponse oGetItemResponse in oGetItemResponses) { switch (oGetItemResponse.Result) { case ServiceResult.Success: oReturnItem = oGetItemResponse.Item; // EmailMessage oEmailMessage = (EmailMessage)oReturnItem; // recasting example MessageBox.Show("ServiceResult.Success"); //// The following is for geting the MIME string //if (oGetItemResponse.Item.MimeContent == null) //{ // // Do something //} //UTF8Encoding oUTF8Encoding = new UTF8Encoding(); //string sMIME = oUTF8Encoding.GetString(oGetItemResponse.Item.MimeContent.Content); break; case ServiceResult.Error: string sError = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sError, "ServiceResult.Error"); break; case ServiceResult.Warning: string sWarning = "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; MessageBox.Show(sWarning, "ServiceResult.Warning"); break; //default: // // Should never get here. // string sSomeError = // "ErrorCode: " + oGetItemResponse.ErrorCode.ToString() + "\r\n" + // "\r\nErrorMessage: " + oGetItemResponse.ErrorMessage + "\r\n"; // MessageBox.Show(sSomeError, "Some sort of error"); // break; } } oItem = oReturnItem; return(bRet); }
private void Run() { try { Status = MessageProcessorStatus.Started; var fullPropertySet = new PropertySet(PropertySet.FirstClassProperties) { EmailMessageSchema.IsRead, EmailMessageSchema.IsReadReceiptRequested, EmailMessageSchema.IsDeliveryReceiptRequested, ItemSchema.DateTimeSent, ItemSchema.DateTimeReceived, ItemSchema.DateTimeCreated, ItemSchema.ItemClass, ItemSchema.MimeContent, ItemSchema.Categories, ItemSchema.Importance, ItemSchema.InReplyTo, ItemSchema.IsFromMe, ItemSchema.IsReminderSet, ItemSchema.IsResend, ItemSchema.IsDraft, ItemSchema.ReminderDueBy, ItemSchema.Sensitivity, ItemSchema.Subject, ItemSchema.Id, ExchangeHelper.MsgPropertyContentType, ExchangeHelper.PidTagFollowupIcon, }; if (service.RequestedServerVersion != ExchangeVersion.Exchange2007_SP1) { fullPropertySet.Add(ItemSchema.ConversationId); fullPropertySet.Add(ItemSchema.IsAssociated); } if (service.RequestedServerVersion == ExchangeVersion.Exchange2013) { fullPropertySet.Add(ItemSchema.ArchiveTag); fullPropertySet.Add(ItemSchema.Flag); fullPropertySet.Add(ItemSchema.IconIndex); } SearchFilter.SearchFilterCollection filter = new SearchFilter.SearchFilterCollection(); filter.LogicalOperator = LogicalOperator.And; if (_startDate != null) { Logger.Debug("Getting mails from " + _startDate); filter.Add(new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, _startDate)); } if (_endDate != null) { Logger.Debug("Getting mails up until " + _endDate); filter.Add(new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, _endDate)); } foreach (var exchangeFolder in folders) { ItemView view = new ItemView(_pageSize, 0, OffsetBasePoint.Beginning); view.PropertySet = PropertySet.IdOnly; List <EmailMessage> emails = new List <EmailMessage>(); Boolean more = true; while (more) { try { more = FindExchangeMessages(exchangeFolder, filter, view, emails, fullPropertySet); if (emails.Count > 0) { try { foreach (var emailMessage in emails) { try { String subject; if (!emailMessage.TryGetProperty(ItemSchema.Subject, out subject) || subject == null) { Logger.Warn("Item " + emailMessage.Id.UniqueId + " has no subject assigned, unable to determine subject."); } Logger.Debug("Exporting " + emailMessage.Id.UniqueId + " from " + exchangeFolder.FolderPath + " : " + subject); var flags = new Collection <MessageFlags>(); Boolean flag; if (emailMessage.TryGetProperty(EmailMessageSchema.IsRead, out flag) && !flag) { flags.Add(MessageFlags.Unread); } if (emailMessage.TryGetProperty(ItemSchema.IsDraft, out flag) && flag) { flags.Add(MessageFlags.Draft); } if ( emailMessage.TryGetProperty(EmailMessageSchema.IsReadReceiptRequested, out flag) && flag) { flags.Add(MessageFlags.ReadReceiptRequested); } if ( emailMessage.TryGetProperty( EmailMessageSchema.IsDeliveryReceiptRequested, out flag) && flag) { flags.Add(MessageFlags.DeliveryReceiptRequested); } if (emailMessage.TryGetProperty(ItemSchema.IsReminderSet, out flag) && flag) { flags.Add(MessageFlags.ReminderSet); } if (emailMessage.TryGetProperty(ItemSchema.IsAssociated, out flag) && flag) { flags.Add(MessageFlags.Associated); } if (emailMessage.TryGetProperty(ItemSchema.IsFromMe, out flag) && flag) { flags.Add(MessageFlags.FromMe); } if (emailMessage.TryGetProperty(ItemSchema.IsResend, out flag) && flag) { flags.Add(MessageFlags.Resend); } var message = new RawMessageDescriptor { SourceId = emailMessage.Id.UniqueId, Subject = subject, Flags = flags, RawMessage = "", SourceFolder = exchangeFolder.FolderPath, DestinationFolder = exchangeFolder.MappedDestination, IsPublicFolder = exchangeFolder.IsPublicFolder, }; Object result; if (emailMessage.TryGetProperty(ItemSchema.MimeContent, out result) && result != null) { message.RawMessage = Encoding.UTF8.GetString(emailMessage.MimeContent.Content); } if (emailMessage.TryGetProperty(ItemSchema.ItemClass, out result) && result != null) { message.ItemClass = emailMessage.ItemClass; } if (emailMessage.TryGetProperty(ItemSchema.IconIndex, out result) && result != null) { message.IconIndex = (int)emailMessage.IconIndex; } if (emailMessage.TryGetProperty(ItemSchema.Importance, out result) && result != null) { message.Importance = (int)emailMessage.Importance; } if (emailMessage.TryGetProperty(ItemSchema.Sensitivity, out result) && result != null) { message.Sensitivity = (int)emailMessage.Sensitivity; } if (emailMessage.TryGetProperty(ItemSchema.InReplyTo, out result) && result != null) { message.InReplyTo = emailMessage.InReplyTo; } if (emailMessage.TryGetProperty(ItemSchema.ConversationId, out result) && result != null) { message.ConversationId = emailMessage.ConversationId.ChangeKey; } if (emailMessage.TryGetProperty(ItemSchema.ReminderDueBy, out result) && result != null) { message.ReminderDueBy = emailMessage.ReminderDueBy; } if ( emailMessage.TryGetProperty(ExchangeHelper.PidTagFollowupIcon, out result) && result != null) { message.FlagIcon = ExchangeHelper.ConvertFlagIcon((int)result); } if (emailMessage.TryGetProperty(ItemSchema.DateTimeReceived, out result) && result != null) { message.ReceivedDateTime = emailMessage.DateTimeReceived; } if (emailMessage.TryGetProperty(ItemSchema.DateTimeSent, out result) && result != null) { message.SentDateTime = emailMessage.DateTimeSent; } if (emailMessage.TryGetProperty(ItemSchema.Flag, out result) && result != null) { message.FollowUpFlag = new FollowUpFlag() { StartDateTime = ((Flag)result).StartDate, DueDateTime = ((Flag)result).DueDate, CompleteDateTime = ((Flag)result).CompleteDate, Status = ExchangeHelper.ConvertFlagStatus(((Flag)result).FlagStatus), } } ; if (emailMessage.TryGetProperty(ItemSchema.Categories, out result) && result != null && emailMessage.Categories.Count > 0) { foreach (var category in emailMessage.Categories) { message.Categories.Add(category); } } if (emailMessage.ExtendedProperties != null) { foreach (var extendedProperty in emailMessage.ExtendedProperties) { if ( extendedProperty.PropertyDefinition.Equals( ExchangeHelper.MsgPropertyContentType)) { if (extendedProperty.Value.ToString().Contains("signed-data")) { message.IsEncrypted = true; } } } } NextReader.Process(message); SucceededMessageCount++; } catch (Exception e) { Logger.Error("Failed to load properties for message " + emailMessage.Id.UniqueId, e); FailedMessageCount++; } } } catch (Exception e) { Logger.Error("Failed to load properties for messages in " + exchangeFolder.FolderPath, e); FailedMessageCount += emails.Count; } ProcessedMessageCount += emails.Count; } if (more) { view.Offset += _pageSize; } } catch (Exception e) { Logger.Error("Failed to find results against folder " + exchangeFolder.FolderPath, e); more = false; } } } } catch (Exception e) { Logger.Error("Failed to run exporter", e); } finally { Close(); } }
public static PropertySet GetMappings(this Type type) { var metadata = new PropertySet() as IDictionary <string, object>; var items = (from item in type.GetCustomAttributes(false) let p = item as IMetadata where p != null group p by p.Name into g select new { Name = g.Key, g } ).ToList(); foreach (var item in MetadataAttributeVisitor.Current.VisitType(type)) { var group = item.ToList(); var props = (from p in item.Key.GetProperties() where !(p.Name == "TypeId" && p.PropertyType == typeof(object)) select new { Name = p.Name, Handler = p.GetGetMethod(), Result = new List <object>() }).ToList(); var fields = (from p in item.Key.GetFields() select new { Name = p.Name, Field = p, Result = new List <object>() }).ToList(); foreach (var i in group) { foreach (var p in props) { p.Result.Add(p.Handler.FastFuncInvoke(i, new object[0])); } foreach (var p in fields) { p.Result.Add(p.Field.GetValue(i)); } } foreach (var p in props) { if (p.Result.Count == 1) { metadata.Add(p.Name, p.Result[0]); } else if (p.Result.Count > 1) { try { metadata.Add(p.Name, p.Result.ToArray()); } catch { Console.WriteLine(p.Name); } } } foreach (var p in fields) { if (p.Result.Count == 1) { metadata.Add(p.Name, p.Result[0]); } else if (p.Result.Count > 1) { metadata.Add(p.Name, p.Result.ToArray()); } } } foreach (var item in items) { var vals = item.g.ConvertAll <IMetadata, object>(p => p.Value).ToArray(); if (vals.Length > 1) { metadata.Add(item.Name, vals); } else if (vals.Length == 1) { metadata.Add(item.Name, vals[0]); } } return(metadata as PropertySet); }
public static bool SaveItemListViewToCsv( ExchangeService oExchangeService, ListView oListView, string sFilePath, List <AdditionalPropertyDefinition> oAdditionalPropertyDefinitions, List <ExtendedPropertyDefinition> oExtendedPropertyDefinitions, CsvExportOptions oCsvExportOptions ) { bool bRet = false; string sHeader = string.Empty; string sLine = string.Empty; int iFolderPathColumn = 14; // Folder Path PropertySet oExtendedPropSet = new PropertySet(BasePropertySet.IdOnly); if (oExtendedPropertyDefinitions != null) { foreach (ExtendedPropertyDefinition oEPD in oExtendedPropertyDefinitions) { oExtendedPropSet.Add(oEPD); } } StreamWriter w = File.AppendText(sFilePath); char[] TrimChars = { ',', ' ' }; StringBuilder SbHeader = new StringBuilder(); int iHeaderCount = 0; // Build header part for listview foreach (ColumnHeader oCH in oListView.Columns) { iHeaderCount++; // Exclusions if (oCsvExportOptions._CsvExportGridExclusions != Exports.CsvExportGridExclusions.ExportAll) { if (oCsvExportOptions._CsvExportGridExclusions == Exports.CsvExportGridExclusions.ExcludeAllInGridExceptFilePath) { if (iFolderPathColumn == iHeaderCount) { SbHeader.Append(oCH.Text); SbHeader.Append(","); } } } else { SbHeader.Append(oCH.Text); SbHeader.Append(","); } } sHeader = SbHeader.ToString(); sHeader = sHeader.TrimEnd(TrimChars); // Add headers for custom properties. if (oAdditionalPropertyDefinitions != null) { sHeader += "," + AdditionalProperties.GetExtendedPropertyHeadersAsCsvContent(oAdditionalPropertyDefinitions); sHeader = sHeader.TrimEnd(TrimChars); } w.WriteLine(sHeader); ItemId oItemId = null; string sExtendedValue = string.Empty; int iCount = 0; string s = string.Empty; foreach (ListViewItem oListViewItem in oListView.SelectedItems) { iCount++; StringBuilder SbLine = new StringBuilder(); ItemTag oCalendarItemTag = (ItemTag)oListViewItem.Tag; oItemId = oCalendarItemTag.Id; byte[] oFromBytes; if (oListViewItem.Selected == true) { int iColumnCount = 0; foreach (ListViewItem.ListViewSubItem o in oListViewItem.SubItems) { iColumnCount++; s = (o.Text); // clean or encode strings to prevent issus with usage in a CSV? ---------- if (oCsvExportOptions._CsvStringHandling != CsvStringHandling.None) { s = AdditionalProperties.DoStringHandling(s, oCsvExportOptions._CsvStringHandling); } if (oCsvExportOptions.HexEncodeBinaryData == true) { if (oListViewItem.Tag != null) { if (oListViewItem.Tag.ToString() == "Binary") { oFromBytes = System.Convert.FromBase64String(s); // Base64 to byte array. s = StringHelper.HexStringFromByteArray(oFromBytes, false); } } } //// If its base64 encoded then convert it to hex encoded. //if (oCsvExportOptions.HexEncodeBinaryData == true) //{ // //bColumnIsByteArray = StringHelper.IsBase64Encoded(s); // if (StringHelper.IsBase64Encoded(s) == true) // { // oFromBytes = System.Convert.FromBase64String(s); // Base64 to byte array. // s = StringHelper.HexStringFromByteArray(oFromBytes, false); // } //} // Exclusions -------------------------------------------- if (oCsvExportOptions._CsvExportGridExclusions != Exports.CsvExportGridExclusions.ExportAll) { if (oCsvExportOptions._CsvExportGridExclusions == Exports.CsvExportGridExclusions.ExcludeAllInGridExceptFilePath) { if (iFolderPathColumn == iColumnCount) { SbLine.Append(s); SbLine.Append(","); } } } else { SbLine.Append(s); SbLine.Append(","); } } } sLine = SbLine.ToString(); sLine = sLine.TrimEnd(TrimChars); // Add Additional Properties ---------------------------------------------- StringBuilder oStringBuilder = new StringBuilder(); if (oExtendedPropertyDefinitions != null) { string sExt = AdditionalProperties.GetExtendedPropertiesForItemAsCsvContent( oExchangeService, oItemId, oExtendedPropertyDefinitions, oCsvExportOptions ); sLine += "," + sExt; //sLine = SbLine.ToString(); sLine = sLine.TrimEnd(TrimChars); } w.WriteLine(sLine); bRet = true; } w.Close(); return(bRet); }
public void GetAndSetValue() { PropertySet set = new PropertySet(); Assert.IsNull(set.GetValue("key")); set.SetValue("key", "value"); Assert.AreEqual("value", set.GetValue("key")); set.SetValue("key", "different value"); Assert.AreEqual("different value", set.GetValue("key")); set.SetValue("key", null); Assert.IsNull(set.GetValue("key")); set.Add("key", "value1"); Assert.AreEqual("value1", set.GetValue("key")); }
public void AsReadOnly() { PropertySet original = new PropertySet(); original.Add("abc", "123"); PropertySet readOnly = original.AsReadOnly(); Assert.IsTrue(readOnly.IsReadOnly); AssertAreEqual(original, readOnly); MbUnit.Framework.Assert.Throws<NotSupportedException>(delegate { readOnly.Add("def", "456"); }); }
/// <summary> /// Adds a property key/value pair. /// </summary> /// <param name="key">The property key.</param> /// <param name="value">The property value.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="key"/> or <paramref name="value"/> is null.</exception> /// <exception cref="InvalidOperationException">Thrown if <paramref name="key"/> is already in the property set.</exception> public void AddProperty(string key, string value) { properties.Add(key, value); // note: implicitly checks arguments }
static void FindFoldersWithPolicyTag(ExchangeService oExchangeService, WellKnownFolderName oParentFolder, string sPolicyTag, ref ListView oListView, FolderTraversal oFolderTraversal) { int pageSize = 5; int offset = 0; FolderView oFolderView = new FolderView(pageSize + 1, offset); //ItemView view = new ItemView(pageSize + 1, offset); PropertySet oPropertySet = new PropertySet(BasePropertySet.IdOnly); oPropertySet.Add(FolderSchema.DisplayName); oPropertySet.Add(FolderSchema.FolderClass); oPropertySet.Add(Prop_PR_POLICY_TAG); oPropertySet.Add(Prop_PR_RETENTION_FLAGS); oPropertySet.Add(Prop_PR_RETENTION_PERIOD); //oPropertySet.Add(Prop_PR_RETENTION_DATE); //oPropertySet.Add(Prop_PR_ARCHIVE_TAG); //oPropertySet.Add(Prop_PR_ARCHIVE_PERIOD); oPropertySet.Add(FolderSchema.TotalCount); oPropertySet.Add(Prop_PR_FOLDER_PATH); oPropertySet.Add(Prop_PR_IS_HIDDEN); oListView.Columns.Add("Id", 200, HorizontalAlignment.Left); oListView.Columns.Add("FolderName", 250, HorizontalAlignment.Left); oListView.Columns.Add("Folder Path", 400, HorizontalAlignment.Left); oListView.Columns.Add("PR_POLICY_TAG", 100, HorizontalAlignment.Left); oListView.Columns.Add("PR_RETENTION_FLAGS", 100, HorizontalAlignment.Left); oListView.Columns.Add("PR_RETENTION_Period", 100, HorizontalAlignment.Left); oListView.Columns.Add("PR_IS_HIDDEN", 100, HorizontalAlignment.Left); oListView.Columns.Add("TotalCount", 100, HorizontalAlignment.Left); oFolderView.PropertySet = oPropertySet; oFolderView.Traversal = oFolderTraversal; string sPath = string.Empty;; FindFoldersResults oFindFoldersResults = null; ListViewItem oListViewItem = null; bool moreItems = true; //FolderId anchorId = null; while (moreItems) { try { oExchangeService.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oFindFoldersResults = oExchangeService.FindFolders(oParentFolder, oFolderView); moreItems = oFindFoldersResults.MoreAvailable; if (moreItems) { oFolderView.Offset += pageSize; } int displayCount = oFindFoldersResults.Folders.Count > pageSize ? pageSize : oFindFoldersResults.Folders.Count; string sPR_POLICY_TAG = string.Empty; string iPR_RETENTION_FLAGS = string.Empty; string iPR_RETENTION_PERIOD = string.Empty; //private static ExtendedPropertyDefinition Prop_PR_POLICY_TAG = new ExtendedPropertyDefinition(0x3019, MapiPropertyType.Binary); // PR_POLICY_TAG 0x3019 Data type: PtypBinary, 0x0102 //private static ExtendedPropertyDefinition Prop_PR_RETENTION_FLAGS = new ExtendedPropertyDefinition(0x301D, MapiPropertyType.Integer); // PR_RETENTION_FLAGS 0x301D //private static ExtendedPropertyDefinition Prop_PR_RETENTION_PERIOD = new ExtendedPropertyDefinition(0x301A, MapiPropertyType.Integer); // PR_RETENTION_PERIOD 0x301A for (int i = 0; i < displayCount; i++) { Folder oFolder = oFindFoldersResults.Folders[i]; //string sResult = EwsExtendedPropertyHelper.GetExtendedProp_Byte_AsString(oFolder, Prop_PR_POLICY_TAG); //sResult = EwsExtendedPropertyHelper.GetExtendedProp_Int_AsString(oFolder, Prop_PR_RETENTION_FLAGS); //sResult = EwsExtendedPropertyHelper.GetExtendedProp_Int_AsString(oFolder, Prop_PR_RETENTION_PERIOD); string sFrom = EwsExtendedPropertyHelper.GetExtendedProp_Byte_AsString(oFolder, Prop_PR_POLICY_TAG); if (sFrom == "") { sPR_POLICY_TAG = ""; } else { byte[] oFromBytes = System.Convert.FromBase64String(sFrom); Guid guidTemp = new Guid(oFromBytes); sPR_POLICY_TAG = guidTemp.ToString(); } string sPR_RETENTION_FLAGS = EwsExtendedPropertyHelper.GetExtendedProp_Int_AsString(oFolder, Prop_PR_RETENTION_FLAGS); string sPR_RETENTION_PERIOD = EwsExtendedPropertyHelper.GetExtendedProp_Int_AsString(oFolder, Prop_PR_RETENTION_PERIOD); if (sPR_POLICY_TAG != "") { Console.WriteLine("Folder: " + oFolder.DisplayName + " Policy: " + sPR_POLICY_TAG); } if (sPR_POLICY_TAG == sPolicyTag) { oListViewItem = oListView.Items.Add(oFolder.Id.ToString()); oListViewItem.SubItems.Add(oFolder.DisplayName); EwsFolderHelper.GetFolderPath(oFolder, ref sPath); oListViewItem.SubItems.Add(sPath); oListViewItem.SubItems.Add(sPR_POLICY_TAG); // Policy oListViewItem.SubItems.Add(sPR_RETENTION_FLAGS); oListViewItem.SubItems.Add(sPR_RETENTION_PERIOD); //oListViewItem.SubItems.Add(EwsExtendedPropertyHelper.GetExtendedProp_Byte_AsString(oFolder, Prop_PR_RETENTION_PERIOD).ToString()); oListViewItem.SubItems.Add(EwsExtendedPropertyHelper.GetExtendedProp_Bool_AsString(oFolder, Prop_PR_IS_HIDDEN).ToString()); oListViewItem.SubItems.Add(FolderSchema.TotalCount.ToString()); } } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error while paging results"); return; } } }
//~CanvasRenderingContextHolographicSpace() //{ // deviceContext.MakeCurrent(IntPtr.Zero); // deviceContext.DeleteContext(context); //} private IntPtr CreateEglContext(HolographicSpace holographicSpace, SpatialStationaryFrameOfReference stationaryReferenceFrame) { IntPtr context; int[] configAttribs = new int[] { Egl.RED_SIZE, 8, Egl.GREEN_SIZE, 8, Egl.BLUE_SIZE, 8, Egl.ALPHA_SIZE, 8, Egl.DEPTH_SIZE, 8, Egl.STENCIL_SIZE, 8, Egl.NONE }; int[] contextAttribs = new int[] { Egl.CONTEXT_CLIENT_VERSION, 2, Egl.NONE }; int[] surfaceAttribs = new int[] { EGL_ANGLE_SURFACE_RENDER_TO_BACK_BUFFER, Egl.TRUE, Egl.NONE }; int[] defaultDisplayAttribs = new int[] { EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, Egl.TRUE, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, Egl.TRUE, Egl.NONE }; int[] fl9_3DisplayAttributes = new int[] { // These can be used to request ANGLE's D3D11 renderer, with D3D11 Feature Level 9_3. // These attributes are used if the call to eglInitialize fails with the default display attributes. EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, 9, EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, 3, EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, Egl.TRUE, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, Egl.TRUE, Egl.NONE }; int[] warpDisplayAttributes = new int[] { // These attributes can be used to request D3D11 WARP. // They are used if eglInitialize fails with both the default display attributes and the 9_3 display attributes. EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE, EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_DEVICE_TYPE_WARP_ANGLE, EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, Egl.TRUE, EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, Egl.TRUE, Egl.NONE }; int[] configCount = new int[1]; IntPtr[] configs = new IntPtr[8]; if (Egl.BindAPI(Egl.OPENGL_ES_API) == false) { throw new InvalidOperationException("No OpenGL ES API"); } if ((display = Egl.GetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, IntPtr.Zero, defaultDisplayAttribs)) == IntPtr.Zero) { throw new InvalidOperationException("Unable to get EGL display"); } if (!Egl.Initialize(display, null, null)) { if ((display = Egl.GetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, IntPtr.Zero, fl9_3DisplayAttributes)) == IntPtr.Zero) { throw new InvalidOperationException("Unable to get EGL display"); } if (!Egl.Initialize(display, null, null)) { if ((display = Egl.GetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, IntPtr.Zero, warpDisplayAttributes)) == IntPtr.Zero) { throw new InvalidOperationException("Unable to get EGL display"); } if (!Egl.Initialize(display, null, null)) { throw new InvalidOperationException("Unable to initialize EGL"); } } } if (!Egl.ChooseConfig(display, configAttribs, configs, 1, configCount)) { throw new InvalidOperationException("Unable to choose configuration"); } holographicSpaceHandle = GCHandle.Alloc(holographicSpace); IntPtr holographicSpacePointer = Marshal.GetIUnknownForObject(holographicSpace); //PropertySet surfaceCreationProperties = new PropertySet //{ // { "EGLNativeWindowTypeProperty", (IntPtr)holographicSpaceHandle } //}; PropertySet surfaceCreationProperties = new PropertySet(); surfaceCreationProperties.Add("EGLNativeWindowTypeProperty", holographicSpacePointer); //if (stationaryReferenceFrame != null) //{ // stationaryReferenceFrameHandle = GCHandle.Alloc(stationaryReferenceFrame); // surfaceCreationProperties.Add("EGLBaseCoordinateSystemProperty", (IntPtr)stationaryReferenceFrameHandle); //} GCHandle surfaceCreationPropertiesHandle = GCHandle.Alloc(surfaceCreationProperties); IntPtr surfaceCreationPropertiesPointer = Marshal.GetIUnknownForObject(surfaceCreationProperties); if ((surface = Egl.CreateWindowSurface(display, configs[0], surfaceCreationPropertiesPointer, surfaceAttribs)) == IntPtr.Zero) { throw new InvalidOperationException("Unable to create EGL fullscreen surface"); } if ((context = Egl.CreateContext(display, configs[0], IntPtr.Zero, contextAttribs)) == IntPtr.Zero) { throw new InvalidOperationException("Unable to create context"); } return(context); }