Beispiel #1
0
        public string GetUserListDownloadUrl()
        {
            //Aggregate the current data into one csv file
            ICentralizedFileStorageProvider fs = CentralizedFileStorage.GetFileStore(Constants.FILESTOREKEY);

            if (fs != null)
            {
                var header = fs.GetFile("", _headerFileName);

                if (header != null)
                {
                    StringBuilder fileBuffer = new StringBuilder();

                    using (StreamReader sr = new StreamReader(header.OpenReadStream()))
                    {
                        fileBuffer.AppendLine(sr.ReadToEnd());
                    }

                    //Build a new csv file
                    foreach (var response in fs.GetFiles(_responsesFolder, PathSearchOption.AllPaths))
                    {
                        using (StreamReader sr = new StreamReader(response.OpenReadStream()))
                        {
                            fileBuffer.Append(sr.ReadToEnd());
                        }
                    }

                    return(WriteFileToCfs(fileBuffer, "", "userlist.csv").GetDownloadUrl());
                }
            }

            return(null);
        }
Beispiel #2
0
        public bool SaveDetails(string email, IDictionary additionalFields)
        {
            //To prevent conflicts each repsonse is added to a single file and then aggregated when downloaded
            ICentralizedFileStorageProvider fs = CentralizedFileStorage.GetFileStore(Constants.FILESTOREKEY);

            if (fs != null)
            {
                var header = fs.GetFile("", _headerFileName);

                if (header == null)
                {
                    StringBuilder headerBuffer = new StringBuilder();
                    //Add in the headers
                    headerBuffer.AppendLine(string.Join(",", EnumerateFieldsIntoList(additionalFields, (dictionary, field) => field).Concat(new [] { "email" }).Select(Csv.Escape)));

                    WriteFileToCfs(headerBuffer, "", _headerFileName);
                }

                StringBuilder responseBuffer = new StringBuilder();

                responseBuffer.AppendLine(string.Join(",", EnumerateFieldsIntoList(additionalFields, (dictionary, field) => dictionary[field].ToString()).Concat(new [] { email }).Select(Csv.Escape)));

                WriteFileToCfs(responseBuffer, _responsesFolder, Guid.NewGuid().ToString());

                return(true);
            }

            return(false);
        }
Beispiel #3
0
        /// <summary>
        /// Initialises a new file system watcher.
        /// </summary>
        /// <param name="fileStoreKey">The CFS file store key.</param>
        /// <param name="changeAction">The change action.</param>
        /// <param name="path">The file store sub-path.</param>
        void InitialiseFileSystemWatcher(string fileStoreKey, Action changeAction, string path = null)
        {
            ICentralizedFileStorageProvider fileStore = CentralizedFileStorage.GetFileStore(fileStoreKey);

            if (fileStore is FileSystemFileStorageProvider)
            {
                string basePath      = GetBasePath(fileStoreKey);
                string fileStorePath = Path.Combine(Globals.CalculateFileSystemStorageLocation(basePath), fileStoreKey);

                if (!String.IsNullOrEmpty(path))
                {
                    fileStorePath = Path.Combine(fileStorePath, path);
                }

                if (!String.IsNullOrEmpty(fileStorePath) && Directory.Exists(fileStorePath))
                {
                    // Create a new EnableFileSystemWatcher and set it to watch for changes in LastAccess and LastWrite times.
                    FileSystemWatcher watcher = new FileSystemWatcher
                    {
                        IncludeSubdirectories = true,
                        Path         = fileStorePath,
                        NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                    };

                    // Add event handlers.
                    watcher.Changed            += OnChanged;
                    watcher.EnableRaisingEvents = true;

                    _pathWatchers.Add(fileStoreKey, watcher);
                    _pathActions.Add(fileStorePath, changeAction);
                }
            }
        }
Beispiel #4
0
        internal void GenerateHostVersionedSourceMaps()
        {
            ICentralizedFileStorageProvider fileStore = CentralizedFileStorage.GetFileStore(Constants.ThemeFiles);
            string stylesheetPath = string.Format(@"s.fd.{0}.{1}", _siteThemeName, Constants.ThemeStylesheetFiles);
            var    files          = fileStore.GetFiles(stylesheetPath, PathSearchOption.TopLevelPathOnly);

            // Update source maps
            foreach (ICentralizedFile file in files.Where(f => f.FileName.EndsWith(".css")))
            {
                UpsertSourceMap(file.FileName, file.FileStoreKey, file.Path);
            }
        }
Beispiel #5
0
        private ICentralizedFile WriteFileToCfs(StringBuilder buffer, string path, string filename)
        {
            ICentralizedFileStorageProvider fs = CentralizedFileStorage.GetFileStore(Constants.FILESTOREKEY);

            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter wr = new StreamWriter(ms))
                {
                    wr.Write(buffer);
                    wr.Flush();

                    ms.Seek(0, SeekOrigin.Begin);

                    return(fs.AddUpdateFile(path, filename, ms));
                }
            }
        }
Beispiel #6
0
        private AppData GetOrExtractAppData(ICentralizedFile sourceFile, ICentralizedFileStorageProvider targetFileStore, string targetPath)
        {
            var appDataFile = targetFileStore.GetFile(targetPath, "appdata");

            if (appDataFile != null)
            {
                using (Stream appDataStream = appDataFile.OpenReadStream())
                {
                    byte[] data = new byte[appDataStream.Length];
                    appDataStream.Read(data, 0, data.Length);
                    var qs = System.Web.HttpUtility.ParseQueryString(Encoding.UTF8.GetString(data));

                    return(new AppData {
                        Name = qs["name"] ?? sourceFile.FileName,
                        ApplicationId = qs["appid"] ?? string.Empty,
                        Image = string.IsNullOrEmpty(qs["image"]) ? null : targetFileStore.GetFile(targetPath, qs["image"]),
                        IsDirectlyInstallable = string.IsNullOrEmpty(qs["installable"]) || qs["installable"] == "true",
                        AppType = (AppType)Enum.Parse(typeof(AppType), qs["apptype"] ?? "Unknown", true),
                        File = sourceFile
                    });
                }
            }

            AppData appData = new AppData();

            appData.File    = sourceFile;
            appData.AppType = AppType.Unknown;
            appData.IsDirectlyInstallable = false;

            using (var inStream = sourceFile.OpenReadStream())
            {
                using (var archive = new ZipArchive(inStream, ZipArchiveMode.Read, false))
                {
                    var imageEntry = GetImageEntry(archive, ImageSearchPaths);
                    if (imageEntry != null)
                    {
                        using (var imageStream = imageEntry.Open())
                        {
                            byte[] data = new byte[imageEntry.Length];
                            imageStream.Read(data, 0, data.Length);
                            using (var tempStream = new MemoryStream(data))
                            {
                                tempStream.Seek(0, SeekOrigin.Begin);
                                appData.Image = targetFileStore.AddUpdateFile(targetPath, "icon.png", tempStream);
                            }
                        }
                    }

                    if (string.Compare(Path.GetExtension(sourceFile.FileName), ".apk", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        appData.AppType = AppType.Android;
                        appData.IsDirectlyInstallable = true;
                    }
                    else if (string.Compare(Path.GetExtension(sourceFile.FileName), ".ipa", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        appData.AppType = AppType.iOS;
                        appData.IsDirectlyInstallable = false;

                        var iTunesEntry = archive.GetEntry(@"iTunesMetadata.plist");
                        if (iTunesEntry != null)
                        {
                            using (var iTunesStream = iTunesEntry.Open())
                            {
                                byte[] data = new byte[iTunesEntry.Length];
                                iTunesStream.Read(data, 0, data.Length);
                                using (var tempStream = new MemoryStream(data))
                                {
                                    tempStream.Seek(0, SeekOrigin.Begin);

                                    var    iTunesData = (Dictionary <string, object>)PlistCS.Plist.readPlist(tempStream, PlistCS.plistType.Auto);
                                    object d;
                                    if (iTunesData.TryGetValue("softwareVersionBundleId", out d))
                                    {
                                        appData.ApplicationId = d.ToString();
                                    }

                                    if (iTunesData.TryGetValue("playlistName", out d))
                                    {
                                        appData.Name = d.ToString();
                                    }
                                }
                            }
                        }
                        else
                        {
                            // this is not packaged for iTunes, check the Payload for developer/enterprise-deployment details
                            foreach (var entry in archive.Entries.Where(x => x.FullName.StartsWith(@"Payload/", StringComparison.OrdinalIgnoreCase) && x.FullName.EndsWith(@"/Info.plist", StringComparison.OrdinalIgnoreCase)))
                            {
                                var appFolder = entry.FullName.Substring(8, entry.FullName.Length - 19);
                                if (!appFolder.Contains(@"/"))
                                {
                                    using (var plistStream = entry.Open())
                                    {
                                        byte[] data = new byte[entry.Length];
                                        plistStream.Read(data, 0, data.Length);
                                        using (var tempStream = new MemoryStream(data))
                                        {
                                            tempStream.Seek(0, SeekOrigin.Begin);

                                            var    plistData = (Dictionary <string, object>)PlistCS.Plist.readPlist(tempStream, PlistCS.plistType.Auto);
                                            object d;
                                            if (plistData.TryGetValue("CFBundleIdentifier", out d))
                                            {
                                                appData.ApplicationId = d.ToString();
                                            }

                                            if (plistData.TryGetValue("CFBundleName", out d))
                                            {
                                                appData.Name = d.ToString();
                                            }
                                        }
                                    }

                                    imageEntry = GetImageEntry(archive, new string[] {
                                        string.Concat(@"Payload/", appFolder, @"/icon-320.png"),
                                        string.Concat(@"Payload/", appFolder, @"/[email protected]"),
                                        string.Concat(@"Payload/", appFolder, @"/[email protected]"),
                                        string.Concat(@"Payload/", appFolder, @"/[email protected]"),
                                        string.Concat(@"Payload/", appFolder, @"/[email protected]"),
                                        string.Concat(@"Payload/", appFolder, @"/icon.png")
                                    });

                                    if (imageEntry != null)
                                    {
                                        using (var imageStream = imageEntry.Open())
                                        {
                                            byte[] data = new byte[imageEntry.Length];
                                            imageStream.Read(data, 0, data.Length);
                                            using (var tempStream = new MemoryStream(data))
                                            {
                                                tempStream.Seek(0, SeekOrigin.Begin);
                                                using (var uncrushedStream = new MemoryStream())
                                                {
                                                    PNGDecrush.PNGDecrusher.Decrush(tempStream, uncrushedStream);
                                                    uncrushedStream.Seek(0, SeekOrigin.Begin);
                                                    appData.Image = targetFileStore.AddUpdateFile(targetPath, "icon.png", uncrushedStream);
                                                }
                                            }
                                        }
                                    }

                                    var provisionEntry = archive.GetEntry(string.Concat(@"Payload/", appFolder, @"/embedded.mobileprovision"));
                                    if (provisionEntry != null)
                                    {
                                        appData.IsDirectlyInstallable = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(appData.Name))
            {
                appData.Name = sourceFile.FileName.Substring(0, sourceFile.FileName.LastIndexOf('.'));
            }

            if (appData.ApplicationId == null)
            {
                appData.ApplicationId = "";
            }

            StringBuilder qstr = new StringBuilder();

            qstr.Append("name=");
            qstr.Append(Uri.EscapeDataString(appData.Name));
            qstr.Append("&appid=");
            qstr.Append(Uri.EscapeDataString(appData.ApplicationId));
            qstr.Append("&image=");
            qstr.Append(appData.Image == null ? "" : Uri.EscapeDataString(appData.Image.FileName));
            qstr.Append("&installable=");
            qstr.Append(appData.IsDirectlyInstallable ? "true" : "false");
            qstr.Append("&apptype=");
            qstr.Append(Uri.EscapeDataString(appData.AppType.ToString()));

            using (var appDataStream = new MemoryStream(Encoding.UTF8.GetBytes(qstr.ToString())))
            {
                appDataStream.Seek(0, SeekOrigin.Begin);
                targetFileStore.AddUpdateFile(targetPath, "appdata", appDataStream);
            }

            return(appData);
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="lastInstalledVersion"></param>
        public void Install(Version lastInstalledVersion)
        {
            //TODO:Code clean-up
            Uninstall();

            try
            {
                string root = RootFsPath;

                if (root != null)
                {
                    string filename;

                    XmlDocument doc = LoadOverrideDocument(root, out filename);

                    const string overrideString = @"
                                          <Override  xpath=""/CommunityServer/Core/editors/editor[@name='Enhanced']"" mode=""remove"" product=""FourRoads.TelligentCommunity.CustomEditor"" />
                                          <Override xpath=""/CommunityServer/Core/editors"" mode=""add"" product=""FourRoads.TelligentCommunity.CustomEditor"">
                                            <editor name=""Enhanced"" type=""FourRoads.TelligentCommunity.CustomEditor.EditorWrapper, FourRoads.TelligentCommunity.CustomEditor"" default=""true"" resourceName=""EditorType_Enhanced_Name"">
                                              <editorOption name=""imageUpload"" value=""/customeditor.ashx""/>
                                            </editor>
                                          </Override>";

                    var docFragment = doc.CreateDocumentFragment();
                    docFragment.InnerXml = overrideString;

                    XmlNode node = doc.SelectSingleNode("Overrides");

                    if (node != null)
                    {
                        // ReSharper disable once PossibleNullReferenceException
                        foreach (XmlNode nodeAdd in docFragment.SelectNodes("/Override"))
                        {
                            node.AppendChild(nodeAdd);
                        }
                    }

                    doc.Save(filename);
                }

                //Add the default files into the filestore
                string basePath = FourroadsTelligentcommunityCustomeditorResources + ".JavascriptFiles.";

                ICentralizedFileStorageProvider fileStore = CustomEditorFileStore.GetFileStoreProvider();

                foreach (string resourceName in _resourceNames.Where(r => r.StartsWith(basePath)))
                {
                    // ReSharper disable once PossibleNullReferenceException
                    fileStore.AddFile("", Path.GetFileName(resourceName).Replace(basePath, ""), EmbeddedResources.GetStream(resourceName), false);
                }

                //Install CSS into theme's
                UpdateThemeCss(EmbeddedResources.GetString(FourroadsTelligentcommunityCustomeditorResources + ".redactor.css"));
            }
            catch (Exception ex)
            {
                new Telligent.Evolution.Components.CSException(Telligent.Evolution.Components.CSExceptionType.UnknownError, "Failed to install Custom Editor", ex).Log();
            }

            HttpRuntime.UnloadAppDomain();
        }
Beispiel #8
0
        private void UpsertSourceMap(string fileName, string fileStoreKey, string path)
        {
            const string propertyName = Constants.ThemeStylesheetFiles;

            // Test if modified file is a stylesheet
            if (fileName.EndsWith(".css") && fileStoreKey == Constants.ThemeFiles && path.EndsWith(propertyName))
            {
                ICentralizedFileStorageProvider fileStore = CentralizedFileStorage.GetFileStore(fileStoreKey);
                string mapName = string.Concat(fileName, ".map");

                if (fileStore != null)
                {
                    ICentralizedFile mapFile = fileStore.GetFile(path, mapName);

                    // Check if source map exists
                    if (mapFile != null)
                    {
                        string writePath = GetSanitisedPath(_siteThemeTypeId, _themeContextId, _siteThemeName,
                                                            propertyName, new Uri(Globals.FullPath("~/")));

                        if (CentralizedFileStorage.GetFileStore(Constants.ThemeFiles).GetFile(writePath, mapName) == null)
                        {
                            lock (_lock)
                            {
                                if (CentralizedFileStorage.GetFileStore(Constants.ThemeFiles).GetFile(writePath, mapName) ==
                                    null)
                                {
                                    using (DistributedMonitor distributedMonitor = new DistributedMonitor())
                                    {
                                        const int limit = 5;

                                        for (int i = 0; i < limit; i++)
                                        {
                                            using (
                                                DistributedLock distributedLock =
                                                    distributedMonitor.Enter(Constants.DistributedMonitorKey))
                                            {
                                                if (distributedLock.IsOwner)
                                                {
                                                    if (
                                                        CentralizedFileStorage.GetFileStore(Constants.ThemeFiles)
                                                        .GetFile(writePath, mapName) ==
                                                        null)
                                                    {
                                                        byte[] array;

                                                        using (Stream stream = mapFile.OpenReadStream())
                                                        {
                                                            array = new byte[stream.Length];
                                                            stream.Read(array, 0, array.Length);
                                                            stream.Close();
                                                        }

                                                        string text = Encoding.UTF8.GetString(array);

                                                        // Modify paths
                                                        text = text.Replace("../",
                                                                            string.Format("{0}/cfs-file/__key/themefiles/s-fd-{1}-",
                                                                                          CSContext.Current.ApplicationPath, _siteThemeName));
                                                        array = Encoding.UTF8.GetBytes(text);
                                                        CentralizedFileStorage.GetFileStore(Constants.ThemeFiles)
                                                        .AddUpdateFile(writePath, mapName, new MemoryStream(array));
                                                    }
                                                    break;
                                                }
                                                distributedMonitor.Wait(distributedLock, 5);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }