Ejemplo n.º 1
0
        /// <summary>
        /// CTOR
        /// </summary>
        internal MgProperties(String propertiesFileName)
        {
            byte[] propertiesContentBytes = HandleFiles.readToByteArray(propertiesFileName, "");
            var    propertiesContentXML   = Encoding.UTF8.GetString(propertiesContentBytes, 0, propertiesContentBytes.Length);

            loadFromXML(propertiesContentXML, Encoding.UTF8);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// </summary>
        /// <param name="propertiesFileName"></param>
        internal void WriteToXMLFile(String propertiesFileName)
        {
            var propertiesContentXML = new StringBuilder();

            storeToXML(propertiesContentXML);
            HandleFiles.writeToFile(propertiesFileName, Encoding.UTF8.GetBytes(propertiesContentXML.ToString()));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// </summary>
        /// <param name="completeCachedFileRetrievalURL">complete cached file retrieval request (including the server-side time stamp),
        /// e.g. http://[server]/[requester]?CTX=&CACHE=My Application_DbhDataIds.xml|31/07/2013%2020:15:15</param>
        /// <returns>true if the requested cached file ('completeCachedFileRetrievalURL') exists in the local cache folder.</returns>
        internal bool IsCompleteCacheRequestURLExistsLocally(string completeCachedFileRetrievalURL)
        {
            string cachedFileServerFileName;
            string cachedFileLocalFileName;

            CompleteCacheRequestURLToFileNames(completeCachedFileRetrievalURL, out cachedFileServerFileName, out cachedFileLocalFileName);
            return(HandleFiles.isExists(cachedFileLocalFileName));
        }
Ejemplo n.º 4
0
        /// <summary> Saves the initial response in the LastOffline file. </summary>
        /// <param name="initialResponse"></param>
        internal void SaveInitialResponseInLastOfflineFile(String initialResponse)
        {
            String fileName = GetLastOfflineExecutionPropertiesFileName();
            String fileTime = HandleFiles.getFileTime(fileName);

            LastOfflineExecutionProperties[ConstInterface.INITIAL_RESPONSE] = initialResponse;

            LastOfflineExecutionProperties.WriteToXMLFile(fileName);
            HandleFiles.setFileTime(fileName, fileTime);
        }
Ejemplo n.º 5
0
        ///<summary>
        /// check that content exists in the cache folder for 'url'.
        ///</summary>
        /// <param name="url">URL to a cached file, excluding the server-side time stamp, e.g. /MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml.</param>
        ///<returns>true if content exists for 'url'.</returns>
        public bool IsExists(string url)
        {
            bool contentFound = false;

            lock (this)
            {
                String localFilename = URLToLocalFileName(url);
                contentFound = HandleFiles.isExists(localFilename);
            }
            return(contentFound);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// record an offline-required metadata + its local time
 /// </summary>
 /// <param name="requestedURL">complete cache file retrieval request to an offline-required metadata,
 /// e.g. http://[server]/[requester]?CTX=&CACHE=MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml|31/07/2013%2020:15:15</param>
 internal void Collect(string requestedURL)
 {
     if (Enabled)
     {
         string cachedFileServerFileName;
         string cachedFileLocalFileName;
         PersistentOnlyCacheManager.GetInstance().CompleteCacheRequestURLToFileNames(requestedURL, out cachedFileServerFileName, out cachedFileLocalFileName);
         Debug.Assert(HandleFiles.isExists(cachedFileLocalFileName));
         CollectedMetadata[cachedFileServerFileName] = HandleFiles.getFileTime(cachedFileLocalFileName);
     }
 }
Ejemplo n.º 7
0
        ///<summary>
        /// check that an up-to-date content exists in the cache folder for 'url'.
        ///</summary>
        /// <param name="url">URL to a cached file, excluding the server-side time stamp, e.g. /MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml.</param>
        /// <param name="remoteTime">modification time of the file on the server side.</param>
        ///<returns>true if content exists for 'url' and matches 'remoteTime'.</returns>
        public bool CheckFile(string url, string remoteTime)
        {
            bool upToDateContentFound = false;

            lock (this)
            {
                String localFilename = URLToLocalFileName(url);
                String localTime     = HandleFiles.getFileTime(localFilename);

                upToDateContentFound = (HandleFiles.equals(localTime, remoteTime));
            }

            return(upToDateContentFound);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// verify that the last initial response file saved on the client for offline execution is valid (otherwise remove it).
        /// the last saved initial response file becomes invalid in the following case:
        ///   (*) the executed program's public name (ClientManager.Instance.getPrgName()) doesn't match the one saved in the last initial response file.
        /// </summary>
        internal void VerifyLastOfflineInitialResponseFile()
        {
            InitializeEncryptor();

            // extract the program's public name from the last :
            string initialResponsePrgName = GetPublicNameFromLastOfflineInitialResponse();

            /// the last saved initial response file becomes invalid in case the executed program's public name (ClientManager.Instance.getPrgName())
            ///   doesn't match the one saved in the last initial response file.
            if (!ClientManager.Instance.getPrgName().Equals(initialResponsePrgName))
            {
                string lastOfflineExecutionFileName = GetLastOfflineExecutionPropertiesFileName();
                HandleFiles.deleteFile(lastOfflineExecutionFileName);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// get content from the cache
        /// </summary>
        /// <param name="url">URL to a cached file, excluding the server-side time stamp, e.g. /MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml.</param>
        public byte[] GetFile(String url)
        {
            lock (this)
            {
                byte[] content = null;

                String localFilename = URLToLocalFileName(url);
                if (HandleFiles.isExists(localFilename))
                {
                    content = HandleFiles.readToByteArray(localFilename, "");
                }

                return(content);
            }
        }
Ejemplo n.º 10
0
        internal SourcesSyncStatus()
        {
            TablesIncompatibleWithDataSources = false;
            InvalidSources = false;

            String cachFoldername = CacheUtils.GetCacheFolderName();
            String fileName       = ClientManager.Instance.getAppName() + "_SourcesSyncStatus";

            StatusFileName = cachFoldername + "\\" + fileName;

            // Read the synchronization status of sources in previous execution, if exist.
            // If file does not exist, this means in previous execution sources were synchronized without any failure.
            if (HandleFiles.isExists(StatusFileName))
            {
                ReadFromFile();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// get content from the cache; if the cached content's loading time differs from 'remoteTime', return null.
        /// </summary>
        /// <param name="url">URL to a cached file, excluding the server-side time stamp, e.g. /MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml.</param>
        /// <param name="remoteTime"></param>
        public byte[] GetFile(String url, String remoteTime)
        {
            lock (this)
            {
                byte[] content       = null;
                String localFilename = URLToLocalFileName(url);

                String localTime = HandleFiles.getFileTime(localFilename);

                if (HandleFiles.equals(localTime, remoteTime))
                {
                    content = HandleFiles.readToByteArray(localFilename, "");
                }

                return(content);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Retrieve a file from the server to the client's default folder.
        /// In case the file wasn't modified since last retrieved, it will not be downloaded from the server
        ///   and will not be copied to the client's default folder.
        /// </summary>
        /// <param name="serverFileName">file name, as known in the server's file system.</param>
        /// <param name="currTask">the current executing task.</param>
        /// <returns>true if the file was found on the client's default folder.</returns>
        internal bool CopyToDefaultFolder(string serverFileName, Task currTask)
        {
            Debug.Assert(currTask != null);

            string clientFileName = (serverFileName.Substring(serverFileName.LastIndexOf('\\') + 1));
            string cachedFileName = GetLocalFileName(serverFileName, currTask, false);

            if (!String.IsNullOrEmpty(cachedFileName))
            {
                // if the file was modified since last retrieved, copy it from the client's cache to the client's default folder
                if (HandleFiles.getFileTime(cachedFileName) != HandleFiles.getFileTime(clientFileName))
                {
                    HandleFiles.copy(cachedFileName, clientFileName, true, false);
                }
            }

            return(HandleFiles.isExists(clientFileName));
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Saves an indication of unsynchronized metadata in LastOffline to instruct client to start in connected mode next time
        /// </summary>
        internal void SaveUnsyncronizedMetadataFlagInLastOfflineFile()
        {
            String fileName = GetLastOfflineExecutionPropertiesFileName();
            String fileTime = HandleFiles.getFileTime(fileName);

            MgProperties offlineExecutionProps = LastOfflineExecutionProperties.Clone();

            offlineExecutionProps.Add(ConstInterface.MG_TAG_UNSYNCRONIZED_METADATA, "Y");

            String initialResponse = offlineExecutionProps[ConstInterface.INITIAL_RESPONSE];

            if (GetLastOfflineExecutionPropertyBool(ConstInterface.DISABLE_ENCRYPTION))
            {
                initialResponse = XMLConstants.CDATA_START + OSEnvironment.EolSeq + initialResponse + OSEnvironment.EolSeq + XMLConstants.CDATA_END;
                offlineExecutionProps[ConstInterface.INITIAL_RESPONSE] = initialResponse;
            }

            offlineExecutionProps.WriteToXMLFile(fileName);
            HandleFiles.setFileTime(fileName, fileTime);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// checks file exist with specified remote time.
        /// when remote time is null, then check only file is exist or not
        /// otherwise check if source with remotetime exist
        /// </summary>
        /// <param name="fileFullName">Full name of the file</param>
        /// <param name="remoteTime">last modification time of the file (for story#138618: remote time will be null)</param>
        /// <returns></returns>
        private bool IsFileExistWithRequestedTime(String fileFullName, String remoteTime)
        {
            bool isFileExist = HandleFiles.isExists(fileFullName);

            try
            {
                if (isFileExist && remoteTime != null)
                {
                    String localTime = HandleFiles.getFileTime(fileFullName);
                    if (!HandleFiles.equals(localTime, remoteTime))
                    {
                        isFileExist = false;
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Instance.WriteExceptionToLog(exception.Message);
                throw;
            }

            return(isFileExist);
        }
Ejemplo n.º 15
0
        /// <summary> Creates (on the disk) the executable used the launch the application after
        /// the current executable exits
        /// </summary>
        /// <returns> path to the newly created executable </returns>
        private static string CreateRCSpawnerAssembly()
        {
            String asmName = getSpawnerAssemblyPath();

            if (HandleFiles.isExists(asmName))
            {
                HandleFiles.deleteFile(asmName);
            }

            // Get the assmbly code from the resource
            Byte[] asmBuf;
#if PocketPC
            asmBuf = RichClient.Properties.Resources.MgxpaRIAMobile_spawner;
#else
            asmBuf = RichClient.Properties.Resources.MgxpaRIA_spawner;
#endif

            // Write the assembly code to the file
            BinaryWriter bw = new BinaryWriter(File.Open(asmName, FileMode.Create));
            bw.Write(asmBuf);
            bw.Close();

            return(asmName);
        }
Ejemplo n.º 16
0
        /// <summary>convert the file path on the server's file system or the url to the file name in the client's cached folder.</summary>
        /// <param name="serverFilename">a file name in the Server's file system.</param>
        /// <param name="task"></param>
        /// <param name="refreshClientCopy"></param>
        /// <returns>file name in the local file system.</returns>
        internal override string GetLocalFileName(string serverFilename, Task task, bool refreshClientCopy)
        {
            string localFileName = String.Empty;

            if (!String.IsNullOrEmpty(serverFilename))
            {
                if (Misc.isWebURL(serverFilename, ClientManager.Instance.getEnvironment().ForwardSlashUsage))
                {
                    localFileName = CacheUtils.URLToLocalFileName(serverFilename);
                }
                else
                {
                    localFileName = CacheUtils.ServerFileToLocalFileName(serverFilename);
                }

                if (!HandleFiles.isExists(localFileName))
                {
                    localFileName = String.Empty;
                    //TODO: Kaushal. Raise InAccessibleServer event.
                }
            }

            return(localFileName);
        }
Ejemplo n.º 17
0
        private String _cacheFolder; //absolute path of the cache folder

        /// <summary>
        /// Save 'content' into the cache folder, identified by 'url', and set the file's time to 'remote Time'.
        /// </summary>
        /// <param name="url">URL to a cached file, excluding the server-side time stamp, e.g. /MG1VAI3T_MP_0$$$_$_$_N02400$$$$G8FM01_.xml.</param>
        /// <param name="content">content to save for future access to the url.</param>
        /// <param name="remoteTime">modification time of the file on the server-side (for story#138618: remote time will be null).</param>
        public void PutFile(String url, byte[] content, String remoteTime)
        {
            lock (this)
            {
                try
                {
                    String localFilename = URLToLocalFileName(url);
                    bool   success       = HandleFiles.writeToFile(HandleFiles.getFile(localFilename), content, false, true, ClientManager.Instance.GetWriteClientCacheMaxRetryTime());
                    if (!success)
                    {
                        throw (new CacheManagerException(string.Format("Failed to save the file {0} in cache directory. Check log for details", localFilename)));
                    }
                    if (remoteTime != null)
                    {
                        HandleFiles.setFileTime(localFilename, remoteTime);
                    }
                }
                catch (Exception e)
                {
                    Misc.WriteStackTrace(e, Console.Error);
                    throw (e);
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary> Read numbers from file, convert to/from our format and write to output file
        /// </summary>
        /// <param name="fileName"></param>
        internal static void EncodeDecode(String[] args, NumUtilOperation operation)
        {
            String errorMsg = null;

            // Output file
            String fileName;

            if (operation == NumUtilOperation.ENCODE)
            {
                fileName = args[0].Substring(ClientManager.ENCODE.Length);
            }
            else
            {
                fileName = args[0].Substring(ClientManager.DECODE.Length);
            }

            System.IO.StreamWriter output = null;
            try
            {
                output = new System.IO.StreamWriter(fileName + ".out");
            }
            catch (Exception e)
            {
                errorMsg = e.Message;
            }

            // attribute, picture
            StorageAttribute attr = StorageAttribute.NUMERIC;
            String           pic  = null;

            for (int i = 1; i < args.Length; i++)
            {
                if (args[i].StartsWith("/Attribute=", StringComparison.OrdinalIgnoreCase))
                {
                    attr = (StorageAttribute)args[i].Substring(args[i].IndexOf('=') + 1).Trim()[0];
                }
                else if (args[i].StartsWith("/Picture=", StringComparison.OrdinalIgnoreCase))
                {
                    pic = args[i].Substring(args[i].IndexOf('=') + 1);
                }
            }
            if (pic == null)
            {
                switch (attr)
                {
                case StorageAttribute.NUMERIC:
                    pic = "N18.2";
                    break;

                case StorageAttribute.DATE:
                    pic = "DD/MM/YY";
                    break;

                case StorageAttribute.TIME:
                    pic = "HH:MM:SS";
                    break;
                }
            }

            // Input
            String numbers = HandleFiles.readToString(fileName);

            if (output != null && !String.IsNullOrEmpty(numbers))
            {
                string[] parsed = numbers.Split(new[] { ',' });
                String   result = null;

                ClientManager.Instance.getEnvironment().setSignificantNumSize(10);
                ClientManager.Instance.getEnvironment().setDecimalSeparator('.');
                ClientManager.Instance.getEnvironment().setDateSeparator('/');
                ClientManager.Instance.getEnvironment().setTimeSeparator(':');

                foreach (String numStr in parsed)
                {
                    if (numStr.Length == 0)
                    {
                        continue;
                    }
                    switch (operation)
                    {
                    case NumUtilOperation.ENCODE:
                        result = Encode(numStr.Trim(), attr, pic);
                        break;

                    case NumUtilOperation.DECODE:
                        result = Decode(numStr.Trim(), attr, pic);
                        break;
                    }

                    output.Write(result + ",");
                }

                output.Close();
            }
            else
            {
                if (String.IsNullOrEmpty(errorMsg))
                {
                    if (operation == NumUtilOperation.ENCODE)
                    {
                        errorMsg = "MgxpaRIA.exe /NumericEncode=file-name (comma-delimited plain values) [/Attribute=<...>] [/Picture=<...>]";
                    }
                    else
                    {
                        errorMsg = "MgxpaRIA.exe /NumericDecode=file-name (comma-delimited encoded values) [/Attribute=<...>] [/Picture=<...>]";
                    }
                }

                // This function is used only when RC is run for automatic testing. There are no GUI/worker thread,
                // but a single simple thread, so there should be no problem to use GUI calls here
                System.Windows.Forms.MessageBox.Show(errorMsg, "Error:");
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Clear status
 /// </summary>
 public void Clear()
 {
     TablesIncompatibleWithDataSources = false;
     InvalidSources = false;
     HandleFiles.deleteFile(StatusFileName);
 }
Ejemplo n.º 20
0
        /// <summary>
        /// commit modified sources to cache.
        /// </summary>
        internal void Commit()
        {
            Logger.Instance.WriteSupportToLog("Commit():>>>> ", true);

            bool success = true;

            // It is about to start committing the sources. So save the status. If process get terminated during commit,
            // in next execution, client will get to know the status of sources synchronization and take action accordingly.
            SourcesSyncStatus.InvalidSources = true;
            SourcesSyncStatus.SaveToFile();

            // Renames the temporary sources to original names.
            foreach (String url in _commitList)
            {
                String tempFileName               = BuildTemporarySourceFileName(GetFileNameFromURL(url));
                String tempSourceFileFullName     = PersistentOnlyCacheManager.GetInstance().URLToLocalFileName(tempFileName);
                String originalSourceFileFullName = PersistentOnlyCacheManager.GetInstance().URLToLocalFileName(GetFileNameFromURL(url));
                String remoteTime = GetRemoteTime(url);

                // check if source with remotetime exist
                if (IsFileExistWithRequestedTime(tempSourceFileFullName, remoteTime))
                {
                    Logger.Instance.WriteSupportToLog(String.Format("commit(): renaming {0}", tempFileName), true);

                    success = HandleFiles.renameFile(tempSourceFileFullName, originalSourceFileFullName);
                    if (!success)
                    {
                        break;
                    }

                    if (remoteTime != null)
                    {
                        HandleFiles.setFileTime(originalSourceFileFullName, remoteTime);
                    }

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

            if (!success)
            {
                String errorMessage;

                // sources commit failed
                // If tables were converted and committed, there structure won't match the sources
                if (SourcesSyncStatus.TablesIncompatibleWithDataSources == true)
                {
                    errorMessage = ClientManager.Instance.getMessageString(MsgInterface.RC_ERROR_INCOMPATIBLE_DATASOURCES);
                }
                else
                {
                    errorMessage = ClientManager.Instance.getMessageString(MsgInterface.RC_ERROR_INVALID_SOURCES);
                }

                throw new InvalidSourcesException(errorMessage, null);
            }

            // Commit is done successfully, clear the status.
            SourcesSyncStatus.Clear();

            Logger.Instance.WriteSupportToLog("Commit():<<<< ", true);
        }