private QueryFilter ApplyFolderFilter(QueryFilter filter, MailboxInfo mailboxInfo, MultiMailboxSearchClient client) { if (!string.IsNullOrEmpty(mailboxInfo.Folder)) { Recorder.Trace(5L, TraceType.InfoTrace, "FastLocalSearchResultsProvider.Search folder inclusion Folder:", mailboxInfo.Folder); VersionedId versionedId = VersionedId.Deserialize(mailboxInfo.Folder); filter = QueryFilter.AndTogether(new QueryFilter[] { filter, new ComparisonFilter(ComparisonOperator.Equal, StoreObjectSchema.ParentEntryId, versionedId.ObjectId) }); } else { List <StoreId> excludedFolderListForMailbox = client.GetExcludedFolderListForMailbox(mailboxInfo); if (excludedFolderListForMailbox != null && excludedFolderListForMailbox.Count > 0) { Recorder.Trace(5L, TraceType.InfoTrace, "FastLocalSearchResultsProvider.Search folder exclusion List:", excludedFolderListForMailbox); List <QueryFilter> list = new List <QueryFilter>(); list.Add(filter); list.AddRange(from s in excludedFolderListForMailbox select new ComparisonFilter(ComparisonOperator.NotEqual, StoreObjectSchema.ParentEntryId, s)); filter = QueryFilter.AndTogether(list.ToArray()); } } return(filter); }
private void ValidateAndAddToFinalSourceMailboxes(string searchQuery, StorageMiniRecipient recipient, IList <ISource> finalSourceMailboxes, IList <string> versionSkippedMailboxes, IList <string> rbacDeniedMailboxes, Dictionary <MiniRecipient, MailboxInfo> crossPremiseMailboxes) { if (!this.ExecutingUserRunspace.IsCmdletAllowedInScope("New-MailboxSearch", new string[] { "EstimateOnly" }, recipient, ScopeLocation.RecipientWrite)) { rbacDeniedMailboxes.Add(recipient.LegacyExchangeDN); return; } if (!this.ValidExchangeVersion(recipient)) { versionSkippedMailboxes.Add(recipient.LegacyExchangeDN); return; } MailboxInfo value = new MailboxInfo(recipient, MailboxType.Primary); SourceMailbox item; if ((recipient.RecipientTypeDetails & (RecipientTypeDetails)((ulong)-2147483648)) == (RecipientTypeDetails)((ulong)-2147483648) || (recipient.RecipientTypeDetails & RecipientTypeDetails.RemoteRoomMailbox) == RecipientTypeDetails.RemoteRoomMailbox || (recipient.RecipientTypeDetails & RecipientTypeDetails.RemoteEquipmentMailbox) == RecipientTypeDetails.RemoteEquipmentMailbox || (recipient.RecipientTypeDetails & RecipientTypeDetails.RemoteTeamMailbox) == RecipientTypeDetails.RemoteTeamMailbox || (recipient.RecipientTypeDetails & RecipientTypeDetails.RemoteSharedMailbox) == RecipientTypeDetails.RemoteSharedMailbox) { crossPremiseMailboxes.Add(recipient, value); item = new SourceMailbox(recipient.ExternalEmailAddress.AddressString, recipient.DisplayName, recipient.LegacyExchangeDN, BackEndLocator.GetBackEndWebServicesUrl(recipient), searchQuery); finalSourceMailboxes.Add(item); return; } item = new SourceMailbox(recipient.PrimarySmtpAddress.ToString(), recipient.DisplayName, recipient.LegacyExchangeDN, BackEndLocator.GetBackEndWebServicesUrl(recipient), searchQuery); ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromMiniRecipient(recipient, RemotingOptions.AllowCrossSite); if (exchangePrincipal.MailboxInfo.Location.ServerVersion < Server.E15MinVersion || exchangePrincipal.MailboxInfo.Location == null || string.IsNullOrEmpty(exchangePrincipal.MailboxInfo.Location.ServerFqdn)) { versionSkippedMailboxes.Add(recipient.LegacyExchangeDN); return; } finalSourceMailboxes.Add(item); }
public IEnumerable <FanoutParameters> GetServer(ISearchPolicy policy, IEnumerable <SearchSource> sources) { Recorder.Trace(5L, TraceType.InfoTrace, "AutoDiscoveryServerProvider.GetServer Sources:", sources); long discoveryTimeLocal = 0L; long discoveryTimeCrossPremise = 0L; IEwsEndpointDiscovery endpointDiscovery = Factory.Current.GetEwsEndpointDiscovery((from t in sources select t.MailboxInfo).ToList <MailboxInfo>(), policy.RecipientSession.SessionSettings.CurrentOrganizationId, policy.CallerInfo); Dictionary <GroupId, List <MailboxInfo> > mailboxServerMap = endpointDiscovery.FindEwsEndpoints(out discoveryTimeLocal, out discoveryTimeCrossPremise); foreach (GroupId key in mailboxServerMap.Keys) { using (List <MailboxInfo> .Enumerator enumerator2 = mailboxServerMap[key].GetEnumerator()) { while (enumerator2.MoveNext()) { MailboxInfo mailbox = enumerator2.Current; FanoutParameters fanoutParameters = new FanoutParameters(); fanoutParameters.GroupId = key; fanoutParameters.Source = sources.FirstOrDefault((SearchSource t) => t.MailboxInfo == mailbox); yield return(fanoutParameters); } } } yield break; }
public void GetFolderCount_ErrorResponse_Failure() { _mockTransport.Setup(x => x.GetCupiResponse(It.IsAny <string>(), MethodType.GET, It.IsAny <ConnectionServerRest>(), It.IsAny <string>(), true)).Returns(new WebCallResult { Success = true, ResponseText = "{\"DisplayName\":\"Voice Mailbox\"}" }); MailboxInfo oInfo = new MailboxInfo(_mockServer, "objectid"); //error response _mockTransport.Setup(x => x.GetCupiResponse(It.IsAny <string>(), MethodType.GET, It.IsAny <ConnectionServerRest>(), It.IsAny <string>(), true)).Returns(new WebCallResult { Success = false, ResponseText = "error text", StatusCode = 404 }); int iCount; var res = oInfo.GetFolderCount(MailboxInfo.FolderTypes.deleted, out iCount); Assert.IsFalse(res.Success, "Calling GetFolderCount with error response should fail"); }
public void GetFolderCount_GarbageResponse_Failure() { _mockTransport.Setup(x => x.GetCupiResponse(It.IsAny <string>(), MethodType.GET, It.IsAny <ConnectionServerRest>(), It.IsAny <string>(), true)).Returns(new WebCallResult { Success = true, ResponseText = "{\"DisplayName\":\"Voice Mailbox\"}" }); MailboxInfo oInfo = new MailboxInfo(_mockServer, "objectid"); Console.WriteLine(oInfo.DumpAllProps()); //garbage response _mockTransport.Setup(x => x.GetCupiResponse(It.IsAny <string>(), MethodType.GET, It.IsAny <ConnectionServerRest>(), It.IsAny <string>(), true)).Returns(new WebCallResult { Success = true, TotalObjectCount = 1, ResponseText = "garbage response that cannot be parsed for mailbox info", }); int iCount; var res = oInfo.GetFolderCount(MailboxInfo.FolderTypes.deleted, out iCount); Assert.IsFalse(res.Success, "Calling GetFolderCount with garbage response should fail"); }
public MailBox(MailboxInfo Box) { Name = Box.Name; FreeStorage = Box.FreeStorage; UsedStorage = Box.UsedStorage; MessageCount = Box.Messages; UnreadMessageCount = Box.Unread; Flags = Box.Flags; }
public void MailboxInfo_MessageInfoTests() { MailboxInfo oInfo = null; try { oInfo = new MailboxInfo(_connectionServer, _tempUser.ObjectId); } catch (Exception ex) { Assert.Fail("Failed creating new MailboxInfo object:" + ex); } Console.WriteLine(oInfo.DumpAllProps()); Console.WriteLine(oInfo.ToString()); int iInboxCount, iDeletedCount, iSentCount; //check counts WebCallResult res = oInfo.GetFolderMessageCounts(out iInboxCount, out iDeletedCount, out iSentCount); Assert.IsTrue(res.Success, "Failed to fetch message folder counts off empty mailbox:" + res); Assert.IsTrue(iInboxCount == 0, "New mailbox reporting more than 0 inbox messages"); Assert.IsTrue(oInfo.CurrentSizeInBytes == 0, "Newly created mailbox reporting non empty mailbox"); Assert.IsTrue(oInfo.IsMailboxMounted, "Newly created mailbox reporting it's not mounted"); Assert.IsTrue(oInfo.IsPrimary, "Newly created mailbox is not reproting itself as primary"); Assert.IsFalse(oInfo.IsReceiveQuotaExceeded, "Newly created mailbox is reporting over quota"); //leave message MessageAddress oRecipient = new MessageAddress(); oRecipient.AddressType = MessageAddressType.TO; oRecipient.SmtpAddress = _tempUser.SmtpAddress; res = UserMessage.CreateMessageLocalWav(_connectionServer, _tempUser.ObjectId, "test subject", "dummy.wav", false, SensitivityType.Normal , false, false, false, false, new CallerId { CallerNumber = "1234" }, true, oRecipient); Assert.IsTrue(res.Success, "Failed to create new message from WAV file:" + res); //wait for message to be delivered Thread.Sleep(10000); //refetch mailbox info res = oInfo.RefetchMailboxData(); Assert.IsTrue(res.Success, "Failed to refetch mailbox data:" + res); //recheck counts res = oInfo.GetFolderMessageCounts(out iInboxCount, out iDeletedCount, out iSentCount); Assert.IsTrue(res.Success, "Failed to fetch message folder counts off mailbox with one message:" + res); Assert.IsTrue(iInboxCount == 1, "Mailbox reporting with single message not reporting correct inbox count:" + iInboxCount); }
static MailQueueItemSettings() { using (var db = new DbManager(MailBoxManager.ConnectionStringName)) { var imap_flags = db.ExecuteList(new SqlQuery(DbSchema.ImapFlags.table) .Select(DbSchema.ImapFlags.Columns.folder_id, DbSchema.ImapFlags.Columns.name, DbSchema.ImapFlags.Columns.skip)) .ConvertAll(r => new { folder_id = Convert.ToInt32(r[0]), name = (string)r[1], skip = Convert.ToBoolean(r[2]) }); SkipImapFlags = imap_flags.FindAll(i => i.skip).ConvertAll(i => i.name).ToArray(); ImapFlags = new Dictionary <string, int>(); imap_flags.FindAll(i => !i.skip).ForEach(i => { ImapFlags[i.name] = i.folder_id; }); SpecialDomainFolders = new Dictionary <string, Dictionary <string, MailboxInfo> >(); db.ExecuteList(new SqlQuery(DbSchema.ImapSpecialMailbox.table) .Select(DbSchema.ImapSpecialMailbox.Columns.server, DbSchema.ImapSpecialMailbox.Columns.name, DbSchema.ImapSpecialMailbox.Columns.folder_id, DbSchema.ImapSpecialMailbox.Columns.skip)) .ForEach(r => { var server = ((string)r[0]).ToLower(); var name = ((string)r[1]).ToLower(); var mb = new MailboxInfo { folder_id = Convert.ToInt32(r[2]), skip = Convert.ToBoolean(r[3]) }; if (SpecialDomainFolders.Keys.Contains(server)) { SpecialDomainFolders[server][name] = mb; } else { SpecialDomainFolders[server] = new Dictionary <string, MailboxInfo> { { name, mb } } }; }); PopUnorderedDomains = db.ExecuteList(new SqlQuery(DbSchema.PopUnorderedDomain.table) .Select(DbSchema.PopUnorderedDomain.Columns.server)) .ConvertAll(r => (string)r[0]) .ToArray(); } }
private RawMessageDescriptor GetImapMessage(ImapClient imapClient, MailboxInfo folder, uint uid) { String eml = imapClient.GetMessageData(uid, false, folder.Name); if (String.IsNullOrWhiteSpace(eml)) { throw new IOException("Failed to read UID " + uid + " from imap server " + folder.Name); } return(new RawMessageDescriptor { SourceId = uid.ToString(), RawMessage = eml }); }
public void MailboxInfo_MessageInfoFailure() { MailboxInfo oInfo = null; try { oInfo = new MailboxInfo(_connectionServer, "junk"); Assert.Fail("Mailbox info with invalid objectId should fail"); } catch (Exception ex) { Console.WriteLine("Exepcted failure:" + ex); } }
public void MainboxInfo_Test() { _errorString = ""; try { MailboxInfo oMailboxInfo = new MailboxInfo(_connectionServer, _tempUser.ObjectId); } catch (Exception ex) { Assert.Fail("[ERROR] fetching MailboxInfo:" + ex); } Assert.IsTrue(string.IsNullOrEmpty(_errorString), "Error parsing Json for mailbox info:" + _errorString); }
protected internal override void Parse(ImapResponseReader reader) { MailboxInfo = new MailboxInfo(_mailboxName); while (true) { if (reader.IsUntagged) { MailboxInfo.InjectLine(reader.CurrentLine); } reader.ReadNextLine(); if (reader.IsCompleted) { MatchPermissions(MailboxInfo, reader.CurrentLine); TakeSnapshot(reader); break; } } }
static MailQueueItemSettings() { using (var db = new DbManager(MailBoxManager.ConnectionStringName)) { var imap_flags = db.ExecuteList(new SqlQuery(Dal.DbSchema.ImapFlags.table) .Select(Dal.DbSchema.ImapFlags.Columns.folder_id, Dal.DbSchema.ImapFlags.Columns.name, Dal.DbSchema.ImapFlags.Columns.skip)) .ConvertAll(r => new { folder_id = Convert.ToInt32(r[0]), name = (string) r[1], skip = Convert.ToBoolean(r[2]) }); SkipImapFlags = imap_flags.FindAll(i => i.skip).ConvertAll(i => i.name).ToArray(); ImapFlags = new Dictionary<string, int>(); imap_flags.FindAll(i => !i.skip).ForEach(i => { ImapFlags[i.name] = i.folder_id; }); SpecialDomainFolders = new Dictionary<string, Dictionary<string, MailboxInfo>>(); db.ExecuteList(new SqlQuery(ImapSpecialMailbox.table) .Select(ImapSpecialMailbox.Columns.server, ImapSpecialMailbox.Columns.name, ImapSpecialMailbox.Columns.folder_id, ImapSpecialMailbox.Columns.skip)) .ForEach(r => { var server = ((string) r[0]).ToLower(); var name = ((string)r[1]).ToLower(); var mb = new MailboxInfo { folder_id = Convert.ToInt32(r[2]), skip = Convert.ToBoolean(r[3]) }; if (SpecialDomainFolders.Keys.Contains(server)) SpecialDomainFolders[server][name] = mb; else SpecialDomainFolders[server] = new Dictionary<string, MailboxInfo> { { name, mb } }; }); PopUnorderedDomains = db.ExecuteList(new SqlQuery(PopUnorderedDomain.table) .Select(PopUnorderedDomain.Columns.server)) .ConvertAll(r => (string) r[0]) .ToArray(); } }
private static void MatchPermissions(MailboxInfo info, string line) { { var matches = new Regex(RegexPatterns.ReadWritePattern).Matches(line); if (matches.Count > 0) { info.Permissions = MailboxPermissions.Read | MailboxPermissions.Write; return; } } { var matches = new Regex(RegexPatterns.ReadOnlyPattern).Matches(line); if (matches.Count > 0) { info.Permissions = MailboxPermissions.Read; return; } } }
public List <Message> FetchMailList() { _mailboxInfo = _commandHandler.GetAllMessagesInfo(); var numberOfMessages = _mailboxInfo.MailboxSize; var listOfMessages = new List <Message>(); for (var i = 0; i < 10; i++) { try { var message = _commandHandler.GetMessage(numberOfMessages - i); message.IndexInMailList = _mailboxInfo.ListOfMessageInfo[i].MessageId; listOfMessages.Add(message); } catch { } } return(listOfMessages); }
/// <summary> /// Creates grouping subscriptions and waits for the notification events to flow /// </summary> /// <param name="impersonationId"></param> /// <returns></returns> async public System.Threading.Tasks.Task CreateStreamingSubscriptionGroupingAsync(string impersonationId) { var database = EWSConstants.Config.Database; using (EWSDbContext context = new EWSDbContext(database)) { var smtpAddresses = await context.RoomListRoomEntities.ToListAsync(); foreach (var sMailbox in smtpAddresses) { var addedBox = _mailboxes.AddMailbox(sMailbox.SmtpAddress); if (!addedBox) { _traceListener.Trace("SyncProgram", $"Failed to add SMTP {sMailbox.SmtpAddress}"); } MailboxInfo mailboxInfo = _mailboxes.Mailbox(sMailbox.SmtpAddress); if (mailboxInfo != null) { GroupInfo groupInfo = null; if (_groups.ContainsKey(mailboxInfo.GroupName)) { groupInfo = _groups[mailboxInfo.GroupName]; } else { groupInfo = new GroupInfo(mailboxInfo.GroupName, mailboxInfo.SMTPAddress, mailboxInfo.EwsUrl, EwsToken, _traceListener); _groups.Add(mailboxInfo.GroupName, groupInfo); } if (groupInfo.Mailboxes.Count > 199) { // We already have enough mailboxes in this group, so we rename it and create a new one // Renaming it means that we can still put new mailboxes into the correct group based on GroupingInformation int i = 1; while (_groups.ContainsKey($"{groupInfo.Name}-{i}")) { i++; } // Remove previous grouping name from stack _groups.Remove(groupInfo.Name); // Add the grouping back with the new grouping name [keep the GroupInfo with previous name] _groups.Add($"{groupInfo.Name}-{i}", groupInfo); // Provision a new GroupInfo with the GroupName groupInfo = new GroupInfo(mailboxInfo.GroupName, mailboxInfo.SMTPAddress, mailboxInfo.EwsUrl, EwsToken, _traceListener); // Add GroupInfo to stack _groups.Add(mailboxInfo.GroupName, groupInfo); } // Add the mailbox to the collection groupInfo.Mailboxes.Add(sMailbox.SmtpAddress); } } // Enable the Grouping foreach (var _group in _groups) { _traceListener.Trace("SyncProgram", $"Opening connections for {_group.Key}"); var groupName = _group.Key; var groupInfo = _group.Value; // Create a streaming connection to the service object, over which events are returned to the client. // Keep the streaming connection open for 30 minutes. if (AddGroupSubscriptions(context, groupName)) { _traceListener.Trace("SyncProgram", $"{groupInfo.Mailboxes.Count()} mailboxes primed for StreamingSubscriptions."); } else { _traceListener.Trace("SyncProgram", $"Group {groupInfo.Name} failed in StreamingSubscription events."); } } } using (var semaphore = new System.Threading.SemaphoreSlim(1)) { // Block the Thread semaphore.Wait(); // Establish the StreamingSubscriptionConnections based on the GroupingInfo foreach (var connection in _connections) { var _group = _groups[connection.Key]; var _connection = connection.Value; if (_connection.IsOpen) { _group.IsConnectionOpen = true; return; } try { _connection.Open(); _group.IsConnectionOpen = true; } catch (Exception ex) { _traceListener.Trace("SyncProgram", $"Error opening streamingsubscriptionconnection for group {_group.Name} MSG {ex.Message}"); } } // Lock the Thread Until its cancelled or fails await semaphore.WaitAsync(CancellationTokenSource.Token); } }
private static void RunTests() { //you can attach to multiple different Connection servers an interact with them in the same program easily by just creating //new instances of ConnectionServer objects - all objects "know" which server they are associated with. This example, of course, //just attaches to one server. ConnectionServerRest connectionServer = null; Logger.Log("Starting log output"); //attach to server - insert your Connection server name/IP address and login information here. try { connectionServer = new ConnectionServerRest("connection server", "login", "password"); } catch (Exception ex) { //return an exit code of 1 to indicate failure exit. Console.WriteLine("Could not attach to Connection server: " + ex.Message); Console.Read(); Environment.Exit(1); } //turn on "chatty" output to console connectionServer.DebugMode = true; //the Connection server object spits out the server name and version number in the ToString function. Console.WriteLine("Attached to Connection server: " + connectionServer); //do a version check - most things will work on older versions as well but voice name updates and some other functions will not. if (connectionServer.Version.IsVersionAtLeast(8, 5, 0, 0) == false) { Console.WriteLine("WARNING! The ConnectionCUPIFunctions library was written and tested against Connection 8.5 and later." + " The version you are attached to is less than that."); } //the WebCallResult is the structure returned on most calls into the CUPIFunctions library. WebCallResult res; //fetch user with alias of "operator" UserFull oUserTestDude; res = UserBase.GetUser(out oUserTestDude, connectionServer, "", "operator"); if (res.Success == false) { Console.WriteLine(res); return; } List <UserMessage> oUserMessages; res = UserMessage.GetMessages(connectionServer, oUserTestDude.ObjectId, out oUserMessages); if (res.Success == false) { Console.WriteLine(res); return; } ////**** ////play voice messages using the phone as a media device - aka TRAP ////**** PhoneRecording oPhone; try { oPhone = new PhoneRecording(connectionServer, "1001"); } catch (Exception ex) { Console.WriteLine("Failed to connect to phone extension:" + ex); return; } List <UserMessage> oTestUserMessages; res = UserMessage.GetMessages(connectionServer, oUserTestDude.ObjectId, out oTestUserMessages); if (res.Success == false) { Console.WriteLine("Error fetching messages:" + res.ToString()); Console.ReadLine(); } foreach (var oMessage in oTestUserMessages) { res = oPhone.PlayMessageFile(oMessage.MsgId, 100, 100, 0, oUserTestDude.ObjectId); if (res.Success == false) { Console.WriteLine("Error playing stream:" + res.ToString()); Console.ReadLine(); } } //hang up oPhone.Dispose(); //get the schedule details off all the schedules (both holiday and regular) that the user is associated with. The schedule //assignment comes through the user's primary call handler - it references a schedule set which can contain 1 or more schedules. //Each schedule has 0 or more details associated with it. foreach (var oSchedule in oUserTestDude.PrimaryCallHandler().GetScheduleSet().Schedules()) { Console.WriteLine("Schedle name=" + oSchedule.DisplayName); Console.WriteLine(" Details:"); foreach (var oDetail in oSchedule.ScheduleDetails()) { Console.WriteLine(oDetail.DumpAllProps(" ")); } } //determine if the current schedule state is ACTIVE, INACTIVE or HOLIDAY. Console.WriteLine("Evaluating schedule state"); Console.WriteLine(" Schedule state right now=" + oUserTestDude.PrimaryCallHandler().GetScheduleSet().GetScheduleState(DateTime.Now).ToString()); TransferOption oTransferAlternateSmith; res = oUserTestDude.PrimaryCallHandler().GetTransferOption(TransferOptionTypes.Alternate, out oTransferAlternateSmith); //not a lot of reasons this would fail but just in case if (res.Success == false) { Console.WriteLine("Could not find alternate transfer rule for jsmith"); Console.ReadLine(); Environment.Exit(1); } //update the transfer number to 12345 oTransferAlternateSmith.Extension = "12345"; oTransferAlternateSmith.Update(); //enable the transfer rule with no end date oTransferAlternateSmith.UpdateTransferOptionEnabledStatus(true); //**** //Add a new user //**** //The user template name passed here is the default one created by setup and should be present on any system. There are functions included //in the library that make presenting lists of templates for user selection easy - see the CUPIFastStart project for details. UserFull oUser; res = UserBase.AddUser(connectionServer, "voicemailusertemplate", "TestUserAlias", "80001", null, out oUser); if (res.Success == false) { //the ToString for the WebCallResult structure dumps its entire contents out which is handy for logging schenarios like this. Console.WriteLine("Failed creating new user:"******"\n\rUser created, new ObjectId=" + oUser.ObjectId); //**** //Edit that user's display name //**** //We could have passed the display name, first name and any other properties we wanted into the AddUser function above if we wanted. //This just demonstrates how easy it is to update properties on a standing user object with a few lines of code. The library sends //only the items that have changed when sending the update. The full list of properties send in the body is contained in the WebCallResult //structure passed back so if there's a problem the "ToString()" call will contain the entire URL, command type, body and everything //returned by the server for easy evaluation of what went wrong. oUser.DisplayName = "Test User"; oUser.FirstName = "Test"; oUser.LastName = "User"; res = oUser.Update(); if (res.Success == false) { Console.WriteLine("Failed updating user:"******"\n\rUser Updated: " + res.ToString()); //update greeting Greeting oMyGreeting; res = oUser.PrimaryCallHandler().GetGreeting(GreetingTypes.Alternate, out oMyGreeting); if (res.Success == false) { Console.WriteLine("Error fetching alternate greeting:" + res.ToString()); Console.ReadLine(); return; } res = oMyGreeting.SetGreetingWavFile(1033, @"c:\clean.wav", true); if (res.Success == false) { Console.WriteLine("Error applying greeting stream file:" + res.ToString()); Console.ReadLine(); return; } //**** //Dump the user properties for review //**** //the user "toString" shows the alias, display name and extension for the user. The DumpAllProps does a complete list of every property //and it's value for the user. You will find all objects defined in the ConnectionCUPIFunctions library follow this design pattern. Console.WriteLine("\n\rUser properties for: {0}\r\n{1}", oUser, oUser.DumpAllProps(" ")); //**** //Add an alternate extension to that User //**** //this adds the alternate extension "800012" as the first administrator added alternate extension. res = AlternateExtension.AddAlternateExtension(connectionServer, oUser.ObjectId, 1, "800012"); if (res.Success == false) { Console.WriteLine("Failed adding alternate extension:" + res.ToString()); Console.Read(); Environment.Exit(1); } //whenever adding a new object using a method that does not return an instance of that object (as we do with the alternate extension above) the ObjectId //of the newly created object (if the call suceeds) can be pulled from the WebCallResult structure's ReturnedObjectId property. Console.WriteLine("\n\rAlternate Extension added, ObjectId returned= " + res.ReturnedObjectId); //you can always turn around and now fetch an object instance of that alternate extension like this - remember that when fetching or editing alternate //extensions you have to provide the user's objectId as well. AlternateExtension oAltExt; res = AlternateExtension.GetAlternateExtension(connectionServer, oUser.ObjectId, res.ReturnedObjectId, out oAltExt); if (res.Success == false) { Console.WriteLine("Failed fetching new alternate extension object: " + res.ToString()); Environment.Exit(1); } //now we can update the alternate extension easily - you'll find this same type of pattern on all objects in the library (when they are completed). oAltExt.DtmfAccessId = "800013"; res = oAltExt.Update(); if (res.Success == false) { Console.WriteLine("Failed to update the alternate extension: " + res.ToString()); Environment.Exit(1); } Console.WriteLine("\n\rAlternate extension updated: " + oAltExt); //**** //List the user's notification devices //**** Console.WriteLine("\n\rNotification devices for: " + oUser.Alias); foreach (NotificationDevice oDevice in oUser.NotificationDevices()) { Console.WriteLine(oDevice.ToString()); Console.WriteLine(oDevice.DumpAllProps(" ")); } //****** //List the users menu entry keys //****** Console.WriteLine("\n\rMenu entry keys for: " + oUser.Alias); foreach (MenuEntry oMenu in oUser.PrimaryCallHandler().GetMenuEntries()) { //use the GetActionDescription method on the ConnectionServer object to produce a bit more readable output for the //actions menu keys are assigned to. You can still use the oMenu.ToString() here as well to dump out the raw data instead. Console.WriteLine("{0}:{1}", oMenu.TouchtoneKey, connectionServer.GetActionDescription(oMenu.Action, oMenu.TargetConversation, oMenu.TargetHandlerObjectId)); } //**** //List the first 5 system call handlers found in the system. //**** ////Pass the query for any object's "get(object name)s" by passing in a list of strings at the end - the library makes sure these are ////put onto the URL with proper escape codes and "?" and "&" symbols. It does not check the syntax of the items, however, and remember ////that they ARE case sensitive. ////Remember "IsPrimary" is set to 1 when it's a special handler associated with a user. List <CallHandler> oCallHandlers; res = CallHandler.GetCallHandlers(connectionServer, out oCallHandlers, "query=(IsPrimary is 0)", "rowsPerPage=5", "pageNumber=1"); if (res.Success == false) { Console.WriteLine("Failed fetching system call handlers: " + res.ToString()); Console.Read(); Environment.Exit(1); } Console.WriteLine("\n\rUp to the first 5 Call Handlers in the system:"); foreach (CallHandler oHandler in oCallHandlers) { Console.WriteLine(oHandler.ToString()); } //**** //Reset the users PIN //**** //pass the optional flags for forcing change, not expiring etc... if these are not passed the current values for the credential settings //will be left alone. You can pass just these flags and a blank PIN string if you want - the PIN will NOT be set to blank (that is not //allowed in this class library). If you wish to force a blank password (assuming such a thing is allowed in your configuration which is //not advisable) then you will have to do so manually calling the credential update on your own via the RestTransportFunctions library. res = oUser.ResetPin("123454321", false, false, false, true); if (res.Success == false) { Console.WriteLine("Failure updating PIN for user: "******"True" to convert to PCM - it does more than just change the codec, it also forces it into 16 Khz, 8 bit mono which //Connection is happy with - even PCM with a different sample rate can cause it to send the dreded "invalid media format" error back. res = oUser.SetVoiceName(@"WAVFiles\TestGuyVoiceName.wav", true); if (res.Success == false) { Console.WriteLine("Failure updating voice name for user: "******"Error fetching the alternate greeting for the user: "******"WAVFiles\TestGuyGreeting.wav", true); if (res.Success == false) { Console.WriteLine("Error setting alternate greeting recording: " + res.ToString()); } //By default the greeting is set to play the system generated greeting prompts - to play the custom recorded greeting we just //uploaded you need to set the "PlayWhat" to "1" (which is wrapped in the PlayWhatTypes enum here for readability. oGreeting.PlayWhat = PlayWhatTypes.RecordedGreeting; res = oGreeting.Update(); if (res.Success == false) { Console.WriteLine("Error setting alternate greeting playwhat property: " + res.ToString()); } //use the helper function to enable the alternate greeting (it's disabled by default). This call sets it to be enabled forever. res = oGreeting.UpdateGreetingEnabledStatus(true); if (res.Success == false) { Console.WriteLine("Error alternate greeting enabled property: " + res.ToString()); } //GET the user's mailbox store stats (quotas, size etc...) MailboxInfo oMailboxInfo = new MailboxInfo(connectionServer, oUser.ObjectId); Console.WriteLine(oMailboxInfo.DumpAllProps()); //get messages for user - get the first 50 messages, sorted by urgent first and restrict the list //to only unread voice messages. List <UserMessage> oMessages; res = UserMessage.GetMessages(connectionServer, oUser.ObjectId, out oMessages, 1, 50, MessageSortOrder.URGENT_FIRST, MessageFilter.Type_Voice | MessageFilter.Read_False); //list subject, sender and time sent for each message returned if (res.Success) { foreach (UserMessage oMessage in oMessages) { Console.WriteLine(oMessage.ToString()); } } //remove test user res = oUser.Delete(); if (res.Success) { Console.WriteLine("User deleted..."); } //give you time to review the console output before exiting. Console.WriteLine("\n\rPress enter to exit..."); Console.ReadLine(); //indicate success exit code Environment.Exit(0); }
private void GetMails(MailboxInfo info) { try { using (var client = new Pop3Client()) { //Get Zabbix metrics var stopwatch = new Stopwatch(); stopwatch.Start(); //Get mail count client.Connect(info.Hostname, info.Port, false); client.Authenticate(info.User, info.Password); stopwatch.Stop(); //Send it to Zabbix Functions.Zabbix.SendData(new ZabbixItem { Host = _config.HostKey, Key = info.Type + _config.TimingKey, Value = stopwatch.ElapsedMilliseconds.ToString() }); Functions.Log.Debug("Send [{0}] timing to Zabbix: connected to '{1}' as '{2}', timing {3}ms", info.Type, info.Hostname, info.User, stopwatch.ElapsedMilliseconds); var count = client.GetMessageCount(); if (count == 0) return; Functions.Log.Debug("We've got new {0} messages in '{1}'", count, info.User); //Send messages to sorting block for (var i = 0; i < count; i++) { try { var mailInfo = new MessageInfo { IsSpam = false, Mail = client.GetMessage(i + 1), Type = MessageType.UNKNOWN, Subtype = null, Recipient = null, Mailbox = info }; Functions.Log.Debug("Download message from '{0}'. Size: {1}b", info.User, mailInfo.Mail.RawMessage.Length); while (!_sortMailDataBlock.Post(mailInfo)) Thread.Sleep(500); //Save every mail to archive Functions.Log.Debug("Archive message"); Functions.Archive.Info(Functions.MessageToString(mailInfo.Mail)); } catch (Exception ex) { Functions.Log.Error("Parse email error: {0}", ex.Message); Functions.ErrorsCounters[info.Type].Increment(); //Archive mail anyway Functions.Log.Debug("Archive message"); Functions.Archive.Info(Encoding.Default.GetString(client.GetMessageAsBytes(i + 1))); } if (_config.DeleteMail) client.DeleteMessage(i + 1); if (_stopPipeline) break; } Functions.Log.Debug("Done with '{0}'", info.User); } } catch (Exception ex) { Functions.Log.Error("General error - type: {0}, message: {1}", ex, ex.Message); Functions.ErrorsCounters[info.Type].Increment(); } }
public void Constructor_NullConnectionServer_Failure() { MailboxInfo otest = new MailboxInfo(null, ""); Console.WriteLine(otest); }
public void Constructor_InvalidObjectId_Failure() { MailboxInfo otest = new MailboxInfo(_connectionServer, "bogus"); Console.WriteLine(otest); }
public void Constructor_EmptyConnectionServer_Failure() { MailboxInfo otest = new MailboxInfo(new ConnectionServerRest(new RestTransportFunctions()), "blah"); Console.WriteLine(otest); }
public void Constructor_EmptyObjectId_Failure() { MailboxInfo otest = new MailboxInfo(_mockServer, ""); Console.WriteLine(otest); }