public void testConstructedGenericClass() {
			var typeSystem = new Library(new String[] { bin });
			var typeInfo = typeSystem.getType("stab/bytecode/test/classes/GenericClass");
			var args = new ArrayList<TypeInfo>();
			args.add(typeSystem.getType("java/lang/String"));
			doTest("ConstructedGenericClass", typeSystem.getGenericType(typeInfo, args));
		}
Example #2
0
 internal unsafe EntityInfo(Library.EntityInfo handle, ITranslationUnitItemFactory itemFactory)
 {
     _itemFactory = itemFactory;
     _handle = handle;
     _name = new string(_handle.name);
     _usr = new string(_handle.USR);
 }
Example #3
0
        public Menu(Library.States.State previousState, string headerText, bool immediate)
        {
            mPreviousState = previousState;

            mHeaderText = headerText;

            mActions = new List<Action>();

            mOffsetX = 240f + (immediate ? 0 : 480f);

            mSelection = 0;

            mCurrentKeyCode = Keys.None;

            mBackground = new Library.Graphics.Flat(new Vector2(Application.Instance.GraphicsDevice.Viewport.Width, Application.Instance.GraphicsDevice.Viewport.Height), Color.Black, null);
            mBackground.Layer = Layers.Menu;

            mIgnoreKeys = new Dictionary<Keys, bool>();
            mIgnoreButtons = new Dictionary<Buttons, bool>();

            mBackground.Opacity = .75f;

            mHeader = new Library.Graphics.String("fonts/menus/headers", mHeaderText);
            mHeader.Layer = Layers.MenuText;
        }
        public static void Save(Library sourceLib, string Path)
        {
            try
            {
                string[] chn = new string[Library.CurrentLength()];
                string[] eng = new string[Library.CurrentLength()];
                string[] frequencyString = new string[Library.CurrentLength()];

                for (int i = 0; i < Library.CurrentLength(); i++)
                {
                    //if (sourceLib.GetEntry(i) == null)
                    //{
                    //chn[i] = "";
                    //eng[i] = "";
                    //frequencyString[i] = "0";
                    //}//prevent empty entry : string ""
                    //else
                    //{
                    chn[i] = sourceLib.GetEntry(i).GetChinese();
                    eng[i] = sourceLib.GetEntry(i).GetEnglish();
                    frequencyString[i] = sourceLib.GetEntry(i).GetFrequency().ToString();

                    //}
                }

                System.IO.File.WriteAllLines(frequencyPath, frequencyString);
                System.IO.File.WriteAllLines(engPath, eng);
                System.IO.File.WriteAllLines(chnPath, chn);
            }
            catch { DeleteLibrary(); }
        }
        /// <summary>
        ///     Loads all the play-lists in the play-list folder
        /// </summary>
        public static void LoadPlaylists(Library libary)
        {
            //var playlistFiles = FileSystemHelper.SearchFiles(PlaylistFolder, "*.m3u", false);

            //Playlists = playlistFiles.Select(playlistFile => LoadPlaylist(playlistFile, libary)).ToList();
            Playlists = new List<Playlist>();
        }
Example #6
0
        public GenreItem(Library.GalleryItem title, IModelItem owner, List<TitleFilter> filter)
            : base(owner)
        {
            this.Description = title.Name;
            this.DefaultImage=title.MenuCoverArt;
            this.Metadata = string.Format("{0} titles", title.ForcedCount);
            this.Invoked += delegate(object sender, EventArgs args)
            {
                //am I being silly here copying this?
                List<TitleFilter> newFilter = new List<TitleFilter>();
                foreach (TitleFilter filt in filter)
                {
                    newFilter.Add(filt);
                }
                newFilter.Add(new TitleFilter(title.Category.FilterType, title.Name));
                OMLProperties properties = new OMLProperties();
                properties.Add("Application", OMLApplication.Current);
                properties.Add("I18n", I18n.Instance);
                Command CommandContextPopOverlay = new Command();
                properties.Add("CommandContextPopOverlay", CommandContextPopOverlay);

                Library.Code.V3.GalleryPage gallery = new Library.Code.V3.GalleryPage(newFilter, title.Description);

                properties.Add("Page", gallery);
                OMLApplication.Current.Session.GoToPage(@"resx://Library/Library.Resources/V3_GalleryPage", properties);
            };
        }
        /// <summary>
        /// Called when [after_ add class properties].
        /// </summary>
        /// <param name="assemblyCode">The assembly code.</param>
        /// <param name="process">The process.</param>
        /// <param name="isInfoProperty">if set to <c>true</c> [is information property].</param>
        /// <param name="resolveRefTypes">if set to <c>true</c> [resolve reference types].</param>
        /// <param name="skipId">if set to <c>true</c> [skip identifier].</param>
        public override void OnAfter_AddClassProperties(StringBuilder assemblyCode, Library.Process.Publisher.Definitions.IProcessDefinition process, bool isInfoProperty, bool resolveRefTypes, bool skipId = false)
        {
            base.OnAfter_AddClassProperties(assemblyCode, process, isInfoProperty, resolveRefTypes, skipId);

            if (!isInfoProperty) return;

            foreach (var crf in process.RootTable.FieldList.Where(f => f.ColumnType == ColumnTypes.Reference && !f.IsHidden && f.IncludeInList))
            {
                assemblyCode.AppendFormat(@"
        private {1}Info _{0}Member;
        public {1}Info {0}Member
        {{ 
            get 
            {{
                if (_{0}Member == null && {0}Id > 0) 
                {{
                    var items = {1}List.Get{1}PageList(string.Empty, {0}Id, 1, null, null);
                    if (items.Count > 0) 
                    {{
                        _{0}Member = items[0];
                    }}
                }}
                return _{0}Member;
            }}
        }}
"
                    , crf.ColumnName, crf.ReferencedProcessName);
            }
        }
Example #8
0
        /// <summary>
        /// This method is called before ActionManager.InvokeActions in EditableRoot.DataPortal_Update.
        /// </summary>
        /// <param name="code">
        /// The code.
        /// </param>
        /// <param name="process">
        /// The process.
        /// </param>
        public override void OnBefore_EditableRoot_DataPortal_Update_InvokeActions(StringBuilder code, Library.Process.Publisher.Definitions.IProcessDefinition process)
        {
            // Update action items if BasePerson.OutOfOffice changes.
            code.AppendFormat(@"
            ActionItemManager.CheckOutOfOffice(this, oldItem);
");
        }
Example #9
0
 public Charts()
 {
     this.InitializeComponent();
     library = new Library();
     this.Loaded += MainPage_Loaded;
     rtrackact = new RootObjectTrackAct();
 }
Example #10
0
        /// <summary>
        /// Creates a <see cref="ILibraryExport"/> containing the references necessary
        /// to use the provided <see cref="Library"/> during compilation.
        /// </summary>
        /// <param name="library">The <see cref="Library"/> to export</param>
        /// <returns>A <see cref="ILibraryExport"/> containing the references exported by this library</returns>
        public ILibraryExport ExportLibrary(Library library, DependencyManager dependencies)
        {
            // Check if we have a value cached on the Library
            var export = library.GetItem<ILibraryExport>(LibraryExportLibraryPropertyName);
            if (export != null)
            {
                return export;
            }

            switch (library.Identity.Type)
            {
                case LibraryTypes.Package:
                    export = ExportPackageLibrary(library);
                    break;

                case LibraryTypes.Project:
                    export = ExportProjectLibrary(library, dependencies);
                    break;

                default:
                    export = ExportOtherLibrary(library);
                    break;
            }

            // Cache for later use.
            library[LibraryExportLibraryPropertyName] = export;
            LogExport(library, export);
            return export;
        }
        public BulkThumbnailGenerator(Library library, SizedThumbnailGenerator thumbnailGenerator)
        {
            _library = library;
            _thumbnailGenerator = thumbnailGenerator;

            ThumbnailGenerated += (_, __) => { };
        }
 public GroupElement(Group group, ConfigLocation location, Library representing)
     : base(@group.Name, null)
 {
     Group = group;
     Location = location;
     Representing = representing;
 }
Example #13
0
        public IList<String> Parse(string input, bool showOutput)
        {
            Context.Parser = this;
            Context.Object = null;
            Context.IndirectObject = null;
            
            parserResults = new List<string>();

            Library L = new Library();
            bool wasLit = L.IsLit();

            var userInput = new UserInput();
            var inputResult = userInput.Parse(input);
            isAll = inputResult.IsAll;

            if (inputResult.HasError)
            {
                parserResults.Add(inputResult.Error);
            }
            else
            {
                HandleInputResult(inputResult);
            }

            if (!wasLit && L.IsLit())
                L.Look(true);

            return GetResults(showOutput);
        }
        public ActionResult Create(Library library, HttpPostedFileBase file, Guid id)
        {
            string fileName = Path.GetFileName(file.FileName);
            if (fileName != null)
            {
                var path = Path.Combine(Server.MapPath("~/Image"), library.Name+".jpg");

                file.SaveAs(path);
            }
            library.Address = new Address()
            {
                City = library.Address.City,
                Contry = library.Address.Contry,
                PostCode = library.Address.PostCode,
                Street = library.Address.Street,
                Number = library.Address.Number
            };
            library.Photo = library.Name + ".jpg";
            try
            {
                if (_libraryRepository.AddLibrary(library,_libraryRepository.GetUserByGuid(id) ))
                {
                    return RedirectToActionPermanent("Index", "Home");
                }
            }
            catch (Exception)
            {
                return View(library);
            }
            return View(library);
        }
Example #15
0
 new void Start()
 {
     base.Start();
     library = GameObject.FindObjectOfType<Library>();
     button = GetComponent<Button>();
     button.onClick.AddListener(delegate { UseButton(); });
 }
Example #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Simulation"/> class.
        /// </summary>
        /// <param name="playGroundSize">Size of the play ground.</param>
        /// <param name="sharksLifeTime">The sharks life time.</param>
        /// <param name="sharksHunger">The sharks hunger.</param>
        /// <param name="sepiasLifeTime">The sepias life time.</param>
        /// <param name="sharksCount">The sharks count.</param>
        /// <param name="sepiasCount">The sepias count.</param>
        /// <remarks></remarks>
        public Simulation(Library.Pair playGroundSize, int sharksLifeTime, int sharksHunger,
            int sepiasLifeTime, int sharksCount, int sepiasCount, int sepiasChildren, int sharksChildren)
        {
            _sharksHunger = sharksHunger;
            _sharksLifeTime = sharksLifeTime;
            _sepiasLifeTime = sepiasLifeTime;
            if (sharksCount + sepiasCount > (playGroundSize.Y * playGroundSize.X))
            {
                throw new Exception("Too much creatures!");
            }
            if (playGroundSize.X < 5 || playGroundSize.Y < 5)
            {
                throw new Exception("Too small field");
            }

            _positionsCatalog = new List<Library.Pair>();
            _positionsCatalog.Add(new Library.Pair(-1, -1));
            _positionsCatalog.Add(new Library.Pair(0, -1));
            _positionsCatalog.Add(new Library.Pair(1, -1));
            _positionsCatalog.Add(new Library.Pair(-1, 0));
            _positionsCatalog.Add(new Library.Pair(1, 0));
            _positionsCatalog.Add(new Library.Pair(-1, 1));
            _positionsCatalog.Add(new Library.Pair(0, 1));
            _positionsCatalog.Add(new Library.Pair(1, 1));

            _sepiasChildren = sepiasChildren;
            _sharksChildren = sharksChildren;
            SepiasCount = sepiasCount;
            SharksCount = sharksCount;
            InitializeField(playGroundSize);
            Thread run = new Thread(new ThreadStart(RunSimulation));
            run.IsBackground = true;
            run.Start();
        }
Example #17
0
    static void Main(string[] args)
    {
        Book firstBook = new Book("C#", "Svetlin Nakov");
        Book secondBook = new Book("Java", "Svetlin Nakov");
        Book thirdBook = new Book(".NET", "Svetlin Nakov");
        Book fourthBook = new Book("Ice and fire", "George Martin");

        Library telerikLib = new Library("Telerik Library");
        
        
        telerikLib.Add(firstBook);
        telerikLib.Add(secondBook);
        telerikLib.Add(thirdBook);
        telerikLib.Add(fourthBook);
        Console.WriteLine("Display library :");
        telerikLib.DisplayAll();

        int startIndx = 0;
        int indxFound;

        while (telerikLib.IndexOf("Svetlin Nakov", startIndx, SearchOption.Author) != -1)
        {
            indxFound = telerikLib.IndexOf("Svetlin Nakov", startIndx, SearchOption.Author);
            telerikLib.DeleteAt(indxFound);
        }
        Console.WriteLine("\nAfter deleting :");
        telerikLib.DisplayAll();
    }
 protected override bool FoundInLibrary(Library lib, SearchResult searchResult)
 {
     bool duplicate = false;
     SearchResultMonster srm = searchResult as SearchResultMonster;
     Creature c = lib.FindCreatureCaseInsensitive(srm.Name, Convert.ToInt32(srm.Level));
     if (c != null)
     {
         if (c.HP == 1)
         {
             Minion m = c.Role as Minion;
             if (m.HasRole)
             {
                 duplicate = m.Type.ToString() == srm.CombatRole;
             }
         }
         else
         {
             ComplexRole cr = c.Role as ComplexRole;
             duplicate = srm.CombatRole.StartsWith(cr.Type.ToString()) &&
                         (cr.Leader == srm.CombatRole.Contains("Leader")) &&
                         (cr.Flag.ToString() == srm.GroupRole);
         }
     }
     return duplicate;
 }
Example #19
0
        // this method basically shows a serious design flaw. because the parser does not
        // currently remember the last command
        private void ObjectNotSpecified()
        {
            var L = new Library();

            // do not use Print, go directly to output
            Context.Output.Print("What do you want to unlock the {0} with?", Object.Name);
            
            string input = Context.CommandPrompt.GetInput();
            if (string.IsNullOrEmpty(input))
            {
                Print(L.DoNotUnderstand);
                return;
            }

            var tokenizer = new InputTokenizer();
            var tokens = tokenizer.Tokenize(input);

            // player is answering the question (no verb specified) vs. re-typing
            // a complete sentence
            if (!tokens.StartsWithVerb())
            {
                // this is very simplistic right now
                input = "unlock " + Object.Synonyms[0] + " with " + String.Join(" ", tokens.ToArray());
            }

            Context.Parser.Parse(input);

        }
Example #20
0
 public userMapOverlay(IMapDrawable drawable, Geocode geocode, Library.User user)
 {
     _drawable = (userMapDrawable)drawable;
     _geocode = geocode;
     _user = user;
     _offset = new Point((ClientSettings.SmallArtSize + (ClientSettings.Margin * 2) / 2), (ClientSettings.SmallArtSize + (ClientSettings.Margin * 2)));
 }
Example #21
0
    public PropertyStatus(Library.ProjectEdit project, string propertyName)
    {
      _propertyName = propertyName;
      _project = project;
      _project.PropertyChanged += _project_PropertyChanged;

    }
        public Library GetLibrary(LibraryRange libraryRange, NuGetFramework targetFramework)
        {
            var key = Tuple.Create(targetFramework, libraryRange.Name);
            LockFileTargetLibrary library = null;

            // Determine if we have a library for this target
            if (_targetLibraries.TryGetValue(key, out library) &&
                libraryRange.VersionRange.IsBetter(current: null, considering: library.Version))
            {
                var dependencies = GetDependencies(library, targetFramework);

                var description = new Library {
                    LibraryRange = libraryRange,
                    Identity = new LibraryIdentity
                    {
                        Name = library.Name,
                        Version = library.Version,
                        Type = LibraryTypes.Package
                    },
                    Resolved = true,
                    Dependencies = dependencies,

                    [KnownLibraryProperties.LockFileLibrary] = _libraries[Tuple.Create(library.Name, library.Version)],
                    [KnownLibraryProperties.LockFileTargetLibrary] = library
                };
                
                return description;
            }

            return null;
        }
Example #23
0
        public Project()
        {
            Uid = Guid.NewGuid();
            _services = new ServiceContainer();

            Name = "Project";

            _levels = new NamedResourceCollection<Level>();
            _levels.Modified += (s, e) => OnModified(EventArgs.Empty);

            _libraryManager = new LibraryManager();
            _libraryManager.Libraries.Modified += (s, e) => OnModified(EventArgs.Empty);

            Library defaultLibrary = new Library();

            _libraryManager.Libraries.Add(defaultLibrary);

            Extra = new List<XmlElement>();

            _texturePool = new MetaTexturePool();
            _texturePool.AddPool(defaultLibrary.Uid, defaultLibrary.TexturePool);

            _tilePools = new MetaTilePoolManager(_texturePool);
            _tilePools.AddManager(defaultLibrary.Uid, defaultLibrary.TilePoolManager);
            _objectPools = new MetaObjectPoolManager(_texturePool);
            _objectPools.AddManager(defaultLibrary.Uid, defaultLibrary.ObjectPoolManager);
            _tileBrushes = new MetaTileBrushManager();
            _tileBrushes.AddManager(defaultLibrary.Uid, defaultLibrary.TileBrushManager);

            SetDefaultLibrary(defaultLibrary);

            _services.AddService(typeof(TilePoolManager), _tilePools);

            ResetModified();
        }
Example #24
0
        public async Task Initialize()
        {
            // Quickly create a new domain named 'test' with its schema MyModelDefinition
            var domain = await StoreBuilder.CreateDomain<LibraryDefinition>("lib");

            // Allow to omit the domain argument when you create a domain element.            
            domain.Store.DefaultSessionConfiguration.DefaultDomainModel = domain;

            // Instanciate a new Library within the domain (always in a session)
            var rnd = new Random();
            using (var session = domain.Store.BeginSession())
            { 
                Library = new Library();
                Library.Name = "My library";

                for (int i = 1; i < 20; i++)
                {
                    var b = new Book();
                    b.Title = "Book " + i.ToString();
                    b.Copies = 1 + rnd.Next(10);
                    Library.Books.Add(b);

                    var m = new Member();
                    m.Name = "Member " + i.ToString();
                    Library.Members.Add(m);
                }

                session.AcceptChanges();
            }
        }
Example #25
0
		static void Main(string[] args)
		{
			Database.SetInitializer(new LibraryInitializer());
			//var person = new Author
			//{
			//    AuthorId = 2,
			//    Email = "*****@*****.**",
			//    Name = "Helen",
			//    BirthDate = DateTime.Now,
			//};
			//var collection = new BooksCollection
			//{
			//    Name = "New collection",
			//    BooksCollectionId = 1,
			//    CollectorId = 2
			//};
			//var book = new Book
			//{
			//    BookId = 1,
			//    Name = "First book",
			//    AuthorId = 2,
			//    BookCollectionId = 1,
			//};
			using (var db = new Library())
			{
			//    db.Collections.Add(collection);
			//    db.Authors.Add(person);
			//    db.Books.Add(book);
			    db.SaveChanges();
			//    //var author = db.Books.First().Author; author is NULL!!!!
			//    //Console.Write(string.Format("Firat book author name is {0}, email is {1}", author.Name, author.Email));
			}
			Console.Write("Author saved !");
			Console.ReadLine();
		}
        public static string ToInfoMessage(Library.Net.Amoeba.Seed seed)
        {
            if (seed == null) throw new ArgumentNullException("seed");

            try
            {
                var keywords = seed.Keywords.Where(n => !string.IsNullOrWhiteSpace(n)).ToList();

                StringBuilder builder = new StringBuilder();

                if (!string.IsNullOrWhiteSpace(seed.Name)) builder.AppendLine(string.Format("{0}: {1}", LanguagesManager.Instance.Seed_Name, seed.Name));
                if (seed.Certificate != null) builder.AppendLine(string.Format("{0}: {1}", LanguagesManager.Instance.Seed_Signature, seed.Certificate.ToString()));
                builder.AppendLine(string.Format("{0}: {1:#,0}", LanguagesManager.Instance.Seed_Length, seed.Length));
                if (keywords.Count != 0) builder.AppendLine(string.Format("{0}: {1}", LanguagesManager.Instance.Seed_Keywords, String.Join(", ", keywords)));
                builder.AppendLine(string.Format("{0}: {1} UTC", LanguagesManager.Instance.Seed_CreationTime, seed.CreationTime.ToUniversalTime().ToString(LanguagesManager.Instance.DateTime_StringFormat, System.Globalization.DateTimeFormatInfo.InvariantInfo)));
                if (!string.IsNullOrWhiteSpace(seed.Comment)) builder.AppendLine(string.Format("{0}: {1}", LanguagesManager.Instance.Seed_Comment, seed.Comment));

                if (builder.Length != 0) return builder.ToString().Remove(builder.Length - 2);
                else return null;
            }
            catch (Exception e)
            {
                throw new ArgumentException("ArgumentException", e);
            }
        }
		public void testObjectMethods() {
			var typeSystem = new Library(new String[] {});
			var typeInfo = typeSystem.getType("java/lang/Object");
			var names = Query.asIterable(new String[] { 
				"<init>", "equals", "getClass", "hashCode", "notify", "notifyAll", "toString", "wait", "wait", "wait" });
			Assert.assertTrue(typeInfo.Methods.where(p => p.IsPublic).select(p => p.Name).orderBy(p => p).sequenceEqual(names));
		}
Example #28
0
        /// <summary>
        /// Starts the applications logic. Loads libraries, ect.
        /// </summary>
        public void Start()
        {
            //Load the app settings
            _settings = new Settings();
            _settings.Load();

            try
            {
                FileInfo dataFile = new FileInfo(_settings.LibraryDatabaseFilePath);
                if(!dataFile.Directory.Exists )
                {
                    dataFile.Directory.Create();
                }
            }
            catch(Exception e)
            {
                //Well this puts us in a pickle

             //   System.Windows.Forms.MessageBox.Show("Unable to start αPlay! Could not find nor create αPlay directory.\r\nError: " + e.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

            //Load main library
            Library mainLib = new Library(_settings.LibraryDatabaseFilePath);
            _libraries.Add(mainLib);

            //Start UI thread
               // _uiThread = new Thread(new ThreadStart(delegate {Application.Run(new MainWindow(this));}));
            //_uiThread.SetApartmentState(ApartmentState.STA);
            //_uiThread.IsBackground = false;
            //_uiThread.Start();
        }
        public Library GetLibrary(LibraryRange libraryRange, NuGetFramework targetFramework)
        {
            var package = FindCandidate(libraryRange.Name, libraryRange.VersionRange);

            if (package != null)
            {
                NuspecReader nuspecReader = null;
                using (var stream = File.OpenRead(package.ManifestPath))
                {
                    nuspecReader = new NuspecReader(stream);
                }

                var description = new Library
                    {
                        LibraryRange = libraryRange,
                        Identity = new LibraryIdentity
                            {
                                Name = package.Id,
                                Version = package.Version,
                                Type = LibraryTypes.Package
                            },
                        Path = package.ManifestPath,
                        Dependencies = GetDependencies(nuspecReader, targetFramework)
                    };

                description.Items["package"] = package;
                description.Items["metadata"] = nuspecReader;

                return description;
            }

            return null;
        }
Example #30
0
 public RemoteVolume(Library.Interface.IFileEntry file, string hash = null)
 {
     this.Name = file.Name;
     this.Size = file.Size;
     this.Hash = hash;
     this.File = file;
 }
Example #31
0
        public void MergePin(Task task)
        {
            Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> Processing MergePin.");
            var prfMonMethod = new PrfMon();

            var fromSite = _siteRepository.Single(x => x.Pin == task.FromPin.Value);
            var toSite   = _siteRepository.Single(x => x.Pin == task.ToPin.Value);
            var fromSiteDocumentLibraries = _libraryRepository.Query(x => x.SiteId == fromSite.Id).ToList();

            var activeDirectoryContributeGroup       = _parameterService.GetParameterByNameAndCache <string>(ParameterNames.ActiveDirectoryContributeGroup);
            var activeDirectoryContributeClosedGroup = _parameterService.GetParameterByNameAndCache <string>(ParameterNames.ActiveDirectoryContributeClosedGroup);
            var activeDirectoryReadGroup             = _parameterService.GetParameterByNameAndCache <string>(ParameterNames.ActiveDirectoryReadGroup);
            var pinSiteDocumentLibraries             = new Dictionary <Guid, Guid>();

            using (var context = new ClientContext(SiteCollectionUrl(fromSite.ProvisionedSite.ProvisionedSiteCollection.Name)))
            {
                var web = _contextService.Load(context, Credentials);

                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> CheckRequiredSecurityGroupsExist. Started.");
                var checkRequiredSecurityGroupsExistPrfMonTriggers = new PrfMon();
                var spFromSite = web.Webs.Single(x => x.Url == fromSite.Url);
                var colGroup   = spFromSite.SiteGroups;
                context.Load(colGroup);
                var globalSystemsAdminUser =
                    web.EnsureUser(
                        _parameterService.GetParameterByNameAndCache <string>(
                            ParameterNames.ActiveDirectoryGlobalSystemsAdministratorGroup));
                foreach (var library in
                         fromSiteDocumentLibraries.Select(s => new { s.ProjectId, s.IsClosed }).Distinct().ToList())
                {
                    web.GetActiveDirectoryContributorGroup(activeDirectoryContributeGroup,
                                                           activeDirectoryContributeClosedGroup, fromSite.RestrictedUser, library.IsClosed, fromSite.Pin,
                                                           library.ProjectId);
                    web.GetActiveDirectoryGroup(activeDirectoryReadGroup, fromSite.RestrictedUser, fromSite.Pin,
                                                library.ProjectId);
                }
                context.Load(globalSystemsAdminUser, u => u.Id);
                var spFromPinMembersGroup  = colGroup.GetByName(string.Format(SharePointPinGroupNames.PinMembers, fromSite.Pin));
                var spFromPinVisitorsGroup = colGroup.GetByName(string.Format(SharePointPinGroupNames.PinVisitors, fromSite.Pin));
                context.Load(spFromPinMembersGroup.Users, x => x.Include(u => u.Id, u => u.PrincipalType, u => u.Title));
                context.Load(spFromPinVisitorsGroup.Users, x => x.Include(u => u.Id, u => u.PrincipalType, u => u.Title));
                context.ExecuteQuery();
                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> CheckRequiredSecurityGroupsExist. Completed. Average Execution: {0:0.000}s", checkRequiredSecurityGroupsExistPrfMonTriggers.Stop());

                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> CheckFromPinSiteDocumentSizes. Started.");
                var checkFromPinSiteDocumentSizesPrfMonTriggers = new PrfMon();
                var maximumFileSizeBytes = _parameterService.GetParameterByNameAndCache <int>(ParameterNames.MaximumFileSizeMb) * 1024 * 1024;
                var allLists             = spFromSite.Lists;
                context.Load(allLists, lc => lc.Include(l => l.Id, l => l.Title, l => l.IsSiteAssetsLibrary, l => l.Hidden,
                                                        l => l.BaseType, l => l.ContentTypesEnabled, l => l.IsApplicationList, l => l.IsCatalog,
                                                        l => l.IsPrivate, l => l.RootFolder.ServerRelativeUrl));
                context.ExecuteQuery();
                foreach (var list in allLists)
                {
                    if (!list.Hidden && (list.BaseType == BaseType.DocumentLibrary) && list.ContentTypesEnabled &&
                        !list.IsApplicationList && !list.IsCatalog && !list.IsSiteAssetsLibrary && !list.IsPrivate)
                    {
                        var folder = list.RootFolder;
                        folder.CheckFolderFileSizesWithinSizeLimit(context, fromSite.Pin, list.Title, maximumFileSizeBytes);
                    }
                }

                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> CheckFromPinSiteDocumentSizes. Completed. Average Execution: {0:0.000}s", checkFromPinSiteDocumentSizesPrfMonTriggers.Stop());

                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> PinFromSitePermissions. Started.");
                var pinSitePermissionsPrfMonTriggers = new PrfMon();
                var contributeUsers = spFromPinMembersGroup.Users.Where(u => u.PrincipalType == PrincipalType.SecurityGroup &&
                                                                        u.Title.EndsWith("_CONTRIBUTE") ||
                                                                        u.Title.EndsWith("_CONTRIBUTE_CLOSED") ||
                                                                        u.Title.EndsWith($"_CONTRIBUTE_{fromSite.Pin}") ||
                                                                        u.Title.EndsWith($"_CONTRIBUTE_CLOSED_{fromSite.Pin}")).ToList();
                foreach (var user in contributeUsers)
                {
                    spFromPinMembersGroup.Users.RemoveById(user.Id);
                }
                var readUsers = spFromPinVisitorsGroup.Users.Where(u => u.PrincipalType == PrincipalType.SecurityGroup && u.Title.EndsWith("_READ") || u.Title.EndsWith($"_READ_{fromSite.Pin}")).ToList();
                foreach (var user in readUsers)
                {
                    spFromPinVisitorsGroup.Users.RemoveById(user.Id);
                }
                var globalSystemAdminUser = spFromPinMembersGroup.Users.FirstOrDefault(u => u.Id == globalSystemsAdminUser.Id);
                if (globalSystemAdminUser != null)
                {
                    spFromPinMembersGroup.Users.RemoveById(globalSystemsAdminUser.Id);
                }
                context.ExecuteQuery();
                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> PinFromSitePermissions. Completed. Average Execution: {0:0.000}s", pinSitePermissionsPrfMonTriggers.Stop());

                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> RemoveDocumentLibraryPermissions. Started.");
                var libraryPermissionsPrfMonTriggers = new PrfMon();
                foreach (var documentLibrary in fromSiteDocumentLibraries)
                {
                    var documentLibraryList = spFromSite.Lists.GetById(documentLibrary.ListId);
                    documentLibraryList.OnQuickLaunch = false;
                    documentLibraryList.Update();
                    context.Load(documentLibraryList);
                    context.Load(documentLibraryList.RoleAssignments, r => r.Include(m => m.Member.Id));
                    context.ExecuteQuery();
                    var currentProjectContributorsGroup = web.GetActiveDirectoryContributorGroup(activeDirectoryContributeGroup, activeDirectoryContributeClosedGroup, fromSite.RestrictedUser, documentLibrary.IsClosed, fromSite.Pin, documentLibrary.ProjectId);
                    context.Load(currentProjectContributorsGroup, u => u.Id);
                    context.ExecuteQuery();
                    documentLibraryList.RoleAssignments.Where(r => r.Member.Id == currentProjectContributorsGroup.Id || r.Member.Id == globalSystemsAdminUser.Id).ToList().ForEach(ra => ra.DeleteObject());
                    context.ExecuteQuery();
                }
                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> RemoveDocumentLibraryPermissions. Completed. Average Execution: {0:0.000}s", libraryPermissionsPrfMonTriggers.Stop());

                _contextService.Audit(context, task, string.Format(TaskResources.Audit_MergePin, fromSite.Pin, toSite.Pin));
            }

            using (var context = new ClientContext(SiteCollectionUrl(toSite.ProvisionedSite.ProvisionedSiteCollection.Name)))
            {
                var web = _contextService.Load(context, Credentials);

                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> LoadRequiredSecurityGroups. Started.");
                var loadRequiredSecurityGroupsExistPrfMonTriggers = new PrfMon();
                var spToSite = web.Webs.Single(x => x.Url == toSite.Url);
                var colGroup = spToSite.SiteGroups;
                context.Load(colGroup);
                var globalSystemsAdminUser = web.EnsureUser(_parameterService.GetParameterByNameAndCache <string>(ParameterNames.ActiveDirectoryGlobalSystemsAdministratorGroup));
                context.Load(globalSystemsAdminUser, u => u.Id);
                var spToPinMembersGroup  = colGroup.GetByName(string.Format(SharePointPinGroupNames.PinMembers, toSite.Pin));
                var spToPinVisitorsGroup = colGroup.GetByName(string.Format(SharePointPinGroupNames.PinVisitors, toSite.Pin));
                context.Load(spToPinMembersGroup.Users, x => x.Include(u => u.Id, u => u.PrincipalType, u => u.Title));
                context.Load(spToPinVisitorsGroup.Users, x => x.Include(u => u.Id, u => u.PrincipalType, u => u.Title));
                context.Load(spToSite, s => s.Lists.Include(l => l.Title));
                context.ExecuteQuery();
                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> LoadRequiredSecurityGroups. Completed. Average Execution: {0:0.000}s", loadRequiredSecurityGroupsExistPrfMonTriggers.Stop());

                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> CreateDocumentLibraries. Started.");
                var createDocumentLibrariesPrfMonTriggers = new PrfMon();
                var mergePinLibraries = fromSiteDocumentLibraries.ToList();
                foreach (var mergePinLibrary in mergePinLibraries)
                {
                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> CreateDocumentLibrary. Started.");
                    var createDocumentLibraryPrfMonTriggers = new PrfMon();
                    var documentLibraryList = spToSite.CreateDocumentLibrary(mergePinLibrary.CaseId.ToString());
                    context.Load(documentLibraryList, d => d.ContentTypes);
                    context.ExecuteQuery();
                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> CreateDocumentLibrary. Completed. Average Execution: {0:0.000}s", createDocumentLibraryPrfMonTriggers.Stop());

                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> UpdateDocumentLibraryList. Started.");
                    var updateDocumentLibraryPrfMonTriggers = new PrfMon();
                    documentLibraryList.UpdateDocumentLibraryList(web.ContentTypes, ContentTypeGroupNames.CaseDocumentContentTypes, mergePinLibrary.Title);
                    context.Load(documentLibraryList, d => d.Id, d => d.Fields);
                    context.ExecuteQuery();
                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> UpdateDocumentLibraryList. Completed. Average Execution: {0:0.000}s", updateDocumentLibraryPrfMonTriggers.Stop());

                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> UpdateDocumentLibraryMetaData. Started.");
                    var documentLibraryMetaDataPrfMonTriggers = new PrfMon();
                    var dictionary = context.CreateDocumentLibraryMetaData(documentLibraryList, spToSite, mergePinLibrary.Dictionary, toSite.Pin);
                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> UpdateDocumentLibraryMetaData. Completed. Average Execution: {0:0.000}s", documentLibraryMetaDataPrfMonTriggers.Stop());

                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> PinToSiteVisitorsPermissions. Started.");
                    var pinSitePermissionsPrfMonTriggers = new PrfMon();
                    var projectReadGroup = web.GetActiveDirectoryGroup(activeDirectoryReadGroup, toSite.RestrictedUser, toSite.Pin, mergePinLibrary.ProjectId);
                    spToPinVisitorsGroup.Users.AddUser(projectReadGroup);
                    context.Load(spToPinVisitorsGroup);
                    context.Load(documentLibraryList.RoleAssignments);
                    context.ExecuteQuery();
                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> PinToSiteVisitorsPermissions. Completed. Average Execution: {0:0.000}s", pinSitePermissionsPrfMonTriggers.Stop());

                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> SetupDocumentLibraryMembershipPermissions. Started.");
                    var setupDocumentLibraryMembershipPermissionsPrfMonTriggers = new PrfMon();
                    var projectContributorsGroup = web.GetActiveDirectoryContributorGroup(activeDirectoryContributeGroup, activeDirectoryContributeClosedGroup, toSite.RestrictedUser,
                                                                                          mergePinLibrary.IsClosed, toSite.Pin, mergePinLibrary.ProjectId);
                    documentLibraryList.BreakRoleInheritanceAndRemoveRoles(true, false, true);
                    documentLibraryList.AddRoleWithPermissions(context, web, globalSystemsAdminUser, RoleType.Contributor);
                    documentLibraryList.AddRoleWithPermissions(context, web, projectContributorsGroup, RoleType.Contributor);
                    documentLibraryList.AddRoleWithPermissions(context, web, spToPinVisitorsGroup, RoleType.Reader);
                    documentLibraryList.Update();
                    context.ExecuteQuery();
                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> SetupDocumentLibraryMembershipPermissions. Completed. Average Execution: {0:0.000}s", setupDocumentLibraryMembershipPermissionsPrfMonTriggers.Stop());

                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> DatabaseSynchronisation. Started.");
                    var databaseSynchronisationPrfMonTriggers = new PrfMon();
                    pinSiteDocumentLibraries.Add(mergePinLibrary.ListId, documentLibraryList.Id);
                    var now     = DateTime.Now;
                    var library = new Library
                    {
                        CaseId       = mergePinLibrary.CaseId,
                        Title        = mergePinLibrary.Title,
                        ProjectId    = mergePinLibrary.ProjectId,
                        SiteId       = toSite.Id,
                        ListId       = documentLibraryList.Id,
                        IsClosed     = mergePinLibrary.IsClosed,
                        Url          = $"{CaseDocumentLibraryUrl(toSite.ProvisionedSite.ProvisionedSiteCollection.Name, toSite.Pin.ToString(), mergePinLibrary.CaseId.ToString())}",
                        Dictionary   = dictionary,
                        InsertedDate = now,
                        InsertedBy   = _userIdentity.Name,
                        UpdatedDate  = now,
                        UpdatedBy    = _userIdentity.Name
                    };
                    _libraryService.Delete(mergePinLibrary.Id);
                    _libraryService.Create(library);
                    Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> DatabaseSynchronisation. Completed. Average Execution: {0:0.000}s", databaseSynchronisationPrfMonTriggers.Stop());
                }
                if (!fromSite.ProvisionedSite.ProvisionedSiteCollection.Name.SafeEquals(toSite.ProvisionedSite.ProvisionedSiteCollection.Name))
                {
                    _contextService.Audit(context, task, string.Format(TaskResources.Audit_MergePin, fromSite.Pin, toSite.Pin));
                }
                Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> CreateDocumentLibraries. Completed. Average Execution: {0:0.000}s", createDocumentLibrariesPrfMonTriggers.Stop());
            }

            Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> MergePinSiteContent. Started.");
            var mergePinSiteContentPrfMonTriggers = new PrfMon();
            var fromPinSite = new PinSite(fromSite.Url, Credentials);
            var toPinSite   = new PinSite(toSite.Url, Credentials);

            foreach (var listSource in fromPinSite.Lists)
            {
                var listDestination       = toPinSite.GetList(listSource, pinSiteDocumentLibraries);
                var rootFolderSource      = listSource.GetRootFolder(fromPinSite.Context);
                var rootFolderDestination = listDestination.GetRootFolder(toPinSite.Context);
                var listName = GetListNameFromServerRelativeUrl(rootFolderDestination.ServerRelativeUrl);
                rootFolderSource.MoveFilesTo(rootFolderDestination, rootFolderDestination.ServerRelativeUrl, listName);
            }
            Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> MergePinSiteContent. Completed. Average Execution: {0:0.000}s", mergePinSiteContentPrfMonTriggers.Stop());

            DeletePin(new Task {
                Handler = TaskHandlerNames.OperationsHandler, Name = TaskNames.DeletePin, Pin = fromSite.Pin
            });

            Debug.WriteLine("Fujitsu.AFC.Services.PinService.cs -> Completed Processing MergePin. Duration: {0:0.000}s", prfMonMethod.Stop());
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string  code     = dataGridView1.Rows[e.RowIndex].Cells[colCode].Value.ToString();
                var     product  = SingletonProduct.Instance().ProductDetails.Where(w => w.Enable == true).FirstOrDefault(w => w.Code == code);
                var     checkQty = dataGridView1.Rows[e.RowIndex].Cells[colQty].Value ?? "0";
                decimal qty      = decimal.Parse(checkQty.ToString());
                switch (e.ColumnIndex)
                {
                /// Code
                case 1:
                    if (product != null)
                    {
                        dataGridView1.Rows[e.RowIndex].Cells[colId].Value           = product.Id;
                        dataGridView1.Rows[e.RowIndex].Cells[colName].Value         = product.Products.ThaiName;
                        dataGridView1.Rows[e.RowIndex].Cells[colUnit].Value         = product.ProductUnit.Name;
                        dataGridView1.Rows[e.RowIndex].Cells[colPricePerUnit].Value = Library.ConvertDecimalToStringForm(product.SellPrice);
                        dataGridView1.Rows[e.RowIndex].Cells[colVatType].Value      = product.Products.ProductVatType.Name;
                        if (dataGridView1.Rows[e.RowIndex].Cells[colDiscount].Value == null)
                        {
                            dataGridView1.Rows[e.RowIndex].Cells[colDiscount].Value = "0.00";
                        }

                        if (qty == 0)
                        {
                            dataGridView1.Rows[e.RowIndex].Cells[colQty].Value        = "1";
                            dataGridView1.Rows[e.RowIndex].Cells[colTotalPrice].Value = Library.ConvertDecimalToStringForm(product.SellPrice);
                        }
                        else
                        {
                            dataGridView1.Rows[e.RowIndex].Cells[colQty].Value        = qty;
                            dataGridView1.Rows[e.RowIndex].Cells[colTotalPrice].Value = Library.ConvertDecimalToStringForm(qty * product.SellPrice);
                        }
                        TotalSummary();
                    }
                    else
                    {
                        //MessageBox.Show("ไม่พบข้อมูล");
                    }
                    break;

                case 7:     // คีย์ ส่วนลด
                    decimal pricePerUnit = decimal.Parse(dataGridView1.Rows[e.RowIndex].Cells[colPricePerUnit].Value.ToString());
                    decimal total        = pricePerUnit * qty;
                    decimal discount     = decimal.Parse(dataGridView1.Rows[e.RowIndex].Cells[colDiscount].Value.ToString());
                    dataGridView1.Rows[e.RowIndex].Cells[colTotalPrice].Value = Library.ConvertDecimalToStringForm(total - discount);
                    TotalSummary();
                    break;

                case 5:     // จำนวน
                    if (qty == 0)
                    {
                        dataGridView1.Rows[e.RowIndex].Cells[colQty].Value        = "1";
                        dataGridView1.Rows[e.RowIndex].Cells[colTotalPrice].Value = Library.ConvertDecimalToStringForm(product.SellPrice);
                    }
                    else
                    {
                        dataGridView1.Rows[e.RowIndex].Cells[colQty].Value        = qty;
                        dataGridView1.Rows[e.RowIndex].Cells[colTotalPrice].Value = Library.ConvertDecimalToStringForm(qty * product.SellPrice);
                    }
                    /// คีย์จำนวน ต้องไปเชค Stock
                    int     id      = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[colId].Value.ToString());
                    decimal qtyUnit = decimal.Parse(dataGridView1.Rows[e.RowIndex].Cells[colQty].Value.ToString());
                    using (SSLsEntities db = new SSLsEntities())
                    {
                        var stockWms = db.WmsStockDetail.Where(w => w.Enable == true && w.FKProductDetail == id).OrderByDescending(w => w.CreateDate).FirstOrDefault();
                        Console.WriteLine("row " + e.RowIndex + " Want: " + qtyUnit + " stock: " + stockWms.ResultQtyUnit);
                        if (qtyUnit > stockWms.ResultQtyUnit)
                        {
                            MessageBox.Show("Stock คงเหลือ " + stockWms.ResultQtyUnit);
                            //dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[colQty];
                            //dataGridView1.CurrentCell.Selected = true;
                        }
                        else
                        {
                        }
                    }
                    TotalSummary();
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
            }
        }
Example #33
0
        /// <summary>
        /// Main running method for the application.
        /// </summary>
        /// <param name="args">Commandline arguments to the application.</param>
        /// <returns>Returns the application error code.</returns>
        private int Run(string[] args)
        {
            try
            {
                Librarian         librarian = null;
                SectionCollection sections  = new SectionCollection();

                // parse the command line
                this.ParseCommandLine(args);

                // exit if there was an error parsing the command line (otherwise the logo appears after error messages)
                if (this.messageHandler.EncounteredError)
                {
                    return(this.messageHandler.LastErrorNumber);
                }

                if (0 == this.inputFiles.Count)
                {
                    this.showHelp = true;
                }
                else if (null == this.outputFile)
                {
                    if (1 < this.inputFiles.Count)
                    {
                        throw new WixException(WixErrors.MustSpecifyOutputWithMoreThanOneInput());
                    }

                    this.outputFile = Path.ChangeExtension(Path.GetFileName(this.inputFiles[0]), ".wixlib");
                }

                if (this.showLogo)
                {
                    AppCommon.DisplayToolHeader();
                }

                if (this.showHelp)
                {
                    Console.WriteLine(LitStrings.HelpMessage);
                    AppCommon.DisplayToolFooter();
                    return(this.messageHandler.LastErrorNumber);
                }

                foreach (string parameter in this.invalidArgs)
                {
                    this.messageHandler.Display(this, WixWarnings.UnsupportedCommandLineArgument(parameter));
                }
                this.invalidArgs = null;

                // create the librarian
                librarian          = new Librarian();
                librarian.Message += new MessageEventHandler(this.messageHandler.Display);
                librarian.ShowPedanticMessages = this.showPedanticMessages;

                if (null != this.bindPaths)
                {
                    foreach (string bindPath in this.bindPaths)
                    {
                        if (-1 == bindPath.IndexOf('='))
                        {
                            this.sourcePaths.Add(bindPath);
                        }
                    }
                }

                // load any extensions
                foreach (string extension in this.extensionList)
                {
                    WixExtension wixExtension = WixExtension.Load(extension);

                    librarian.AddExtension(wixExtension);

                    // load the binder file manager regardless of whether it will be used in case there is a collision
                    if (null != wixExtension.BinderFileManager)
                    {
                        if (null != this.binderFileManager)
                        {
                            throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, LitStrings.EXP_CannotLoadBinderFileManager, wixExtension.BinderFileManager.GetType().ToString(), this.binderFileManager.GetType().ToString()), "ext");
                        }

                        this.binderFileManager = wixExtension.BinderFileManager;
                    }
                }

                // add the sections to the librarian
                foreach (string inputFile in this.inputFiles)
                {
                    string inputFileFullPath = Path.GetFullPath(inputFile);
                    string dirName           = Path.GetDirectoryName(inputFileFullPath);

                    if (!this.sourcePaths.Contains(dirName))
                    {
                        this.sourcePaths.Add(dirName);
                    }

                    // try loading as an object file
                    try
                    {
                        Intermediate intermediate = Intermediate.Load(inputFileFullPath, librarian.TableDefinitions, this.suppressVersionCheck, this.suppressSchema);
                        sections.AddRange(intermediate.Sections);
                        continue; // next file
                    }
                    catch (WixNotIntermediateException)
                    {
                        // try another format
                    }

                    // try loading as a library file
                    Library loadedLibrary = Library.Load(inputFileFullPath, librarian.TableDefinitions, this.suppressVersionCheck, this.suppressSchema);
                    sections.AddRange(loadedLibrary.Sections);
                }

                // and now for the fun part
                Library library = librarian.Combine(sections);

                // save the library output if an error did not occur
                if (null != library)
                {
                    if (this.bindFiles)
                    {
                        // if the binder file manager has not been loaded yet use the built-in binder extension
                        if (null == this.binderFileManager)
                        {
                            this.binderFileManager = new BinderFileManager();
                        }


                        if (null != this.bindPaths)
                        {
                            foreach (string bindPath in this.bindPaths)
                            {
                                if (-1 == bindPath.IndexOf('='))
                                {
                                    this.binderFileManager.BindPaths.Add(bindPath);
                                }
                                else
                                {
                                    string[] namedPair = bindPath.Split('=');

                                    //It is ok to have duplicate key.
                                    this.binderFileManager.NamedBindPaths.Add(namedPair[0], namedPair[1]);
                                }
                            }
                        }

                        foreach (string sourcePath in this.sourcePaths)
                        {
                            this.binderFileManager.SourcePaths.Add(sourcePath);
                        }
                    }
                    else
                    {
                        this.binderFileManager = null;
                    }

                    foreach (string localizationFile in this.localizationFiles)
                    {
                        Localization localization = Localization.Load(localizationFile, librarian.TableDefinitions, this.suppressSchema);

                        library.AddLocalization(localization);
                    }

                    WixVariableResolver wixVariableResolver = new WixVariableResolver();

                    wixVariableResolver.Message += new MessageEventHandler(this.messageHandler.Display);

                    library.Save(this.outputFile, this.binderFileManager, wixVariableResolver);
                }
            }
            catch (WixException we)
            {
                this.messageHandler.Display(this, we.Error);
            }
            catch (Exception e)
            {
                this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace));
                if (e is NullReferenceException || e is SEHException)
                {
                    throw;
                }
            }

            return(this.messageHandler.LastErrorNumber);
        }
        public ActionResult AddDocument(int Page_ID, int Library_ID, string Name)
        {
            Library lib      = db.Libraries.Find(Library_ID);
            string  pathRoot = "~/" + DOC_BASE_ROOT + lib.Library_Name + "/";
            string  dbRoot   = DOC_BASE_ROOT + lib.Library_Name + "/";

            if (!System.IO.Directory.Exists(Server.MapPath(pathRoot)))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(pathRoot));
            }
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files["Document"];
                if (file != null)
                {
                    if (file.ContentLength > 0)
                    {
                        if (file.ContentLength < MAX_DOC_SIZE)
                        {
                            string       fileName     = file.FileName;
                            string       fileNameNoEx = Path.GetFileNameWithoutExtension(file.FileName);
                            string       ext          = Path.GetExtension(file.FileName).ToLower();
                            DocumentType type         = (DocumentType)db.DocumentTypes.Where(x => x.Extension == ext).FirstOrDefault();
                            if (type != null)
                            {
                                fileNameNoEx = UploadFile(file, pathRoot, fileName, fileNameNoEx, ext);
                                fileName     = fileNameNoEx + ext;
                                Document doc = new Document();
                                doc.Name         = Name;
                                doc.Path         = dbRoot + fileName;
                                doc.Library_ID   = Library_ID;
                                doc.Date_Added   = DateTime.Now;
                                doc.Added_By     = User.Identity.Name.ToString();///TODO: auth
                                doc.Archived     = false;
                                doc.DocumentType = type;
                                db.Documents.Add(doc);
                                db.SaveChanges();
                                return(RedirectToAction("Edit", new { Page_ID = Page_ID, Library_ID = Library_ID }));
                            }
                            else
                            {
                                ModelState.AddModelError("", "The '" + ext + "' document type is not supported.");
                                LibraryEditViewModel libViewMod = new LibraryEditViewModel(lib, Page_ID);
                                return(View("Edit", libViewMod));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "Documents must be less than 30 MB");
                            LibraryEditViewModel libViewMod = new LibraryEditViewModel(lib, Page_ID);
                            return(View("Edit", libViewMod));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "You must select a 'Document' to upload");
                        LibraryEditViewModel libViewMod = new LibraryEditViewModel(lib, Page_ID);
                        return(View("Edit", libViewMod));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "You must select a 'Document' to upload");
                    LibraryEditViewModel libViewMod = new LibraryEditViewModel(lib, Page_ID);
                    return(View("Edit", libViewMod));
                }
            }
            else
            {
                ModelState.AddModelError("", "You must select a 'Document' to upload");
                LibraryEditViewModel libViewMod = new LibraryEditViewModel(lib, Page_ID);
                return(View("Edit", libViewMod));
            }
        }
        public ActionResult AddDocuments(HttpPostedFileBase[] files, int Page_ID, int Library_ID, string Library_Name)
        {
            string successUploads = "<h3>Successful Uploads</h3><hr /><table role=\"presentation\" class=\"table table-striped\"><tbody class=\"files\">";
            string failedUploads  = "<h3>Failed Uploads</h3><hr /><table role=\"presentation\" class=\"table table-striped\"><tbody class=\"files\">";
            int    success        = 0;
            int    failed         = 0;

            foreach (HttpPostedFileBase DocFile in files)
            {
                if (DocFile != null)
                {
                    try
                    {
                        Regex        r             = new Regex("[^a-zA-Z0-9]");
                        string       dirName       = r.Replace(Library_Name, "");
                        string       pathRoot      = "~/" + DOC_BASE_ROOT + dirName + "/";
                        string       dbRoot        = DOC_BASE_ROOT + dirName + "/";
                        string       displayRoot   = "/" + DOC_BASE_ROOT + dirName + "/";
                        string       fileNameNoExt = System.IO.Path.GetFileNameWithoutExtension(DocFile.FileName);
                        string       ext           = System.IO.Path.GetExtension(DocFile.FileName).ToLower();
                        DocumentType type          = (DocumentType)db.DocumentTypes.Where(x => x.Extension == ext).FirstOrDefault();
                        if (type != null)
                        {
                            if (DocFile.ContentLength <= MAX_DOC_SIZE)
                            {
                                if (!System.IO.Directory.Exists(Server.MapPath(pathRoot)))
                                {
                                    System.IO.Directory.CreateDirectory(Server.MapPath(pathRoot));
                                }

                                string filePath     = Server.MapPath(pathRoot) + DocFile.FileName;
                                string filePathTemp = Server.MapPath(pathRoot) + DocFile.FileName;


                                try
                                {
                                    fileNameNoExt = UploadFile(DocFile, pathRoot, fileNameNoExt, ext);
                                }
                                catch (Exception ex)
                                {
                                    return(Json(new { error = "Upload Failed", message = ex.Message }));
                                }



                                Document doc = new Document();
                                doc.Name         = fileNameNoExt.Replace("_", " ").Replace("-", " ");
                                doc.Path         = dbRoot + fileNameNoExt + ext;
                                doc.Library_ID   = Library_ID;
                                doc.Date_Added   = DateTime.Now;
                                doc.Added_By     = User.Identity.Name.ToString();///TODO: auth
                                doc.Archived     = false;
                                doc.DocumentType = type;
                                db.Documents.Add(doc);


                                string displayPath = "/Libraries/Download/" + doc.Document_ID;
                                successUploads += "<tr class=\"table table-striped\"><td class=\"col-md-6\"><span class=\"preview\"><div class=\"col-sm-6 col-md-4\"><div class=\"thumbnail\"><img class=\"img-responsive\" alt=\"No Image Found\" src=\"/images/document-icon.png\"\"></img></a></div></div></span></td><td class=\"col-md-2\"><p class=\"name\">" + DocFile.FileName + "</p></td><td class=\"col-md-2\"><img class=\"img-responsive col-md-6\" src=\"../images/green_tick.png\" alt\"No Image Found\"></img></td></tr>";
                                success++;
                                //var files = new List<object>();
                                //files.Add(new { url = displayPath.Replace("\\", "\\/"), thumbnailUrl = "/images/document-icon.png", name = DocFile.FileName, type = doc.DocumentType.Content_Type, size = DocFile.ContentLength, deleteUrl = displayPath.Replace("\\", "\\/"), deleteType = "DELETE" });
                                //return Json(files, JsonRequestBehavior.AllowGet);
                            }
                            else
                            {
                                failedUploads += "<tr class=\"table table-striped\"><td class=\"col-md-6\"><span class=\"label label-danger\">Error:</span>&nbsp;File must be less than 30 MB</td><td class=\"col-md-2\"><p class=\"name\">" + DocFile.FileName + "</p></td><td class=\"col-md-2\"><img class=\"img-responsive col-md-6\" src=\"../images/red_x.png\" alt\"No Image Found\"></img></td></tr>";
                                failed++;
                            }
                        }
                        else
                        {
                            failedUploads += "<tr class=\"table table-striped\"><td class=\"col-md-6\"><span class=\"label label-danger\">Error:</span>&nbsp;" + ext + " is not a supported document format</td><td class=\"col-md-2\"><p class=\"name\">" + DocFile.FileName + "</p></td><td class=\"col-md-2\"><img class=\"img-responsive col-md-6\" src=\"../images/red_x.png\" alt\"No Image Found\"></img></td></tr>";
                            failed++;
                        }
                    }
                    catch (Exception EX)
                    {
                        failedUploads += "<tr class=\"table table-striped\"><td class=\"col-md-6\"><span class=\"label label-danger\">Error:</span>&nbsp;" + EX.Message + "</td><td class=\"col-md-2\"><p class=\"name\">" + DocFile.FileName + "</p></td><td class=\"col-md-2\"><img class=\"img-responsive col-md-6\" src=\"../images/red_x.png\" alt\"No Image Found\"></img></td></tr>";
                        failed++;
                    }
                }
            }
            db.SaveChanges();
            if (success > 0)
            {
                successUploads += "</tbody></table>";
            }
            else
            {
                successUploads = "";
            }
            if (failed > 0)
            {
                failedUploads += "</tbody></table>";
            }
            else
            {
                failedUploads = "";
            }

            ViewBag.Success_Uploads = successUploads;
            ViewBag.Failed_Uploads  = failedUploads;
            string cssClass = "warning";

            if (failed == 0)
            {
                cssClass = "success";
            }
            else if (success == 0)
            {
                cssClass = "danger";
            }
            if (success > 0 || failed > 0)
            {
                ViewBag.Upload_Counts = "<div class=\"alert alert-" + cssClass + " alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button><strong>Upload Complete:</strong> " + success + " file(s) uploaded successfully, " + failed + " failed.</div>";
            }
            else
            {
                ViewBag.Upload_Counts = "";
            }
            Library lib             = db.Libraries.Find(Library_ID);
            LibraryEditViewModel vm = new LibraryEditViewModel(lib, Page_ID);

            return(View("Edit", vm));
        }
Example #36
0
        public override bool FormCheckValid()
        {
            if (txtMa_Kho.Text.Trim() == string.Empty)
            {
                Common.MsgCancel(Languages.GetLanguage("Ma_Kho") + " " + Languages.GetLanguage("Cannot_Empty"));
                return(false);
            }

            if (txtMa_Vt.Text.Trim() == string.Empty)
            {
                Common.MsgCancel(Languages.GetLanguage("Ma_Vt") + " " + Languages.GetLanguage("Cannot_Empty"));
                return(false);
            }

            if (dteNgay_Ct.IsNull)
            {
                Common.MsgCancel(Languages.GetLanguage("Date") + " " + Languages.GetLanguage("Cannot_Empty"));
                return(false);
            }


            DataRow drVattu = DataTool.SQLGetDataRowByID("LIVATTU", "Ma_Vt", txtMa_Vt.Text);

            if ((bool)drVattu["LotSerial"])
            {
                if (txtMa_Lo.Text.Trim() == string.Empty)
                {
                    Common.MsgCancel(Languages.GetLanguage("Ma_Lo") + " " + Languages.GetLanguage("Cannot_Empty"));
                    return(false);
                }

                if (dteHan_Sd.IsNull)
                {
                    Common.MsgCancel(Languages.GetLanguage("Han_Sd") + " " + Languages.GetLanguage("Cannot_Empty"));
                    return(false);
                }
            }

            bool Is_Check = false;

            if (enuNew_Edit == enuEdit.Edit)
            {
                if (((DateTime)drEdit["Ngay_Ct"]).ToString("dd/MM/yyyy") == ((DateTime)drEdit["Ngay_Ct", DataRowVersion.Original]).ToString("dd/MM/yyyy") &&
                    (string)drEdit["Ma_Kho"] == (string)drEdit["Ma_Kho", DataRowVersion.Original] &&
                    (string)drEdit["Ma_Vt"] == (string)drEdit["Ma_Vt", DataRowVersion.Original])
                {
                    Is_Check = false;
                }
                else
                {
                    Is_Check = true;
                }
            }
            if (enuNew_Edit == enuEdit.New || Is_Check)
            {
                if (DataTool.SQLCheckExist("INDUDAU", new string[] { "Ngay_Ct", "Ma_Kho", "Ma_Vt", "Ma_DvCs" }, new object[] { Library.StrToDate(dteNgay_Ct.Text), txtMa_Kho.Text, txtMa_Vt.Text, Element.sysMa_DvCs }))
                {
                    string strMsg = "Ngay_Ct = {" + dteNgay_Ct.Text + "}, Ma_Kho = {" + txtMa_Kho.Text + "}, Ma_Vt = {" + txtMa_Vt.Text + "}, Ma_DvCs = {" + Element.sysMa_DvCs + "}";
                    strMsg += Element.sysLanguage == enuLanguageType.English ? " must be unique" : " phải duy nhất";

                    Common.MsgCancel(strMsg);
                    return(false);
                }
            }



            return(true);
        }
Example #37
0
        public override void Construct()
        {
            Root.RegisterForUpdate(this);

            Border = "border-fancy";

            int w = Root.RenderData.VirtualScreen.Width;
            int h = Root.RenderData.VirtualScreen.Height;

            Rect = new Rectangle(Root.RenderData.VirtualScreen.Center.X - w / 2, Root.RenderData.VirtualScreen.Center.Y - h / 2, w, h);

            var playerClasses = Library.EnumerateClasses().Where(c => c.PlayerClass).ToList();

            foreach (var job in playerClasses)
            {
                Applicants.Add(job.Name, new GeneratedApplicant {
                    Applicant = GenerateApplicant(job.Name)
                });
            }

            var left = AddChild(new Widget()
            {
                AutoLayout  = AutoLayout.DockTop,
                Padding     = new Margin(5, 5, 32, 32),
                MinimumSize = new Point(48 * 2 * playerClasses.Count, 40 * 2 + 40)
            });

            var right = AddChild(new Widget()
            {
                AutoLayout = AutoLayout.DockFill
            });

            var buttonRow = right.AddChild(new Widget
            {
                AutoLayout  = AutoLayout.DockBottom,
                MinimumSize = new Point(0, 30)
            });

            var jobDescription = right.AddChild(new Widget
            {
                MinimumSize     = new Point((int)(w * 0.4f), 0),
                InteriorMargin  = new Margin(16, 16, 16, 16),
                WrapWithinWords = false,
                WrapText        = true,
                AutoLayout      = AutoLayout.DockLeft,
                Font            = "font10"
            });

            var applicantInfo = right.AddChild(new ApplicantInfo
            {
                AutoLayout = AutoLayout.DockFill
            }) as ApplicantInfo;

            applicantInfo.Hidden = true;
            left.AddChild(new Widget
            {
                Text        = "Applicants",
                AutoLayout  = AutoLayout.DockTop,
                MinimumSize = new Point(0, 20),
                Font        = "font16"
            });

            foreach (var job in playerClasses)
            {
                var frame = left.AddChild(new Widget()
                {
                    MinimumSize = new Point(48 * 2, 40 * 2 + 15),
                    AutoLayout  = AutoLayout.DockLeft
                });

                var applicant = Applicants[job.Name];
                var layers    = applicant.Applicant.GetLayers();

                applicant.Portrait = frame.AddChild(new EmployeePortrait()
                {
                    Tooltip             = "Click to review applications for " + job.Name,
                    AutoLayout          = AutoLayout.DockTop,
                    TextHorizontalAlign = HorizontalAlign.Center,
                    TextVerticalAlign   = VerticalAlign.Bottom,
                    OnClick             = (sender, args) =>
                    {
                        jobDescription.Text = "\n\n" + applicant.Applicant.Class.JobDescription;
                        jobDescription.Invalidate();
                        applicantInfo.Hidden = false;
                        HireButton.Hidden    = false;
                        HireButton.Invalidate();
                        applicantInfo.Applicant = applicant.Applicant;
                    },
                    MinimumSize     = new Point(48 * 2, 40 * 2),
                    MaximumSize     = new Point(48 * 2, 40 * 2),
                    Sprite          = layers,
                    AnimationPlayer = applicant.Applicant.GetAnimationPlayer(layers, "WalkingFORWARD")
                }) as EmployeePortrait;

                frame.AddChild(new Widget()
                {
                    Text                = job.Name,
                    MinimumSize         = new Point(0, 15),
                    TextColor           = Color.Black.ToVector4(),
                    Font                = "font8",
                    AutoLayout          = AutoLayout.DockTop,
                    TextHorizontalAlign = HorizontalAlign.Center
                });
            }

            buttonRow.AddChild(new Widget
            {
                Text       = "Back",
                Border     = "border-button",
                AutoLayout = AutoLayout.DockLeft,
                Font       = "font16",
                OnClick    = (sender, args) =>
                {
                    this.Close();
                },
                ChangeColorOnHover = true,
            });

            HireButton = buttonRow.AddChild(new Button
            {
                Text       = "Hire",
                Border     = "border-button",
                AutoLayout = AutoLayout.DockRight,
                OnClick    = (sender, args) =>
                {
                    var applicant = applicantInfo.Applicant;
                    if (applicant != null)
                    {
                        Settings.InstanceSettings.InitalEmbarkment.Employees.Add(applicant);

                        applicantInfo.Hidden = true;
                        HireButton.Hidden    = true;
                        this.Invalidate();
                        applicantInfo.Invalidate();
                        HireButton.Invalidate();

                        var newApplicant = GenerateApplicant(applicant.Class.Name);
                        Applicants[applicant.Class.Name].Applicant                = newApplicant;
                        Applicants[applicant.Class.Name].Portrait.Sprite          = newApplicant.GetLayers();
                        Applicants[applicant.Class.Name].Portrait.AnimationPlayer = newApplicant.GetAnimationPlayer(Applicants[applicant.Class.Name].Portrait.Sprite, "WalkingFORWARD");
                    }
                },
                Hidden             = true,
                Font               = "font16",
                ChangeColorOnHover = true,
            }) as Button;

            this.Layout();

            OnUpdate += (sender, time) =>
            {
                foreach (var applicant in Applicants)
                {
                    applicant.Value.Portrait.AnimationPlayer.Update(new DwarfTime(time), false, Timer.TimerMode.Real);
                    applicant.Value.Portrait.Invalidate();
                    applicant.Value.Portrait.Sprite.Update(GameStates.GameState.Game.GraphicsDevice);
                }
            };
        }
Example #38
0
        public override bool Process()
        {
            // Get all subkeys and sort based on LastWrite times
            RegistryKey[] subkeys = Key.GetListOfSubkeys();
            if (null != subkeys && 0 < subkeys.Length)
            {
                List <ComplexContainer>     list            = new List <ComplexContainer>();
                Dictionary <string, object> innerDictionary = new Dictionary <string, object>();
                Dictionary <double, List <ComplexContainer> > dictionary = new Dictionary <double, List <ComplexContainer> >();
//                    uint start = uint.MaxValue;
                uint type = 0;

                string precedent;
                string timestamp;

                foreach (RegistryKey subkey in subkeys)
                {
                    innerDictionary.Clear();
//                        start = uint.MaxValue;

                    try {
                        type = (uint)subkey.GetValue("Type").GetDataAsObject();
                    } catch {
                        type = 0;
                    }

                    if (0x001 == type || 0x002 == type)
                    {
                        continue;
                    }


                    innerDictionary.Add("name", subkey.Name);

                    try {
                        innerDictionary.Add("displayName", subkey.GetValue("DisplayName").GetDataAsObject());
                    } catch {
                        innerDictionary.Add("displayName", string.Empty);
                    }

                    try {
                        innerDictionary.Add("imagePath", subkey.GetValue("ImagePath").GetDataAsObject());
                    } catch {
                        innerDictionary.Add("imagePath", string.Empty);
                    }

/*
 * どうせstart使ってない
 *                  try {
 *                      start = subkey.GetValue("Start").GetData();
 *                      if (START_TYPES.Contains(start)) {
 *                          innerDictionary.Add("start", start);
 *                      }
 *                  } catch {
 *                      innerDictionary.Add("start", uint.MaxValue);
 *                  }
 */
                    try {
                        innerDictionary.Add("objectName", subkey.GetValue("ObjectName").GetDataAsObject());
                    } catch {
                        innerDictionary.Add("objectName", string.Empty);
                    }



                    if (dictionary.ContainsKey(subkey.Timestamp))
                    {
                        list = dictionary[subkey.Timestamp];
                        list.Add(new ComplexContainer(
                                     innerDictionary["name"].ToString(), innerDictionary["displayName"].ToString(),
                                     innerDictionary["imagePath"].ToString(), //(uint)dictionary["start"],
                                     innerDictionary["objectName"].ToString()));
                        dictionary[subkey.Timestamp] = list;
                    }
                    else
                    {
                        list = new List <ComplexContainer>();
                        list.Add(new ComplexContainer(
                                     innerDictionary["name"].ToString(), innerDictionary["displayName"].ToString(),
                                     innerDictionary["imagePath"].ToString(), //(uint)dictionary["start"],
                                     innerDictionary["objectName"].ToString()));
                        dictionary.Add(subkey.Timestamp, list);
                    }
                }

                List <KeyValuePair <double, List <ComplexContainer> > > sorted = new List <KeyValuePair <double, List <ComplexContainer> > >(dictionary);
                sorted.Sort(
                    delegate(KeyValuePair <double, List <ComplexContainer> > first, KeyValuePair <double, List <ComplexContainer> > next) {
                    return(next.Key.CompareTo(first.Key));
                }
                    );

                precedent = string.Empty;
                StringBuilder builder;
                foreach (KeyValuePair <double, List <ComplexContainer> > pair in sorted)
                {
                    timestamp = Library.TransrateTimestamp(pair.Key, TimeZoneBias, OutputUtc);

                    if (!precedent.Equals(timestamp))
                    {
                        Reporter.Write("");
                        Reporter.Write(timestamp /* + "Z"*/);
                        precedent = timestamp;
                    }

                    foreach (ComplexContainer container in pair.Value)
                    {
                        builder = new StringBuilder();
                        builder.Append("  " + container.Name);

                        if (string.Empty.Equals(container.ImagePath))
                        {
                            if (!string.Empty.Equals(container.DisplayName))
                            {
                                builder.Append(" (" + container.DisplayName + ")");
                            }
                        }
                        else
                        {
                            builder.Append(" (" + container.ImagePath + ")");
                        }

                        if (!string.Empty.Equals(container.ObjectName))
                        {
                            builder.Append(" [" + container.ObjectName + "]");
                        }

                        Reporter.Write(builder.ToString());
                    }
                }
            }
            else
            {
                Reporter.Write(KeyPath + " にはサブキーがありませんでした。");
            }

            return(true);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("PolyLineAnnotation Sample:");
            // ReSharper disable once UnusedVariable
            using (Library lib = new Library())
            {
                Console.WriteLine("Initialized the library.");

                String sOutput = "PolyLineAnnotations-out.pdf";

                if (args.Length > 0)
                {
                    sOutput = args[0];
                }

                Console.WriteLine("Writing to output " + sOutput);

                // Create a new document and blank first page
                Document doc  = new Document();
                Rect     rect = new Rect(0, 0, 612, 792);
                Page     page = doc.CreatePage(Document.BeforeFirstPage, rect);
                Console.WriteLine("Created new document and first page.");

                // Create a vector of polyline vertices
                List <Point> vertices = new List <Point>();
                Point        p        = new Point(100, 100);
                vertices.Add(p);
                p = new Point(200, 300);
                vertices.Add(p);
                p = new Point(400, 200);
                vertices.Add(p);
                Console.WriteLine("Created an array of vertex points.");

                // Create and add a new PolyLineAnnotation to the 0th element of first page's annotation array
                PolyLineAnnotation polyLineAnnot = new PolyLineAnnotation(page, rect, vertices, -1);
                Console.WriteLine("Created new PolyLineAnnotation as 0th element of annotation array.");

                // Now let's retrieve and display the vertices
                IList <Point> vertices2;
                vertices2 = polyLineAnnot.Vertices;
                Console.WriteLine("Retrieved the vertices of the polyline annotation.");
                Console.WriteLine("They are:");
                for (int i = 0; i < vertices2.Count; i++)
                {
                    Console.WriteLine("Vertex " + i + ": " + vertices2[i]);
                }

                // Add some line ending styles to the ends of our PolyLine
                polyLineAnnot.StartPointEndingStyle = LineEndingStyle.ClosedArrow;
                polyLineAnnot.EndPointEndingStyle   = LineEndingStyle.OpenArrow;

                // Let's set some colors and then ask the polyline to generate an appearance stream
                Color color = new Color(0.5, 0.3, 0.8);
                polyLineAnnot.InteriorColor = color;
                color = new Color(0.0, 0.8, 0.1);
                polyLineAnnot.Color = color;
                Console.WriteLine("Set the stroke and fill colors.");
                Form form = polyLineAnnot.GenerateAppearance();
                polyLineAnnot.NormalAppearance = form;
                Console.WriteLine("Generated the appearance stream.");

                // Update the page's content and save the file with clipping
                page.UpdateContent();
                doc.Save(SaveFlags.Full, sOutput);

                // Dispose the doc object
                doc.Dispose();
                Console.WriteLine("Disposed document object.");
            }
        }
Example #40
0
            public void NativeCanCallFuncWithParameter()
            {
                var result = Library.ExecuteFuncT1T2(x => 5 * x);

                Assert.Equal(25, result);
            }
Example #41
0
        public static ExpeditionDataSource BuildExpeditionDataSource(Library library, int num_topics, bool add_autotags, bool add_tags, ExpeditionBuilderProgressUpdateDelegate progress_update_delegate)
        {
            WPFDoEvents.AssertThisCodeIs_NOT_RunningInTheUIThread();

            // Initialise the datasource
            ExpeditionDataSource data_source = new ExpeditionDataSource();

            data_source.date_created = DateTime.UtcNow;

            try
            {
                // Check that we have a progres update delegate
                if (null == progress_update_delegate)
                {
                    progress_update_delegate = DefaultExpeditionBuilderProgressUpdate;
                }

                // What are the sources of data?
                progress_update_delegate("Assembling tags");
                HashSet <string>   tags          = BuildLibraryTagList(library, add_autotags, add_tags);
                List <PDFDocument> pdf_documents = library.PDFDocumentsWithLocalFilePresent;

                progress_update_delegate("Adding tags");
                data_source.words = new List <string>();
                foreach (string tag in tags)
                {
                    data_source.words.Add(tag);
                }

                progress_update_delegate("Adding docs");
                data_source.docs = new List <string>();
                foreach (PDFDocument pdf_document in pdf_documents)
                {
                    data_source.docs.Add(pdf_document.Fingerprint);
                }

                progress_update_delegate("Rebuilding indices");
                data_source.RebuildIndices();

                // Now go through each doc and find the tags that match
                int DATA_SOURCE_DOCS_COUNT = data_source.docs.Count;
                data_source.words_in_docs = new int[DATA_SOURCE_DOCS_COUNT][];

                //int total_processed = 0;

                Parallel.For(0, DATA_SOURCE_DOCS_COUNT, d =>
                             //for (int d = 0; d < DATA_SOURCE_DOCS_COUNT; ++d)
                {
                    //int total_processed_local = Interlocked.Increment(ref total_processed);
                    //if (0 == total_processed_local % 50)
                    if (0 == d % 50)
                    {
                        if (!progress_update_delegate("Scanning documents", d, DATA_SOURCE_DOCS_COUNT))
                        {
                            // Parallel.For() doc at https://docs.microsoft.com/en-us/archive/msdn-magazine/2007/october/parallel-performance-optimize-managed-code-for-multi-core-machines
                            // says:
                            //
                            // Finally, if any exception is thrown in any of the iterations, all iterations are canceled
                            // and the first thrown exception is rethrown in the calling thread, ensuring that exceptions
                            // are properly propagated and never lost.
                            //
                            // --> We can thus easily use an exception to terminate/cancel all iterations of Parallel.For()!
                            throw new TaskCanceledException("Operation canceled by user");
                        }
                    }

                    List <int> tags_in_document = new List <int>();

                    {
                        PDFDocument pdf_document = pdf_documents[d];
                        string full_text         = " " + pdf_document.PDFRenderer.GetFullOCRText() + " ";
                        string full_text_lower   = full_text.ToLower();

                        for (int t = 0; t < data_source.words.Count; ++t)
                        {
                            string tag = ' ' + data_source.words[t] + ' ';

                            string full_text_to_search = full_text;
                            if (StringTools.HasSomeLowerCase(tag))
                            {
                                full_text_to_search = full_text_lower;
                                tag = tag.ToLower();
                            }

                            int num_appearances = StringTools.CountStringOccurence(full_text_to_search, tag);
                            for (int i = 0; i < num_appearances; ++i)
                            {
                                tags_in_document.Add(t);
                            }
                        }
                    }

                    data_source.words_in_docs[d] = tags_in_document.ToArray();
                }
                             );

                // Initialise the LDA
                if (!progress_update_delegate("Building themes sampler"))
                {
                    // Parallel.For() doc at https://docs.microsoft.com/en-us/archive/msdn-magazine/2007/october/parallel-performance-optimize-managed-code-for-multi-core-machines
                    // says:
                    //
                    // Finally, if any exception is thrown in any of the iterations, all iterations are canceled
                    // and the first thrown exception is rethrown in the calling thread, ensuring that exceptions
                    // are properly propagated and never lost.
                    //
                    // --> We can thus easily use an exception to terminate/cancel all iterations of Parallel.For()!
                    throw new TaskCanceledException("Operation canceled by user");
                }

                int    num_threads = Math.Min(1, (Environment.ProcessorCount - 1) / 2);
                double alpha       = 2.0 / num_topics;
                double beta        = 0.01;
                data_source.lda_sampler = new LDASampler(alpha, beta, num_topics, data_source.words.Count, data_source.docs.Count, data_source.words_in_docs);

                LDASamplerMCSerial lda_sampler_mc = new LDASamplerMCSerial(data_source.lda_sampler, num_threads);
                lda_sampler_mc.MC(MAX_TOPIC_ITERATIONS, (iteration, num_iterations) =>
                {
                    if (!progress_update_delegate("Building themes", iteration, num_iterations))
                    {
                        // Parallel.For() doc at https://docs.microsoft.com/en-us/archive/msdn-magazine/2007/october/parallel-performance-optimize-managed-code-for-multi-core-machines
                        // says:
                        //
                        // Finally, if any exception is thrown in any of the iterations, all iterations are canceled
                        // and the first thrown exception is rethrown in the calling thread, ensuring that exceptions
                        // are properly propagated and never lost.
                        //
                        // --> We can thus easily use an exception to terminate/cancel all iterations of Parallel.For()!
                        throw new TaskCanceledException("Operation canceled by user");
                    }
                });
            }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
            catch (TaskCanceledException ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
            {
                // This exception should only occur when the user *canceled* the process and should therefor
                // *not* be propagated. Instead, we have to report an aborted result:
                progress_update_delegate("Cancelled Expedition", 1, 1);
                return(null);
            }

            progress_update_delegate("Built Expedition", 1, 1);

            return(data_source);
        }
Example #42
0
            public void ManagedCanCallActionWithParameter()
            {
                var action = Library.GetNativeActionT1();

                action(5);
            }
Example #43
0
            public void NativeCanCallFunc()
            {
                var result = Library.ExecuteFuncT1(() => 5);

                Assert.Equal(5, result);
            }
Example #44
0
        public void Reset()
        {
            mainPanel.Clear();
            Rectangle rect = GuiRoot.RenderData.VirtualScreen;

            mainPanel.AddChild(new Gui.Widgets.Button
            {
                Text = "< Back",
                TextHorizontalAlign = HorizontalAlign.Center,
                TextVerticalAlign   = VerticalAlign.Center,
                Border  = "border-button",
                Font    = "font16",
                OnClick = (sender, args) =>
                {
                    GameStateManager.PopState();
                },
                AutoLayout = AutoLayout.FloatBottomLeft,
            });


            var widgetList = mainPanel.AddChild(new WidgetListView()
            {
                AutoLayout = AutoLayout.DockTop,
                SelectedItemForegroundColor = Color.Black.ToVector4(),
                SelectedItemBackgroundColor = new Vector4(0, 0, 0, 0),
                ItemBackgroundColor2        = new Vector4(0, 0, 0, 0.1f),
                ItemBackgroundColor1        = new Vector4(0, 0, 0, 0),
                ItemHeight  = 64,
                MinimumSize = new Point(0, 3 * GuiRoot.RenderData.VirtualScreen.Height / 4)
            }) as WidgetListView;

            var factions = Overworld.Natives.Where(f => f.InteractiveFaction && Library.GetRace(f.Race).IsIntelligent);

            foreach (var faction in factions)
            {
                var diplomacy = Overworld.GetPolitics(faction, Overworld.Natives.FirstOrDefault(n => n.Name == "Player"));
                var details   = diplomacy.GetEvents().Select(e => string.Format("{0} ({1})", TextGenerator.ToSentenceCase(e.Description), e.Change > 0 ? "+" + e.Change.ToString() : e.Change.ToString()));

                var entry = widgetList.AddItem(new Widget()
                {
                    Background = new TileReference("basic", 0),
                });
                StringBuilder sb = new StringBuilder();
                foreach (var detail in details)
                {
                    sb.AppendLine(detail);
                }
                entry.Tooltip = "Recent events:\n" + sb.ToString();
                if (sb.ToString() == "")
                {
                    entry.Tooltip = "No recent events.";
                }
                var titlebar = entry.AddChild(new Widget()
                {
                    InteriorMargin = new Margin(5, 5, 5, 5),
                    MinimumSize    = new Point(512, 36),
                    AutoLayout     = AutoLayout.DockTop,
                });
                titlebar.AddChild(new Widget()
                {
                    Background  = new TileReference("map-icons", Library.GetRace(faction.Race).Icon),
                    MaximumSize = new Point(32, 32),
                    MinimumSize = new Point(32, 32),
                    AutoLayout  = AutoLayout.DockLeft,
                });
                titlebar.AddChild(new Widget()
                {
                    Text = String.Format("{0} ({1}){2}", faction.Name, faction.Race, diplomacy.IsAtWar ? " -- At war!" : ""),
                    TextHorizontalAlign = HorizontalAlign.Right,
                    TextVerticalAlign   = VerticalAlign.Bottom,
                    Font       = "font10",
                    AutoLayout = AutoLayout.DockLeft
                });


                var relation          = diplomacy.GetCurrentRelationship();
                var relationshipColor = Color.Black.ToVector4();
                if (relation == Relationship.Loving)
                {
                    relationshipColor = GameSettings.Default.Colors.GetColor("Positive", Color.DarkGreen).ToVector4();
                }
                else if (relation == Relationship.Hateful)
                {
                    relationshipColor = GameSettings.Default.Colors.GetColor("Negative", Color.Red).ToVector4();
                }
                entry.AddChild(new Widget()
                {
                    Text = String.Format("    Relationship: {0}", diplomacy.GetCurrentRelationship()),
                    TextHorizontalAlign = HorizontalAlign.Left,
                    TextVerticalAlign   = VerticalAlign.Top,
                    Font       = "font8",
                    AutoLayout = AutoLayout.DockTop,
                    TextColor  = relationshipColor
                });
                entry.AddChild(new Widget()
                {
                    Text = "",
                    TextHorizontalAlign = HorizontalAlign.Left,
                    TextVerticalAlign   = VerticalAlign.Top,
                    Font       = "font8",
                    AutoLayout = AutoLayout.DockTop
                });
            }

            mainPanel.Layout();
        }
Example #45
0
            public void ManagedCanCallAction()
            {
                var action = Library.GetNativeAction();

                action();
            }
        public void BinddingAddShared(decimal value)
        {
            DateTime dateEnd = Singleton.SingletonThisBudgetYear.Instance().ThisYear.EndDate;

            textBoxTotalShared.Text = (value + old) + "";
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                int id = int.Parse(dataGridView2.Rows[i].Cells[col2Id].Value.ToString());

                if (id == 0)
                {
                    dataGridView2.Rows.RemoveAt(i);
                    continue;
                }
            }
            // add dataGridView2
            // แปลง วันที่ thai เป็น EN
            string   dateShared  = maskedTextBoxCreateDate.Text;
            var      split       = dateShared.Split('/');
            var      yyyy        = int.Parse(split[2]) - 543;
            DateTime dateshared  = new DateTime(yyyy, int.Parse(split[1]), int.Parse(split[0]));
            var      ageOfShared = SingletonAgeOfShare.Instance().AgeOfShare.ToList();
            int      c           = int.Parse(dateshared.ToString("yyyyMMdd"));
            int      f           = int.Parse(ageOfShared.FirstOrDefault().TermStart.ToString("yyyyMMdd"));
            string   sharedAge   = "";

            if (c < f)
            {
                // แปล ว่า ครบปี แน่ๆ
                sharedAge     = "ครบปี";
                fkAgeOfShared = ageOfShared.FirstOrDefault().Id;
            }
            else
            {
                bool isTerm = false;
                foreach (var item in ageOfShared)
                {
                    if (Library.CheckAgeOfShared(dateshared, item.TermStart, item.TermEnd))
                    {
                        isTerm    = true;
                        sharedAge = item.ShareAge + " เดือน";
                        if (item.ShareAge == 12)
                        {
                            sharedAge = "ครบปี";
                        }
                        fkAgeOfShared = item.Id;
                        break;
                    }
                }
            }
            ///////////////////Edit 1
            //DateTime dateshared = DateTime.Parse(localDate.ToString("en-GB"));

            //int yearShared = localDate.Year;

            //var diffMonths = (dateEnd.Month + dateEnd.Year) - (localDate.Month + localDate.Year);
            //DateDiff dateDiff = new DateDiff(date1, date2);
            ///////////////////Edit 2
            //int diffMonths = Library.MonthDiff(dateshared, dateEnd);

            //if (diffMonths >= 12)
            //{
            //    sharedAge = "ครบปี";
            //}
            //else
            //{
            //    sharedAge = diffMonths + " เดือน";
            //}
            //Console.WriteLine(diffMonths + "");

            dataGridView2.Rows.Add
                (0,
                value,
                maskedTextBoxCreateDate.Text,
                Library.ConvertDecimalToStringForm(SingletonShared.Instance().Share.Value *value),
                Singleton.SingletonAuthen.Instance().Name
                //,sharedAge
                );
            this.value = value;
        }
Example #47
0
 public static void BeginMaintainence(HTTPCacheMaintananceParams maintananceParam)
 {
     if (maintananceParam == null)
     {
         throw new ArgumentNullException("maintananceParams == null");
     }
     if (IsSupported && !InMaintainenceThread)
     {
         InMaintainenceThread = true;
         SetupCacheFolder();
         new Thread((ParameterizedThreadStart) delegate
         {
             try
             {
                 lock (Library)
                 {
                     DateTime t = DateTime.UtcNow - maintananceParam.DeleteOlder;
                     List <HTTPCacheFileInfo> list = new List <HTTPCacheFileInfo>();
                     foreach (KeyValuePair <Uri, HTTPCacheFileInfo> item in Library)
                     {
                         if (item.Value.LastAccess < t && DeleteEntity(item.Key, removeFromLibrary: false))
                         {
                             list.Add(item.Value);
                         }
                     }
                     for (int i = 0; i < list.Count; i++)
                     {
                         Library.Remove(list[i].Uri);
                         UsedIndexes.Remove(list[i].MappedNameIDX);
                     }
                     list.Clear();
                     ulong num = GetCacheSize();
                     if (num > maintananceParam.MaxCacheSize)
                     {
                         List <HTTPCacheFileInfo> list2 = new List <HTTPCacheFileInfo>(library.Count);
                         foreach (KeyValuePair <Uri, HTTPCacheFileInfo> item2 in library)
                         {
                             list2.Add(item2.Value);
                         }
                         list2.Sort();
                         int num2 = 0;
                         while (num >= maintananceParam.MaxCacheSize && num2 < list2.Count)
                         {
                             try
                             {
                                 HTTPCacheFileInfo hTTPCacheFileInfo = list2[num2];
                                 ulong num3 = (ulong)hTTPCacheFileInfo.BodyLength;
                                 DeleteEntity(hTTPCacheFileInfo.Uri);
                                 num -= num3;
                             }
                             catch
                             {
                             }
                             finally
                             {
                                 num2++;
                             }
                         }
                     }
                 }
             }
             finally
             {
                 SaveLibrary();
                 InMaintainenceThread = false;
             }
         }).Start();
     }
 }
        /// <summary>
        /// save สร้างใหม่ กรณี ถอนหุ้น Disable เฉพาะ remove sheard
        /// </summary>
        void SaveCommit()
        {
            Member member = new Member();

            member.Code = textBoxCode.Text;
            //if (Singleton.SingletonMember.Instance().Members.FirstOrDefault(w => w.Code == member.Code) != null)
            //{
            //    textBoxCode.SelectAll();
            //    label10.Text = "รหัสสมาชิกซ้ำ";
            //    label10.Visible = true;
            //    return;
            //}
            //label10.Visible = false;
            member.Enable     = true;
            member.Name       = textBoxName.Text;
            member.Address    = textBoxAddress.Text;
            member.CreateDate = DateTime.Now;
            member.CreateBy   = Singleton.SingletonAuthen.Instance().Id;
            member.UpdateDate = DateTime.Now;
            member.UpdateBy   = Singleton.SingletonAuthen.Instance().Id;
            if (radioButtonFemale.Checked == true) //
            {
                member.FKSex = MyConstant.Sex.Female;
            }
            else
            {
                member.FKSex = MyConstant.Sex.male;
            }
            member.TaxId = textBoxTax.Text.Replace("-", "");
            var date = Library.ConvertTHToENDate(textBoxBirthDate.Text);

            if (date == null)
            {
                MessageBox.Show("วันเกิดไม่ถูกต้อง");
                return;
            }
            else
            {
                member.BirthDate = date.Value;
            }
            member.Age = decimal.Parse(textBoxAge.Text);

            if (radioButtonRemove.Checked == true)
            {
                member.IsRemoveShared = true;
            }
            else
            {
                member.IsRemoveShared = false;
            }
            member.Tel = textBoxTel.Text;
            /// มากกว่า 0 ถึง เพิ่ม
            if (this.value > 0)
            {
                MemberShare ms = new MemberShare();
                ms.Enable = true;
                var dateC = Library.ConvertTHToENDate(maskedTextBoxCreateDate.Text);
                if (dateC == null)
                {
                    MessageBox.Show("วันที่เพิ่มหุ้นไม่ถูกต้อง");
                    return;
                }
                ms.CreateDate   = (DateTime)dateC;
                ms.CreateBy     = Singleton.SingletonAuthen.Instance().Id;
                ms.UpdateDate   = DateTime.Now;
                ms.UpdateBy     = Singleton.SingletonAuthen.Instance().Id;
                ms.FKShare      = MyConstant.Shared.General;
                ms.FKBudgetYear = Singleton.SingletonThisBudgetYear.Instance().ThisYear.Id;
                ms.Qty          = value;
                ms.FKAgeOfShare = CheckAgeOfShared(ms.CreateDate);
                // เชค อายุหุ้น
                CheckAgeOfShared(ms.CreateDate);
                member.MemberShare.Add(ms);
            }
            using (SSLsEntities db = new SSLsEntities())
            {
                db.Member.Add(member);
                db.SaveChanges();
                memberNew = new Member();
                string myName = Singleton.SingletonAuthen.Instance().Id;
                memberNew = db.Member.Include("Sex").Include("MemberShare.Share").Include("MemberShare.AgeOfShare")
                            .OrderByDescending(w => w.CreateDate).FirstOrDefault(w => w.CreateBy == myName);
                label10.ForeColor = Color.Red;
                label10.Text      = "* Enter";
                this.value        = 0;
            }
        }
        void CheckCurrentRowAndBindding()
        {
            RowId = 0;
            GbEditRemove.Visible = false;
            int index  = dataGridView1.CurrentRow.Index;
            int id     = int.Parse(dataGridView1.Rows[index].Cells[col1Id].Value.ToString());
            var member = Singleton.SingletonMember.Instance().Members.SingleOrDefault(w => w.Id == id);

            // bindding now
            textBoxId.Text   = member.Id + "";
            textBoxCode.Text = member.Code;
            textBoxName.Text = member.Name;
            maskedTextBoxMemberCreate.Text = Library.ConvertDateToThaiDate(member.CreateDate);
            if (member.FKSex == MyConstant.Sex.Female)
            {
                radioButtonFemale.Checked = true;
            }
            else
            {
                radioButtonMale.Checked = true;
            }
            /// ส่วนของ ถอนหุ้น
            if (member.IsRemoveShared == true)
            {
                radioButtonRemove.Checked = true;
                dateTimePicker1.Value     = member.ResignDate.Value;
                GbEditRemove.Visible      = true;
                RowId = member.Id;
            }
            else
            {
                radioButtonNotRemove.Checked = true;
            }

            textBoxTax.Text         = member.TaxId;
            textBoxBirthDate.Text   = Library.ConvertDateToThaiDate(member.BirthDate);
            textBoxAge.Text         = member.Age + "";
            textBoxAddress.Text     = member.Address;
            textBoxTotalShared.Text = member.MemberShare.Where(w => w.Enable == true).Sum(w => w.Qty) + "";
            this.old        = member.MemberShare.Where(w => w.Enable == true).Sum(w => w.Qty);
            textBoxTel.Text = member.Tel;
            // add dataGridView2
            dataGridView2.Rows.Clear();
            dataGridView2.Refresh();
            DateTime dateEnd = Singleton.SingletonThisBudgetYear.Instance().ThisYear.EndDate;


            //Edit By tin  Calculat new MemberShare  DateEdit 14/05/2018
            dataGridView3.Rows.Clear();
            dataGridView3.Refresh();

            //var ds = (from MemberS in member.MemberShare.Where(w => w.Enable == true)
            //         .Select(s => new
            //         {
            //             Id = s.Id,
            //             Qty = s.Qty,
            //             CreateDate = s.CreateDate,
            //             CreateBy = s.CreateBy,
            //             bath = s.Share.Value * s.Qty
            //         })
            //          join Pdtl in db.ProductDetails.Include("ProductUnit") on new { Pro = dtl.FKProduct, Issueuit = true, en = true } equals new { Pro = Pdtl.FKProduct, Issueuit = Pdtl.IssueUnit == true, en = Pdtl.Enable == true } into ps from p in ps.DefaultIfEmpty()
            var d = comboBox1.Text.Trim();

            using (SSLsEntities db = new SSLsEntities())
            {
                string queryString = ";with GetBudGetY as (select top(1) StartDate,EndDate from pos.BudgetYear where Enable = 1 and ThaiYear = '" + d + "' ) " +
                                     "select  Code,Name,sum(Qty)Qty,sum(Bath)Bath,ThaiYear,Status from ( " +
                                     "select  t.Code,t.Name,t.CreateDate,t.Qty,t.Bath,b.ThaiYear,case when t.CreateDate < (select StartDate from GetBudGetY) then 'ครบปี' " +
                                     "when t.CreateDate >= (select StartDate from GetBudGetY) and t.CreateDate <= (select EndDate from GetBudGetY) then  " +
                                     "isnull((select convert(varchar,isnull(AgeMonth,'')) + ' เดือน' " +
                                     "from mem.ShareMonth where Enable = 1 and FORMAT(t.CreateDate,'MMdd') >= FORMAT(TermMonthStart,'MMdd') and FORMAT(t.CreateDate,'MMdd') <= FORMAT(TermMonthEnd,'MMdd')),'ไม่คิด') " +
                                     "else '0' end Status from ( " +
                                     "select m.Code,m.Name,s.CreateDate,Qty,(Qty * e.Value) Bath from mem.Member m left join mem.MemberShare s on m.Id = s.FKMember left join mem.Share e on s.FKShare = e.Id  " +
                                     "where m.Enable = 1 and s.Enable = 1 and m.Code = '" + member.MemberShare.Where(w => w.Enable == true).Select(s => s.Member.Code).FirstOrDefault() + "' " +
                                     "and s.CreateDate <= (select EndDate from GetBudGetY) " +
                                     ")t left join pos.BudgetYear b on t.CreateDate >= b.StartDate and t.CreateDate <= b.EndDate and b.Enable = 1 " +
                                     ")tt group by Code,Name,ThaiYear,Status";
                var getdata = db.Database.ExecuteEntities <GetToDataGrid3>(queryString);
                if (getdata.Count() > 0)
                {
                    foreach (var item in getdata)
                    {
                        dataGridView3.Rows.Add((int)item.Qty, item.ThaiYear, item.Bath, item.Status);
                    }
                }
            }



            //End Edit By tin
            foreach (MemberShare item in member.MemberShare.Where(w => w.Enable == true).OrderBy(w => w.CreateDate).ToList())
            {
                //string sharedAge = "";
                string bath = Library.ConvertDecimalToStringForm(item.Share.Value * item.Qty);
                //sharedAge = item.AgeOfShare.ShareAge + " เดือน";
                //if (item.AgeOfShare.ShareAge == 12)
                //{
                //    sharedAge = "ครบปี";
                //}
                dataGridView2.Rows.Add
                    (item.Id,
                    (int)item.Qty,
                    Library.ConvertDateToThaiDate(item.CreateDate),
                    bath,
                    Library.GetFullNameUserById(item.CreateBy)
                    //sharedAge
                    );
            }
        }
Example #50
0
        public Librarian(string configPath = "")
        {
            InitializeNLog();

            //
            // Deserialize the configuration xml to get the location of the symbology library
            //

            XmlSerializer serializer = new XmlSerializer(typeof(JMSMLConfig));

            serializer.UnknownNode      += new XmlNodeEventHandler(serializer_UnknownNode);
            serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);

            if (configPath != "")
            {
                _configPath = configPath;
            }
            else
            {
                string s = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                _configPath = Path.Combine(s, "jmsml.config");
            }

            if (File.Exists(_configPath))
            {
                using (FileStream fs = new FileStream(_configPath, FileMode.Open, FileAccess.Read))
                {
                    if (fs.CanRead)
                    {
                        _configData = (JMSMLConfig)serializer.Deserialize(fs);
                    }
                    else
                    {
                        logger.Error("Unreadable config file: " + _configPath);
                    }
                }
            }
            else
            {
                logger.Error("Config file is missing: " + _configPath);
            }

            //
            // If the config data was good then...
            //

            if (_configData != null)
            {
                //
                // Deserialize the library's base xml to get the base contents of the symbology standard
                //

                serializer = new XmlSerializer(typeof(Library));

                string path = _configData.LibraryPath + "/" + _configData.LibraryName;

                if (File.Exists(path))
                {
                    using (FileStream fsLibrary = new FileStream(path, FileMode.Open, FileAccess.Read))
                    {
                        if (fsLibrary.CanRead)
                        {
                            this._library = (Library)serializer.Deserialize(fsLibrary);

                            //
                            // Deserialize each symbolSet xml
                            //

                            foreach (LibraryDimension dimension in this._library.Dimensions)
                            {
                                foreach (LibraryDimensionSymbolSetRef ssRef in dimension.SymbolSets)
                                {
                                    ushort ssCode = CodeToShort(ssRef.SymbolSetCode);
                                    if (!_sortedSymbolSets.ContainsKey(ssCode))
                                    {
                                        path = _configData.LibraryPath + "/" + ssRef.Instance;
                                        if (File.Exists(path))
                                        {
                                            using (FileStream fsSymbolSet = new FileStream(path, FileMode.Open, FileAccess.Read))
                                            {
                                                if (fsSymbolSet.CanRead)
                                                {
                                                    serializer = new XmlSerializer(typeof(SymbolSet));
                                                    SymbolSet ss = (SymbolSet)serializer.Deserialize(fsSymbolSet);

                                                    if (ss != null)
                                                    {
                                                        _sortedSymbolSets.Add(ssCode, ss);
                                                        _symbolSets.Add(ss);
                                                    }
                                                }
                                                else
                                                {
                                                    logger.Error("Unreadable symbol set: " + path);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            logger.Error("Symbol set is missing: " + path);
                                        }
                                    }
                                }
                            }

                            //
                            // Create special invalid and retired symbols for this library
                            //

                            _invalidSymbol = new Symbol(this, SIDC.INVALID);
                            _retiredSymbol = new Symbol(this, SIDC.RETIRED);
                        }
                        else
                        {
                            logger.Error("Unreadable symbol library: " + path);
                        }
                    }
                }
                else
                {
                    logger.Error("Specified library is missing: " + path);
                }
            }
        }
        /// <summary>
        /// Add Member
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("คุณต้องการบันทึกข้อมูล ใช่หรือไม่ ?",
                                              "คำเตือนจากระบบ", MessageBoxButtons.YesNo);

            switch (dr)
            {
            case DialogResult.Yes:
                // แปลว่า add new
                if (textBoxId.Text == "")
                {
                    SaveCommit();
                    reload();
                }
                else
                {
                    // edit
                    using (SSLsEntities db = new SSLsEntities())
                    {
                        int    id     = int.Parse(textBoxId.Text.ToString());
                        Member member = new Member();
                        //member = Singleton.SingletonMember.Instance().Members.SingleOrDefault(w => w.Id == id);
                        member = db.Member.SingleOrDefault(w => w.Id == id);
                        if (radioButtonRemove.Checked == true)
                        {
                            // ถ้าถอนหุ้น วิ่งไปอัพเดท
                            member.IsRemoveShared = true;
                            member.ResignDate     = DateTime.Now;
                            //foreach (var item in member.MemberShare.Where(w => w.Enable == true))
                            //{
                            //    item.UpdateDate = DateTime.Now;
                            //    item.UpdateBy = Singleton.SingletonAuthen.Instance().Id;
                            //    item.Enable = false;
                            //    db.Entry(item).State = EntityState.Modified;
                            //}
                        }
                        else
                        {
                            member.Name       = textBoxName.Text;
                            member.Code       = textBoxCode.Text.Trim();
                            member.CreateDate = (DateTime)Library.ConvertTHToENDate(maskedTextBoxMemberCreate.Text);

                            if (radioButtonFemale.Checked == true)
                            {
                                member.FKSex = MyConstant.Sex.Female;
                            }
                            else
                            {
                                member.FKSex = MyConstant.Sex.male;
                            }
                            member.TaxId = textBoxTax.Text;
                            var date = Library.ConvertTHToENDate(textBoxBirthDate.Text);
                            if (date == null)
                            {
                                MessageBox.Show("วันเกิดไม่ถูกต้อง");
                                return;
                            }
                            else
                            {
                                member.BirthDate = date.Value;
                            }
                            member.Tel     = textBoxTel.Text;
                            member.Age     = decimal.Parse(textBoxAge.Text);
                            member.Address = textBoxAddress.Text;
                            // หุ้นมากกว่า 0 ถึงเพิ่ม
                            if (this.value > 0)
                            {
                                MemberShare ms = new MemberShare();
                                ms.Enable = true;
                                var dateC = Library.ConvertTHToENDate(maskedTextBoxCreateDate.Text);
                                if (dateC == null)
                                {
                                    MessageBox.Show("วันที่เพิ่มหุ้นไม่ถูกต้อง");
                                    return;
                                }
                                ms.CreateDate   = dateC.Value;
                                ms.CreateBy     = Singleton.SingletonAuthen.Instance().Id;
                                ms.UpdateDate   = DateTime.Now;
                                ms.UpdateBy     = Singleton.SingletonAuthen.Instance().Id;
                                ms.FKShare      = MyConstant.Shared.General;
                                ms.FKBudgetYear = Singleton.SingletonThisBudgetYear.Instance().ThisYear.Id;
                                ms.Qty          = value;
                                ms.FKMember     = member.Id;
                                //ms.FKAgeOfShare = this.fkAgeOfShared;
                                ms.FKAgeOfShare = CheckAgeOfShared(ms.CreateDate);
                                db.MemberShare.Add(ms);
                                //db.SaveChanges();
                            }
                            // check edit share
                            for (int i = 0; i < dataGridView2.Rows.Count; i++)
                            {
                                int idShared = int.Parse(dataGridView2.Rows[i].Cells[0].Value.ToString());
                                if (idShared != 0)
                                {
                                    // หุ้น
                                    decimal     shareVal  = decimal.Parse(dataGridView2.Rows[i].Cells[1].Value.ToString());
                                    MemberShare shareEdit = member.MemberShare.SingleOrDefault(w => w.Id == idShared);
                                    if (shareVal < 1)     // ใส่ 0 เพื่อต้องการ ลบ หุ้นออก *Disable
                                    {
                                        shareEdit.Enable     = false;
                                        shareEdit.UpdateDate = DateTime.Now;
                                        shareEdit.UpdateBy   = SingletonAuthen.Instance().Id;
                                    }
                                    else if (shareEdit.Qty != shareVal)
                                    {
                                        // แปลว่าแก้ไข จำนวนหุ้น ให้อัพเดท
                                        shareEdit.Qty        = shareVal;
                                        shareEdit.UpdateDate = DateTime.Now;
                                        shareEdit.UpdateBy   = SingletonAuthen.Instance().Id;
                                    }
                                    db.Entry(shareEdit).State = EntityState.Modified;
                                }
                            }
                        }
                        //db.Member.Attach(member);
                        member.UpdateDate      = DateTime.Now;
                        member.UpdateBy        = Singleton.SingletonAuthen.Instance().Id;
                        db.Entry(member).State = EntityState.Modified;

                        db.SaveChanges();
                        var members = Singleton.SingletonMember.Instance().Members;
                        member = members.SingleOrDefault(w => w.Id == id);
                        members.Remove(member);
                        var lastEditMember = db.Member.Include("Sex").Include("MemberShare.Share").Include("MemberShare.AgeOfShare")
                                             .SingleOrDefault(w => w.Id == member.Id);
                        members.Add(lastEditMember);
                        this.value         = 0;
                        this.fkAgeOfShared = 0;
                        reload();
                    }
                }
                break;

            case DialogResult.No:
                break;
            }
        }
Example #52
0
        public void ShouldRecurseDirectories()
        {
            var library = new Library("./data/mp3/Music");

            Assert.Equal(2, library.Tracks.Count);
        }
Example #53
0
 public void Initialize()
 {
     _library = new Library();
     _library.AddParsers(new BookParser(), new NewsPaperParser(), new PatentParser());
     _library.AddWriters(new BookWriter(), new NewsPaperWriter(), new PatentWriter());
 }