public static bool SaveRazorLayoutTbb(MappingInfo mapping, string title, string code, string tcmContainer, out string stackTraceMessage)
        {
            stackTraceMessage = "";

            if (!EnsureValidClient(mapping))
                return false;

            if (ExistsItem(mapping, tcmContainer, title))
            {
                string id = GetItemTcmId(mapping, tcmContainer, title);
                if (String.IsNullOrEmpty(id))
                    return false;

                return SaveRazorLayoutTbb(mapping, id, code, out stackTraceMessage);
            }

            try
            {
                TemplateBuildingBlockData tbbData = new TemplateBuildingBlockData
                {
                    Content = code,
                    Title = title,
                    LocationInfo = new LocationInfo { OrganizationalItem = new LinkToOrganizationalItemData { IdRef = tcmContainer } },
                    Id = "tcm:0-0-0",
                    TemplateType = "RazorTemplate"
                };

                tbbData = Client.Save(tbbData, new ReadOptions()) as TemplateBuildingBlockData;
                if (tbbData == null)
                    return false;

                Client.CheckIn(tbbData.Id, new ReadOptions());
                return true;
            }
            catch (Exception ex)
            {
                stackTraceMessage = ex.Message;
                return false;
            }
        }
        public static ComponentData GetComponent(MappingInfo mapping, string id)
        {
            if (String.IsNullOrEmpty(id))
                return null;

            if (!EnsureValidClient(mapping))
                return null;

            ComponentData component = ReadItem(mapping, id) as ComponentData;
            if (component == null)
                return null;

            if (component.BluePrintInfo.IsShared == true)
            {
                id = GetBluePrintTopTcmId(mapping, id);
                component = ReadItem(mapping, id) as ComponentData;
            }

            return component;
        }
        public static List<ItemInfo> GetComponents(MappingInfo mapping, string tcmSchema)
        {
            if (!EnsureValidClient(mapping))
                return null;

            return Client.GetListXml(tcmSchema, new UsingItemsFilterData { ItemTypes = new[] { ItemType.Component } }).ToList(ItemType.Component);
        }
        public static void FillNamedPath(this TridionFolderInfo tridionFolder, MappingInfo mapping)
        {
            if (tridionFolder == null || !String.IsNullOrEmpty(tridionFolder.NamedPath) || tridionFolder.TcmIdPath == null)
                return;

            List<string> names = new List<string>();
            foreach (string currTcmId in tridionFolder.TcmIdPath)
            {
                var item = ReadItem(mapping, currTcmId);
                if (item != null)
                    names.Add(item.Title);
            }
            names.Reverse();
            tridionFolder.NamedPath = string.Join("/", names);
        }
        public static BinaryContentData GetBinaryData(MappingInfo mapping, string filePath)
        {
            EnsureValidStreamUploadClient(mapping);

            string title = Path.GetFileName(filePath);

            string tempLocation;
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                tempLocation = StreamUploadClient.UploadBinaryContent(title, fs);
            }
            if (String.IsNullOrEmpty(tempLocation))
                return null;

            BinaryContentData binaryContent = new BinaryContentData();
            binaryContent.UploadFromFile = tempLocation;
            binaryContent.Filename = title;
            binaryContent.MultimediaType = new LinkToMultimediaTypeData { IdRef = GetMimeTypeId(mapping, filePath) };

            return binaryContent;
        }
        public static bool EnsureValidClient(MappingInfo mapping)
        {
            if (Client == null || Client is SessionAwareCoreServiceClient && ((SessionAwareCoreServiceClient)Client).InnerChannel.State == CommunicationState.Faulted)
            {
                if (ClientBindingType == BindingType.HttpBinding)
                    Client = GetHttpClient(mapping.Host, mapping.Username, mapping.Password);
                else
                    Client = GetTcpClient(mapping.Host, mapping.Username, mapping.Password);

                try
                {
                    var publications = Client.GetSystemWideListXml(new PublicationsFilterData());
                }
                catch (Exception ex)
                {
                    WriteErrorLog("Not able to connect to TCM. Check your credentials and try again", ex.StackTrace);
                    Client = null;
                    return false;
                }
            }
            return true;
        }
        public static List<ItemInfo> Expand(this List<ItemInfo> list, MappingInfo mapping, TridionSelectorMode tridionSelectorMode, List<string> tcmIdPath, string selectedTcmId)
        {
            if (tcmIdPath == null || String.IsNullOrEmpty(selectedTcmId))
                return list;

            foreach (ItemInfo item in list)
            {
                if (tcmIdPath.Any(x => x == item.TcmId))
                {
                    item.IsExpanded = true;
                    item.IsSelected = item.TcmId == selectedTcmId;

                    if (item.IsSelected)
                        continue;

                    if (String.IsNullOrEmpty(item.TcmId))
                        continue;

                    item.ChildItems = null;
                    if (item.ItemType == ItemType.Publication)
                    {
                        if (tridionSelectorMode == TridionSelectorMode.Folder)
                        {
                            item.ChildItems = GetFoldersByPublication(mapping, item.TcmId);
                        }
                        if (tridionSelectorMode == TridionSelectorMode.StructureGroup)
                        {
                            item.ChildItems = GetStructureGroupsByPublication(mapping, item.TcmId);
                        }
                        if (tridionSelectorMode == TridionSelectorMode.FolderAndStructureGroup)
                        {
                            item.ChildItems = GetFoldersAndStructureGroupsByPublication(mapping, item.TcmId);
                        }
                    }
                    if (item.ItemType == ItemType.Folder)
                    {
                        item.ChildItems = GetFoldersByParentFolder(mapping, item.TcmId);
                    }
                    if (item.ItemType == ItemType.StructureGroup)
                    {
                        item.ChildItems = GetStructureGroupsByParentStructureGroup(mapping, item.TcmId);
                    }

                    if (item.ChildItems != null && item.ChildItems.Count > 0)
                    {
                        item.ChildItems.SetParent(item);
                    }

                    if (item.ChildItems != null && item.ChildItems.Count > 0)
                    {
                        item.ChildItems.Expand(mapping, tridionSelectorMode, tcmIdPath, selectedTcmId);
                    }
                }
                else
                {
                    item.ChildItems = new List<ItemInfo> { new ItemInfo { Title = "Loading..." } };
                }
            }
            return list;
        }
        public static void UnLocalizeAll(MappingInfo mapping, string id)
        {
            if (!EnsureValidClient(mapping))
                return;

            UnLocalizeAll(id);
        }
        private static bool DeleteTridionObject(MappingInfo mapping, string tcmItem, string parentTcmId, bool currentVersion, out string stackTraceMessage)
        {
            stackTraceMessage = "";

            if (tcmItem.StartsWith("tcm:0-"))
                return false;

            if (!EnsureValidClient(mapping))
                return false;

            tcmItem = GetBluePrintTopTcmId(mapping, tcmItem);

            bool isAnyLocalized = IsAnyLocalized(tcmItem);

            List<string> usingItems = GetUsingItems(tcmItem);
            List<string> usingCurrentItems = GetUsingCurrentItems(tcmItem);

            if (currentVersion)
            {
                foreach (string usingItem in usingItems)
                {
                    LinkStatus status = RemoveDependency(mapping, usingItem, tcmItem);
                    if (status == LinkStatus.Error)
                    {
                        return false;
                    }
                    if (status != LinkStatus.Found)
                    {
                        DeleteTridionObject(mapping, usingItem, tcmItem, usingCurrentItems.Any(x => x == usingItem), out stackTraceMessage);
                    }
                }
            }

            try
            {
                if (!currentVersion)
                {
                    //remove used versions
                    LinkStatus status = RemoveHistory(tcmItem, parentTcmId, out stackTraceMessage);
                    if (status == LinkStatus.Error)
                        return false;
                }
                else
                {
                    //unlocalize before delete
                    if (isAnyLocalized)
                    {
                        UnLocalizeAll(tcmItem);
                    }

                    //undo checkout
                    try
                    {
                        Client.UndoCheckOut(tcmItem, true, new ReadOptions());
                    }
                    catch (Exception)
                    {
                    }

                    //delete used item
                    Client.Delete(tcmItem);
                }
            }
            catch (Exception ex)
            {
                stackTraceMessage = ex.Message;
                return false;
            }

            return true;
        }
 public static bool TestConnection(MappingInfo mapping)
 {
     using (TcpClient tcpScan = new TcpClient())
     {
         try
         {
             tcpScan.Connect(mapping.Host, 80);
             return true;
         }
         catch (Exception ex)
         {
             WriteErrorLog("Connecting failed", ex.StackTrace);
             return false;
         }
     }
 }
        public static bool CreateStructureGroup(MappingInfo mapping, string title, string tcmContainer)
        {
            if (!EnsureValidClient(mapping))
                return false;

            try
            {
                StructureGroupData sgData = new StructureGroupData
                {
                    Title = title,
                    Directory = title,
                    LocationInfo = new LocationInfo { OrganizationalItem = new LinkToOrganizationalItemData { IdRef = tcmContainer } },
                    Id = "tcm:0-0-0"
                };

                sgData = Client.Save(sgData, new ReadOptions()) as StructureGroupData;
                if (sgData == null)
                    return false;

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public static void SyncRazorLayoutTbb(MappingInfo mapping, string tcmContainer, ProjectFileInfo file, ProjectFolderRole role, string serverTimeZoneId)
        {
            string path = file.FullPath;
            if (String.IsNullOrEmpty(path))
                return;

            if (!File.Exists(path))
            {
                //remove non-existing file from mapping
                foreach (ProjectFolderInfo folder in mapping.ProjectFolders)
                {
                    DeleteFileFromMapping(folder, path);
                }
                return;
            }

            IncludeProjectItem(path);

            string title;
            if (String.IsNullOrEmpty(file.Title))
            {
                title = Path.GetFileNameWithoutExtension(path);
                file.Title = title;
            }
            else
            {
                title = file.Title;
            }

            string id;
            if (String.IsNullOrEmpty(file.TcmId))
            {
                id = GetItemTcmId(mapping, tcmContainer, title);
                file.TcmId = id;
            }
            else
            {
                id = file.TcmId;
            }

            string fileContent = TransformRazor2Mediator(File.ReadAllText(path));

            bool updated = false;

            if (String.IsNullOrEmpty(id))
            {
                TridionDestinationDialogWindow dialog = new TridionDestinationDialogWindow();
                dialog.Mapping = mapping;
                dialog.FilterItemTcmId = tcmContainer;
                dialog.PublicationTcmId = GetPublicationTcmId(tcmContainer);
                dialog.LayoutTitle = title;
                dialog.TemplateTitle = String.IsNullOrEmpty(file.TemplateTitle) ? title : file.TemplateTitle;
                bool res = dialog.ShowDialog() == true;
                if (res)
                {
                    file.Title = dialog.LayoutTitle;
                    file.TemplateTitle = dialog.TemplateTitle;
                    tcmContainer = GetBluePrintItemTcmId(tcmContainer, dialog.PublicationTcmId);
                    string stackTraceMessage;
                    updated = SaveRazorLayoutTbb(mapping, file.Title, fileContent, tcmContainer, out stackTraceMessage);
                    if (updated)
                    {
                        id = GetItemTcmId(mapping, tcmContainer, file.Title);
                        if (String.IsNullOrEmpty(id))
                        {
                            WriteErrorLog(file.Path + " - Item is broken after updating");
                            return;
                        }
                        file.TcmId = id;
                    }
                    else
                    {
                        WriteErrorLog(file.Path + " - Creating failed", stackTraceMessage);
                        return;
                    }
                }
            }

            TemplateBuildingBlockData item = ReadItem(mapping, id) as TemplateBuildingBlockData;

            if (item == null || item.VersionInfo.RevisionDate == null)
            {
                WriteErrorLog(string.Format("Item {0} does not exist", id));
                return;
            }

            FileInfo fi = new FileInfo(path);
            DateTime fileDate = fi.LastWriteTime;
            DateTime tridionDate = (DateTime) item.VersionInfo.RevisionDate;
            DateTime tridionLocalDate = tridionDate.GetLocalTime(serverTimeZoneId);

            if (updated)
            {
                File.SetAttributes(path, FileAttributes.Normal);
                File.SetLastWriteTime(path, tridionLocalDate);
                WriteSuccessLog(file.Path + " - Saved to Tridion CM successfully");
                return;
            }

            if (fileDate == tridionLocalDate)
                return;

            string tridionContent = item.Content;
            file.Title = item.Title;

            if (Equals(fileContent, tridionContent))
            {
                File.SetAttributes(path, FileAttributes.Normal);
                File.SetLastWriteTime(path, tridionLocalDate);
                WriteSuccessLog(file.Path + " - Date of project item is updated to " + tridionLocalDate);
            }
            else
            {
                string user = item.VersionInfo is FullVersionInfo && ((FullVersionInfo)item.VersionInfo).Revisor != null ? ((FullVersionInfo)item.VersionInfo).Revisor.Title : "Unknown";

                DiffDialogWindow dialog = new DiffDialogWindow();
                if (fileDate > tridionLocalDate)
                {
                    dialog.StartItemInfo = string.Format("Tridion Item: {0} ({1}), {2}, {3}", item.Title, item.Id, tridionLocalDate, user);
                    dialog.EndItemInfo = string.Format("VS File: {0}, {1}", Path.GetFileName(path), fileDate);
                    dialog.StartItemText = tridionContent;
                    dialog.EndItemText = fileContent;
                    dialog.SyncState = SyncState.VS2Tridion;
                    dialog.Tridion2VSEnabled = true;
                    dialog.VS2TridionEnabled = !IsCheckedOut(mapping, item.Id);
                }
                else
                {
                    dialog.StartItemInfo = string.Format("VS File: {0}, {1}", Path.GetFileName(path), fileDate);
                    dialog.EndItemInfo = string.Format("Tridion Item: {0} ({1}), {2}, {3}", item.Title, item.Id, tridionLocalDate, user);
                    dialog.StartItemText = fileContent;
                    dialog.EndItemText = tridionContent;
                    dialog.SyncState = SyncState.Tridion2VS;
                    dialog.Tridion2VSEnabled = true;
                    dialog.VS2TridionEnabled = true;
                }

                bool res = dialog.ShowDialog() == true;
                if (res)
                {
                    if (dialog.SyncState == SyncState.VS2Tridion)
                    {
                        string stackTraceMessage;
                        updated = SaveRazorLayoutTbb(mapping, id, fileContent, out stackTraceMessage);
                        if (updated)
                        {
                            item = ReadItem(mapping, id) as TemplateBuildingBlockData;
                            if (item == null || item.VersionInfo.RevisionDate == null)
                            {
                                WriteErrorLog(string.Format("Item {0} does not exist", id));
                            }
                            else
                            {
                                tridionDate = (DateTime)item.VersionInfo.RevisionDate;
                                tridionLocalDate = tridionDate.GetLocalTime(serverTimeZoneId);
                                File.SetAttributes(path, FileAttributes.Normal);
                                File.SetLastWriteTime(path, tridionLocalDate);
                                WriteSuccessLog(file.Path + " - Saved to Tridion CM successfully");
                            }
                        }
                        else
                        {
                            WriteErrorLog(file.Path + " - Updating failed", stackTraceMessage);
                        }
                    }
                    else if (dialog.SyncState == SyncState.Tridion2VS)
                    {
                        SaveVSItem(path, tridionContent);
                        File.SetAttributes(path, FileAttributes.Normal);
                        File.SetLastWriteTime(path, tridionLocalDate);
                        WriteSuccessLog(file.Path + " - Saved to Visual Studio successfully");
                    }
                }
            }
        }
        public static string CreateFolderChain(MappingInfo mapping, string folderPath, string tcmContainer)
        {
            if(String.IsNullOrEmpty(folderPath))
                return tcmContainer;

            if (String.IsNullOrEmpty(tcmContainer))
                return tcmContainer;

            string[] chain = folderPath.Trim('\\').Split('\\');
            if(chain.Length == 0)
                return tcmContainer;

            string topFolder = chain[0];
            List<ItemInfo> items = GetFoldersByParentFolder(mapping, tcmContainer);
            if (items.All(x => x.Title != topFolder))
            {
                CreateFolder(mapping, topFolder, tcmContainer);
                items = GetFoldersByParentFolder(mapping, tcmContainer);
            }

            string tcmTopFolder = items.First(x => x.Title == topFolder).TcmId;

            return CreateFolderChain(mapping, string.Join("\\", chain.Skip(1)), tcmTopFolder);
        }
        public static void SyncMultimedia(MappingInfo mapping, ProjectFileInfo file, string tcmContainer, string serverTimeZoneId)
        {
            string path = file.FullPath;

            if (!File.Exists(path))
            {
                //remove non-existing file from mapping
                foreach (ProjectFolderInfo folder in mapping.ProjectFolders)
                {
                    DeleteFileFromMapping(folder, path);
                }
                return;
            }

            IncludeProjectItem(path);

            string title;
            if (String.IsNullOrEmpty(file.Title))
            {
                title = Path.GetFileNameWithoutExtension(path);
                file.Title = title;
            }
            else
            {
                title = file.Title;
            }

            string id;
            if (String.IsNullOrEmpty(file.TcmId))
            {
                id = GetItemTcmId(mapping, tcmContainer, title);
                if (String.IsNullOrEmpty(id))
                    id = GetItemTcmId(mapping, tcmContainer, Path.GetFileNameWithoutExtension(path));
                if (String.IsNullOrEmpty(id))
                    id = GetItemTcmId(mapping, tcmContainer, Path.GetFileName(path));

                file.TcmId = id;
            }
            else
            {
                id = file.TcmId;
            }

            if (!File.Exists(path) && String.IsNullOrEmpty(id))
                return;

            bool updated = false;

            if (File.Exists(path) && String.IsNullOrEmpty(id))
            {
                TridionDestinationDialogWindow dialog = new TridionDestinationDialogWindow();
                dialog.Mapping = mapping;
                dialog.FilterItemTcmId = tcmContainer;
                dialog.PublicationTcmId = GetPublicationTcmId(tcmContainer);
                dialog.LayoutTitle = title;
                bool res = dialog.ShowDialog() == true;
                if (res)
                {
                    file.Title = dialog.LayoutTitle;
                    tcmContainer = GetBluePrintItemTcmId(tcmContainer, dialog.PublicationTcmId);
                    string stackTraceMessage;
                    updated = SaveMultimediaComponentFromBinary(mapping, path, file.Title, tcmContainer, out stackTraceMessage);
                    if (updated)
                    {
                        id = GetItemTcmId(mapping, tcmContainer, Path.GetFileName(path));
                        if (String.IsNullOrEmpty(id))
                            id = GetItemTcmId(mapping, tcmContainer, Path.GetFileNameWithoutExtension(path));

                        if (String.IsNullOrEmpty(id))
                        {
                            WriteErrorLog(file.Path + " - Item is broken after updating");
                            return;
                        }
                        file.TcmId = id;
                    }
                    else
                    {
                        WriteErrorLog(path + " - Creating failed", stackTraceMessage);
                        return;
                    }
                }
            }

            ComponentData item = ReadItem(mapping, id) as ComponentData;

            if (item == null || item.VersionInfo.RevisionDate == null)
            {
                WriteErrorLog(string.Format("Item {0} does not exist", id));
                return;
            }

            FileInfo fi = new FileInfo(path);
            DateTime fileDate = fi.LastWriteTime;
            DateTime tridionDate = (DateTime)item.VersionInfo.RevisionDate;
            DateTime tridionLocalDate = tridionDate.GetLocalTime(serverTimeZoneId);

            if (updated)
            {
                File.SetAttributes(path, FileAttributes.Normal);
                File.SetLastWriteTime(path, tridionLocalDate);
                WriteSuccessLog(path + " - Saved to Tridion CM successfully");
                return;
            }

            if (fileDate == tridionLocalDate)
            {
                return;
            }

            file.Title = item.Title;

            if (fi.Length == item.BinaryContent.FileSize)
            {
                File.SetAttributes(path, FileAttributes.Normal);
                File.SetLastWriteTime(path, tridionLocalDate);
                WriteSuccessLog(path + " - Saved to Tridion CM successfully");
            }
            else
            {
                BinaryDiffDialogWindow dialog = new BinaryDiffDialogWindow();
                if (fileDate > tridionLocalDate)
                {
                    dialog.StartItemInfo = string.Format("Tridion Item: {0} ({1}), {2}", item.Title, item.Id, tridionLocalDate);
                    dialog.EndItemInfo = string.Format("VS File: {0}, {1}", Path.GetFileName(path), fileDate);
                    dialog.SyncState = SyncState.VS2Tridion;
                    dialog.Tridion2VSEnabled = true;
                    dialog.VS2TridionEnabled = !IsCheckedOut(mapping, item.Id);
                }
                else
                {
                    dialog.StartItemInfo = string.Format("VS File: {0}, {1}", Path.GetFileName(path), fileDate);
                    dialog.EndItemInfo = string.Format("Tridion Item: {0} ({1}), {2}", item.Title, item.Id, tridionLocalDate);
                    dialog.SyncState = SyncState.Tridion2VS;
                    dialog.Tridion2VSEnabled = true;
                    dialog.VS2TridionEnabled = true;
                }

                bool res = dialog.ShowDialog() == true;
                if (res)
                {
                    if (dialog.SyncState == SyncState.VS2Tridion)
                    {
                        string stackTraceMessage;
                        updated = SaveMultimediaComponentFromBinary(mapping, id, path, out stackTraceMessage);
                        if (updated)
                        {
                            item = ReadItem(mapping, id) as ComponentData;
                            if (item == null || item.VersionInfo.RevisionDate == null)
                            {
                                WriteErrorLog(string.Format("Item {0} does not exist", id));
                            }
                            else
                            {
                                tridionDate = (DateTime)item.VersionInfo.RevisionDate;
                                tridionLocalDate = tridionDate.GetLocalTime(serverTimeZoneId);
                                File.SetAttributes(path, FileAttributes.Normal);
                                File.SetLastWriteTime(path, tridionLocalDate);
                                WriteSuccessLog(path + " - Saved to Tridion CM successfully");
                            }
                        }
                        else
                        {
                            WriteErrorLog(path + " - Updating failed", stackTraceMessage);
                        }
                    }
                    else if (dialog.SyncState == SyncState.Tridion2VS)
                    {
                        SaveVSBinaryItem(mapping, id, path);
                        File.SetAttributes(path, FileAttributes.Normal);
                        File.SetLastWriteTime(path, tridionLocalDate);
                        WriteSuccessLog(path + " - Saved to Visual Studio successfully");
                    }
                }
            }
        }
        private static LinkStatus RemoveTbbFromPageTemplate(MappingInfo mapping, string tcmPageTemplate, string tcmTbb, out string stackTraceMessage)
        {
            stackTraceMessage = "";

            PageTemplateData pageTemplate = ReadItem(mapping, tcmPageTemplate) as PageTemplateData;
            if (pageTemplate == null)
                return LinkStatus.NotFound;

            List<TbbInfo> tbbList = GetTbbList(pageTemplate.Content);
            if (tbbList.Any(x => x.TcmId.Split('-')[1] == tcmTbb.Split('-')[1]))
            {
                if (tbbList.Count == 1)
                    return LinkStatus.Mandatory;
            }
            else
            {
                return LinkStatus.NotFound;
            }

            string newContent = RemoveTbbFromTemplate(pageTemplate.Content, tcmTbb);

            if (pageTemplate.BluePrintInfo.IsShared == true)
            {
                tcmPageTemplate = GetBluePrintTopTcmId(tcmPageTemplate);

                pageTemplate = ReadItem(mapping, tcmPageTemplate) as PageTemplateData;
                if (pageTemplate == null)
                    return LinkStatus.NotFound;
            }

            try
            {
                pageTemplate = Client.CheckOut(pageTemplate.Id, true, new ReadOptions()) as PageTemplateData;
            }
            catch (Exception ex)
            {
                stackTraceMessage = ex.Message;
                return LinkStatus.NotFound;
            }

            if (pageTemplate == null)
                return LinkStatus.NotFound;

            pageTemplate.Content = newContent;

            try
            {
                pageTemplate = Client.Update(pageTemplate, new ReadOptions()) as PageTemplateData;
                if (pageTemplate == null)
                    return LinkStatus.NotFound;

                Client.CheckIn(pageTemplate.Id, new ReadOptions());
                return LinkStatus.Found;
            }
            catch (Exception ex)
            {
                stackTraceMessage = ex.Message;

                if (pageTemplate == null)
                    return LinkStatus.Error;

                Client.UndoCheckOut(pageTemplate.Id, true, new ReadOptions());
                return LinkStatus.Error;
            }
        }
 private static void EnsureCredentialsNotEmpty(MappingInfo mapping)
 {
     if (String.IsNullOrEmpty(mapping.Username) || String.IsNullOrEmpty(mapping.Password))
     {
         if (String.IsNullOrEmpty(mapping.Username) || String.IsNullOrEmpty(mapping.Password))
         {
             PasswordDialogWindow dialog = new PasswordDialogWindow();
             dialog.Mapping = mapping;
             bool res = dialog.ShowDialog() == true;
             if (res)
             {
                 if (CredentialsChanged != null)
                 {
                     CredentialsChanged();
                 }
             }
         }
     }
 }
        private static void SaveVSBinaryItem(MappingInfo mapping, string id, string path)
        {
            string directory = Path.GetDirectoryName(path);
            if (!String.IsNullOrEmpty(directory))
            {
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                    ProjectItem dir = Project.ProjectItems.AddFromDirectory(directory);
                    Marshal.ReleaseComObject(dir);
                }
            }

            SaveBinaryFromMultimediaComponent(mapping, id, directory);

            IncludeProjectItem(path);
        }
 private static void EnsureValidStreamUploadClient(MappingInfo mapping)
 {
     if (StreamUploadClient == null || StreamUploadClient.InnerChannel.State == CommunicationState.Faulted)
     {
         StreamUploadClient = GetStreamUploadClient(mapping);
     }
 }
        public static bool ExistsItem(MappingInfo mapping, string tcmContainer, string itemTitle)
        {
            if (String.IsNullOrEmpty(tcmContainer))
                return false;

            if (!EnsureValidClient(mapping))
                return false;

            OrganizationalItemItemsFilterData filter = new OrganizationalItemItemsFilterData();
            return Client.GetList(tcmContainer, filter).Any(x => x.Title == itemTitle);
        }
        private static string GetContainerTcmId(MappingInfo mapping, TridionRole tridionRole, ProjectFolderInfo folder, string path)
        {
            if (folder != null && !String.IsNullOrEmpty(folder.TcmId))
                return folder.TcmId;

            if (mapping.TridionFolders.Any(x => x.TridionRole == tridionRole))
            {
                if (mapping.TridionFolders.Count(x => x.TridionRole == tridionRole) == 1)
                {
                    string tcm = mapping.TridionFolders.First(x => x.TridionRole == tridionRole).TcmId;
                    if (folder != null)
                        folder.TcmId = tcm;
                    return tcm;
                }

                SelectTridionFolderDialogWindow dialog = new SelectTridionFolderDialogWindow();
                dialog.Path = path;
                dialog.TridionFolders = mapping.TridionFolders.Where(x => x.TridionRole == tridionRole).ToList().FillNamedPath(mapping);
                bool res = dialog.ShowDialog() == true;
                if (res)
                {
                    return dialog.SelectedTridionFolder.TcmId;
                }
            }

            return String.Empty;
        }
 public static List<TridionFolderInfo> FillNamedPath(this List<TridionFolderInfo> list, MappingInfo mapping)
 {
     foreach (TridionFolderInfo folder in list)
     {
         folder.FillNamedPath(mapping);
     }
     return list;
 }
 private static string GetContainerTcmId(MappingInfo mapping, TridionRole tridionRole, string path)
 {
     return GetContainerTcmId(mapping, tridionRole, null, path);
 }
        public static List<ItemInfo> FindCheckedOutItems(MappingInfo mapping)
        {
            if (!EnsureValidClient(mapping))
                return null;

            return Client.GetSystemWideListXml(new RepositoryLocalObjectsFilterData()).ToList();
        }
 private static string GetContainerTcmId(MappingInfo mapping, TridionRole tridionRole, ProjectFolderInfo folder)
 {
     if(folder == null)
         return String.Empty;
     return GetContainerTcmId(mapping, tridionRole, folder, folder.Path);
 }
        public static string GetBluePrintTopTcmId(MappingInfo mapping, string id)
        {
            if (!EnsureValidClient(mapping))
                return String.Empty;

            return GetBluePrintTopTcmId(id);
        }
 private static string GetContainerTcmId(MappingInfo mapping, TridionRole tridionRole, ProjectFileInfo file)
 {
     ProjectFolderInfo folder = GetTopFolder(file);
     return GetContainerTcmId(mapping, tridionRole, folder, file.Path);
 }
        public static List<XElement> GetComponentHistory(MappingInfo mapping, string tcmId)
        {
            if (!EnsureValidClient(mapping))
                return null;

            VersionsFilterData versionsFilter = new VersionsFilterData();
            XElement listOfVersions = Client.GetListXml(tcmId, versionsFilter);
            return listOfVersions.Descendants().ToList();
        }
        private static LinkStatus RemoveDependency(MappingInfo mapping, string tcmItem, string tcmDependentItem)
        {
            ItemType itemType = GetItemType(tcmItem);
            ItemType dependentItemType = GetItemType(tcmDependentItem);
            LinkStatus status = LinkStatus.NotFound;
            string stackTraceMessage = "";

            //remove TBB from page template
            if (itemType == ItemType.PageTemplate && dependentItemType == ItemType.TemplateBuildingBlock)
            {
                status = RemoveTbbFromPageTemplate(mapping, tcmItem, tcmDependentItem, out stackTraceMessage);
            }

            //remove TBB from component template
            if (itemType == ItemType.ComponentTemplate && dependentItemType == ItemType.TemplateBuildingBlock)
            {
                status = RemoveTbbFromComponentTemplate(mapping, tcmItem, tcmDependentItem, out stackTraceMessage);
            }

            if (status == LinkStatus.Found)
            {
                status = RemoveHistory(tcmItem, tcmDependentItem, out stackTraceMessage);
            }

            if (status == LinkStatus.Error)
            {
                WriteErrorLog(string.Format("Not able to unlink \"{1}\" from \"{0}\"", tcmItem, tcmDependentItem), stackTraceMessage);
            }

            return status;
        }
        public static MappingInfo GetDefaultMapping(string rootPath, string name)
        {
            MappingInfo mapping = new MappingInfo();
            mapping.Name = name;
            mapping.Host = "localhost";
            mapping.Username = "";
            mapping.Password = "";

            mapping.TridionFolders = new List<TridionFolderInfo>();
            mapping.TridionFolders.Add(new TridionFolderInfo { TridionRole = TridionRole.PageLayoutContainer, ScanForItems = true});
            mapping.TridionFolders.Add(new TridionFolderInfo { TridionRole = TridionRole.ComponentLayoutContainer, ScanForItems = true });
            mapping.TridionFolders.Add(new TridionFolderInfo { TridionRole = TridionRole.PageTemplateContainer });
            mapping.TridionFolders.Add(new TridionFolderInfo { TridionRole = TridionRole.ComponentTemplateContainer });

            mapping.ProjectFolders = new List<ProjectFolderInfo>();
            mapping.ProjectFolders.Add(new ProjectFolderInfo
            {
                ProjectFolderRole = TridionVSRazorExtension.ProjectFolderRole.PageLayout,
                Checked = true,
                RootPath = rootPath,
                Path = "Views\\PageLayouts",
                TemplateFormat =
                    "<CompoundTemplate xmlns=\"http://www.tridion.com/ContentManager/5.3/CompoundTemplate\"><TemplateInvocation><Template xlink:href=\"{0}\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:title=\"{1}\" /><TemplateParameters></TemplateParameters></TemplateInvocation></CompoundTemplate>",
                SyncTemplate = true
            });
            mapping.ProjectFolders.Add(new ProjectFolderInfo
            {
                ProjectFolderRole = TridionVSRazorExtension.ProjectFolderRole.ComponentLayout,
                Checked = true,
                RootPath = rootPath,
                Path = "Views\\ComponentLayouts",
                TemplateFormat =
                    "<CompoundTemplate xmlns=\"http://www.tridion.com/ContentManager/5.3/CompoundTemplate\"><TemplateInvocation><Template xlink:href=\"{0}\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:title=\"{1}\" /><TemplateParameters></TemplateParameters></TemplateInvocation></CompoundTemplate>",
                SyncTemplate = true
            });
            return mapping;
        }
        public static bool CreateFolder(MappingInfo mapping, string title, string tcmContainer)
        {
            if (!EnsureValidClient(mapping))
                return false;

            try
            {
                FolderData folderData = new FolderData
                {
                    Title = title,
                    LocationInfo = new LocationInfo { OrganizationalItem = new LinkToOrganizationalItemData { IdRef = tcmContainer } },
                    Id = "tcm:0-0-0"
                };

                folderData = Client.Save(folderData, new ReadOptions()) as FolderData;
                if (folderData == null)
                    return false;

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }