Skip to content

Instantly share code, notes, and snippets.

@zclancy
Created July 17, 2012 15:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zclancy/3129960 to your computer and use it in GitHub Desktop.
Save zclancy/3129960 to your computer and use it in GitHub Desktop.
A simple console application for testing Lync Group Chat SDK. Command line parameters build the message, and specify the chat room. NDesk.Options is used for command line argument parsing.
using System;
using System.Configuration;
using System.Net;
using Microsoft.Rtc.Collaboration;
using Microsoft.Rtc.Collaboration.GroupChat;
using Microsoft.Rtc.Signaling;
namespace GroupChat
{
public static class Common
{
#region Common variables to be used throughout the program
public static string OcsServer = ConfigurationManager.AppSettings["OcsServer"];
public static Uri LookupServerUri = new Uri(ConfigurationManager.AppSettings["LookupServerUri"]);
// This user must be setup as a Manager of the ROOT Chat Room Category or setup as
// a "super user" (who can manage every Category/ChatRoom). To setup a "super user", you
// can choose them during the Group Chat server installation, or you can use the Group Chat
// Admin Tool client to manage that user and check all the boxes under Permissions.
public static string UserSipUri = ConfigurationManager.AppSettings["UserSipUri"];
public static string Username = ConfigurationManager.AppSettings["Username"];
// Storing passwords in cleartext is an obvious security vulnerability - only
// shown here for completeness.
public static string Password = ConfigurationManager.AppSettings["Password"];
#endregion
public static UserEndpoint ConnectOfficeCommunicationServer(string userSipUri, string ocsServer, string username, string password)
{
// Create the OCS UserEndpoint and attempt to connect to OCS
Console.WriteLine("Connecting to Lync... [{0}]", ocsServer);
// Use the appropriate SipTransportType depending on current OCS deployment
var platformSettings = new ClientPlatformSettings("GroupChatDispatch", SipTransportType.Tls);
var collabPlatform = new CollaborationPlatform(platformSettings);
// Initialize the platform
collabPlatform.EndStartup(collabPlatform.BeginStartup(null, null));
// You can also pass in the server's port # here.
var userEndpointSettings = new UserEndpointSettings(userSipUri, ocsServer)
{Credential = new NetworkCredential(username, password)};
var userEndpoint = new UserEndpoint(collabPlatform, userEndpointSettings);
// Login to OCS.
userEndpoint.EndEstablish(userEndpoint.BeginEstablish(null, null));
Console.WriteLine("\tSuccess");
return userEndpoint;
}
public static GroupChatEndpoint ConnectGroupChatServer(UserEndpoint userEndpoint, Uri lookupServerUri)
{
Console.WriteLine("Connecting to Group Chat Server...");
var groupChatEndpoint = new GroupChatEndpoint(lookupServerUri, userEndpoint);
groupChatEndpoint.EndEstablish(groupChatEndpoint.BeginEstablish(null, null));
Console.WriteLine("\tSuccess");
return groupChatEndpoint;
}
public static void DisconnectGroupChatServer(GroupChatEndpoint groupChatEndpoint)
{
Console.WriteLine("Disconnecting from Group Chat Server...");
groupChatEndpoint.EndTerminate(groupChatEndpoint.BeginTerminate(null, null));
Console.WriteLine("\tSuccess");
}
public static void DisconnectOfficeCommunicationServer(UserEndpoint userEndpoint)
{
Console.WriteLine("Disconnecting from OCS...");
userEndpoint.EndTerminate(userEndpoint.BeginTerminate(null, null));
var platform = userEndpoint.Platform;
platform.EndShutdown(platform.BeginShutdown(null, null));
Console.WriteLine("\tSuccess");
}
public static ChatRoomCategorySummary CategorySearchExisting(GroupChatEndpoint groupChatEndpoint, string categoryName)
{
Console.WriteLine(String.Format("Searching for category [{0}]...", categoryName));
var categoryMgmt = groupChatEndpoint.GroupChatServices.CategoryManagementServices;
var categories = categoryMgmt.EndFindCategoriesByCriteria(
categoryMgmt.BeginFindCategoriesByCriteria(categoryName, false, null, null));
Console.WriteLine(String.Format("\tFound {0} categories(s):", categories.Count));
if (categories.Count > 0)
{
foreach (var summary in categories)
Console.WriteLine(String.Format("\tName: {0}\n\tURI:{1}", summary.Name, summary.Uri));
return categories[0];
}
return null;
}
public static ChatRoomSnapshot RoomSearchExisting(GroupChatEndpoint groupChatEndpoint, string chatRoomName)
{
Console.WriteLine(String.Format("Searching for chat room [{0}]...", chatRoomName));
var chatServices = groupChatEndpoint.GroupChatServices;
var chatRooms = chatServices.EndBrowseChatRoomsByCriteria(
chatServices.BeginBrowseChatRoomsByCriteria(chatRoomName, false, null, null));
Console.WriteLine(String.Format("\tFound {0} chat room(s):", chatRooms.Count));
if (chatRooms.Count > 0)
{
foreach (var snapshot in chatRooms)
Console.WriteLine(String.Format("\tName: {0}\n\tURI:{1}", snapshot.Name, snapshot.ChatRoomUri));
return chatRooms[0];
}
return null;
}
public static ChatRoomSession RoomJoinExisting(GroupChatEndpoint groupChatEndpoint, ChatRoomSummary summary)
{
Console.WriteLine(String.Format("Joining chat room by NAME [{0}]...", summary.Name));
var session = new ChatRoomSession(groupChatEndpoint);
session.EndJoin(session.BeginJoin(summary, null, null));
Console.WriteLine("\tSuccess");
return session;
}
public static ChatRoomSession RoomJoinExisting(GroupChatEndpoint groupChatEndpoint, Uri roomUri)
{
Console.WriteLine(String.Format("Joining chat room by URI [{0}]...", roomUri));
var session = new ChatRoomSession(groupChatEndpoint);
session.EndJoin(session.BeginJoin(roomUri, null, null));
Console.WriteLine("\tSuccess");
return session;
}
}
}
using System;
using Microsoft.Rtc.Collaboration.GroupChat;
using NDesk.Options;
namespace GroupChat
{
// Holds our 'message' properties, values, and settings.
public class DispatchMessage
{
public static string ChatRoomName;
public static string Subject;
public static string Body;
public static bool IsAlert;
public static ChatRoomSnapshot RoomSnapshot;
public static ChatRoomSession RoomSession;
}
static class Chat
{
public static void Main(string[] args)
{
// Set a flag for help at startup
var showHelp = false;
// Set up our command line arguments
var commands = new OptionSet()
{
{ "r|room=", "the Group Chat room to login to.", v => DispatchMessage.ChatRoomName = v },
{ "s|subject:", "the subject of the message (optional).", v => DispatchMessage.Subject = v},
{ "b|body=", "the body of the message.", v => DispatchMessage.Body = v},
{ "a|!|alert", "this is an alert.", v => DispatchMessage.IsAlert = v != null},
{ "h|?|help", "show the help section and exit.", v => showHelp = v != null}
};
// Parse our command line parameters, execute based on it's findings.
try
{
commands.Parse(args);
}
catch (OptionException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Something went wrong. Try GroupChat --help for information on usage.");
return;
}
// See if we should show our help section
if (showHelp)
{
ShowHelp(commands);
return;
}
try
{
// Connect to Lync
var userEndpoint = Common.ConnectOfficeCommunicationServer(Common.UserSipUri, Common.OcsServer, Common.Username, Common.Password);
// Connect to the Group Chat server
var groupChatEndpoint = Common.ConnectGroupChatServer(userEndpoint, Common.LookupServerUri);
// Search for the room we've been given
DispatchMessage.RoomSnapshot = Common.RoomSearchExisting(groupChatEndpoint, DispatchMessage.ChatRoomName);
// Make sure we have a room handle before joining
if (DispatchMessage.RoomSnapshot != null)
{
DispatchMessage.RoomSession = Common.RoomJoinExisting(groupChatEndpoint, DispatchMessage.RoomSnapshot);
}
else
{
// The room doesn't exist, or can't be found by our search.
Console.WriteLine(String.Format("Unable to join [{0}], please ensure it exists and you are a member.", DispatchMessage.ChatRoomName));
}
// Make sure we have a session before chatting.
if (DispatchMessage.RoomSession != null)
{
// Send our story message to the room
RoomChat();
// We're done here, exit stage left.
RoomLeave();
}
else
{
Console.WriteLine(String.Format("Can't chat in [{0}], please try again.", DispatchMessage.ChatRoomName));
}
// Disconnect from Group Chat and Lync
Common.DisconnectGroupChatServer(groupChatEndpoint);
Common.DisconnectOfficeCommunicationServer(userEndpoint);
}
catch (InvalidOperationException invalidOperationException)
{
Console.Out.WriteLine("InvalidOperationException: " + invalidOperationException.Message);
}
catch (ArgumentNullException argumentNullException)
{
Console.Out.WriteLine("ArgumentNullException: " + argumentNullException.Message);
}
catch (ArgumentException argumentException)
{
Console.Out.WriteLine("ArgumentException: " + argumentException.Message);
}
catch (Microsoft.Rtc.Signaling.AuthenticationException authenticationException)
{
Console.Out.WriteLine("AuthenticationException: " + authenticationException.Message);
}
catch (Microsoft.Rtc.Signaling.FailureResponseException failureResponseException)
{
Console.Out.WriteLine("FailureResponseException: " + failureResponseException.Message);
}
catch (System.IO.FileNotFoundException fileNotFoundException)
{
Console.Out.WriteLine("FileNotFoundExeption: " + fileNotFoundException.Message);
}
}
private static void RoomChat()
{
var session = DispatchMessage.RoomSession;
Console.WriteLine(String.Format("Chatting in chat room [{0}]...", session.Name));
Console.WriteLine("\tSubscribe to incoming messages");
session.ChatMessageReceived += SessionChatMessageReceived;
// Check our message parameters, if a subject exists, send a story, otherwise send it as normal.
// If it is set as an alert, we'll send it as an alert.
if (String.IsNullOrEmpty(DispatchMessage.Subject))
{
var chatSimpleStory = new FormattedOutboundChatMessage(DispatchMessage.IsAlert);
chatSimpleStory.AppendPlainText(DispatchMessage.Body);
session.EndSendChatMessage(session.BeginSendChatMessage(chatSimpleStory, null, null));
}
// Subject found, send a story.
else
{
var chatSimpleStory = new FormattedOutboundChatMessage(DispatchMessage.IsAlert, DispatchMessage.Subject);
chatSimpleStory.AppendPlainText(DispatchMessage.Body);
session.EndSendChatMessage(session.BeginSendChatMessage(chatSimpleStory, null, null));
}
session.ChatMessageReceived -= SessionChatMessageReceived;
Console.WriteLine("\tSuccess");
}
private static void RoomLeave()
{
var session = DispatchMessage.RoomSession;
Console.WriteLine(String.Format("Leaving chat room [{0}]...", session.Name));
session.EndLeave(session.BeginLeave(null, null));
Console.WriteLine("\tSuccess");
}
static void SessionChatMessageReceived(object sender, ChatMessageReceivedEventArgs e)
{
Console.WriteLine("\tChat message received");
Console.WriteLine(String.Format("\t from:[{0}]", e.Message.MessageAuthor));
Console.WriteLine(String.Format("\t room:[{0}]", e.Message.ChatRoomName));
Console.WriteLine(String.Format("\t body:[{0}]", e.Message.MessageContent));
foreach (MessagePart part in e.Message.FormattedMessageParts)
Console.WriteLine(String.Format("\t part:[{0}]", part.RawText));
}
static void ShowHelp (OptionSet commands)
{
Console.WriteLine("Usage: GroupChat.exe [OPTIONS]");
Console.WriteLine("Sends a message into a specified Lync Group Chat room.");
Console.WriteLine("If a subject is given, message will be sent as a story.");
Console.WriteLine();
Console.WriteLine("Options:");
commands.WriteOptionDescriptions(Console.Out);
}
}
}
@barcar
Copy link

barcar commented Oct 22, 2012

Would you be willing to share a compiled version of this tool?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment