Exemplo n.º 1
0
        public static LibraryData AddBaseLib(LibraryData oldLib)
        {
            LibraryData lb = new LibraryData();

            FileInfo precompFile = new FileInfo("Base.LibraryData");

            if (!precompFile.Exists)
            {
                MessageBox.Show("Unable to load baselibrary. Base.LibraryData File not found.");
                return(oldLib);
            }

            IFormatter formatter = new BinaryFormatter();
            Stream     stream    = precompFile.OpenRead();

            try
            {
                lb.Join((LibraryData)formatter.Deserialize(stream));
                lb.JoinNew(oldLib);
                stream.Close();
            }
            catch (Exception err)
            {
                stream.Close();

                MessageBox.Show("Error parsing library.");
                return(oldLib);
            }

            return(lb);
        }
Exemplo n.º 2
0
        public MainViewModel()
        {
            if (Application.Current != null)
            {
                Application.Current.Exit += (sender, args) =>
                {
                    //close connections
                    DisconnectAllUnists();

                    //save speaker library
                    SpeakerMethods.SaveSpeakerlib();

                    //save project settings
                    Properties.Settings.Default.Save();
                }
            }
            ;
            _recentFilesLogic = new RecentFilesLogic(this);

            Thread dispThread = Thread.CurrentThread;

            Dispatcher.FromThread(dispThread);


            _tabs.Add(_comViewModel);


#if DEBUG
            if (IsInDesignMode)
            {
                LibraryData.CreateEmptySystem();
            }
            Open(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\d.esc");
#endif
        }
Exemplo n.º 3
0
        //Функция, которая имеет тип структуры LibraryData (это значит, что данные, которая она возратит будет с той структурой,
        //которую мы создали ранее. Эта функция считает с файла данные и подготовит ее в той структуре, которая нам нужна.
        static public LibraryData WriteFile(string path)                 //в скобочках указано значение, которое будет передаваться в эту функцию извне
        {
            LibraryData data = new LibraryData();                        //Экземпляр нашей основной структуры

            data.Books = new Book[10];                                   //Указываем число книг (например 10). На самом деле это неправильно, ибо мы не знаем сколько у нас книг в файле. Для этого хорошо бы юзать List<> (список), там длину массива указывать не требуется, но со структурами это хз как выглядеть будет.

            int i = 0;                                                   //Объявляем счетчик итераций (численный тип). Он нам будет помогать считать какая итерация массива сейчас идет.

            StreamReader rdr = new StreamReader(path, Encoding.Default); //Открываем файл в режиме чтения (поток чтения) в нужной кодировке по пути, который передали

            string[] primaryInfo = rdr.ReadLine().Split('|');            // Для начала считываем название библиотеки и имя владельца библиотеки
            data.Name  = primaryInfo[0];                                 //И заносим их в экземпляр структуры
            data.Owner = primaryInfo[1];

            while (!rdr.EndOfStream) //Объявляем цикл и пробежимся по всему файла до конца (грубо говоря: ПОКА (НЕ КОНЧИТСЯ ФАЙЛ))
            {
                //Данный код будет выполняться при чтении каждой строки в файле
                string   tempStr = rdr.ReadLine();     //Читаем строку и заносим ее в специальную переменную, где она будет храниться во время данной итерации
                string[] tempArr = tempStr.Split('|'); //Разбиваем эту строку по сепаратору (разделителю) '|', делаем из этого массив подстрок

                //Теперь заносим полученную и уже разделенную строку в наш массив структур
                data.Books[i].Writer       = tempArr[0].ToString();
                data.Books[i].Title        = tempArr[1].ToString();
                data.Books[i].PubHouse     = tempArr[2].ToString();
                data.Books[i].Year         = Convert.ToInt32(tempArr[3]); //Т.к. в структуре год - числовой тип, а в файле - строка, то принудительно конвертируем строку в числовой тип
                data.Books[i].StoragePlace = tempArr[4].ToString();

                //В конце итерации увеличиваем счетчик на 1 (i++ это то же самое, что и i = i + 1;)
                i++;
            }

            //Цикл закончится только когда файл полностью прочитается. Как это произойдет код перейдет сюда
            //Последним этапом будет просто возвратить массив
            return(data);
        }
Exemplo n.º 4
0
        public Player(PlayerSeat seat, TeamData teamData = null, LibraryData deckData = null,
                      Configurations configurations      = null)
        {
            Configurations = configurations;
            Seat           = seat;
            Hand           = new Collection <IRuntimeCard>();

            if (teamData != null)
            {
                Team = new Team(this, teamData);
            }

            if (deckData != null)
            {
                Library = new Library(this, deckData, configurations);
            }

            Graveyard = new Graveyard(this);

            #region Mechanics

            DrawMechanics       = new DrawMechanics(this);
            DiscardMechanics    = new DiscardMechanics(this);
            PlayCardMechanics   = new PlayCardMechanics(this);
            StartTurnMechanics  = new StartTurnMechanics(this);
            FinishTurnMecahnics = new FinishTurnMecahnics(this);
            SpawnMechanics      = new SpawnMechanics(this);
            ManaMechanics       = new ManaMechanics(this);

            #endregion
        }
Exemplo n.º 5
0
        //Невозвращаемая функция (типа void). Она ничего не возвращает. Просто сделана для удобства, чтобы не громоздить программу большим кол-вом кода, ибо эта процедура будет выполняться много раз
        static public void ShowTable(LibraryData data)
        {
            Console.WriteLine("-------------------------------------------------------------------------------------------");
            Console.Write("| {0,15} |", data.Name);
            Console.WriteLine(" {0,63} |", data.Owner);
            Console.WriteLine("-------------------------------------------------------------------------------------------");
            foreach (var item in data.Books) //Пройдемся по массиву (грубо говоря: ДЛЯ КАЖДОГО)
            {
                if (item.Writer != null)     //Если значение "Автор" данной итерации не пустое, то:
                {
                    //Выводим все на экран консоли + небольшое подобие таблицы
                    Console.Write("| {0,15} |", item.Writer);
                    Console.Write(" {0,15} |", item.Title);
                    Console.Write(" {0,15} |", item.PubHouse);
                    Console.Write(" {0,15} |", item.Year);
                    Console.WriteLine(" {0,15} |", item.StoragePlace);
                    Console.WriteLine("-------------------------------------------------------------------------------------------");
                }
            }

            Console.WriteLine(); //Пропускаем строку вниз
            Console.WriteLine("Операции с данными:");
            Console.WriteLine("1. Добавить запись");
            Console.WriteLine("2. Удалить запись");
            Console.WriteLine("3. Поиск книги по автору");
            Console.WriteLine("4. Поиск книги по названию");
            Console.Write("Нажмите соответствующую цифру на клавиатуре: ");
        }
Exemplo n.º 6
0
        public static void SendCompressor(int id, CompressorModel compressor)
        {
            if (!bool.Parse(LibraryData.Settings["CompressorEnabled"]))
            {
                return;
            }
            if (compressor == null)
            {
                return;
            }
            if (compressor.CompressorValues == null)
            {
                return;
            }

            try
            {
                for (var i = 0; i < 7; i++)
                {
                    LibraryData.AddData(new SetCompressor(id, i, compressor.CompressorValues));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Failed to upload compressor: " + e);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        ///     Close current system
        /// </summary>
        private bool Close()
        {
            if (!LibraryData.SystemIsOpen)
            {
                return(true);
            }

            if (!IsInDesignMode)
            {
                var qq = new SystemFileSaveAsk();
                if (!qq.Save())
                {
                    return(false);
                }
            }

            LibraryData.CloseProject();
            TabCollection.RemoveAll(q => q is MainUnitViewModel || q is PanelViewModel);

            LibraryData.SystemFileName = string.Empty;

            RaisePropertyChanged(() => FileName);


            RaisePropertyChanged(() => InstallerVersion);
            return(true);
        }
Exemplo n.º 8
0
        /// <summary>
        ///     adds a new mainunit to the system
        /// </summary>
        private void AddMainUnit()
        {
            if (!LibraryData.SystemIsOpen)
            {
                LibraryData.CreateEmptySystem();
            }

            var t = new UcEscNum(LibraryData.FuturamaSys.MainUnits.Select(n => n.Id).ToList());

            if (t.ShowDialog() == false)
            {
                return;
            }

            var mu = LibraryData.AddEsc(t.Result);

            if (mu == null)
            {
                return;
            }
            var newunit = new MainUnitViewModel(mu, this);

            TabCollection.Add(newunit);
            OnSystemChanged(new SystemChangedEventArgs()
            {
                NewMainUnit = newunit
            });
        }
Exemplo n.º 9
0
        /// <summary>
        /// Create a new system
        /// </summary>
        /// <returns>true if file creation succeeded, false if user cancelled or otherwise</returns>
        private bool New()
        {
            if (!Close())
            {
                return(false);
            }

            MessageBox.Show(Main.SaveNewSystem, Main.SaveNewSystemTitle, MessageBoxButton.OK,
                            MessageBoxImage.Information, MessageBoxResult.OK);

            LibraryData.CreateEmptySystem();

            LibraryData.FuturamaSys.CreatedInstallerVersion =
                Assembly.GetExecutingAssembly().GetName().Version.ToString();

            if (!IsInDesignMode)
            {
                var q = new SystemFileSaveAs();
                if (!q.Save())
                {
                    LibraryData.CloseProject();
                    return(false);
                }
            }

            RaisePropertyChanged(() => FileName);
            AddMainUnitsToTab();
            _recentFilesLogic.AddFile(FileName);

            RaisePropertyChanged(() => InstallerVersion);

            return(true);
        }
Exemplo n.º 10
0
        public void BackupFile()
        {
            LibraryData.CreateEmptySystem();
            SystemFileBackup u = new SystemFileBackup();

            u.Save();
        }
    void Start()
    {
        rawKeywords    = "";
        libData        = FindObjectOfType <LibraryData> ();
        panelTransform = gameObject.GetComponent <Transform> ().Find("Panel");

        if (libData == null)
        {
            Debug.Log("NO LIBRARY_DATA!");
        }
        if (panelFirst == null)
        {
            Debug.Log("NO PANEL_1!");
        }
        if (panelSecond == null)
        {
            Debug.Log("NO PANEL_2!");
        }
        if (panelThird == null)
        {
            Debug.Log("NO PANEL_3!");
        }
        if (panelThird == null)
        {
            Debug.Log("NO PANEL_WARNING!");
        }
    }
        /// <summary>
        /// Returns all available libraries
        /// </summary>
        public LibraryData GetLibraries()
        {
            LibraryData dataSet = new LibraryData();


            DbConnection.db.LoadDataSet("vts_spLibraryGetAll", dataSet, new string[] { "Libraries" });
            return dataSet;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Returns all available libraries
        /// </summary>
        public LibraryData GetLibraries()
        {
            LibraryData dataSet = new LibraryData();


            DbConnection.db.LoadDataSet("vts_spLibraryGetAll", dataSet, new string[] { "Libraries" });
            return(dataSet);
        }
Exemplo n.º 14
0
        public LibraryService()
        {
            LibraryData         libraryData = new LibraryData();
            BasicLibraryHandler libraryDao  = new BasicLibraryHandler(libraryData);

            UOW = new UnitOfWork(libraryData, libraryDao);
            PrefillLibraryDataWithConstants();
        }
Exemplo n.º 15
0
    static LibraryManager()
    {
        LibraryData libraryData = CardLoaderSaver.LoadLibraryFromResources();

        _libraryActions  = libraryData.actionCards;
        _libraryBondages = libraryData.bondageCards;
        _libraryTouches  = libraryData.touchCards;
    }
        public override global::System.Data.DataSet Clone()
        {
            LibraryData cln = ((LibraryData)(base.Clone()));

            cln.InitVars();
            cln.SchemaSerializationMode = this.SchemaSerializationMode;
            return(cln);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Retrieves the cache version of the given library.
        /// </summary>
        public int GetRepositoryVersion(string libraryName)
        {
            if (libraryName == null)
            {
                throw new ArgumentNullException("libraryName");
            }
            LibraryData ld = FindLibraryData(libraryName, true);

            return(ld.RepositoryVersion);
        }
Exemplo n.º 18
0
 private void timerCheckForUpdates_Tick(object sender, EventArgs e)
 {
     timerCheckForUpdates.Enabled = false;
     if (!needsUpdate)
     {
         needsUpdate = LibraryData.GetFilesListNeedsUpdateStatus();
     }
     //uxRefresh.Enabled = needsUpdate;
     timerCheckForUpdates.Enabled = !needsUpdate;
 }
Exemplo n.º 19
0
        /// <summary>
        /// Opens esc file
        /// </summary>
        private void Open(string filename)
        {
            var initialDirectory = string.Empty;

            if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.RecentLocationProject))
            {
                initialDirectory = Properties.Settings.Default.RecentLocationProject;
            }

            if (string.IsNullOrWhiteSpace(filename) || filename == "open")
            {
                filename = FileManagement.OpenFileDialog(initialDirectory).FileName;
            }


            if (string.IsNullOrWhiteSpace(filename))
            {
                return;
            }

            FuturamaSysModel t;

            try
            {
                t = FileManagement.OpenSystemFile(filename);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Could't open file", MessageBoxButton.OK, MessageBoxImage.Error,
                                MessageBoxResult.OK);
                return;
            }

            Properties.Settings.Default.RecentLocationProject = Path.GetDirectoryName(filename);

            if (LibraryData.SystemIsOpen)
            {
                if (!Close())
                {
                    return;
                }
            }

            FileName = filename;

            LibraryData.OpenSystem(t);

            _comViewModel.UpdateConnections();
            RaisePropertyChanged(() => InstallerVersion);
            _recentFilesLogic.AddFile(filename);
            AddMainUnitsToTab();
            AddConnections();
            SelectedTab = TabCollection.FirstOrDefault(i => i.Id == 0);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Sets the repository version used for loading/saving the library's shapes/model objects.
        /// </summary>
        public void SetRepositoryVersion(string libraryName, int version)
        {
            // The core library will not be enlisted in the project settings
            if (string.Compare(libraryName, Project.CoreLibraryName) == 0)
            {
                return;
            }
            LibraryData ld = FindLibraryData(libraryName, true);

            ld.RepositoryVersion = version;
        }
 /// <summary>
 /// Update the library in the database
 /// </summary>
 public void UpdateLibrary(LibraryData updatedLibrary)
 {
     SqlConnection connection = new SqlConnection(DbConnection.NewDbConnectionString);
     SqlCommand insertCommand = new SqlCommand("vts_spLibraryUpdate", connection);
     insertCommand.CommandType = CommandType.StoredProcedure;
     insertCommand.Parameters.Add(new SqlParameter("@LibraryID", SqlDbType.Int, 4, "LibraryID"));
     insertCommand.Parameters.Add(new SqlParameter("@LibraryName", SqlDbType.NVarChar, 255, "LibraryName"));
     insertCommand.Parameters.Add(new SqlParameter("@Description", SqlDbType.NText, 10000, "Description"));
     insertCommand.Parameters.Add(new SqlParameter("@DefaultLanguageCode", SqlDbType.NVarChar, 50, "DefaultLanguageCode"));
     DbConnection.db.UpdateDataSet(updatedLibrary, "Libraries", insertCommand, new SqlCommand(), insertCommand, UpdateBehavior.Transactional);
 }
Exemplo n.º 22
0
        //Функция меню №1: добавление значение. В функцию мы получаем все данные, проводим действия с данными, и выводим готовые. Прямо как перерабатывающий завод.
        static public LibraryData AddBook(LibraryData data, string writer, string title, string pubhouse, int year, string storageplace)
        {
            Array.Resize(ref data.Books, data.Books.Length + 1);     //Увеличиваем длину массива на 1, чтобы записать новые данные
            data.Books[data.Books.Length - 1].Writer       = writer; //И забиваем новые данные
            data.Books[data.Books.Length - 1].Title        = title;
            data.Books[data.Books.Length - 1].PubHouse     = pubhouse;
            data.Books[data.Books.Length - 1].Year         = year;
            data.Books[data.Books.Length - 1].StoragePlace = storageplace;

            return(data); //Потом просто возвращаем измененные данные
        }
 /// <summary>
 /// Adds a new library in the database
 /// </summary>
 /// <param name="newAnswerType">Library object with information about what to add. Only Id must be ommited</param>
 public void AddLibrary(LibraryData newLibrary)
 {
     SqlConnection connection = new SqlConnection(DbConnection.NewDbConnectionString);
     SqlCommand insertCommand = new SqlCommand("vts_spLibraryAddNew", connection);
     insertCommand.CommandType = CommandType.StoredProcedure;
     insertCommand.Parameters.Add(new SqlParameter("@LibraryName", SqlDbType.VarChar, 0xff, "LibraryName"));
     insertCommand.Parameters.Add(new SqlParameter("@LibraryId", SqlDbType.Int, 4, "LibraryId"));
     insertCommand.Parameters.Add(new SqlParameter("@Description", SqlDbType.NText, 10000, "Description"));
     insertCommand.Parameters.Add(new SqlParameter("@DefaultLanguageCode", SqlDbType.NVarChar, 50, "DefaultLanguageCode")); 
     insertCommand.Parameters["@LibraryId"].Direction = ParameterDirection.Output;
     DbConnection.db.UpdateDataSet(newLibrary, "Libraries", insertCommand, new SqlCommand(), new SqlCommand(), UpdateBehavior.Transactional);
 }
Exemplo n.º 24
0
    public static void SaveLibrary(LibraryData libraryData)
    {
        Directory.CreateDirectory(GetDirectory());

        using (FileStream fs = new FileStream(GetPath(), FileMode.Create))
        {
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.Write(JsonUtility.ToJson(libraryData, true));
            }
        }
    }
        /// <summary>
        /// Return a library object that reflects the database library
        /// </summary>
        /// <param name="answerTypeId">Id of the library you need</param>
        /// <returns>An Library data object with the current database values</returns>
        public LibraryData GetLibraryById(int libraryId)
        {
            LibraryData dataSet = new LibraryData();

            ArrayList commandParameters = new ArrayList();
            {
                commandParameters.Add(new SqlParameter("@LibraryID", libraryId).SqlValue);
            }

            DbConnection.db.LoadDataSet("vts_spLibraryGetDetails", dataSet, new string[] { "Libraries" }, commandParameters.ToArray());
            return dataSet;
        }
Exemplo n.º 26
0
    private void SaveLibraryList()
    {
        BinaryFormatter bf   = new BinaryFormatter();
        FileStream      file = File.Create(Application.persistentDataPath + "/library.dat");

        LibraryData data = new LibraryData();

        data.savedDecks = savedDecks;

        bf.Serialize(file, data);
        file.Close();
    }
        public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs)
        {
            LibraryData ds = new LibraryData();

            global::System.Xml.Schema.XmlSchemaComplexType type     = new global::System.Xml.Schema.XmlSchemaComplexType();
            global::System.Xml.Schema.XmlSchemaSequence    sequence = new global::System.Xml.Schema.XmlSchemaSequence();
            global::System.Xml.Schema.XmlSchemaAny         any      = new global::System.Xml.Schema.XmlSchemaAny();
            any.Namespace = ds.Namespace;
            sequence.Items.Add(any);
            type.Particle = sequence;
            global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
            if (xs.Contains(dsSchema.TargetNamespace))
            {
                global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
                global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
                try {
                    global::System.Xml.Schema.XmlSchema schema = null;
                    dsSchema.Write(s1);
                    for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();)
                    {
                        schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                        s2.SetLength(0);
                        schema.Write(s2);
                        if ((s1.Length == s2.Length))
                        {
                            s1.Position = 0;
                            s2.Position = 0;
                            for (; ((s1.Position != s1.Length) &&
                                    (s1.ReadByte() == s2.ReadByte()));)
                            {
                                ;
                            }
                            if ((s1.Position == s1.Length))
                            {
                                return(type);
                            }
                        }
                    }
                }
                finally {
                    if ((s1 != null))
                    {
                        s1.Close();
                    }
                    if ((s2 != null))
                    {
                        s2.Close();
                    }
                }
            }
            xs.Add(dsSchema);
            return(type);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Update the library in the database
        /// </summary>
        public void UpdateLibrary(LibraryData updatedLibrary)
        {
            SqlConnection connection    = new SqlConnection(DbConnection.NewDbConnectionString);
            SqlCommand    insertCommand = new SqlCommand("vts_spLibraryUpdate", connection);

            insertCommand.CommandType = CommandType.StoredProcedure;
            insertCommand.Parameters.Add(new SqlParameter("@LibraryID", SqlDbType.Int, 4, "LibraryID"));
            insertCommand.Parameters.Add(new SqlParameter("@LibraryName", SqlDbType.NVarChar, 255, "LibraryName"));
            insertCommand.Parameters.Add(new SqlParameter("@Description", SqlDbType.NText, 10000, "Description"));
            insertCommand.Parameters.Add(new SqlParameter("@DefaultLanguageCode", SqlDbType.NVarChar, 50, "DefaultLanguageCode"));
            DbConnection.db.UpdateDataSet(updatedLibrary, "Libraries", insertCommand, new SqlCommand(), insertCommand, UpdateBehavior.Transactional);
        }
Exemplo n.º 29
0
        // ------------------------------------------------------------

        public Library(IPlayer player, LibraryData deckData, Configurations configurations)
        {
            if (deckData == null)
            {
                Debug.LogError("A deck can't have null cards");
            }

            Deck             = deckData;
            Owner            = player;
            Configurations   = configurations;
            cardDataRegister = Deck.GetCards();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Adds a new library in the database
        /// </summary>
        /// <param name="newAnswerType">Library object with information about what to add. Only Id must be ommited</param>
        public void AddLibrary(LibraryData newLibrary)
        {
            SqlConnection connection    = new SqlConnection(DbConnection.NewDbConnectionString);
            SqlCommand    insertCommand = new SqlCommand("vts_spLibraryAddNew", connection);

            insertCommand.CommandType = CommandType.StoredProcedure;
            insertCommand.Parameters.Add(new SqlParameter("@LibraryName", SqlDbType.VarChar, 0xff, "LibraryName"));
            insertCommand.Parameters.Add(new SqlParameter("@LibraryId", SqlDbType.Int, 4, "LibraryId"));
            insertCommand.Parameters.Add(new SqlParameter("@Description", SqlDbType.NText, 10000, "Description"));
            insertCommand.Parameters.Add(new SqlParameter("@DefaultLanguageCode", SqlDbType.NVarChar, 50, "DefaultLanguageCode"));
            insertCommand.Parameters["@LibraryId"].Direction = ParameterDirection.Output;
            DbConnection.db.UpdateDataSet(newLibrary, "Libraries", insertCommand, new SqlCommand(), new SqlCommand(), UpdateBehavior.Transactional);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Return a library object that reflects the database library
        /// </summary>
        /// <param name="answerTypeId">Id of the library you need</param>
        /// <returns>An Library data object with the current database values</returns>
        public LibraryData GetLibraryById(int libraryId)
        {
            LibraryData dataSet = new LibraryData();

            ArrayList commandParameters = new ArrayList();

            {
                commandParameters.Add(new SqlParameter("@LibraryID", libraryId).SqlValue);
            }

            DbConnection.db.LoadDataSet("vts_spLibraryGetDetails", dataSet, new string[] { "Libraries" }, commandParameters.ToArray());
            return(dataSet);
        }
Exemplo n.º 32
0
    //public void LoadDeck() {
    //    DestroyAllListings();

    //    if (File.Exists(Application.persistentDataPath + "/deckData.dat")) {
    //        BinaryFormatter bf = new BinaryFormatter();
    //        FileStream file = File.Open(Application.persistentDataPath + "/deckData.dat", FileMode.Open);

    //        DeckData data = (DeckData)bf.Deserialize(file);
    //        file.Close();

    //        List<int> listToLoad = new List<int>();

    //        for (int i = 0; i < data.savedDecklist.Count; i++) {
    //            //Debug.Log(data.savedDeckInProgress[i] + " is an id being copied to LOAD");
    //            listToLoad.Add(data.savedDecklist[i]);
    //        }

    //        List<CardData> deckList = new List<CardData>();

    //        for (int i = 0; i < listToLoad.Count; i++) {

    //            CardIDs.CardID id = (CardIDs.CardID)listToLoad[i];
    //            CardData cardData = Finder.FindCardDataFromDatabase(id);

    //            deckList.Add(cardData);
    //        }

    //        //PopulateLoadedDeck(data.deckName, deckList);

    //    }
    //}

    private void LoadLibraryList()
    {
        if (File.Exists(Application.persistentDataPath + "/library.dat"))
        {
            BinaryFormatter bf   = new BinaryFormatter();
            FileStream      file = File.Open(Application.persistentDataPath + "/library.dat", FileMode.Open);

            LibraryData data = (LibraryData)bf.Deserialize(file);
            file.Close();

            savedDecks = data.savedDecks;
        }
    }
Exemplo n.º 33
0
        private void uxRefresh_Click(object sender, EventArgs e)
        {
            LibraryData.UpdateFilesList();
            uxImagesView.DataSource = LibraryData.GetAllItems().ToList();

            treeBuilder.Load();
            uxWhere.Properties.DataSource = treeTable.DefaultView;

            Filter();
            needsUpdate = false;
            //uxRefresh.Enabled = false;

            timerCheckForUpdates.Enabled = true;
        }
Exemplo n.º 34
0
 void IEntity.LoadInnerObjects(string propertyName, IRepositoryReader reader, int version)
 {
     Project.AssertSupportedVersion(false, version);
     reader.BeginReadInnerObjects();
     while (reader.BeginReadInnerObject())
     {
         LibraryData ld = new LibraryData(null, null, 0);
         ld.Name              = reader.ReadString();
         ld.AssemblyName      = reader.ReadString();
         ld.RepositoryVersion = reader.ReadInt32();
         libraries.Add(ld);
         reader.EndReadInnerObject();
     }
     reader.EndReadInnerObjects();
 }
 /// <summary>
 /// Adds a new library in the database
 /// </summary>
 /// <param name="newAnswerType">Library object with information about what to add. Only Id must be ommited</param>
 public void AddLibrary(LibraryData newLibrary)
 {
     LibraryFactory.Create().AddLibrary(newLibrary);
 }
Exemplo n.º 36
0
    private void Process_AddLibraryItem()
    {
        PermissionData security_data;
        //Dim folder_data As FolderData
        LibraryConfigData lib_setting_data;
        Collection pagedata;
        string strOperation = "";
        string strLibType = "";
        string strContentId = "";
        long CurrentUserID = 0;
        Ektron.Cms.Library.EkLibrary m_refLibrary;
        string FileName = "";
        string NewFilename = "";
        string MediaPath = "";
        string Extensions = "";
           string[] FilenameArray;
        bool ret = false;
        bool uploadok = false;
          string[] ExtensionArray; //, gtLibraries
           int iLoop;
        bool bThumbnail = true;
        object szPhysicalPath; // ,ThumbLBString
           string actErrorString;

        CurrentUserID = _ContentApi.UserId;
        m_refLibrary = _ContentApi.EkLibraryRef;

        Ektron.Cms.DataIO.EkLibraryRW dataLibObj;
        dataLibObj = new Ektron.Cms.DataIO.EkContentRW(_ContentApi.RequestInformationRef);
        Collection cItemInfo = new Collection();

        try
        {
            if ((_Type == "images") || (_Type == "files"))
            {

                int fileLength = frm_filename.PostedFile.ContentLength;
                byte[] fileData = new byte[fileLength];
                frm_filename.PostedFile.InputStream.Read(fileData, 0, fileLength);
                Stream stream = new MemoryStream(fileData);
                if (EkFunctions.IsImage(Path.GetExtension(frm_filename.PostedFile.FileName)))
                {
                    if (!EkFunctions.isImageStreamValid(stream))
                    {
                        throw new Exception("The image is corrupted or not in correct format.");
                    }
                }

                _FolderId = Convert.ToInt64(Request.Form["frm_folder_id"]);
                strLibType = Request.Form["frm_libtype"];
                strOperation = Request.Form["frm_operation"];
                FileName = (string)(frm_filename.PostedFile.FileName.Substring((frm_filename.PostedFile.FileName).LastIndexOf("\\") + 1));
                FileName = FileName.Replace("%", "");
                lib_setting_data = _ContentApi.GetLibrarySettings(_FolderId);
                security_data = _ContentApi.LoadPermissions(_FolderId, "folder", 0);
                strContentId = Request.Form["frm_content_id"];
                pagedata = new Collection();
                pagedata.Add(_FolderId, "ParentID", null, null);
                pagedata.Add(Request.Form["frm_library_id"], "LibraryID", null, null);
                pagedata.Add(strLibType, "LibraryType", null, null);
                pagedata.Add(Request.Form["frm_title"], "LibraryTitle", null, null);
                pagedata.Add(strContentId, "ContentID", null, null);
                NewFilename = Strings.Trim(Request.Form["frm_oldfilename"]);

                if (((strOperation.ToLower() != "overwrite") && (((security_data.CanAddToImageLib) && (strLibType == "images")) || ((security_data.CanAddToFileLib) && (strLibType == "files")) || ((security_data.CanAddToHyperlinkLib) && (strLibType == "hyperlinks")) || ((security_data.CanAddToQuicklinkLib) && (strLibType == "quicklinks")))) || ((security_data.CanOverwriteLib) && (strOperation.ToLower() == "overwrite")))
                {
                    pagedata.Add(CurrentUserID, "UserID", null, null);
                    FilenameArray = FileName.Split('.');
                    if (strLibType == "images")
                    {
                        Extensions = lib_setting_data.ImageExtensions;
                        MediaPath = lib_setting_data.ImageDirectory;
                    }
                    else
                    {
                        Extensions = lib_setting_data.FileExtensions;
                        MediaPath = lib_setting_data.FileDirectory;
                    }
                    if ((FilenameArray.Length - 1) >= 1)
                    {
                        ExtensionArray = Extensions.Split(',');
                        for (iLoop = 0; iLoop <= (ExtensionArray.Length - 1); iLoop++)
                        {
                            if (Strings.LCase(FilenameArray[FilenameArray.Length - 1]).Trim() == Strings.LCase((string)(ExtensionArray[iLoop])).Trim())
                            {
                                uploadok = true;
                                break;
                            }
                        }
                        if (uploadok == true)
                        {
                            if (strOperation.ToLower() == "overwrite")
                            {
                                pagedata.Add("OverwriteLib", "UpdateLibData", null, null);
                                strOperation = "overwrite";
                            }
                            else
                            {
                                strOperation = "makeunique";
                            }

                            szPhysicalPath = Server.MapPath(MediaPath);
                            if (!Directory.Exists(szPhysicalPath.ToString()))
                            {
                                Directory.CreateDirectory(szPhysicalPath.ToString());
                            }

                            if (strOperation == "overwrite")
                            {
                                actErrorString = NewFilename;
                            }
                            else
                            {
                                actErrorString = FileName;
                            }

                            string strTmpFilename;
                            string strTmpFileExtn;
                            int iUnqueNameIdentifier =0 ;
                            FileInfo CheckFile;
                            actErrorString = Strings.Replace(actErrorString.ToString(), "/", "\\", 1, -1, 0);
                            string[] st = Strings.Split(actErrorString.ToString(), "\\", -1, 0);
                            strTmpFilename = st[st.Length-1];
                            if ((Strings.Right(szPhysicalPath.ToString(), 1) != "\\"))
                            {
                                szPhysicalPath = szPhysicalPath + "\\";
                            }

                            actErrorString = strTmpFilename;
                            strTmpFileExtn = actErrorString.Substring(actErrorString.LastIndexOf("."));
                            strTmpFilename = Strings.Replace(actErrorString.ToString(), strTmpFileExtn.ToString(), "", 1, -1, 0);
                            if (strOperation == "makeunique")
                            {
                                CheckFile = new FileInfo(szPhysicalPath + actErrorString);
                                if (CheckFile.Exists)
                                {
                                    while (CheckFile.Exists)
                                    {
                                        iUnqueNameIdentifier = iUnqueNameIdentifier + 1;
                                        actErrorString = strTmpFilename + "(" + iUnqueNameIdentifier + ")" + strTmpFileExtn;
                                        CheckFile = new FileInfo(szPhysicalPath + actErrorString);
                                    }
                                }
                            }

                            if (!Directory.Exists(szPhysicalPath.ToString()))
                            {
                                Directory.CreateDirectory(szPhysicalPath.ToString());
                            }

                            try
                            {
                                if ((strOperation.ToLower() != "overwrite") && (strLibType == "images" || strLibType == "files"))
                                {
                                    cItemInfo = dataLibObj.GetChildLibraryItemByTitlev2_0(Convert.ToString( Request.Form["frm_title"]), _FolderId, strLibType,Convert.ToInt32( EkEnumeration.CMSContentType.LibraryItem));
                                    if ((cItemInfo.Count > 0) && (Convert.ToInt32( cItemInfo["ContentLanguage"]) == _ContentApi.RequestInformationRef.ContentLanguage))
                                    {
                                        Utilities.ShowError(_MessageHelper.GetMessage("com: library entry already exists"));
                                        return;
                                    }
                                }
                            }
                            catch (Exception)
                            {

                            }

                            frm_filename.PostedFile.SaveAs(szPhysicalPath + actErrorString);

                            if (strLibType == "images")
                            {
                                try
                                {
                                    Utilities.ProcessThumbnail(Server.MapPath(MediaPath), actErrorString.ToString());
                                }
                                catch (Exception)
                                {
                                    bThumbnail = false;
                                }
                            }
                            else
                            {
                                bThumbnail = false;
                            }
                            //----------------- Load Balance ------------------------------------------------------
                            LoadBalanceData[] loadbalance_data;
                            int i = 0;
                            loadbalance_data = _ContentApi.GetAllLoadBalancePathsExtn(_FolderId, strLibType);
                            if (!(loadbalance_data == null))
                            {
                                for (i = 0; i <= loadbalance_data.Length - 1; i++)
                                {
                                    szPhysicalPath = Server.MapPath(loadbalance_data[i].Path);
                                    if ((Strings.Right(szPhysicalPath.ToString(), 1) != "\\"))
                                    {
                                        szPhysicalPath = szPhysicalPath + "\\";
                                    }
                                    frm_filename.PostedFile.SaveAs(szPhysicalPath + actErrorString);
                                    if (bThumbnail)
                                    {
                                        Utilities.ProcessThumbnail(szPhysicalPath.ToString(), actErrorString.ToString());
                                    }

                                }
                            }
                            pagedata.Add(MediaPath + actErrorString, "LibraryFilename", null, null);
                        }
                        else
                        {
                            throw (new Exception(_MessageHelper.GetMessage("error: invalid extension")));
                        }
                    }
                    else
                    {
                        throw (new Exception(_MessageHelper.GetMessage("error: invalid extension")));
                    }
                }
                else
                {
                    throw (new Exception(_MessageHelper.GetMessage("com: user does not have permission")));
                }
            }
            else
            {
                pagedata = new Collection();
                pagedata.Add(Request.Form["frm_folder_id"], "ParentID", null, null);
                pagedata.Add(Request.Form["frm_libtype"], "LibraryType", null, null);
                pagedata.Add(Request.Form["frm_title"], "LibraryTitle", null, null);
                pagedata.Add(Request.Form["frm_filename"], "LibraryFilename", null, null);
                pagedata.Add(Request.Form["frm_content_id"], "ContentID", null, null);
                pagedata.Add(_ContentLanguage, "ContentLanguage", null, null);
                pagedata.Add(CurrentUserID, "UserID", null, null);
            }
            if (_Type != "quicklinks" && _Type != "forms")
            {
                pagedata.Add(GetFormTeaserData(), "ContentTeaser", null, null);
                pagedata.Add(CollectMetaField(), "ContentMetadata", null, null);
            }

            //Adding the Taxonomy category info
            if ((Request.Form["TaxonomyOverrideId"] != null) && Convert.ToInt64(Request.Form["TaxonomyOverrideId"]) != 0)
            {
                TaxonomyOverrideId = Convert.ToInt64( Request.Form["TaxonomyOverrideId"]);
                TaxonomyTreeIdList = Convert.ToString( TaxonomyOverrideId);
            }

            if ((Request.Form[taxonomyselectedtree.UniqueID] != null) && Request.Form[taxonomyselectedtree.UniqueID] != "")
            {
                TaxonomyTreeIdList = Request.Form[taxonomyselectedtree.UniqueID];
                if (TaxonomyTreeIdList.Trim().EndsWith(","))
                {
                    TaxonomyTreeIdList = TaxonomyTreeIdList.Substring(0, TaxonomyTreeIdList.Length - 1);
                }
            }
            if (TaxonomyTreeIdList.Trim() == string.Empty && TaxonomySelectId > 0)
            {
                TaxonomyTreeIdList = Convert.ToString( TaxonomySelectId);
            }
            pagedata.Add(TaxonomyTreeIdList, "Taxonomy", null, null);
            ///'

            if (strOperation == "overwrite")
            {
                ret = m_refLibrary.UpdateLibraryItemByIDv2_0(pagedata, 0, -1);
                FolderData folder_data = _ContentApi.GetFolderById(_FolderId);
                if (folder_data.FolderType == Convert.ToInt32( EkEnumeration.FolderType.Catalog))
                {
                    LibraryData library_data = null;
                    library_data = _ContentApi.GetLibraryItemByID(_Id, _FolderId);
                    FileName = library_data.FileName.Substring(System.Convert.ToInt32((library_data.FileName).LastIndexOf("/") + 1));
                    Ektron.Cms.Commerce.ProductTypeData productTypeData = new Ektron.Cms.Commerce.ProductTypeData();
                    Ektron.Cms.Commerce.ProductType productType = new Ektron.Cms.Commerce.ProductType(_ContentApi.RequestInformationRef);
                    long xmlConfigurationId = folder_data.XmlConfiguration[0].Id;

                    productTypeData = productType.GetItem(xmlConfigurationId);
                    szPhysicalPath = Server.MapPath(MediaPath);

                    if (productTypeData.DefaultThumbnails.Count > 0)
                    {
                        EkFileIO thumbnailCreator = new EkFileIO();
                        bool thumbnailResult = false;
                        string sourceFile = (string)(szPhysicalPath + FileName);
                        foreach (ThumbnailDefaultData thumbnail in productTypeData.DefaultThumbnails)
                        {
                            string fileNameNoExtension = FileName.Replace(System.IO.Path.GetExtension(FileName), "");
                            string fileNameExtension = System.IO.Path.GetExtension(FileName);
                            string thumbnailFile = (string)(szPhysicalPath + "\\" + fileNameNoExtension + thumbnail.Title + fileNameExtension);
                            thumbnailResult = thumbnailCreator.CreateThumbnail(sourceFile, thumbnailFile, thumbnail.Width, thumbnail.Height);
                        }
                    }
                    LibraryData librarydata = new LibraryData();
                    int iThumbnail = 0;
                    if (productTypeData.DefaultThumbnails.Count > 0)
                    {
                        string sourceFile = (string)(szPhysicalPath + FileName);
                        foreach (ThumbnailDefaultData thumbnail in productTypeData.DefaultThumbnails)
                        {
                            iThumbnail++;
                            string fileNameNoExtension = FileName.Replace(System.IO.Path.GetExtension(FileName), "");
                            string fileNameExtension = System.IO.Path.GetExtension(FileName);
                            string thumbnailPath = library_data.FileName.Replace(System.IO.Path.GetFileName(library_data.FileName), "");
                            string thumbnailFile = fileNameNoExtension + thumbnail.Title + fileNameExtension;
                            NewFilename = Strings.Trim(Request.Form["frm_oldfilename"]);

                            librarydata =  new LibraryData();
                            librarydata.Type = "images";
                            librarydata.FileName = thumbnailPath + thumbnailFile;
                            librarydata.Title = library_data.Title + thumbnail.Title;
                            librarydata.ParentId = _FolderId;
                            librarydata.Id = _Id + iThumbnail;
                            actErrorString = NewFilename;

                            Collection ThumbnailData = new Collection();
                            ThumbnailData.Add(librarydata.ParentId, "ParentID", null, null);
                            ThumbnailData.Add(librarydata.Id, "LibraryID", null, null);
                            ThumbnailData.Add(librarydata.Type, "LibraryType", null, null);
                            ThumbnailData.Add(librarydata.Title, "LibraryTitle", null, null);
                            ThumbnailData.Add(strContentId, "ContentID", null, null);
                            ThumbnailData.Add(CurrentUserID, "UserID", null, null);
                            ThumbnailData.Add("OverwriteLib", "UpdateLibData", null, null);
                            ThumbnailData.Add(librarydata.FileName, "LibraryFilename", null, null);
                            ThumbnailData.Add(librarydata.OriginalLibraryId, "OriginalLibraryId", null, null);

                            _ContentApi.UpdateLibraryItemByID(ThumbnailData);
                        }
                    }

                }
            }
            else
            {
                if (_ContentLanguage == Ektron.Cms.Common.EkConstants.ALL_CONTENT_LANGUAGES)
                {
                    _ContentApi.ContentLanguage = _ContentApi.DefaultContentLanguage;
                }
                ret = m_refLibrary.AddLibraryItemv2_0(pagedata, 0);

                // process tag info
                ProcessTags(Convert.ToInt64( pagedata["LibraryID"]), _ContentApi.ContentLanguage);
            }

            if (strOperation.ToLower() == "overwrite")
            {
                Response.Redirect("library.aspx?LangType=" + _ContentLanguage + "&action=ViewLibraryItem&id=" + pagedata["LibraryID"] + "&parent_id=" + pagedata["ParentID"] + "&reload=true", false);
            }
            else
            {
                Response.Redirect((string)("library.aspx?LangType=" + _ContentLanguage + "&action=ViewLibraryByCategory&id=" + _FolderId + "&type=" + strLibType), false);
            }
        }
        catch (Exception ex)
        {
            EkException.ThrowException(ex);
        }
    }
Exemplo n.º 37
0
    protected void MainView()
    {
        if (ContentBlockId > 0)
        {
            Ektron.Cms.LibraryData libData = new LibraryData();
            Ektron.Cms.API.Library lib = new Library();
            libData = lib.GetLibraryItem(ContentBlockId);
            if (!ReferenceEquals(libData, null))
            {
                string title = libData.Title;
                string strTooltip = ToolTip.Trim() == "" ? libData.Title : ToolTip.Trim();
                string strHtml = string.Format(@"<img src=""{0}"" border=""{1}"" width=""{2}"" height=""{3}"" title=""{4}"" alt=""{5}""></img>",
                    libData.FileName.Replace("//", "/"), ImageBorder, Width, Height, strTooltip, strTooltip);
                ltrImage.Text = strHtml;
                ltrImage.Visible = true;
            }

            phContent.Visible = true;
            phHelpText.Visible = false;
        }
        else
        {
            phContent.Visible = false;
            phHelpText.Visible = true;
        }

        if (!(_host == null || _host.IsEditable == false))
        {
            divHelpText.Visible = true;
        }
        else
        {
            divHelpText.Visible = false;
        }
    }
 /// <summary>
 /// Update the library in the database
 /// </summary>
 public void UpdateLibrary(LibraryData updatedLibrary)
 {
     LibraryFactory.Create().UpdateLibrary(updatedLibrary);
 }
Exemplo n.º 39
0
    private void Process_Add()
    {
        try
        {
            Collection page_content_data = new Collection();
            DiscussionBoard board_data = null;
            Ektron.Cms.Content.EkContent m_refContent = m_refContentApi.EkContentRef;
            Ektron.Cms.Content.EkTask ekmessage = m_refContentApi.EkTaskRef;
            string strContent = "";
            string strSearchText = "";
            string strContentTeaser = "";
            bool isapproved = false;

            board_data = m_refContent.GetForumbyID(m_iFolderID.ToString());
            security_data = m_refContentApi.LoadPermissions(m_iFolderID, "folder", 0);
            if ((board_data.Forums[0].ModerateComments == false) || (board_data.Forums[0].ModerateComments == true && (security_data.IsAdmin || security_data.CanAddToImageLib)))
            {
                isapproved = true;
            }
            if (!(security_data.IsAdmin || security_data.CanAddToImageLib)) // you cannot set sticky/announcement unless you are a moderator.
            {

            }
            this.m_iFolderID = Convert.ToInt64(Request.Form[hdn_folderid.UniqueID]);
            strContentTeaser = Request.Form[txt_summ.UniqueID];

            strContent = (string)ctlEditor.Content;

            strSearchText = Utilities.StripHTML((string)ctlEditor.Content);
            if (!(Request.Form["content_html_Action"] == null))
            {
                strContent = Server.HtmlDecode(strContent);
            }
            strContent = this.m_refContentApi.ReplaceWordsForBoardPosts(strContent, board_data.Id);
            page_content_data.Add(EkEnumeration.CMSContentType.DiscussionTopic, "ContentType", null, null);
            page_content_data.Add("", "ContentHtml", null, null);
            page_content_data.Add("", "Comment", null, null);
            page_content_data.Add(0, "ContentID", null, null);
            page_content_data.Add(Request.Form["content_language"], "ContentLanguage", null, null);
            page_content_data.Add(strContentTeaser, "ContentTeaser", null, null);
            page_content_data.Add(this.m_iFolderID, "FolderID", null, null);
            page_content_data.Add(strSearchText, "SearchText", null, null);
            page_content_data.Add("", "GoLive", null, null);
            page_content_data.Add("", "EndDate", null, null);
            page_content_data.Add("", "EndDateAction", null, null);
            page_content_data.Add(true, "IsDiscussionTopic", null, null);
            if (isapproved == false)
            {
                page_content_data.Add(false, "TopicApproved", null, null);
            }
            if (rb_normal.Checked == true)
            {
                page_content_data.Add(EkEnumeration.DiscussionObjPriority.Normal, "Priority", null, null);
            }
            else if (rb_sticky.Checked == true)
            {
                page_content_data.Add(EkEnumeration.DiscussionObjPriority.Sticky, "Priority", null, null);
            }
            else if (rb_announcement.Checked == true)
            {
                page_content_data.Add(EkEnumeration.DiscussionObjPriority.Announcement, "Priority", null, null);
            }
            if (!string.IsNullOrEmpty(Request.Form[chk_adt_lock.UniqueID]))
            {
                page_content_data.Add(true, "LockTopic", null, null);
            }
            else
            {
                page_content_data.Add(false, "LockTopic", null, null);
            }
            string topicTitle = this.m_refContentApi.ReplaceWordsForBoardPosts(Request.Form[txt_topic_title.UniqueID].ToString(), board_data.Id);
            page_content_data.Add(topicTitle, "ContentTitle", null, null);
            page_content_data.Add(false, "AddToQlink", null, null);
            page_content_data.Add(true, "IsSearchable", null, null);
            m_iID = m_refContent.AddNewContentv2_0(page_content_data);

            if (m_refContentApi.RequestInformationRef.ContentLanguage > 0)
            {
                ekmessage.ContentLanguage = m_refContentApi.RequestInformationRef.ContentLanguage;
                ekmessage.LanguageID = m_refContentApi.RequestInformationRef.ContentLanguage;
            }
            else
            {
                ekmessage.ContentLanguage = m_refContentApi.RequestInformationRef.DefaultContentLanguage;
                ekmessage.LanguageID = m_refContentApi.RequestInformationRef.DefaultContentLanguage;
            }
            ekmessage.ContentID = m_iID;
            ekmessage.AssignedByUserID = m_refContentApi.RequestInformationRef.UserId.ToString();
            ekmessage.CreatedByUserID = m_refContentApi.RequestInformationRef.UserId;
            ekmessage.DateCreated = (string)(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
            ekmessage.TaskTypeID = EkEnumeration.TaskType.TopicReply.GetHashCode();
            ekmessage.State = (string)(EkEnumeration.TaskState.Completed.GetHashCode().ToString());
            ekmessage.Description = strContent;
            ekmessage.TaskTitle = "TopicReply";
            ekmessage.ImpersonateUser = true;

            ekmessage.CommentDisplayName = ""; //m_refContentApi.RequestInformationRef.LoggedInUsername
            ekmessage.ParentID = -2;
            ekmessage.CommentEmail = "";
            ekmessage.CommentURI = Request.ServerVariables["REMOTE_ADDR"];
            ekmessage.HostURL = Request.ServerVariables["HTTP_HOST"];
            ekmessage.URLpath = this.m_refContentApi.SitePath + board_data.TemplateFileName;
            ekmessage.AddTask();

            Process_Taxonomy(m_iID);

            ContentData content_data = m_refContentApi.GetContentById(m_iID, ContentAPI.ContentResultType.Published);

            LibraryData lib_item = new LibraryData();
            lib_item.ContentId = m_iID;
            lib_item.DateCreated = content_data.DateCreated;
            lib_item.ContentType = Convert.ToInt32(EkEnumeration.CMSContentType.DiscussionTopic);
            lib_item.DisplayDateCreated = content_data.DisplayDateCreated;
            lib_item.DisplayLastEditDate = content_data.DisplayLastEditDate;
            lib_item.EditorFirstName = content_data.EditorFirstName;
            lib_item.EditorLastName = content_data.EditorLastName;
            lib_item.FileName = board_data.TemplateFileName + ((content_data.TemplateConfiguration.FileName.IndexOf("?") > -1) ? "&" : "?") + "g=posts&t=" + this.m_iID + "&boardid=" + board_data.Id.ToString();
            lib_item.FolderName = content_data.FolderName;
            lib_item.IsPrivate = content_data.IsPrivate;
            lib_item.LanguageId = content_data.LanguageId;
            lib_item.LastEditDate = content_data.LastEditDate;
            lib_item.MetaData = content_data.MetaData;
            lib_item.ParentId = content_data.FolderId;
            lib_item.Title = content_data.Title;
            lib_item.TypeId = 4;
            lib_item.Type = "quicklinks";
            lib_item.UserId = content_data.UserId;

            // Dim CallerID As Integer = m_refContentApi.RequestInformationRef.CallerId
            // m_refContentApi.RequestInformationRef.CallerId = Convert.ToInt32(EkConstants.InternalAdmin)
            this.m_refContentApi.AddLibraryItem(ref lib_item);
            // m_refContentApi.RequestInformationRef.CallerId = CallerID

            if (closeOnFinish == true)
            {
                Response.Redirect("../close.aspx", false);
            }
            else
            {
                Response.Redirect((string)("../content.aspx?action=ViewContentByCategory&id=" + m_iFolderID.ToString()), false);
            }
        }
        catch (Exception ex)
        {
            Utilities.ShowError(ex.Message);
        }
    }
Exemplo n.º 40
0
        protected void btnUpload_Click(object sender, System.EventArgs e)
        {
            string parentId = "";
                if ((Request.QueryString["catalogid"] != null)&& Request.QueryString["catalogid"] != "")
                {
                    parentId = Request.QueryString["catalogid"];
                }

                if (txtTitle.Text.IndexOfAny(new char[]{'<','>'}) > -1)
                {
                    throw (new Ektron.Cms.Exceptions.SpecialCharactersException());
                }
                if (txtAlt.Text.IndexOfAny(new char[]{'<', '>'}) > -1)
                {
                    throw (new Ektron.Cms.Exceptions.SpecialCharactersException());
                }

                CheckAccess();

                try
                {
                    if (!(fuImage.PostedFile == null))
                    {
                        // file was sent
                        HttpPostedFile myFile = fuImage.PostedFile;
                        string sFileExt = "";

                        // Get and check size of uploaded file
                        int nFileLen = myFile.ContentLength;

                        //get and check name and extension
                        string sFileName = myFile.FileName;

                        string sShortName = "";
                        sFileName = sFileName.Replace("%", "");
                        if (sFileName.IndexOf("\\") > -1)
                        {
                            string[] aFilename = sFileName.Split('\\');
                            // take the very last one
                            if (aFilename.Length > 0)
                            {
                                sFileName = aFilename[aFilename.Length - 1];
                            }
                        }

                        //make safe
                        sFileName = sFileName.Replace(" ", "_").Replace("\'", "");

                        string[] aFileExt = sFileName.Split('.');
                        if (aFileExt.Length > 1)
                        {
                            sFileExt = (string) (aFileExt[(aFileExt.Length - 1)].Trim().ToLower()); //use the LAASSTT one.
                            if (sFileExt == "tif" || sFileExt == "bmp")
                            {
                                throw (new Exception("The extension \"" + sFileExt + "\" is not allowed."));
                            }
                            sShortName = sFileName.Substring(0, System.Convert.ToInt32(sFileName.Length - (sFileExt.Length + 1)));
                        }
                        else
                        {
                            throw (new Exception("The extension \"" + sFileExt + "\" is not allowed."));
                        }

                        if (aFileExt.Length > 0)
                        {
                            bool bGo = false;
                            for (int i = 0; i <= (aFileExt.Length - 1); i++)
                            {
                                if (sFileExt == aFileExt[i].Trim().ToLower())
                                {
                                    bGo = true;
                                    break;
                                }
                            }
                            if (bGo == false)
                            {
                                throw (new Exception("The extension \"" + sFileExt + "\" is not allowed."));
                            }
                        }
                        else
                        {
                            throw (new Exception("The extension \"" + sFileExt + "\" is not allowed."));
                        }

                        // Allocate a buffer for reading of the file
                        byte[] myData = new byte[nFileLen + 1];

                        // Read uploaded file from the Stream
                        myFile.InputStream.Read(myData, 0, nFileLen);

                        //check for existence of file.
                        FileInfo CheckFile;
                        int iUnqueNameIdentifier = 0;
                        string uploadImagePath = _ContentApi.GetPathByFolderID(Convert.ToInt64(parentId));
                        string sWebPath = (string) (lib_settings_data.ImageDirectory.TrimEnd("/".ToCharArray()) + uploadImagePath.Replace("\\", "/") .Replace(" ", "_") .Replace(".", "") .TrimEnd("/".ToCharArray()));
                        string sPhysicalPath = Server.MapPath(sWebPath);

                        if (! Directory.Exists(sPhysicalPath))
                        {
                            Directory.CreateDirectory(sPhysicalPath);
                        }

                        CheckFile = new FileInfo(sPhysicalPath + "\\" + sFileName);
                        if (CheckFile.Exists)
                        {
                            while (CheckFile.Exists)
                            {
                                iUnqueNameIdentifier++;
                                sFileName = sShortName + "(" + iUnqueNameIdentifier + ")." + sFileExt;
                                CheckFile = new FileInfo(sPhysicalPath + sFileName);
                            }
                        }

                        //write
                        WriteToFile(sPhysicalPath + "\\" + sFileName, myData);
                        Utilities.ProcessThumbnail(sPhysicalPath, sFileName);

                        //Begins: Generate thumbnails. Generates thumbnails for various pixes sizes.
                        if (_ProductTypeData.DefaultThumbnails.Count > 0)
                        {
                            EkFileIO thumbnailCreator = new EkFileIO();
                            bool thumbnailResult = false;
                            string sourceFile = sPhysicalPath + "\\" + sFileName;
                            foreach (ThumbnailDefaultData thumbnail in _ProductTypeData.DefaultThumbnails)
                            {
                                string fileNameNoExtension = sFileName.Replace(System.IO.Path.GetExtension(sFileName), "");
                                string fileNameExtension = System.IO.Path.GetExtension(sFileName);
                                string thumbnailFile = sPhysicalPath + "\\" + "thumb_" + fileNameNoExtension + thumbnail.Title.Replace("[filename]", "") + fileNameExtension;
                                thumbnailResult = thumbnailCreator.CreateThumbnail(sourceFile, thumbnailFile, thumbnail.Width, thumbnail.Height);

                                //766 load balancing handled by service - no code needed for load balancing

                                _Thumbnails.Add(new ThumbnailData((string) ("thumb_" + fileNameNoExtension + thumbnail.Title.Replace("[filename]", "") + fileNameExtension), (string) (sWebPath.TrimEnd("/".ToCharArray()) + "/"), fileNameNoExtension + thumbnail.Title.Replace("[filename]", "") + fileNameExtension, fileNameNoExtension + thumbnail.Title.Replace("[filename]", "") + fileNameExtension));
                            }
                        }
                        //Ends : Generate Thumbnails.

                        //upload this file to library.
                        LibraryData librarydata = new LibraryData();
                        long libraryId = 0;
                        librarydata.FileName = (string) ((sWebPath.Replace("/\\", "\\") + "/" + sFileName).Replace(" ", "_"));
                        librarydata.Type = "images";
                        if (txtTitle.Text == "")
                        {
                            librarydata.Title = sShortName;
                        }
                        else
                        {
                            librarydata.Title = (string) txtTitle.Text;
                        }
                        librarydata.ParentId = Convert.ToInt64(parentId);
                        libraryId = _ContentApi.AddLibraryItem(ref librarydata);

                        LibraryData retLibraryData = _ContentApi.GetLibraryItemByID(libraryId, Convert.ToInt64(parentId));

                        //Uploading image to libray ends.
                        System.Drawing.Bitmap imageUpload;
                        imageUpload = new System.Drawing.Bitmap(sPhysicalPath + "\\" + sFileName);

                        // Add media image
                        ltrAddMediaJS.Text += "var newImageObj = {";
                        ltrAddMediaJS.Text += "        id: \"" + libraryId.ToString() + "\",";
                        ltrAddMediaJS.Text += "        title: \"" + retLibraryData.Title + "\",";
                        ltrAddMediaJS.Text += "        altText: \"" + txtAlt.Text + "\",";
                        ltrAddMediaJS.Text += "        path: \"" + librarydata.FileName + "\",";
                        ltrAddMediaJS.Text += "        width:" + imageUpload.Width + ",";
                        ltrAddMediaJS.Text += "        height:" + imageUpload.Height;

                        int x = 0;
                        if (_Thumbnails.Count > 0)
                        {
                            string sourceFile = sPhysicalPath + sFileName;
                            ltrAddMediaJS.Text += ",";
                            ltrAddMediaJS.Text += "Thumbnails: [";
                            for (x = 0; x <= _Thumbnails.Count - 1; x++)
                            {
                                ThumbnailData thumbnail = _Thumbnails[x];
                                string fileNameNoExtension = sFileName.Replace(System.IO.Path.GetExtension(sFileName), "");
                                string fileNameExtension = System.IO.Path.GetExtension(sFileName);
                                string thumbnailPath = retLibraryData.FileName.Replace(System.IO.Path.GetFileName(retLibraryData.FileName), "");
                                string thumbnailFile = fileNameNoExtension + thumbnail.Title.Replace("[filename]", "") + fileNameExtension;

                                ltrAddMediaJS.Text += "{";
                                ltrAddMediaJS.Text += "     title: \"" + thumbnail.Title + "\",";
                                ltrAddMediaJS.Text += "     imageName: \"" + thumbnail.ImageName + "\",";
                                ltrAddMediaJS.Text += "     path: \"" + thumbnail.Path + "\"";
                                ltrAddMediaJS.Text += "}" + Environment.NewLine;
                                if (x != _Thumbnails.Count - 1)
                                {
                                    ltrAddMediaJS.Text += "," + Environment.NewLine;
                                }

                            }

                            ltrAddMediaJS.Text += "] " + Environment.NewLine;

                        }

                        ltrAddMediaJS.Text += "  }" + Environment.NewLine;
                        ltrAddMediaJS.Text += "parent.Ektron.Commerce.MediaTab.Images.addNewImage(newImageObj);";

                        //766 LOAD BALANCING HANDLED BY SERVICE
                        //'----------------- Load Balance ------------------------------------------------------
                        //Dim loadbalance_data As LoadBalanceData()
                        //loadbalance_data = _ContentApi.GetAllLoadBalancePathsExtn(parentId, "images")
                        //If (Not (IsNothing(loadbalance_data))) Then
                        //    For j As Integer = 0 To loadbalance_data.Length - 1
                        //        sPhysicalPath = Server.MapPath(loadbalance_data(j).Path)
                        //        If (Right(sPhysicalPath, 1) <> "\") Then
                        //            sPhysicalPath = sPhysicalPath & "\"
                        //        End If
                        //        WriteToFile(sPhysicalPath & "\" & sFileName, myData)
                        //    Next
                        //    'Begins: Generate thumbnails. Generates thumbnails for various pixes sizes.
                        //    If _ProductTypeData.DefaultThumbnails.Count > 0 Then
                        //        Dim thumbnailCreator As New EkFileIO
                        //        Dim thumbnailResult As Boolean = False
                        //        Dim sourceFile As String = sPhysicalPath & "\" & sFileName
                        //        For Each thumbnail As ThumbnailDefaultData In _ProductTypeData.DefaultThumbnails
                        //            Dim fileNameNoExtension As String = sFileName.Replace(System.IO.Path.GetExtension(sFileName), "")
                        //            Dim fileNameExtension As String = System.IO.Path.GetExtension(sFileName)
                        //            Dim thumbnailFile As String = sPhysicalPath & "\" & fileNameNoExtension & Replace(thumbnail.Title, "[filename]", "") & fileNameExtension
                        //            thumbnailResult = thumbnailCreator.CreateThumbnail(sourceFile, thumbnailFile, thumbnail.Width, thumbnail.Height)
                        //        Next
                        //    End If
                        //    'Ends : Generate Thumbnails.
                        //End If
                    }
                    else
                    {
                        throw (new Exception("No File"));
                    }
                }
                catch (Exception ex)
                {
                    litError.Text = ex.Message;
                    ltrErrorJS.Text += "justtoggle(document.getElementById(\'dvErrorMessage\'), true);" + Environment.NewLine;
                }
        }
 private void AddLibraryButton_Click(object sender, System.EventArgs e)
 {
     if (LibraryNameTextBox.Text.Length == 0)
     {
         ((PageBase)Page).ShowErrorMessage(MessageLabel, ((PageBase)Page).GetPageResource("MissingLibraryNameMessage"));
         MessageLabel.Visible = true;
         return;
     }
     else
     {
         LibraryData libraryData = new LibraryData();
         LibraryData.LibrariesRow library = libraryData.Libraries.NewLibrariesRow();
         library.LibraryName = LibraryNameTextBox.Text;
         libraryData.Libraries.Rows.Add(library);
         new Library().AddLibrary(libraryData);
         LibraryNameTextBox.Text = string.Empty;
         BindData();
         ((PageBase)Page).ShowNormalMessage(MessageLabel, ((PageBase)Page).GetPageResource("AddedLibraryNameMessage"));
         MessageLabel.Visible = true;
     }
 }
Exemplo n.º 42
0
    protected void btnUpload_Click(object sender, System.EventArgs e)
    {
        string parentId = "";
        if ((Request.QueryString["catalogid"] != null) && Request.QueryString["catalogid"] != "")
        {
            parentId = Request.QueryString["catalogid"];
        }

        CheckAccess();
        try
        {
            if (!(ul_image.PostedFile == null))
            {
                productType = productTypeManager.GetItem(m_iID);

                int iFolder = iboardid;
                //lib_settings_data = Me.m_refContentApi.GetLibrarySettings(iFolder)

                // file was sent
                HttpPostedFile myFile = ul_image.PostedFile;
                string sFileExt = "";
                // Get and check size of uploaded file
                int nFileLen = myFile.ContentLength;
                //If nFileLen > _board.MaxFileSize Then
                //    Throw New Exception("File is too large. There is a " & _board.MaxFileSize.ToString() & " byte limit.")
                //End If
                //get and check name and extension
                string sFileName = myFile.FileName;
                string sShortName = "";
                if (myFile.FileName.IndexOf("\\") > -1)
                {
                    string[] aFilename = myFile.FileName.Split('\\');
                    // take the very last one
                    if (aFilename.Length > 0)
                    {
                        sFileName = aFilename[aFilename.Length - 1];
                    }
                }
                sFileName = sFileName.Replace(" ", "_").Replace("\'", ""); // make safe
                string[] aFileExt = sFileName.Split('.');
                if (aFileExt.Length > 1)
                {
                    sFileExt = (string)(aFileExt[(aFileExt.Length - 1)].Trim().ToLower()); //use the LAASSTT one.
                    if (sFileExt == "tif" || sFileExt == "bmp")
                    {
                        throw (new Exception("The extension \"" + sFileExt + "\" is not allowed."));
                    }
                    sShortName = sFileName.Substring(0, System.Convert.ToInt32(sFileName.Length - (sFileExt.Length + 1)));
                }
                else
                {
                    throw (new Exception("The extension \"" + sFileExt + "\" is not allowed."));
                }
                //aFileExt = Split(_board.AcceptedExtensions, ",")
                if (aFileExt.Length > 0)
                {
                    bool bGo = false;
                    for (int i = 0; i <= (aFileExt.Length - 1); i++)
                    {
                        if (sFileExt == aFileExt[i].Trim().ToLower())
                        {
                            bGo = true;
                            break;
                        }
                    }
                    if (bGo == false)
                    {
                        throw (new Exception("The extension \"" + sFileExt + "\" is not allowed."));
                    }
                }
                else
                {
                    throw (new Exception("The extension \"" + sFileExt + "\" is not allowed."));
                }

                // Allocate a buffer for reading of the file
                byte[] myData = new byte[nFileLen + 1];

                // Read uploaded file from the Stream
                myFile.InputStream.Read(myData, 0, nFileLen);

                //check for existence of file.
                FileInfo CheckFile;
                int iUnqueNameIdentifier = 0;
                string uploadImagePath = m_refContentApi.GetPathByFolderID(Convert.ToInt64(parentId));
                string sWebPath = lib_settings_data.ImageDirectory + uploadImagePath.Replace(" ", "_").Replace(".", "");
                string sPhysicalPath = Server.MapPath(sWebPath);
                CheckFile = new FileInfo(sPhysicalPath + "\\" + sFileName);
                if (CheckFile.Exists)
                {
                    while (CheckFile.Exists)
                    {
                        iUnqueNameIdentifier++;
                        sFileName = sShortName + "(" + iUnqueNameIdentifier + ")." + sFileExt;
                        CheckFile = new FileInfo(sPhysicalPath + sFileName);
                    }
                }

                //write
                WriteToFile(sPhysicalPath + "\\" + sFileName, myData);
                //----------------- Load Balance ------------------------------------------------------
                LoadBalanceData[] loadbalance_data;
                loadbalance_data = base.m_refContentApi.GetAllLoadBalancePathsExtn(iFolder, "files");
                if (!(loadbalance_data == null))
                {
                    for (int j = 0; j <= loadbalance_data.Length - 1; j++)
                    {
                        sPhysicalPath = Server.MapPath(loadbalance_data[j].Path);
                        if ((sPhysicalPath.Substring(sPhysicalPath.Length - 1, 1) != "\\"))
                        {
                            sPhysicalPath = sPhysicalPath + "\\";
                        }
                        WriteToFile(sPhysicalPath + "\\" + sFileName, myData);
                    }
                }

                //Begins: Generate thumbnails. Generates thumbnails for various pixes sizes.
                if (productType.DefaultThumbnails.Count > 0)
                {
                    foreach (ThumbnailDefaultData thumbnail in productType.DefaultThumbnails)
                    {
                        Utilities.ProcessThumbnail(sPhysicalPath, sFileName, thumbnail.Width, thumbnail.Height, thumbnail.Width);
                        // Utilities.ProcessThumbnail(sPhysicalPath, thumbnail.FileNameFormat.Replace("[filename]", sFileName), thumbnail.Width, thumbnail.Height, thumbnail.Width)
                    }
                }
                //Ends : Generate Thumbnails.

                //upload this file to library.
                LibraryData librarydata = new LibraryData();
                long libraryId = 0;
                librarydata.FileName = (string)((sWebPath.Replace("/\\", "\\") + "\\" + sFileName).Replace(" ", "_"));
                librarydata.Type = "images";
                if (txtTitle.Value == "")
                {
                    librarydata.Title = sShortName;
                }
                else
                {
                    librarydata.Title = (string)txtTitle.Value;
                }
                librarydata.ParentId = Convert.ToInt64(parentId);
                libraryId = m_refContentApi.AddLibraryItem(ref librarydata);

                LibraryData retLibraryData = m_refContentApi.GetLibraryItemByID(libraryId, Convert.ToInt64(parentId));
                //Uploading image to libray ends.
                System.Drawing.Bitmap imageUpload;
                imageUpload = new System.Drawing.Bitmap(sPhysicalPath + "\\" + sFileName);
                // Add media image
                ltrAddMediaJS.Text += "var newImageObj = {";
                ltrAddMediaJS.Text += "        id: \"" + libraryId.ToString() + "\", " + Environment.NewLine;
                ltrAddMediaJS.Text += "        title: \"" + retLibraryData.Title + "\", " + Environment.NewLine;
                ltrAddMediaJS.Text += "        altText: \"" + altTitle.Value + "\", " + Environment.NewLine;
                ltrAddMediaJS.Text += "        path: \"" + retLibraryData.FileName + "\", " + Environment.NewLine;
                ltrAddMediaJS.Text += "        width:" + imageUpload.Width + "," + Environment.NewLine;
                ltrAddMediaJS.Text += "        height:" + imageUpload.Height + "," + Environment.NewLine;
                ltrAddMediaJS.Text += "        Thumbnails: [" + Environment.NewLine;

                int iThumbnail = 0;

                for (iThumbnail = 0; iThumbnail <= productType.DefaultThumbnails.Count - 1; iThumbnail++)
                {
                    int indexThumbnail = retLibraryData.FileName.LastIndexOf("/");
                    string thumbnailpath = retLibraryData.FileName.Substring(0, indexThumbnail + 1);
                    ltrAddMediaJS.Text += "              {path: \"" + thumbnailpath + "thumb" + productType.DefaultThumbnails[iThumbnail].Width + "_" + sFileName + "\"}," + Environment.NewLine;
                }
                ltrAddMediaJS.Text += "        ] " + Environment.NewLine;
                ltrAddMediaJS.Text += "  }; " + Environment.NewLine;

                ltrAddMediaJS.Text += "parent.Ektron.Commerce.MediaTab.Images.addNewImage(newImageObj);";

            }
            else
            {
                throw (new Exception("No File"));
            }
        }
        catch (Exception ex)
        {
            ltr_error.Text = ex.Message;
            ltr_bottomjs.Text += "	justtoggle(document.getElementById(\'dvErrorMessage\'), true);" + Environment.NewLine;
            bError = true;
        }
    }
        protected void OnAddLibrary(Object sender, EventArgs e)
        {
            ((PageBase)Page).CheckRight(NSurveyRights.ManageLibrary, true);

            if (txtLibName.Text.Length == 0)
            {
                ((PageBase)Page).ShowErrorMessage(MessageLabel, ((PageBase)Page).GetPageResource("MissingLibraryNameMessage"));
                MessageLabel.Visible = true;
                return;
            }
            LibraryData libraryData = new LibraryData();
            LibraryData.LibrariesRow library = libraryData.Libraries.NewLibrariesRow();
            library.LibraryId = _libraryId;
            library.LibraryName = txtLibName.Text;
            library.Description = txtLibDescr.Text;
            //  library.DefaultLanguageCode = ddlDefaultLang.SelectedValue;
            //    new MultiLanguage().UpdateSurveyLanguage(LibraryId, ddlDefaultLang.SelectedValue, true, Constants.Constants.EntityLibrary);
            libraryData.Libraries.Rows.Add(library);

            if (LibraryEditMode)
            {
                LibraryFactory.Create().UpdateLibrary(libraryData);

                var ml = new MultiLanguage();
                // Reset all other default items  
                foreach (ListItem item in this.ddlDefaultLang.Items)
                    new MultiLanguage().UpdateSurveyLanguage(LibraryId, item.Value,item.Selected, Constants.Constants.EntityLibrary);
            }
            else
            {
                LibraryFactory.Create().AddLibrary(libraryData);
                new MultiLanguage().UpdateSurveyLanguage(libraryData.Libraries[0].LibraryId, System.Globalization.CultureInfo.CurrentCulture.Name, true, Constants.Constants.EntityLibrary);
                txtLibName.Text = string.Empty;
                txtLibDescr.Text = string.Empty;
            }
            ((PageBase)Page).ShowNormalMessage(MessageLabel, ((PageBase)Page).GetPageResource("UpdatedLibraryNameMessage"));
            MessageLabel.Visible = true;
            UINavigator.NavigateToLibraryDirectory(0, 0, 0);
            FillData();
        }
 private void UpdateLibraryButton_Click(object sender, System.EventArgs e)
 {
     if (LibraryNameTextBox.Text.Length == 0)
     {
         ((PageBase)Page).ShowErrorMessage(MessageLabel, ((PageBase)Page).GetPageResource("MissingLibraryNameMessage"));
         MessageLabel.Visible = true;
         editplaceholder.Visible = true;
         return;
     }
     else
     {
         LibraryData libraryData = new LibraryData();
         LibraryData.LibrariesRow library = libraryData.Libraries.NewLibrariesRow();
         library.LibraryId = int.Parse(ViewState["LibraryId"].ToString());
         library.LibraryName = LibraryNameTextBox.Text;
         libraryData.Libraries.Rows.Add(library);
         new Library().UpdateLibrary(libraryData);
         LibraryNameTextBox.Text = string.Empty;
         BindData();
         ((PageBase)Page).ShowNormalMessage(MessageLabel, ((PageBase)Page).GetPageResource("UpdatedLibraryNameMessage"));
         MessageLabel.Visible = true;
         editplaceholder.Visible = false;
     }
 }
Exemplo n.º 45
0
    private void ShowTagEditArea(ContentAPI m_refcontentapi, LibraryData library_data)
    {
        // display tag edit area
        System.Text.StringBuilder taghtml = new System.Text.StringBuilder();
        error_TagsCantBeBlank.Text = _MessageHelper.GetMessage("msg error Blank Tag");
        error_InvalidChars.Text = _MessageHelper.GetMessage("msg error Tag invalid chars");

        Hashtable htTagsAssignedToUser = new Hashtable();
        taghtml.Append("<div class=\"ektronTopSpace\"></div>");
        taghtml.Append("<div class=\"ektronHeader\">" + _MessageHelper.GetMessage("lbl personal tags") + "</div>");
        taghtml.Append("<div style=\"position: relative; top: 0px; left: 0px;\" >");

        taghtml.Append("    <div id=\"newTagNameDiv\" class=\"ektronWindow\">");
        taghtml.Append("        <div style=\"position: relative; top: 0px; left: 0px;\" >");
        taghtml.Append("            <div style=\"margin-top: 6px; margin-left: 10px; \" >");
        taghtml.Append("                <table class=\"ektronForm\">");
        taghtml.Append("                    <tr>");
        taghtml.Append("                        <td class=\"label\">");
        taghtml.Append(_MessageHelper.GetMessage("name label"));
        taghtml.Append("                        </td>");
        taghtml.Append("                        <td class=\"value\">");
        taghtml.Append("                            <input type=\"text\" style=\"width:275px;\" id=\"newTagName\" value=\"\" size=\"18\" onkeypress=\"if (event && event.keyCode && (13 == event.keyCode)) {SaveNewPersonalTag(); return false;}\" />");
        taghtml.Append("                        </td>");
        taghtml.Append("                    </tr>");
        taghtml.Append("                </table>");
        taghtml.Append("            </div>");

        if (IsSiteMultilingual)
        {
            //taghtml.Append("<div style=""margin-top: 6px; margin-left: 10px; "" >")
            taghtml.Append("<div style=\"display:none;\" >");
        }
        else
        {
            taghtml.Append("<div style=\"display:none;\" >");
        }
        taghtml.Append(_MessageHelper.GetMessage("res_lngsel_lbl") + "&#160;" + GetLanguageDropDownMarkup("TagLanguage"));
        taghtml.Append("    </div>");

        taghtml.Append("        <div style=\"margin-top:.5em;\">");
        taghtml.Append("            <ul class=\"buttonWrapper ui-helper-clearfix\">");
        taghtml.Append("                <li>");
        taghtml.Append("                    <a class=\"button buttonRight buttonInlineBlock redHover buttonClear\" type=\"button\" alt=\"" + _MessageHelper.GetMessage("btn cancel") + "\" title=\"" + _MessageHelper.GetMessage("btn cancel") + "\" onclick=\"CancelSaveNewPersonalTag();\">");
        taghtml.Append("                        <span>" + _MessageHelper.GetMessage("btn cancel") + "</span>");
        taghtml.Append("                    </a>");
        taghtml.Append("                </li>");

        taghtml.Append("                <li>");
        taghtml.Append("                    <a class=\"button buttonRight buttonInlineBlock greenHover buttonUpdate\" type=\"button\" title=\"" + _MessageHelper.GetMessage("btn save") + "\" alt=\"" + _MessageHelper.GetMessage("btn save") + "\" onclick=\"SaveNewPersonalTag();\" />");
        taghtml.Append("                        <span>" + _MessageHelper.GetMessage("btn save") + "</span>");
        taghtml.Append("                    </a>");
        taghtml.Append("                </li>");
        taghtml.Append("            </ul>");
        taghtml.Append("        </div>");

        taghtml.Append("        <input type=\"hidden\" id=\"newTagNameHdn\" name=\"newTagNameHdn\" value=\"\"  />");
        taghtml.Append("        </div>");
        taghtml.Append("    </div>");
        taghtml.Append("</div>");
        taghtml.Append("<div id=\"newTagNameScrollingDiv\" style=\"height: 80px; overflow: auto; border: solid 1px #aaaaaa; z-index: 1;\" >");

        LocalizationAPI localizationApi = new LocalizationAPI();

        //create hidden list of current tags so we know to delete removed ones.
        LanguageData[] languageDataArray = _SiteApi.GetAllActiveLanguages();

        foreach (LanguageData lang in languageDataArray)
        {
            taghtml.Append("<input type=\"hidden\" id=\"flag_" + lang.Id + ("\"  value=\"" + localizationApi.GetFlagUrlByLanguageID(lang.Id) + "\"  />"));
        }
        taghtml.Append("<input type=\"hidden\" id=\"flag_0\"  value=\"" + localizationApi.GetFlagUrlByLanguageID(-1) + "\"  />");

        TagData[] tdaUser = null;
        if (library_data != null)
        {
            if (library_data.Id > 0)
            {
                tdaUser = (new Ektron.Cms.Community.TagsAPI()).GetTagsForObject(library_data.Id, EkEnumeration.CMSObjectTypes.Library, m_refcontentapi.ContentLanguage);
            }
        }
        StringBuilder appliedTagIds = new StringBuilder();

        //build up a list of tags used by user
        //add tags to hashtable for reference later when looping through defualt tag list
        TagData td;
        if (tdaUser != null)
        {
            foreach (TagData tempLoopVar_td in tdaUser)
            {
                td = tempLoopVar_td;
                htTagsAssignedToUser.Add(td.Id, td);
                appliedTagIds.Append(td.Id.ToString() + ",");

                taghtml.Append("<input checked=\"checked\" type=\"checkbox\" id=\"userPTagsCbx_" + td.Id.ToString() + "\" name=\"userPTagsCbx_" + td.Id.ToString() + "\" />&#160;");
                taghtml.Append("<img src=\'" + localizationApi.GetFlagUrlByLanguageID(td.LanguageId) + "\' />");
                taghtml.Append("&#160;" + td.Text + "<br />");
            }
        }

        //create hidden list of current tags so we know to delete removed ones.
        taghtml.Append("<input type=\"hidden\" id=\"currentTags\" name=\"currentTags\" value=\"" + appliedTagIds.ToString() + "\"  />");

        TagData[] tdaAll;
        tdaAll = (new Ektron.Cms.Community.TagsAPI()).GetDefaultTags(EkEnumeration.CMSObjectTypes.Library, m_refcontentapi.ContentLanguage);
        if (tdaAll != null)
        {
            foreach (TagData tempLoopVar_td in tdaAll)
            {
                td = tempLoopVar_td;
                //don't add to list if its already been added with user's tags above
                if (!htTagsAssignedToUser.ContainsKey(td.Id))
                {
                    taghtml.Append("<input type=\"checkbox\" id=\"userPTagsCbx_" + td.Id.ToString() + "\" name=\"userPTagsCbx_" + td.Id.ToString() + "\" />&#160;");
                    taghtml.Append("<img src=\'" + localizationApi.GetFlagUrlByLanguageID(td.LanguageId) + "\' />");
                    taghtml.Append("&#160;" + td.Text + "<br />");
                }
            }
        }

        taghtml.Append("<div id=\"newAddedTagNamesDiv\"></div>");

        taghtml.Append("</div>");

        taghtml.Append("<div style=\"float:left;\">");
        taghtml.Append("    <a class=\"button buttonLeft greenHover buttonAddTagWithText\" href=\"#\" onclick=\"ShowAddPersonalTagArea();\">" + _MessageHelper.GetMessage("btn add personal tag") + "</a>" + "\r\n");
        taghtml.Append("</div>");

        ShowTags.Text = taghtml.ToString();
    }