예제 #1
0
        /// <returns>Returns tool tip header</returns>
        private String GetToolTipHeader()
        {
            var    strBuff   = new StringBuilder();
            String serverUrl = RemoteCommandsProcessor.GetInstance().ServerUrl;

            if (!String.IsNullOrEmpty(serverUrl))
            {
                // Get server URL
                try
                {
                    Uri url = Misc.createURI(RemoteCommandsProcessor.GetInstance().ServerUrl);
                    // Prepare first header line http://servername.com
                    strBuff.Append(url.Scheme + "://" + url.Host);
                }
                catch (Exception ex)
                {
                    Logger.Instance.WriteExceptionToLog(ex.Message);
                }
            }

            // Build tooltip header.
            strBuff.Append("\n" + _tooltipHeader);

            return(strBuff.ToString());
        }
예제 #2
0
        /// <summary>
        ///   send a command to server to update dataview to datasource.
        /// </summary>
        internal bool UpdateDataViewToRemoteDataSource()
        {
            if (dataViewContent != null)
            {
                IClientCommand cmd = CommandFactory.CreateUpdateDataViewToDataSourceCommand(Task.getTaskTag(), command.TaskVarNames,
                                                                                            command.DestinationDataSourceNumber, command.DestinationDataSourceName, command.DestinationColumns, dataViewContent.ToString(), null, null);


                Task.getMGData().CmdsToServer.Add(cmd);

                ResultValue res = new ResultValue();

                // Do not serialize flow monitor messages along with MG_ACT_UPDATE_DATAVIEW_TO_DATASOURCE command
                bool origVal = FlowMonitorQueue.Instance.ShouldSerialize;
                FlowMonitorQueue.Instance.ShouldSerialize = false;

                //Execute MG_ACT_UPDATE_DATAVIEW_TO_DATASOURCE command.
                RemoteCommandsProcessor.GetInstance().Execute(CommandsProcessorBase.SendingInstruction.ONLY_COMMANDS, CommandsProcessorBase.SessionStage.NORMAL, res);

                FlowMonitorQueue.Instance.ShouldSerialize = origVal;
                return(res.Value.Equals("1") ? true : false);
            }

            return(true);
        }
예제 #3
0
        /// <summary>
        /// get command processor for server side operation
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        internal static CommandsProcessorBase GetCommandsProcessor(Task task)
        {
            // for server operation main program must use Remote command processor, otherwise - default command processor must be used
            CommandsProcessorBase commandsProcessor = task.isMainProg() ? RemoteCommandsProcessor.GetInstance() : task.CommandsProcessor;

            return(commandsProcessor);
        }
예제 #4
0
        /// <summary>
        /// Starts session locally without trying to connect to server.
        /// </summary>
        private static bool StartSessionLocally()
        {
            bool succeeded = false;

            // Enable offline required metadata collection which is needed to verify client cache,
            // during connecting to server (switching to connected mode for first server operation)
            ApplicationSourcesManager.GetInstance().OfflineRequiredMetadataCollection.Enabled = true;

            // switch session status from "Uninitialized" to "Local"
            ClientManager.Instance.GetService <IConnectionStateManager>().ConnectionDropped();

            Logger.Instance.WriteServerToLog("Attempting to start locally (Offline mode)");
            succeeded = LocalCommandsProcessor.GetInstance().StartSession();
            if (succeeded)
            {
                // Set server last access status
                RemoteCommandsProcessor.GetInstance().ServerLastAccessStatus = ServerAccessStatus.SkippedConnectionToServer;
            }
            else
            {
                Logger.Instance.WriteServerToLog("Cannot start locally. Terminating client.");
            }

            if (Logger.Instance.IsAccumulatingMessages())
            {
                Logger.Instance.FlushAccumulatedMessages();
            }

            // No cache files should be collected once the session is started.
            ApplicationSourcesManager.GetInstance().OfflineRequiredMetadataCollection.Enabled = false;

            return(succeeded);
        }
예제 #5
0
        /// <summary>
        /// execute the command by pass requests to the server
        /// </summary>
        /// <param name="command"></param>
        internal override ReturnResultBase Execute()
        {
            CommandsTable cmdsToServer = Task.getMGData().CmdsToServer;

            cmdsToServer.Add(Command);
            RemoteCommandsProcessor.GetInstance().Execute(CommandsProcessorBase.SendingInstruction.TASKS_AND_COMMANDS);

            return(new ReturnResult());
        }
예제 #6
0
        /// <summary>
        /// get the commands processor according to the session status.
        /// </summary>
        /// <returns></returns>
        internal static CommandsProcessorBase GetCommandsProcessor()
        {
            if (SessionStatus == SessionStatusEnum.Local)
            {
                ClientManager.Instance.SetService(typeof(TaskServiceBase), new LocalTaskService());
                return((CommandsProcessorBase)LocalCommandsProcessor.GetInstance());
            }

            return((CommandsProcessorBase)RemoteCommandsProcessor.GetInstance());
        }
예제 #7
0
 /// <summary>
 /// get the CommandsProcessor to use for executing the defined task
 /// </summary>
 /// <param name="taskDefinitionId"></param>
 /// <returns></returns>
 internal static CommandsProcessorBase GetCommandsProcessor(TaskDefinitionId taskDefinitionId)
 {
     if (ClientManager.Instance.LocalManager.ApplicationDefinitions.TaskDefinitionIdsManager.IsOfflineTask(taskDefinitionId))
     {
         return(LocalCommandsProcessor.GetInstance());
     }
     else
     {
         return(RemoteCommandsProcessor.GetInstance());
     }
 }
예제 #8
0
 /// <summary>
 /// CTOR
 /// </summary>
 /// <param name="isOfflineTask"></param>
 public CommonCommandProcessorStrategy(bool isOfflineTask)
 {
     if (isOfflineTask)
     {
         taskService = LocalCommandsProcessor.GetInstance();
     }
     else
     {
         taskService = RemoteCommandsProcessor.GetInstance();
     }
 }
예제 #9
0
        /// <summary>
        /// Reads the sources from server and writes its content to temporary sources.
        /// For Local session reads sources from cache.
        /// </summary>
        /// <param name="completeCachedFileRetrievalURL">complete cached file retrieval request (including the server-side time stamp),
        /// e.g. http://[server]/[requester]?CTX=&CACHE=MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml|31/07/2013%2020:15:15</param>
        /// <param name="cachedContentShouldBeReturned">if false, the method will return null as the retrieved content (avoiding retrieval of the requested URL from the local/client cache folder, to save resources / improve performance).</param>
        /// <param name="allowOutdatedContent">if true, check only file existence at client cache</param>
        /// <returns>content</returns>
        internal byte[] ReadSource(String completeCachedFileRetrievalURL, bool cachedContentShouldBeReturned, bool allowOutdatedContent)
        {
            Logger.Instance.WriteSupportToLog("ReadSource():>>>>> ", true);

            byte[] content = null;

            if (_enableSourcesIntegrity && CommandsProcessorManager.SessionStatus == CommandsProcessorManager.SessionStatusEnum.Remote)
            {
                var cachingStrategy = new HttpManager.CachingStrategy()
                {
                    CanWriteToCache = false, CachedContentShouldBeReturned = cachedContentShouldBeReturned, AllowOutdatedContent = allowOutdatedContent
                };
                content = RemoteCommandsProcessor.GetInstance().GetContent(completeCachedFileRetrievalURL, null, null, false, cachingStrategy);

                // if sources were modified (i.e. not retrieved from the cache), save the content to a temporary file:
                if (!cachingStrategy.FoundInCache)
                {
                    WriteToTemporarySourceFile(completeCachedFileRetrievalURL, content);
                    _commitList.Add(completeCachedFileRetrievalURL);
                }
                else
                {
                    // record/register a cached file path + its local time:
                    OfflineRequiredMetadataCollection.Collect(completeCachedFileRetrievalURL);
                }

                if (cachedContentShouldBeReturned)
                {
                    content = PersistentOnlyCacheManager.GetInstance().Decrypt(content);
                }
            }
            else
            {
                if (cachedContentShouldBeReturned)
                {
                    content = CommandsProcessorManager.GetContent(completeCachedFileRetrievalURL, true);
                }
                else
                {
                    if (!PersistentOnlyCacheManager.GetInstance().IsCompleteCacheRequestURLExistsLocally(completeCachedFileRetrievalURL))
                    {
                        throw new LocalSourceNotFoundException("Some of the required files are missing. Please restart the application when connected to the network."); //TODO: use a message from mgconst - here as well as in LocalCommandsProcessor.GetContent
                    }
                }

                // record/register a cached file path + its local time:
                OfflineRequiredMetadataCollection.Collect(completeCachedFileRetrievalURL);
            }

            Logger.Instance.WriteSupportToLog("ReadSource():<<<< ", true);
            return(content);
        }
예제 #10
0
        /// <summary>
        ///   loads a new table start the table parsing process
        ///   delete any old instances of the same table (even if they other unique ids
        /// </summary>
        protected internal void LoadTable(String tableUId)
        {
            CommandsProcessorBase server = RemoteCommandsProcessor.GetInstance();

            // the table must exist in the hashTable at this stage else it is an error
            if (TableExists(tableUId))
            {
                //get the table
                var current = (TableCache)_tables[tableUId];
                try
                {
                    byte[] residentTableContent = server.GetContent(tableUId, true);
                    try
                    {
                        String residentTableContentStr = Encoding.UTF8.GetString(residentTableContent, 0,
                                                                                 residentTableContent.Length);
                        ClientManager.Instance.RuntimeCtx.Parser.loadTableCacheData(residentTableContentStr);
                    }
                    catch (Exception ex)
                    {
                        throw new ApplicationException(
                                  "Unable to parse resident table " + tableUId + ", due to unsupported encoding.", ex);
                    }
                }
                catch (Exception ex)
                {
                    Misc.WriteStackTrace(ex, Console.Error);
                }

                //start parsing
                current.FillData();

                //delete old tables
                var         deletedUids = new List <String>();
                IEnumerator enm         = _tables.Values.GetEnumerator();
                while (enm.MoveNext())
                {
                    var    tbl       = (TableCache)enm.Current;
                    String currIdent = tbl.GetTableCommonIdentifier();
                    if (currIdent.Equals(current.GetTableCommonIdentifier()) && (tbl.GetTableUniqueId() != tableUId))
                    {
                        deletedUids.Add(tbl.GetTableUniqueId());
                    }
                }
                //delete
                for (int i = 0; i < deletedUids.Count; i++)
                {
                    _tables.Remove(deletedUids[i]);
                }
            }
        }
예제 #11
0
        internal SessionStatisticsForm()
        {
            InitializeComponent();

            if (CommandsProcessorManager.SessionStatus == CommandsProcessorManager.SessionStatusEnum.Remote)
            {
                labelServerURL.Text   = RemoteCommandsProcessor.GetInstance().ServerUrl;
                labelApplication.Text = ClientManager.Instance.getAppName();
                string prgDescription = ClientManager.Instance.getPrgDescription();
                if (string.IsNullOrEmpty(prgDescription))
                {
                    prgDescription = ClientManager.Instance.getPrgName();
                }
                labelProgram.Text          = prgDescription;
                labelInternalLogLevel.Text = ClientManager.Instance.getInternalLogLevel();
                labelInternalLogFile.Text  = ClientManager.Instance.getInternalLogFile();

                labelRequests.Text                   = Statistics.GetRequestsCnt().ToString("N0");
                labelUploadedKB.Text                 = string.Format("{0} KB", Statistics.GetAccumulatedUploadedKB().ToString("N0"));
                labelDownloadedKB.Text               = string.Format("{0} KB", Statistics.GetAccumulatedDownloadedKB().ToString("N0"));
                labelUploadedCompressionRatio.Text   = string.Format("{0}", Statistics.GetUploadedCompressionRatio().ToString("N0"));
                labelDownloadedCompressionRatio.Text = string.Format("{0}", Statistics.GetDownloadedCompressionRatio().ToString("N0"));
                ulong sessionTime               = Statistics.GetSessionTime();
                ulong accumulatedExternalTime   = Statistics.GetAccumulatedExternalTime();
                ulong accumulatedMiddlewareTime = Statistics.GetAccumulatedMiddlewareTime();
                ulong accumulatedServerTime     = Statistics.GetAccumulatedServerTime();

                SessionTimeLabel.Text  = ToHHHMMSSms(sessionTime);
                ExternalTimeLabel.Text = ToHHHMMSSms(accumulatedExternalTime);
                ulong networkTime = accumulatedExternalTime - accumulatedMiddlewareTime - accumulatedServerTime;
                NetworkTimeLabel.Text        = ToHHHMMSSms(networkTime);
                MiddlewareTimeLabel.Text     = ToHHHMMSSms(accumulatedMiddlewareTime);
                ServerTimeLabel.Text         = ToHHHMMSSms(accumulatedServerTime);
                ExternalPercentageLabel.Text = (accumulatedExternalTime * 100 / sessionTime).ToString();
                ulong middlewarePercentage = accumulatedMiddlewareTime * 100 / accumulatedExternalTime;
                ulong serverPercentage     = accumulatedServerTime * 100 / accumulatedExternalTime;
                ulong networkPercentage    = 100 - middlewarePercentage - serverPercentage;
                NetworkPercentageLabel.Text = networkPercentage.ToString();
                if (networkPercentage >= 50)
                {
                    NetworkPercentageLabel.ForeColor = Color.Red;
                }
                MiddlewarePercentageLabel.Text = middlewarePercentage.ToString();
                ServerPercentageLabel.Text     = serverPercentage.ToString();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        internal override ReturnResultBase Execute()
        {
            ResultValue res = new ResultValue();

            IClientCommand cmd = CommandFactory.CreatecFetchDataControlValuesCommand(Task.getTaskTag(), control.getName());

            Task.getMGData().CmdsToServer.Add(cmd);

            //Fetch data control values from server.
            RemoteCommandsProcessor.GetInstance().Execute(CommandsProcessorBase.SendingInstruction.TASKS_AND_COMMANDS, CommandsProcessorBase.SessionStage.NORMAL, res);

            //Update DCValRef of every record after fetching the dataControl values.
            for (int i = 0; i < ((DataView)Task.DataView).getSize(); i++)
            {
                ((DataView)Task.DataView).getRecByIdx(i).AddDcValuesReference(control.getDitIdx(), control.getDcRef());
            }

            //Update DCValRef of original record.
            ((DataView)Task.DataView).getOriginalRec().AddDcValuesReference(control.getDitIdx(), control.getDcRef());

            return(new ReturnResult());
        }
예제 #13
0
        /// <summary>
        /// Get contents of files that returned by server on requesting URLs for matching files.
        /// </summary>
        internal void GetMultipleFilesFromServer()
        {
            // Note: This method retrieves contents of each file sequentially. In future, it may extended to support getting
            // content of multiples in one go.

            RemoteCommandsProcessor server = RemoteCommandsProcessor.GetInstance();

            foreach (string filename in ServerFileNames)
            {
                try
                {
                    Debug.Assert(server.ServerFilesToClientFiles.ContainsKey(filename));

                    String cachedUrl = server.ServerFilesToClientFiles[filename];

                    //get the file from the server to local cache if still not cached. File will not be loaded into the memory.
                    server.DownloadContent(cachedUrl);
                }
                catch (System.Exception ex)
                {
                    Logger.Instance.WriteExceptionToLog(ex);
                }
            }
        }
예제 #14
0
        /// <summary>
        /// Start session (Remote/Local)
        /// </summary>
        /// <returns></returns>
        internal static bool StartSession()
        {
            bool succeeded = false;
            bool startInConnectedModeToSyncMetadata = false;
            bool skipConnectionToServer             = false;

            using (Logger.Instance.AccumulateMessages())
            {
                // Check if client is required to start in disconnected mode even when network is available
                // Skip connection if,
                //   1. ConnectOnStartup = N in execution properties
                //   2. LastOffline does not contain "UnsyncronizedMetadata=Y" [which means connect server to sync metadata].
                if (LocalCommandsProcessor.GetInstance().CanStartWithoutNetwork&& !ClientManager.Instance.GetConnectOnStartup())
                {
                    LocalCommandsProcessor.GetInstance().VerifyLastOfflineInitialResponseFile();
                    if (LocalCommandsProcessor.GetInstance().CanStartWithoutNetwork)
                    {
                        if (LocalCommandsProcessor.GetInstance().IsUnsyncronizedMetadata())
                        {
                            startInConnectedModeToSyncMetadata = true;
                        }
                        else
                        {
                            skipConnectionToServer = true;
                        }
                    }
                }

                // Create a communications failure handler and pass it to the Http connection layer.
                HttpManager.GetInstance().SetCommunicationsFailureHandler(
                    LocalCommandsProcessor.GetInstance().CanStartWithoutNetwork
                           ? (ICommunicationsFailureHandler)(new SilentCommunicationsFailureHandler())
                           : (ICommunicationsFailureHandler)(new InteractiveCommunicationsFailureHandler()));

                if (skipConnectionToServer)
                {
                    succeeded = StartSessionLocally();
                }
                else
                {
                    try
                    {
                        ApplicationSourcesManager.GetInstance().OfflineRequiredMetadataCollection.Enabled = true;

                        // access the Server: if accessed - continue remotely, otherwise - locally.
                        succeeded = RemoteCommandsProcessor.GetInstance().StartSession();

                        // Notify the Connection State Manager that a successful connection was established.
                        // The first time this happens, the connection state manager will move from 'Unknown' to 'Connected'.
                        ClientManager.Instance.GetService <IConnectionStateManager>().ConnectionEstablished();
                    }
                    catch (Exception ex)
                    {
                        if (ex is InvalidSourcesException)
                        {
                            throw;
                        }

                        // If client started in connected mode (even when ConnectOnStartup=N in execution properties) because,
                        // UnsyncronisedMetadata was occurred in last execution, and if any sever error occurred during initialization then,
                        // ServerLastAccessStatus() should return 1 (UnsynchroizedMetadata). This way client will avoid trying any server operation.
                        if (startInConnectedModeToSyncMetadata)
                        {
                            RemoteCommandsProcessor.GetInstance().ServerLastAccessStatus = ServerAccessStatus.UnsynchroizedMetadata;
                        }

                        Logger.Instance.WriteServerToLog("Failed connecting to the server: " + ex.Message);
                        if (LocalCommandsProcessor.GetInstance().CanStartWithoutNetwork)
                        {
                            if (Logger.Instance.ShouldLog())
                            {
                                Logger.Instance.FlushAccumulatedMessages();
                            }
                            else
                            {
                                Logger.Instance.DiscardAccumulatedMessages();
                            }
                            Logger.Instance.StopMessageAccumulation();
                            Logger.Instance.WriteServerToLog("Attempting to start locally (Offline mode)");
                            succeeded = LocalCommandsProcessor.GetInstance().StartSession();
                        }

                        if (!succeeded)
                        {
                            Logger.Instance.WriteServerToLog("Cannot start locally. Terminating client.");
                            throw;
                        }
                    }
                    finally
                    {
                        if (Logger.Instance.IsAccumulatingMessages())
                        {
                            Logger.Instance.FlushAccumulatedMessages();
                        }

                        // all offline required cache files are retrieved when the server is started, in the initial response after the two handshake requests.
                        // therefore, no cache files should be collected once the session is started [i.e. StartSession() was executed].
                        ApplicationSourcesManager.GetInstance().OfflineRequiredMetadataCollection.Enabled = false;
                    }
                }
            }

            // if a startupProgram should be started locally then load it locally.
            if (GetCommandsProcessor().ShouldLoadOfflineStartupProgram())
            {
                LocalCommandsProcessor.GetInstance().LoadStartupProgram();
            }

            // From this point onward, all comm failures should show a message.
            HttpManager.GetInstance().SetCommunicationsFailureHandler(new InteractiveCommunicationsFailureHandler());

            return(succeeded);
        }
예제 #15
0
        /// <summary>
        ///   Set the variable:
        ///   1. parse the string
        ///   2. create the param/value couples
        ///   3. for each couple:
        ///   3a. verify the section name exists
        ///   3b. verify the variable is not unmodifieable
        ///   3c. set the variable in the base class
        ///   3d. check and change the environment data if needed
        ///   4. If required, send the data to the server
        /// </summary>
        /// <param name = "s"></param>
        /// <param name = "updateIni"></param>
        /// <returns></returns>
        internal Boolean set(String s, Boolean updateIni)
        {
            Boolean allOK = true;
            Boolean sendToServer = false;
            string  name, val;
            int     i;
            String  serverVal = s;

            // String parsing: every number in 'offsets' shows the offset to the beginning of a name or value
            // 1st offset is always 0
            int[]  offsets      = new int[s.Length + 1];
            char[] offsetsChars = new char[s.Length + 1];

            offsets[0]      = 0;
            offsetsChars[0] = 's';
            int nextOffset = 1;

            // Loop over string, find all the '=', ',' and '*' that are not preceeded by a '\'.
            for (i = 1; i < s.Length; i++)
            {
                if ((s[i] == '=' || s[i] == ',') && s[i - 1] != '\\')
                {
                    offsets[nextOffset]      = i + 1;
                    offsetsChars[nextOffset] = s[i];
                    nextOffset++;
                }
                // IF we find an *, remove it and stop parsing
                if (s[i] == '*')
                {
                    s = s.Remove(i, 1);
                    break;
                }
                if (s[i] == '\\')
                {
                    s = s.Remove(i, 1);
                }
            }

            // add the final offset for the end of the string
            offsets[nextOffset]      = s.Length + 1;
            offsetsChars[nextOffset] = '\0';
            nextOffset++;

            // go over the calculated offsets. the last one is the end of the string, so it is ignored
            for (i = 0; i < nextOffset - 1; i++)
            {
                // get the variable name
                name = s.Substring(offsets[i], offsets[i + 1] - offsets[i] - 1);
                // is there a value, or is it an empty variable?
                if (s[offsets[i + 1] - 1] == '=')
                {
                    i++;
                    int valInit           = i;
                    int allowedSeparators = getAllowedSeparators(name);
                    for (int sep = 0; sep < allowedSeparators; sep++)
                    {
                        if (offsetsChars[i + 1] == ',')
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    // get the value
                    val = s.Substring(offsets[valInit], offsets[i + 1] - offsets[valInit] - 1);
                }
                else
                {
                    val = null;
                }

                // is it a reserved variable?
                if (isReservedLogicalName(name))
                {
                    allOK = false;
                    continue;
                }

                // if there's no section name, add the default one
                if (name[0] != '[')
                {
                    name = name.Insert(0, ConstInterface.INI_SECTION_MAGIC_ENV_BRACKETS);
                }

                // If it's not a logical name, it is case insensitive
                if (!name.StartsWith(ConstInterface.INI_SECTION_LOGICAL_NAMES_BRACKETS))
                {
                    name = name.ToUpper();
                }

                name = name.Trim();
                val  = val.Trim();

                sendToServer = true;
                if (!String.IsNullOrEmpty(val) ||
                    name.StartsWith(ConstInterface.INI_SECTION_LOGICAL_NAMES_BRACKETS))
                {
                    // If we're going to send it to the server NOW, we don't need it in the changes list
                    base.set(name, new MirrorString(val), !updateIni);
                    checkSetInEnvironment(name, val);
                }
                else
                {
                    base.remove(name);
                }
            }

            // if should update the ini file, and we have modified variables, update the server.
            if (updateIni && sendToServer && CommandsProcessorManager.SessionStatus == CommandsProcessorManager.SessionStatusEnum.Remote)
            {
                IClientCommand cmd = CommandFactory.CreateIniputForceWriteCommand(serverVal);
                MGDataCollection.Instance.getMGData(0).CmdsToServer.Add(cmd);

                // execute client to server commands
                RemoteCommandsProcessor.GetInstance().Execute(CommandsProcessorBase.SendingInstruction.ONLY_COMMANDS);
            }

            return(allOK);
        }
예제 #16
0
        /// <summary>
        ///   To allocate and fill inner objects of the class
        /// </summary>
        /// <param name = "foundTagName">possible tag name, name of object, which need be allocated</param>
        /// <param name="openingTaskDetails">additional information of opening task</param>
        /// <returns> xmlParser.getCurrIndex(), the found object tag and ALL its subtags finish</returns>
        private bool initInnerObjects(XmlParser parser, String foundTagName, OpeningTaskDetails openingTaskDetails)
        {
            if (foundTagName == null)
            {
                return(false);
            }

            switch (foundTagName)
            {
            case XMLConstants.MG_TAG_XML:
                parser.setCurrIndex(
                    parser.getXMLdata().IndexOf(XMLConstants.TAG_CLOSE, parser.getCurrIndex()) + 1); // do
                // nothing
                break;

            case ConstInterface.MG_TAG_DATAVIEW:
                if (!insertDataView(parser))
                {
                    // the task of insert data view not found -> set parsers counter to the
                    // end of the data view
                    // the data view, got from server and there is no task to the data view , yet.
                    int endContext = parser.getXMLdata().IndexOf('/' + ConstInterface.MG_TAG_DATAVIEW,
                                                                 parser.getCurrIndex());
                    parser.setCurrIndex(endContext);
                    parser.setCurrIndex2EndOfTag();
                }
                break;

            // read DataViewContent that received as a response of GetDataViewContent Command.
            case ConstInterface.MG_TAG_COMPLETE_DV:
            {
                Task task       = null;
                int  endContext = parser.getXMLdata().IndexOf(XMLConstants.TAG_CLOSE, parser.getCurrIndex());
                int  index      = parser.getXMLdata().IndexOf(ConstInterface.MG_TAG_COMPLETE_DV, parser.getCurrIndex()) +
                                  ConstInterface.MG_TAG_COMPLETE_DV.Length;

                List <String> tokensVector = XmlParser.getTokens(parser.getXMLdata().Substring(index, endContext - index),
                                                                 "\"");

                // get task id
                string attribute = (tokensVector[0]);
                String valueStr;
                if (attribute.Equals(XMLConstants.MG_ATTR_TASKID))
                {
                    valueStr = (tokensVector[1]);
                    String taskId = valueStr;
                    task = getTask(taskId) ?? (Task)MGDataCollection.Instance.GetTaskByID(taskId);
                }

                int start = endContext + 1;
                endContext = parser.getXMLdata().IndexOf(XMLConstants.END_TAG + ConstInterface.MG_TAG_COMPLETE_DV,
                                                         parser.getCurrIndex());

                String dataViewContent = parser.getXMLdata().Substring(start, endContext - start);
                task.dataViewContent = dataViewContent;
                parser.setCurrIndex(endContext);
                parser.setCurrIndex2EndOfTag();
            }

            break;

            case XMLConstants.MG_TAG_TREE:
            {
                int start      = parser.getCurrIndex();
                int endContext = parser.getXMLdata().IndexOf('/' + XMLConstants.MG_TAG_TREE,
                                                             parser.getCurrIndex());
                parser.setCurrIndex(endContext);
                parser.setCurrIndex2EndOfTag();
                String treeData = parser.getXMLdata().Substring(start, parser.getCurrIndex() - start);
                //read tree data using sax parser
                try
                {
                    var mgSAXParser = new MgSAXParser(new TreeSaxHandler());
                    mgSAXParser.parse(Encoding.UTF8.GetBytes(treeData));
                }
                catch (Exception e)
                {
                    Logger.Instance.WriteExceptionToLog(e);
                    Misc.WriteStackTrace(e, Console.Error);
                }
                break;
            }

            case ConstInterface.MG_TAG_CONTEXT:
            {
                int endContext = parser.getXMLdata().IndexOf(XMLConstants.TAG_TERM, parser.getCurrIndex());
                if (endContext != -1 && endContext < parser.getXMLdata().Length)
                {
                    // last position of its tag
                    String tag = parser.getXMLsubstring(endContext);
                    parser.add2CurrIndex(tag.IndexOf(ConstInterface.MG_TAG_CONTEXT) +
                                         ConstInterface.MG_TAG_CONTEXT.Length);
                    parser.setCurrIndex(endContext + XMLConstants.TAG_TERM.Length);  // to delete "/>" too
                }
                break;
            }

            case XMLConstants.MG_TAG_RECOMPUTE:
                var recompTab = new RecomputeTable();
                recompTab.fillData();
                break;

            case ConstInterface.MG_TAG_COMMAND:
                Logger.Instance.WriteDevToLog("goes to command");
                CmdsToClient.fillData();
                break;

            case ConstInterface.MG_TAG_LANGUAGE:
                Logger.Instance.WriteDevToLog("goes to language data");
                ClientManager.Instance.getLanguageData().fillData();
                break;

            case ConstInterface.MG_TAG_KBDMAP_URL:
                Logger.Instance.WriteDevToLog("goes to keyBoard");
                ClientManager.Instance.getEnvironment().fillFromUrl(foundTagName);
                break;

            case ConstInterface.MG_TAG_KBDMAP:
                Logger.Instance.WriteDevToLog("goes to keyBoard");

                int kbdStartIdx = parser.getCurrIndex();
                int kbdEndIdx   = parser.getXMLdata().IndexOf('/' + ConstInterface.MG_TAG_KBDMAP,
                                                              parser.getCurrIndex());
                parser.setCurrIndex(kbdEndIdx);
                parser.setCurrIndex2EndOfTag();
                String kbdData = parser.getXMLdata().Substring(kbdStartIdx, parser.getCurrIndex() - kbdStartIdx);
                ClientManager.Instance.getKbdMap().fillKbdMapTable(Encoding.UTF8.GetBytes(kbdData));

                break;

            case ConstInterface.MG_TAG_COLORTABLE_URL:
                Logger.Instance.WriteDevToLog("goes to color");
                ClientManager.Instance.getEnvironment().fillFromUrl(foundTagName);
                break;

            case XMLConstants.MG_TAG_COLORTABLE:
            {
                Logger.Instance.WriteDevToLog("goes to color");
                int colorStartIdx = parser.getCurrIndex();
                int colorEndIdx   = parser.getXMLdata().IndexOf('/' + XMLConstants.MG_TAG_COLORTABLE,
                                                                parser.getCurrIndex());
                parser.setCurrIndex(colorEndIdx);
                parser.setCurrIndex2EndOfTag();
                String colorData = parser.getXMLdata().Substring(colorStartIdx,
                                                                 parser.getCurrIndex() - colorStartIdx);

                Manager.GetColorsTable().FillFrom(Encoding.UTF8.GetBytes(colorData));
                break;
            }

            case ConstInterface.MG_TAG_FONTTABLE_URL:
                Logger.Instance.WriteDevToLog("goes to font");
                ClientManager.Instance.getEnvironment().fillFromUrl(foundTagName);
                break;

            case ConstInterface.MG_TAG_FONTTABLE:
                Logger.Instance.WriteDevToLog("goes to font");

                int startIdx = parser.getCurrIndex();
                int endIdx   = parser.getXMLdata().IndexOf('/' + ConstInterface.MG_TAG_FONTTABLE,
                                                           parser.getCurrIndex());
                parser.setCurrIndex(endIdx);
                parser.setCurrIndex2EndOfTag();
                String fontData = parser.getXMLdata().Substring(startIdx, parser.getCurrIndex() - startIdx);
                Manager.GetFontsTable().FillFrom(Encoding.UTF8.GetBytes(fontData));
                break;

            case ConstInterface.MG_TAG_COMPMAINPRG:
                Logger.Instance.WriteDevToLog("goes to compmainprg");
                ClientManager.Instance.EventsManager.getCompMainPrgTab().fillData();
                break;

            case ConstInterface.MG_TAG_EVENTS_QUEUE:
                Logger.Instance.WriteDevToLog("goes to eventsqueue");
                fillEventsQueue(parser);
                break;

            case ConstInterface.MG_TAG_TASKURL:
                ClientManager.Instance.ProcessTaskURL();
                break;

            case XMLConstants.MG_TAG_TASK:
                Logger.Instance.WriteDevToLog("goes to task");
                int taskCountBefore = _mprgTab.getSize();

                _mprgTab.fillData(this, openingTaskDetails);

                // QCR #759911: mprg must belong to the main application's MGData.
                // This ensures it will not be discarded until the end of execution.
                // There could be more then 1 mprgs that are added (Qcr #168549)
                if (_id != 0)
                {
                    int    taskCountAfter = _mprgTab.getSize();
                    MGData mgd0           = MGDataCollection.Instance.getMGData(0);

                    // check all the new main prgs.
                    for (int taskIndex = taskCountBefore; taskIndex < taskCountAfter; taskIndex++)
                    {
                        Task newTask = _mprgTab.getTask(taskIndex);


                        if (newTask.isMainProg() && mgd0._mprgTab.getTask(newTask.getTaskTag()) == null)
                        {
                            mgd0._mprgTab.addTask(newTask);
                            mgd0.addTask(newTask);
                        }
                    }
                }
                break;

            case ConstInterface.MG_TAG_ENV:
                Logger.Instance.WriteDevToLog("goes to environment");
                ClientManager.Instance.getEnvironment().fillData();
                break;

            case ConstInterface.MG_TAG_FLWMTR_CONFIG:
                FlowMonitorQueue.Instance.fillData();
                break;

            case XMLConstants.MG_TAG_XML_END:
                parser.setCurrIndex2EndOfTag();
                return(false);

            case ConstInterface.MG_TAG_USER_RIGHTS:
                ClientManager.Instance.fillUserRights();
                break;

            case ConstInterface.MG_TAG_DBH_REAL_IDXS:
                ClientManager.Instance.fillDbhRealIdxs();
                break;

            case ConstInterface.MG_TAG_GLOBALPARAMSCHANGES:
                Logger.Instance.WriteDevToLog("applying global params changes from the server (Set/GetParams)");
                ClientManager.Instance.getGlobalParamsTable().fillData();
                break;

            case ConstInterface.MG_TAG_GLOBALPARAMS:
                Logger.Instance.WriteDevToLog("processing base64 encoded image of all global params from the server");
                ClientManager.Instance.fillGlobalParams();
                break;

            case ConstInterface.MG_TAG_CACHED_FILES:
                RemoteCommandsProcessor.GetInstance().ServerFileToClientHelper.RequestedForFolderOrWildcard = true;
                parser.setCurrIndex(parser.getXMLdata().IndexOf(XMLConstants.TAG_CLOSE, parser.getCurrIndex()) + 1);
                break;

            case ConstInterface.MG_TAG_CACHED_FILES_END:
                parser.setCurrIndex(parser.getXMLdata().IndexOf(XMLConstants.TAG_CLOSE, parser.getCurrIndex()) + 1);
                break;

            case ConstInterface.MG_TAG_CACHED_FILE:
                ClientManager.Instance.fillCacheFilesMap();
                break;

            case ConstInterface.MG_TAG_ENV_PARAM_URL:
                Logger.Instance.WriteDevToLog("goes to env params name ");
                ClientManager.Instance.getEnvironment().fillFromUrl(foundTagName);
                break;

            case ConstInterface.MG_TAG_ENV_PARAM:
                Logger.Instance.WriteDevToLog("goes to env params name ");
                ClientManager.Instance.getEnvParamsTable().fillData();
                break;

            case ConstInterface.MG_TAG_USER_DETAILS:
                UserDetails.Instance.fillData();
                break;

            case ConstInterface.MG_TAG_DBHS:
                ClientManager.Instance.LocalManager.ApplicationDefinitions.DataSourceDefinitionManager.FillData();
                break;

            case ConstInterface.MG_TAG_DATABASE_URL:
                // If data includes only file url
                ClientManager.Instance.LocalManager.ApplicationDefinitions.DatabaseDefinitionsManager.FillUrl();
                break;

            case ConstInterface.MG_TAG_DATABASES_HEADER:
                ClientManager.Instance.LocalManager.ApplicationDefinitions.DatabaseDefinitionsManager.FillData();
                break;

            case ConstInterface.MG_TAG_TASKDEFINITION_IDS_URL:
                Logger.Instance.WriteDevToLog("goes to task definition ids");
                ClientManager.Instance.LocalManager.ApplicationDefinitions.TaskDefinitionIdsManager.FillFromUrl(foundTagName);
                break;

            case ConstInterface.MG_TAG_OFFLINE_SNIPPETS_URL:
                ClientManager.Instance.LocalManager.ApplicationDefinitions.OfflineSnippetsManager.FillFromUrl(foundTagName);
                break;

            case ConstInterface.MG_TAG_STARTUP_PROGRAM:
                CommandsProcessorManager.GetCommandsProcessor().ParseStartupProgram(parser);
                break;

            case ConstInterface.MG_TAG_CONTEXT_ID:
            {
                String ctxId;
                int    ctxEndIdx;

                parser.setCurrIndex(parser.getXMLdata().IndexOf(XMLConstants.TAG_CLOSE, parser.getCurrIndex()) + 1);
                ctxEndIdx = parser.getXMLdata().IndexOf(XMLConstants.TAG_OPEN, parser.getCurrIndex());
                ctxId     = parser.getXMLsubstring(ctxEndIdx).Trim();
                parser.setCurrIndex(ctxEndIdx);
                parser.setCurrIndex2EndOfTag();

                ClientManager.Instance.RuntimeCtx.ContextID = Int64.Parse(ctxId);
            }
            break;

            case ConstInterface.MG_TAG_HTTP_COMMUNICATION_TIMEOUT:
            {
                uint httpCommunicationTimeout;   // communication-level timeout (i.e. the access to the web server, NOT the entire request/response round-trip), in seconds.
                int  httpCommunicationTimeoutIdx;

                parser.setCurrIndex(parser.getXMLdata().IndexOf(XMLConstants.TAG_CLOSE, parser.getCurrIndex()) + 1);
                httpCommunicationTimeoutIdx = parser.getXMLdata().IndexOf(XMLConstants.TAG_OPEN, parser.getCurrIndex());
                httpCommunicationTimeout    = uint.Parse(parser.getXMLsubstring(httpCommunicationTimeoutIdx));
                parser.setCurrIndex(httpCommunicationTimeoutIdx);
                parser.setCurrIndex2EndOfTag();

                HttpManager.GetInstance().HttpCommunicationTimeoutMS = httpCommunicationTimeout * 1000;
            }
            break;

            default:
                Logger.Instance.WriteExceptionToLog(
                    "There is no such tag name in MGData, add case to MGData.initInnerObjects and case to while of MGData.FillData  " +
                    foundTagName);
                return(false);
            }

            return(true);
        }
예제 #17
0
        /// <summary>
        ///   execute recompute
        /// </summary>
        /// <param name = "rec">the record on which the recompute is executed</param>
        internal void execute(Record rec)
        {
            int            i;
            Field          fld;
            CommandsTable  cmdsToServer = Task.getMGData().CmdsToServer;
            IClientCommand cmd;

            try
            {
                rec.setInRecompute(true);

                bool allowServerRecompute = _hasServerLinksRecomputes || (Task.getForm().AllowedSubformRecompute&& checkRefreshSubForms());
                // SERVER
                if (RcmpMode != RcmpBy.CLIENT && allowServerRecompute)
                {
                    bool inClient = _subFormsOnlyRecomp;
                    Task.ExecuteClientSubformRefresh = false;

                    // if the recompute is not only due to sub-forms go to server
                    if (inClient)
                    {
                        inClient = Task.prepareCache(true);
                        //if all sub-form are not update
                        if (inClient)
                        {
                            inClient = Task.testAndSet(true); //try to take dataviews from cache
                        }
                    }
                    if (!inClient)
                    {
                        ((FieldsTable)Task.DataView.GetFieldsTab()).setServerRcmp(true);
                        cmd = CommandFactory.CreateRecomputeCommand(Task.getTaskTag(), OwnerFld.getId(), !Task.getForm().AllowedSubformRecompute);
                        cmdsToServer.Add(cmd);
                        RemoteCommandsProcessor.GetInstance().Execute(CommandsProcessorBase.SendingInstruction.TASKS_AND_COMMANDS);
                    }

                    if (Task.ExecuteClientSubformRefresh)
                    {
                        RefreshSubforms();
                    }
                    else
                    {
                        if (recPrefixSubForms())
                        {
                            recSuffixSubForms();
                        }
                        Task.CleanDoSubformPrefixSuffix();
                    }
                }
                // CLIENT
                else
                {
                    try
                    {
                        FlowMonitorQueue.Instance.addRecompute(OwnerFld.getVarName());

                        // FORM PROPERTIES
                        if (_formProps != null)
                        {
                            _formProps.RefreshDisplay(false, false);
                        }

                        // CTRL PROPERTIES
                        if (_ctrlProps != null)
                        {
                            _ctrlProps.RefreshDisplay(false, false);
                        }

                        //re-cumpute client side fields and links
                        if (_rcmpOrder != null)
                        {
                            for (i = 0; i < _rcmpOrder.Count; i++)
                            {
                                if (_rcmpOrder[i] is Field)
                                {
                                    fld = (Field)_rcmpOrder[i];
                                    fldRcmp(fld, true);
                                }
                                else if (_rcmpOrder[i] is DataviewHeaderBase)
                                {
                                    var curLnk = (DataviewHeaderBase)_rcmpOrder[i];
                                    curLnk.getLinkedRecord(rec);

                                    //if we have recomputed a link we should also start the recompute process on all of its fields
                                    List <Field> linkFields =
                                        ((FieldsTable)Task.DataView.GetFieldsTab()).getLinkFields(curLnk.Id);
                                    rec.setInCompute(true);
                                    bool saveInForceUpdate = rec.InForceUpdate;
                                    rec.InForceUpdate = false;

                                    for (int j = 0; j < linkFields.Count; j++)
                                    {
                                        fldRcmp(linkFields[j], false);
                                        rec.clearFlag((linkFields[j]).getId(), Record.FLAG_UPDATED);
                                        rec.clearFlag((linkFields[j]).getId(), Record.FLAG_MODIFIED);
                                        rec.clearFlag((linkFields[j]).getId(), Record.FLAG_CRSR_MODIFIED);
                                        rec.clearHistoryFlag((linkFields[j]).getId());
                                    }
                                    rec.InForceUpdate = saveInForceUpdate;

                                    //start recompute process on the ret val of the link
                                    Field retFld = curLnk.ReturnField;
                                    if (retFld != null)
                                    {
                                        fldRcmp(retFld, false);
                                    }

                                    rec.setInCompute(false);
                                    rec.setForceSaveOrg(true);
                                }
                                else if (_rcmpOrder[i] is DCValuesRecompute)
                                {
                                    ((DCValuesRecompute)_rcmpOrder[i]).Recompute(Task, rec);
                                }
                            }
                        }

                        RefreshSubforms();
                    }
                    catch (Exception e)
                    {
                        Logger.Instance.WriteExceptionToLog("in Recompute.execute(): " + e.Message);
                    }
                } // END CLIENT BLOCK
            }
            finally
            {
                rec.buildLinksPosStr();
                rec.setInRecompute(false);
            }
        }