public IFileInfo GetFileInfo(string path)
        {
            var dirPath  = Path.GetDirectoryName(path);
            var fileName = Path.GetFileName(path);
            var dir      = GetDirectoryInfo(dirPath);
            var file     = dir.GetFiles().FirstOrDefault(item => string.Equals(fileName, item.Name, StringComparison.OrdinalIgnoreCase));

            if (file == null)
            {
                if (path.StartsWith("sdata:\\attachments", StringComparison.OrdinalIgnoreCase))
                {
                    var attachment = new Attachment {
                        FileName = fileName
                    };
                    file = new AttachmentFileInfo(_client, _formMode, dir, attachment);
                }
                else
                {
                    var document = new LibraryDocument
                    {
                        FileName  = fileName,
                        Directory = new SDataResource {
                            Key = ((LibraryDirectory)((IResourceHolder)dir).Resource).Key
                        }
                    };
                    file = new LibraryFileInfo(_client, _formMode, dir, document);
                }
            }

            return(file);
        }
 public LibraryFileInfo(ISDataClient client, bool formMode, IDirectoryInfo directory, LibraryDocument document)
     : base(directory)
 {
     _client   = client;
     _formMode = formMode;
     _document = document;
 }
        public string GetNodeTitle(string id)
        {
            var query = from nedNodeElements in LibraryDocument.Descendants(NedNodeTag)
                        where (string)nedNodeElements.Attribute(NedNodeIdAttribute) == id
                        select new { NodeTitle = (string)nedNodeElements.Element(TitleTag) };

            return(query.First().NodeTitle);
        }
        public override void Save(Stream stream)
        {
            if (stream == null)
            {
                _document = string.IsNullOrEmpty(_document.Key)
                    ? _client.Post(_document)
                    : _client.Put(_document);
                return;
            }

            var parms = new SDataParameters
            {
                Files = { new AttachedFile(null, _document.FileName, stream) }
            };

            if (string.IsNullOrEmpty(_document.Key))
            {
                parms.Method = HttpMethod.Post;
                parms.Path   = "libraryDocuments";
            }
            else
            {
                parms.Method = HttpMethod.Put;
                parms.Path   = "libraryDocuments(" + SDataUri.FormatConstant(_document.Key) + ")";
                parms.ETag   = _document.ETag;
            }

            if (_formMode)
            {
                foreach (var prop in typeof(LibraryDocument).GetProperties())
                {
                    var name = _client.NamingScheme.GetName(prop);
                    if (!name.StartsWith("$", StringComparison.Ordinal) && !new[] { "createDate", "createUser", "modifyDate", "modifyUser" }.Contains(name, StringComparer.Ordinal))
                    {
                        var value = prop.GetValue(_document, null);
                        if (value != null)
                        {
                            parms.Form[name] = value.ToString();
                        }
                    }
                }

                parms.Path += "/file";
                var results = _client.Execute(parms);
                if (!string.IsNullOrEmpty(results.Location))
                {
                    var selector = new SDataUri(results.Location).GetPathSegment(4).Selector;
                    _document.Key  = selector.Substring(1, selector.Length - 2);
                    _document.ETag = results.ETag;
                }
            }
            else
            {
                parms.Content = _document;
                _document     = _client.Execute <LibraryDocument>(parms).Content;
            }
        }
 public IEnumerable <MediaItemsListModelItem> GetAllMediaItemsUnderId(string id)
 {
     return
         (from mediaItem in MediaItems
          where (
              from rootNode in LibraryDocument.Descendants(NedNodeTag)
              where rootNode.Attribute(NedNodeIdAttribute).Value == id
              from mediaNode in rootNode.Descendants(NedNodeTag)
              let childType = mediaNode.Attribute(NedNodeTypeAttribute).Value
                              where childType != CategoryTagType && childType != CatalogueTagType && childType != LibraryTagType
                              select mediaNode.Attribute(NedNodeIdAttribute).Value
              ).Contains(mediaItem.Id)
          select mediaItem);
 }
        public void DeleteItem(LibraryModelItem item)
        {
            XElement node =
                (from nedNodeElements in LibraryDocument.Descendants(NedNodeTag)
                 where (string)nedNodeElements.Attribute(NedNodeIdAttribute) == item.Id
                 select nedNodeElements).FirstOrDefault();

            if (node != null)
            {
                node.Remove();
            }

            if (item is CatalogueModelItem)
            {
                CatalogueItems.Remove(item as CatalogueModelItem);
                var query = from categoriesToRemove in CategoryItems where categoriesToRemove.ParentId == item.Id select categoriesToRemove;
                List <CategoryModelItem> catTempList = query.ToList <CategoryModelItem>();
                foreach (LibraryModelItem itemToRemove in catTempList)
                {
                    DeleteItem(itemToRemove);
                }
            }
            else if (item is CategoryModelItem)
            {
                CategoryItems.Remove(item as CategoryModelItem);
                foreach (LibraryModelItem miToRemove in (item as CategoryModelItem).Children())
                {
                    DeleteItem(miToRemove);
                }
            }
            else if (item is MediaItemsListModelItem)
            {
                MediaItemsListModelItem mediaItem = item as MediaItemsListModelItem;
                MediaItems.Remove(mediaItem);
                App.Engine.DeleteMediaItem(mediaItem);
            }
            else
            {
                Debug.Assert(false, FileLanguage.LibraryModel_RemovingUnknowTypeError);
            }
            App.Engine.StatisticsManager.LogItemDeleted(item.Id);
            OnLibraryItemRemoved(new LibraryRemovedEventArgs()
            {
                RemovedItem = item
            });
        }
        public LibraryLevel GetNodeType(string id)
        {
            var query = from nedNodeElements in LibraryDocument.Descendants(NedNodeTag)
                        where (string)nedNodeElements.Attribute(NedNodeIdAttribute) == id
                        select new { NodeType = (string)nedNodeElements.Attribute(NedNodeTypeAttribute) };

            switch (query.First().NodeType)
            {
            case LibraryTagType:
                return(LibraryLevel.Catalogue);

            case CatalogueTagType:
                return(LibraryLevel.Category);

            case CategoryTagType:
                return(LibraryLevel.MediaItemsList);

            default:
                return(LibraryLevel.Unknown);
            }
        }
    public HttpResponseMessage Get(int id, string module)
    {
        LibraryDocument rec          = db.LibraryDocuments.Find(id);;
        string          documentPath = WebConfigurationManager.AppSettings["DocumentPath"] + "/";
        UploadResult    res          = new UploadResult();

        if (rec != null)
        {
            res.fileName         = rec.OriginalImageName;
            res.fileInternalName = rec.UniqueImageName;
            res.fileType         = rec.ImageType;
            res.fileId           = rec.Id;
            res.filePath         = documentPath + module + "/";
            res.filesubModule    = rec.SubModule;
            res.filesubModuleId  = rec.SubModuleId;
            return(Request.CreateResponse(HttpStatusCode.OK, res));
        }
        else
        {
            return(Request.CreateResponse(HttpStatusCode.NotFound));
        }
    }
 public override void Refresh()
 {
     _document = _client.Get <LibraryDocument>(_document.Key);
 }
    public async Task <HttpResponseMessage> Post(string module, int moduleId, string subModule, int subModuleId)
    {
        if (String.IsNullOrEmpty(module) || String.IsNullOrEmpty(subModule) ||
            String.IsNullOrEmpty(moduleId.ToString()) || String.IsNullOrEmpty(subModuleId.ToString()))
        {
            return(Request.CreateResponse(HttpStatusCode.BadRequest, "Required parameter module/moduleId/subModule/subModuleId missing!"));
        }

        if (!Request.Content.IsMimeMultipartContent())
        {
            return(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "The request doesn't contain valid content!"));
        }

        List <UploadResult> result = new List <UploadResult>();
        string documentPath        = WebConfigurationManager.AppSettings["DocumentPath"] + "/";

        try
        {
            string fileSaveLocation = WebConfigurationManager.AppSettings["LibraryPath"] + "/" + module;
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);

            try
            {
                // Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (MultipartFileData file in provider.FileData)
                {
                    String fileName       = file.Headers.ContentDisposition.Name;
                    String uniqueFileName = file.Headers.ContentDisposition.FileName;
                    String fileExt        = uniqueFileName.Substring(uniqueFileName.LastIndexOf(".")).ToUpper();
                    String mediaType      = file.Headers.ContentType.MediaType;

                    LibraryDocument newdoc = new LibraryDocument();
                    newdoc.Module            = module;
                    newdoc.ModuleId          = moduleId;
                    newdoc.SubModule         = subModule;
                    newdoc.SubModuleId       = subModuleId;
                    newdoc.OriginalImageName = fileName;
                    newdoc.UniqueImageName   = uniqueFileName;
                    newdoc.UploadDate        = DateTime.Now;
                    if (fileExt == ".JPG" || fileExt == ".JPEG" || fileExt == ".PNG" || fileExt == ".GIF" ||
                        fileExt == ".TIF" || fileExt == ".BMP" || fileExt == ".WMF" || fileExt == ".ICO")
                    {
                        newdoc.ImageType = "IMAGE";
                    }
                    if (fileExt == ".PDF")
                    {
                        newdoc.ImageType = "PDF";
                    }
                    if (fileExt == ".DOC" || fileExt == ".DOCX")
                    {
                        newdoc.ImageType = "WORD";
                    }
                    if (fileExt == ".XLS" || fileExt == ".XLSX")
                    {
                        newdoc.ImageType = "EXCEL";
                    }
                    if (fileExt == ".PPT" || fileExt == ".PPTX")
                    {
                        newdoc.ImageType = "POWERPOINT";
                    }
                    if (fileExt == ".TXT")
                    {
                        newdoc.ImageType = "TEXT";
                    }
                    if (fileExt == ".HTML")
                    {
                        newdoc.ImageType = "HTML";
                    }

                    newdoc.UploadedBy = "";
                    newdoc.Remarks    = mediaType;
                    newdoc.UploadedBy = User.Identity.Name;

                    db.LibraryDocuments.Add(newdoc);

                    try
                    {
                        db.SaveChanges();

                        UploadResult res = new UploadResult();
                        res.fileName         = newdoc.OriginalImageName;
                        res.fileId           = newdoc.Id;
                        res.fileInternalName = newdoc.UniqueImageName;
                        res.fileType         = newdoc.ImageType;
                        res.filePath         = documentPath + module + "/";
                        res.filesubModule    = newdoc.SubModule;
                        res.filesubModuleId  = newdoc.SubModuleId;
                        result.Add(res);
                    }
                    catch
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotImplemented, "Files not saved. Upload again!"));
                    }
                }

                // Send OK Response along with saved file names to the client.
                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }
            catch (System.Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
        catch (Exception e)
        {
            return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message));
        }
    }
 private void SaveLibrary()
 {
     Library.SaveLibraryContents(LibraryDocument.ToString(), ActiveLibrary, App.Engine.LoggedUser);
 }
        // Load library and return it's id
        public string LoadLibrary(Library library)
        {
            ActiveLibrary = library;

            LibraryDocument          = Library.GetLibraryContents(ActiveLibrary, App.Engine.LoggedUser);
            LibraryDocument.Changed += OnLibraryDocumentChanged;

            ChangedContent = Library.GetChangedContent(ActiveLibrary, App.Engine.LoggedUser);

            LibraryId = LibraryDocument.Root.Attribute(NedNodeIdAttribute).Value;

            var mediaItemsQuery =
                from nedNodeElements in LibraryDocument.Descendants(NedNodeTag)
                from nedNodeChildren in nedNodeElements.Element(NedNodeChildrenTag).Elements()
                where (string)nedNodeElements.Attribute(NedNodeTypeAttribute) == CategoryTagType
                select new MediaItemsListModelItem()
            {
                Id            = nedNodeChildren.Attribute(NedNodeIdAttribute).Value,
                LibraryId     = this.LibraryId,
                ParentId      = nedNodeElements.Attribute(NedNodeIdAttribute).Value,
                Title         = nedNodeChildren.Element(TitleTag).Value,
                FileName      = nedNodeChildren.Attribute(NedNodeDataAttribute) != null?nedNodeChildren.Attribute(NedNodeDataAttribute).Value : String.Empty,
                ItemType      = MediaItemsListModelItem.GetTypeFromString(nedNodeChildren.Attribute(NedNodeTypeAttribute).Value),
                Description   = nedNodeChildren.Element(NedNodeDescriptionTag) != null?nedNodeChildren.Element(NedNodeDescriptionTag).Value : String.Empty,
                ExternalLinks = (from linkElement in nedNodeChildren.Elements(NedNodeLinkTag) select linkElement.Value).ToList(),
                Keywords      = (from keywordElement in nedNodeChildren.Elements(NedNodeKeywordTag) select keywordElement.Value).ToList(),
                IsChanged     = ChangedContent != null ? (from changedElements in ChangedContent.Root.Descendants(NedNodeTag)
                                                              where changedElements.Attribute(NedNodeIdAttribute).Value == nedNodeChildren.Attribute(NedNodeIdAttribute).Value
                                                          select changedElements).Count() > 0 : false
            };
            ObservableCollection <MediaItemsListModelItem> AllMediaItemsTemp = new ObservableCollection <MediaItemsListModelItem>();

            foreach (MediaItemsListModelItem item in mediaItemsQuery)
            { // To avoid multiple observers notifications on initialization
                AllMediaItemsTemp.Add(item);
            }
            MediaItems = AllMediaItemsTemp;

            var categoryItemsQuery =
                from nedNodeElements in LibraryDocument.Descendants(NedNodeTag)
                from nedNodeChildren in nedNodeElements.Element(NedNodeChildrenTag).Elements()
                where (string)nedNodeElements.Attribute(NedNodeTypeAttribute) == CatalogueTagType
                select new CategoryModelItem()
            {
                Id        = nedNodeChildren.Attribute(NedNodeIdAttribute).Value,
                ParentId  = nedNodeElements.Attribute(NedNodeIdAttribute).Value,
                Title     = nedNodeChildren.Element(TitleTag).Value,
                IsChanged = ChangedContent != null ? (from changedElements in ChangedContent.Root.Descendants(NedNodeTag)
                                                      where changedElements.Attribute(NedNodeIdAttribute).Value == nedNodeChildren.Attribute(NedNodeIdAttribute).Value
                                                      select changedElements).Count() > 0 : false
            };
            ObservableCollection <CategoryModelItem> AllCategoryItemsTemp = new ObservableCollection <CategoryModelItem>();

            foreach (CategoryModelItem item in categoryItemsQuery)
            { // To avoid multiple observers notifications on initialization
                AllCategoryItemsTemp.Add(item);
            }
            CategoryItems = AllCategoryItemsTemp;
            foreach (CategoryModelItem catItem in CategoryItems)
            {
                catItem.AddChildren((from catChild in MediaItems where catChild.ParentId == catItem.Id select catChild).ToList());
            }

            var catalogueItemsQuery =
                from nedNodeElements in LibraryDocument.Descendants(NedNodeTag)
                from nedNodeChildren in nedNodeElements.Element(NedNodeChildrenTag).Elements()
                where (string)nedNodeElements.Attribute(NedNodeTypeAttribute) == LibraryTagType
                select new CatalogueModelItem()
            {
                Id        = nedNodeChildren.Attribute(NedNodeIdAttribute).Value,
                ParentId  = nedNodeElements.Attribute(NedNodeIdAttribute).Value,
                Title     = nedNodeChildren.Element(TitleTag).Value,
                Subtitle  = CatalogueModelItem.GetSubtitleString(nedNodeChildren.Element(NedNodeChildrenTag).Elements().Count <XElement>()),
                IsChanged = ChangedContent != null ? (from changedElements in ChangedContent.Root.Descendants(NedNodeTag)
                                                      where changedElements.Attribute(NedNodeIdAttribute).Value == nedNodeChildren.Attribute(NedNodeIdAttribute).Value
                                                      select changedElements).Count() > 0 : false
            };
            ObservableCollection <CatalogueModelItem> CatalogueItemsTemp = new ObservableCollection <CatalogueModelItem>();

            foreach (CatalogueModelItem item in catalogueItemsQuery)
            { // To avoid multiple observers notifications on initialization
                CatalogueItemsTemp.Add(item);
            }
            CatalogueItems = CatalogueItemsTemp;
            CatalogueItems.CollectionChanged += OnCatalogueItemsPropertyChanged;

            LibraryName = LibraryDocument.Root.Element(TitleTag).Value;
            UpdateMediaItemsDownloadedStatus();

            return(LibraryId);
        }