/// <summary> /// IServerAdmin.LoadScriptFile impl /// load script file. File needs to be on the server and in an accessible directory /// </summary> /// <param name="clientId"></param> /// <param name="scriptFilePath">path to file to load. If not an xml file will assume that the file contains a list of xml files</param> /// <param name="streamFileContentsBackToClient">should the server stream the files back to the client</param> public AsyncMethodResponse LoadScriptFile(Guid clientId, string scriptFilePath, bool streamFileContentsBackToClient) { AsyncMethodResponse response = new AsyncMethodResponse(clientId, null); //check for empty path if (string.IsNullOrEmpty(scriptFilePath)) { response.AddError("Missing filePath", ErrorCode.Fatal); return(response); } //this call will return right away and //pass back an async ticket. the processing //will be done in a worker //and updates/information about the progress will //be sent back to the caller via a callback. response.AsyncTicket = Guid.NewGuid().ToString(); ClientProxy clientProxy = CallbackManagerImpl.Instance.LookupClientProxy(clientId); //contructing the Impl will start a thread to do the work new LoadSciptFileMethodImpl(this, clientProxy, scriptFilePath, response.AsyncTicket, streamFileContentsBackToClient); return(response); }
/// <summary> /// called by client to get the async call response /// </summary> /// <param name="clientId"></param> /// <param name="payloadTicket"></param> /// <returns></returns> public AsyncMethodResponse GetAsyncResponseData(Guid clientId, Guid payloadTicket) { QueuedResponsePayload payload = null; lock (payloadTicketToResponseMap) { payloadTicketToResponseMap.TryGetValue(payloadTicket, out payload); } if (payload != null && payload.ClientId == clientId) { AsyncMethodResponse response = new AsyncMethodResponse(clientId, payload.AsyncTicket); response.AsyncResponseData = payload.PayloadData; lock (payloadTicketToResponseMap) payloadTicketToResponseMap.Remove(payloadTicket); return(response); } AsyncMethodResponse error = new AsyncMethodResponse(clientId, null); error.AddError("Not found", ErrorCode.RecordNotFound); return(error); }
/// <summary> /// Add a client to subscription list /// </summary> /// <param name="clientId"></param> /// <returns></returns> public AsyncMethodResponse Subscribe(Guid clientId) { try { Guid newClientId = clientId; if (newClientId == Guid.Empty) { newClientId = Guid.NewGuid(); } IServerAdminCallback callback = OperationContext.Current.GetCallbackChannel <IServerAdminCallback>(); ClientProxy clientProxy = new ClientProxy(newClientId, callback); lock (subscribers) { ClientProxy existingClientProxy; if (clientId != Guid.Empty) { subscribers.TryGetValue(clientId, out existingClientProxy); } else { existingClientProxy = null; } if (existingClientProxy == null) { subscribers[newClientId] = clientProxy; } else { existingClientProxy.AssignNewCallback(callback); List <KeyValuePair <PublishEventArgs, PublishEventHandler> > pendingList = existingClientProxy.PopPendingMessageList(); if (pendingList != null) { Dictionary <Guid, ClientProxy> targetClientProxyMap = new Dictionary <Guid, ClientProxy>(); targetClientProxyMap[existingClientProxy.ClientId] = existingClientProxy; foreach (KeyValuePair <PublishEventArgs, PublishEventHandler> pair in pendingList) { Publish(targetClientProxyMap, true, pair.Key, pair.Value); } } } } AsyncMethodResponse response = new AsyncMethodResponse(newClientId, null); return(response); } catch (Exception ex) { AsyncMethodResponse errorResponse = new AsyncMethodResponse(clientId, null); errorResponse.AddError(ex.Message, ErrorCode.Fatal); return(errorResponse); } }
public AsyncMethodResponse GetAsyncResponseData(Guid payloadTicket) { AsyncMethodResponse response = serverAdminClient.GetAsyncResponseData(this.ClientId, payloadTicket); if (response != null && !response.IsSuccessful) { Console.WriteLine(response.ErrorText); } return(response); }
public void OnServerMessage(string message, DateTime timestamp, AsyncMethodResponse response) { if (message == null) { Console.Write("."); lastConsoleWriteIdDot = true; } else { if (lastConsoleWriteIdDot == true) { lastConsoleWriteIdDot = false; Console.WriteLine(); } Console.WriteLine(message); } }
/// <summary> /// handler for scriptloader progress messages /// </summary> /// <param name="sender"></param> /// <param name="mea"></param> private void scriptLoader_NotifyMessage(ScriptLoader sender, ScriptLoader.MessageEventArgs mea) { AsyncMethodResponse response = new AsyncMethodResponse(this.clientProxy.ClientId, this.asyncTicket); Dictionary <Guid, ClientProxy> targetProxyMap = new Dictionary <Guid, ClientProxy>(); targetProxyMap.Add(clientProxy.ClientId, clientProxy); //send null message for tick if (mea.IsProgressTick == true) { CallbackManagerImpl.Instance.PublishMessage(targetProxyMap, null, response); } else { CallbackManagerImpl.Instance.PublishMessage(targetProxyMap, mea.Message, response); } }
/// <summary> /// remove client from subscription list /// </summary> /// <param name="clientId"></param> /// <returns></returns> public AsyncMethodResponse Unsubscribe(Guid clientId) { try { ClientProxy clientProxy = null; lock (this.subscribers) { if (subscribers.TryGetValue(clientId, out clientProxy)) { clientProxy.Unsubscribe(); subscribers.Remove(clientId); } } return(null); } catch (Exception ex) { AsyncMethodResponse response = new AsyncMethodResponse(clientId, null); response.AddError(ex.Message, ErrorCode.Fatal); return(response); } }
public void OnPendingResponseObject(string message, string payloadTicket, DateTime timestamp, AsyncMethodResponse response) { this.Message = message; if (payloadTicket != null) { this.PayloadTicket = new Guid(payloadTicket); } this.StreamDataId = response.StreamDataId; waitForEndResetEvent.Set(); }
public void Open() { AsyncMethodResponse response = serverAdminClient.Subscribe(Guid.Empty); this.ClientId = response.ClientId; }
static int Main(string[] args) { try { bool streamFileContentsBackToClient = false; bool logLocks = false; bool cleanMatches = false; bool matchAll = false; bool resetConfig = false; waitForEndResetEvent = new ManualResetEvent(false); // The command line parser is driven by different states that are triggered by the flags read. Unless a flag has // been read, the command line parser assumes that it's reading the file name from the command line. argumentState = ArgumentState.FileName; // Parse the command line for arguments. foreach (string argument in args) { // Decode the current argument into a state change (or some other action). if (argument == "-f") { continue; } if (argument == "-s") { streamFileContentsBackToClient = true; continue; } if (argument == "-l") { logLocks = true; continue; } if (argument == "-m") { cleanMatches = true; continue; } if (argument == "-ma") { matchAll = true; continue; } if (argument == "-rc") { resetConfig = true; continue; } if (argument == "-i") { argumentState = ArgumentState.FileName; continue; } if (argument == "-p") { argumentState = ArgumentState.Password; continue; } if (argument == "-u") { argumentState = ArgumentState.UserName; continue; } // The parsing state will determine which variable is read next. switch (argumentState) { case ArgumentState.FileName: fileName = Environment.ExpandEnvironmentVariables(argument); break; case ArgumentState.Password: password = Environment.ExpandEnvironmentVariables(argument); break; case ArgumentState.UserName: username = Environment.ExpandEnvironmentVariables(argument); break; } // The default state is to look for the input file name on the command line. argumentState = ArgumentState.FileName; } // Throw a usage message back at the user if no file name was given. if (logLocks == false && cleanMatches == false && matchAll == false && resetConfig == false) { if (fileName == null) { throw new Exception("Usage: \"Script Loader\" [-u username] [-p password] [-f] -i <FileName>"); } if (Path.IsPathRooted(fileName) == false) { fileName = Path.Combine(Environment.CurrentDirectory, fileName); } } // Now that the command line arguments have been parsed into the loader, send the data to the server. Console.Write("Connecting to: "); ChannelStatus.LoginEvent.Set(); bool hasException = true; ServerAdminMessageListner listener = new ServerAdminMessageListner(username, password); try { listener.Open(); ServerAdminMessageSender sender = new ServerAdminMessageSender(listener.ClientId, username, password); try { if (logLocks == true) { sender.OutputLocksToLog(); } else if (cleanMatches == true) { sender.CleanUnpairedMatches(); } else if (matchAll == true) { sender.RematchAllWorkingOrders(); } else if (resetConfig == true) { sender.ResetServerConfigs(); } else { if (sender.SendLoadScriptFile(fileName, streamFileContentsBackToClient) == false) { hasException = false; //error SendLoadScriptFile will write error to console return(-1); } waitForEndResetEvent.WaitOne(); if (listener.StreamDataId == null) { AsyncMethodResponse retVal = listener.GetAsyncResponseData(listener.PayloadTicket); Console.WriteLine(retVal.AsyncResponseData); } else { FluidTrade.Guardian.ServerAdminStreamRef.ServerAdminStreamManagerClient streamClient = new FluidTrade.Guardian.ServerAdminStreamRef.ServerAdminStreamManagerClient("TcpServerAdminStreamMgrEndpoint"); streamClient.ClientCredentials.UserName.UserName = username; streamClient.ClientCredentials.UserName.Password = password; Stream serverStream = streamClient.GetAsyncResponseStreamData(listener.StreamDataId); StreamReader streamReader = new StreamReader(serverStream); string tmp = streamReader.ReadToEnd(); Console.WriteLine(tmp); } //Console.WriteLine(message); //if(response.IsSuccessful == false) //{ // Console.WriteLine("FAILED"); //} //Console.WriteLine(retVal.AsyncResponseData); } hasException = false; } finally { try { if (hasException == false) { sender.Dispose(); } } catch { } } } finally { try { if (hasException == false) { listener.Dispose(); } } catch { } } } catch (Exception ex) { Exception exOut = ex; while (exOut != null) { //// Display the error. Console.WriteLine("{0}: {1}", exOut.Message, ex.ToString()); Console.WriteLine(""); exOut = exOut.InnerException; } return(-1); } return(0); }
/// <summary> /// /// </summary> /// <param name="messageTimeUtc"></param> /// <param name="response"></param> /// <param name="message"></param> /// <param name="payload"></param> public PublishSendResponseTicketEventArg(DateTime messageTimeUtc, AsyncMethodResponse response, string message, QueuedResponsePayload payload) : base(messageTimeUtc, response, message) { this.Payload = payload; }
/// <summary> /// ctor /// </summary> /// <param name="messageTimeUtc"></param> /// <param name="response"></param> /// <param name="message"></param> public PublishMessageEventArg(DateTime messageTimeUtc, AsyncMethodResponse response, string message) : base(messageTimeUtc, response) { this.Message = message; }
/// <summary> /// ctor /// </summary> /// <param name="messageTimeUtc"></param> /// <param name="response"></param> public PublishEventArgs(DateTime messageTimeUtc, AsyncMethodResponse response) { //this.TargetClientProxyMap = targetClientProxyMap; this.MessageTimeUtc = messageTimeUtc; this.Response = response; }
/// <summary> /// Thread Method to do the work of Loading the file in a worker thread /// </summary> /// <param name="state">not used, but needed to match the WaitCallback signature</param> private void LoadScriptFileProc(object state) { AsyncMethodResponse response = new AsyncMethodResponse(this.clientProxy.ClientId, this.asyncTicket); FileStream responseFileStream = null; try { string directoryPath = System.IO.Path.GetDirectoryName(this.scriptFilePath); //figure out what file(s) need to be loaded. if xml then assume it is just one file //if not xml assume that the files contains a list of paths to xml files List <string> filePathList = new List <string>(); if (this.scriptFilePath.EndsWith(".xml") == false) { using (System.IO.FileStream fileStream = new System.IO.FileStream(this.scriptFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (StreamReader sr = new StreamReader(fileStream)) { string curFileLine = null; while ((curFileLine = sr.ReadLine()) != null) { curFileLine = curFileLine.Trim(); if (string.IsNullOrEmpty(curFileLine)) { continue; } curFileLine = Path.IsPathRooted(curFileLine) ? curFileLine : Path.Combine(directoryPath, curFileLine); //make sure to use the absolute path filePathList.Add(curFileLine); } } } } else { filePathList.Add(this.scriptFilePath); } try { foreach (string scriptFile in filePathList) { if (scriptFile == null) { continue; } //create a scriptloader to load the file ScriptLoader scriptLoader = new ScriptLoader(); //subscribe to scriptloader messages so can publish them back to the client scriptLoader.NotifyMessage += new ScriptLoader.MessageEventHander(scriptLoader_NotifyMessage); //set scriptloader in local mode (meaning it is running inside the server) scriptLoader.LocalMode = true; scriptLoader.FileName = scriptFile; //load the file into the MT/DB scriptLoader.Load(); } if (this.streamConents == true) { responseFileStream = File.OpenRead(this.scriptFilePath); } //it all worked response.Result = ErrorCode.Success; } catch (Exception ex) { //response.AddError(ex.Message); //catch exception and add it to the return EventLog.Warning(String.Format("{0}: {1}", ex.GetType(), ex.Message)); response.AddError(ex.Message, ErrorCode.Fatal); } } catch (Exception ex) { //response.AddError(ex.Message); //catch exception and add it to the return //response.AddError(ex); EventLog.Warning(String.Format("{0}: {1}", ex.GetType(), ex.Message)); response.AddError(ex.Message, ErrorCode.Fatal); } if (responseFileStream != null) { CallbackManagerImpl.Instance.PublishSendResponseTicket(this.clientProxy, null, null, responseFileStream, response); } else { //notify client that we are all done CallbackManagerImpl.Instance.PublishSendResponseTicket(this.clientProxy, "PublishSendResponseTicketResp", string.Format("Completed: {0}\r\n", this.scriptFilePath), null, response); } }
/// <summary> /// /// push the result ticket out to the client. The client then needs to turn around and call GetAsyncResponseData /// or GetAsyncResponseStreamData to get the data /// </summary> /// <param name="targetClientProxy"></param> /// <param name="message"></param> /// <param name="dataAttachment"></param> /// <param name="streamAttachment"></param> /// <param name="response"></param> public void PublishSendResponseTicket(ClientProxy targetClientProxy, string message, object dataAttachment, Stream streamAttachment, AsyncMethodResponse response) { QueuedResponsePayload payload = null; if (dataAttachment != null || streamAttachment != null) { payload = new QueuedResponsePayload(dataAttachment, response.AsyncTicket, response.ClientId, streamAttachment); if (payload.PayloadStream != null) { string payloadStreamId = string.Format("{0}.{1}", response.ClientId, payload.PayloadTicket); response.StreamDataId = payloadStreamId; lock (streamIdToPayloadMap) streamIdToPayloadMap[payloadStreamId] = payload; } else if (payload.PayloadData != null) { lock (payloadTicketToResponseMap) payloadTicketToResponseMap[payload.PayloadTicketGuid] = payload; } } Dictionary <Guid, ClientProxy> targetClientProxyMap = new Dictionary <Guid, ClientProxy>(); targetClientProxyMap.Add(targetClientProxy.ClientId, targetClientProxy); PublishSendResponseTicketEventArg psrtea = new PublishSendResponseTicketEventArg(DateTime.UtcNow, response, message, payload); this.Publish(targetClientProxyMap, true, psrtea, this.publishSendResponseTicketHandler); }
/// <summary> /// publish message to subscribers /// </summary> /// <param name="targetClientProxyMap">client to publish to, Guid.Empty to publish to all</param> /// <param name="message">text to publish</param> /// <param name="response"></param> public void PublishMessage(Dictionary <Guid, ClientProxy> targetClientProxyMap, string message, AsyncMethodResponse response) { PublishMessageEventArg pmea = new PublishMessageEventArg(DateTime.UtcNow, response, message); this.Publish(targetClientProxyMap, false, pmea, this.publishMessageHandler); }