// [HttpPost, Route("/api/posts/blogCategoryCreate")]
        public IActionResult CreateEventGroup([DataSourceRequest] DataSourceRequest request, CalendarEventGroup model)
        {
            if (ModelState.IsValid)
            {
                var userContext = _userContextAccessor.GetContext();
                Ensure.NotNull(userContext, "User context is missing.");
                Ensure.NotNullOrEmpty(userContext.UserId, "Cannot resolve user information.");

                if (string.IsNullOrEmpty(model?.EventGroupId) && !string.IsNullOrEmpty(model?.Title))
                {
                    var eventGroup = new CalendarEventGroup
                    {
                        Title        = model.Title,
                        UserId       = userContext.UserId,
                        SiteId       = _siteContext.SiteId,
                        EventGroupId = KeyGen.NewGuid()
                    };

                    eventGroup = _calendarQueryService.CreateEventGroup(eventGroup);

                    return(Json(new[] { eventGroup }.ToDataSourceResult(request, ModelState)));
                }

                return(Ok(model));
            }

            return(BadRequest(ModelState));
        }
        internal static IContainerPlaylist Get(
            ISession session,
            IPlaylistContainer container,
            IntPtr handle,
            IntPtr folderId,
            PlaylistType playlistType)
        {
            KeyGen key = new KeyGen(handle, folderId, playlistType);

            lock (_instanceLock)
            {
                NativeContainerPlaylist instance;

                if (!_instances.TryGetValue(key, out instance))
                {
                    instance = new NativeContainerPlaylist(session, handle, folderId, playlistType, container);
                    instance.Initialize();

                    if (SessionFactory.IsInternalCachingEnabled)
                    {
                        _instances.Add(key, instance);
                    }
                }

                return(instance);
            }
        }
Beispiel #3
0
 private Slide CreateDefaultSlide()
 {
     return(new Models.Slide()
     {
         DocumentId = KeyGen.NewGuid()
     });
 }
Beispiel #4
0
        public void CreateSysMasterPageV0(Site site)
        {
            PageTemplate sysTemplate = new PageTemplate
            {
                Id    = "System.cshtml",
                Title = "System Page"
            };

            var masterPages   = new List <PageMaster>();
            var pageTemplates = new List <PageTemplate>();

            pageTemplates.Add(sysTemplate);

            foreach (var template in pageTemplates)
            {
                var masterPage = new PageMaster
                {
                    Id           = KeyGen.NewGuid().ToString(),
                    SiteId       = site.Id,
                    TemplateId   = template.Id,
                    Title        = template.Title + " Master Page",
                    PreviewPath  = "/img/admin/na.png",
                    IsDefault    = false,
                    IsSystemPage = true
                };

                _masterPageManager.CreateAsync(masterPage).Wait();
                _masterPageManager.CreateInitialVersion(masterPage.Id, true).Wait();

                masterPages.Add(masterPage);
            }
        }
Beispiel #5
0
        public static async Task <IFolder> AddFolderAsync <TDocument>(this IFolderManager <TDocument> manager, string name, string ownerId, string parentId = null)
            where TDocument : class, IDocument
        {
            Ensure.NotNullOrEmpty(name, $"{name} cannot be null or empty.");
            Ensure.NotNullOrEmpty(ownerId, $"{ownerId} cannot be null or empty.");

            var documentLibrary = await manager.GetDocumentLibraryAsync(ownerId);

            Ensure.NotNull(documentLibrary, $"Document Library cannot be null.");

            var result = new Folder()
            {
                DocumentType = typeof(FileDocument).FullName,
                FolderType   = typeof(Folder).FullName,
                OwnerLevel   = OwnerLevel.User,
                OwnerId      = ownerId,
                CreatedBy    = ownerId,
                FolderFlags  = FolderFlag.Shared,
                Id           = KeyGen.NewGuid(),
                //ParentFolder = string.IsNullOrEmpty(parentId) ? null : (await manager.GetFolderAsync(parentId)),
                ParentId          = parentId,
                Title             = name,
                DocumentLibraryId = documentLibrary.Id
            };

            return(await manager.CreateFolderAsync(result));
        }
        public IActionResult GetToken()
        {
            var encoded    = AuthenticationHeaderValue.Parse(Request.Headers[HeaderNames.Authorization]).Parameter;
            var data       = Convert.FromBase64String(encoded);
            var authParams = Encoding.UTF8.GetString(data).Split(":");

            var identity = GetIdentity(authParams[0], authParams[1]);

            if (identity == null)
            {
                return(Forbid());
            }
            //BadRequest(new { errorText = "Invalid username or password." })
            var now = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: configuration.GetValue <string>("AuthOptions:issuer"),
                audience: configuration.GetValue <string>("AuthOptions:audience"),
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(configuration.GetValue <int>("AuthOptions:lifetime"))),
                signingCredentials: new SigningCredentials(KeyGen.GetSymmetricSecurityKey(configuration.GetValue <string>("AuthOptions:key")), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            var response   = new
            {
                access_token = encodedJwt,
                username     = identity.Name
            };

            return(Ok(response));
        }
Beispiel #7
0
        public async Task <IViewComponentResult> InvokeAsync(string layerId, string slideId, string layerType)
        {
            var layerName = "Default";
            var layer     = await GetSlideLayer(layerId);

            if (layer == null)
            {
                layer = new SlideLayer()
                {
                    Id        = KeyGen.NewGuid(),
                    SlideId   = slideId,
                    LayerType = layerType
                };
            }

            switch (layerType)
            {
            case "button":
                layerName = "Button";
                break;

            //TODO image or video, not implemented.
            //case 'image'

            //case 'video'

            default:
                layerName = "Default";
                break;
            }

            return(View(layerName, layer));
        }
Beispiel #8
0
        public async Task AddUriAsync(string tenantKey, string uri, TenantUriType uriType)
        {
            var tenant = await _identityDb.Tenants.FirstOrDefaultAsync(x => x.Key == tenantKey);

            if (tenant == null)
            {
                throw new NullReferenceException($"Tenant {tenantKey} does not exist.");
            }

            uri = NormalizeTenantUri(uri);

            var exists = await _identityDb.TenantUris
                         .AnyAsync(x => x.TenantId == tenantKey && x.Uri == uri && x.Type == uriType);

            if (!exists)
            {
                _identityDb.TenantUris.Add(new TenantUri
                {
                    Id       = KeyGen.NewGuid(),
                    TenantId = tenant.Id,
                    Type     = uriType,
                    Uri      = uri
                });

                await _identityDb.SaveChangesAsync();
            }
        }
Beispiel #9
0
        public new async Task <IdentityResult> CreateAsync(User user, string password)
        {
            Ensure.NotNull(user.UserName);
            Ensure.NotNull(user.DirectoryId);
            Ensure.NotNull(user.Email);

            if (user.TenantId == null)
            {
                var directory = await _db.Directories.FirstOrDefaultAsync(x => x.Id == user.DirectoryId);

                user.TenantId = directory.TenantId;
            }

            // logic for validating on usernames and emails per tenant were extracted to their own validator class
            // see the custom Angelo.Identity.Validators classes

            // Use custom guid & security stamp generator
            if (user.Id == null)
            {
                user.Id = KeyGen.NewGuid();
            }

            if (user.SecurityStamp == null)
            {
                user.SecurityStamp = KeyGen.NewGuid32();
            }

            user.NormalizedEmail    = user.Email.ToLower();
            user.NormalizedUserName = user.UserName.ToLower();

            return(await base.CreateAsync(user, password));
        }
Beispiel #10
0
        private void EnsureSecurityPoolExists(Site site)
        {
            Identity.Models.SecurityPool securityPool = null;

            if (site.SecurityPoolId != null)
            {
                securityPool = _identityDb.SecurityPools.FirstOrDefault(x => x.PoolId == site.SecurityPoolId);
            }

            if (securityPool == null)
            {
                var directory = _identityDb.Directories.FirstOrDefault(x => x.TenantId == site.Client.TenantKey);

                securityPool = new Identity.Models.SecurityPool()
                {
                    PoolId       = site.SecurityPoolId ?? KeyGen.NewGuid(),
                    PoolType     = PoolType.Site,
                    Name         = site.Title + " Security Pool",
                    TenantId     = site.Client.TenantKey,
                    ParentPoolId = site.Client.SecurityPoolId,
                    DirectoryMap = new DirectoryMap[]
                    {
                        new DirectoryMap {
                            DirectoryId = directory.Id
                        }
                    }
                };

                _identityDb.SecurityPools.Add(securityPool);
                _identityDb.SaveChanges();

                site.SecurityPoolId = securityPool.PoolId;
                _connectDb.SaveChanges();
            }
        }
        private string GetToken(string fileName)
        {
            KeyGen keyGen = new KeyGen();
            var    rv     = keyGen.GetHash(fileName);

            return(HttpUtility.UrlEncode(rv));
        }
Beispiel #12
0
        private Slide CreateSlide(FileDocument document, IEffect <Slide> effect, string linkUrl)
        {
            var result = new Slide()
            {
                ImageUrl      = CreateImageUrl(document),
                ThumbnailUrl  = CreateThumbnailUrl(document),
                DocumentId    = KeyGen.NewGuid(),
                Duration      = 4000,
                BackgroundFit = Fit.Cover,
                Direction     = Direction.LeftToRight,
                Title         = GetSlideTitle(document),
                SlideLinkUrl  = linkUrl,
                LinkTarget    = LinkTarget.NewWindow,
                IsLinkEnabled = !string.IsNullOrEmpty(linkUrl)
            };

            // Add effect (if any) to the first slide
            if (effect != null)
            {
                if (effect is Parallax)
                {
                    throw new NotImplementedException();
                }
                else if (effect is KenBurnsEffect)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    throw new NotSupportedException($"Unable to persist effects of type '{effect.GetType().Name}'.");
                }
            }

            return(result);
        }
Beispiel #13
0
        private async Task <FileDocument> CreateFileDocumentAsync(string userId, string image, Folder destination)
        {
            var fileName = image.Substring("/assets/images/".Length);
            var result   = new FileDocument()
            {
                DocumentId = KeyGen.NewGuid(),
                Title      = fileName,
                FileName   = fileName,
                FileType   = FileType.Image
            };

            // upload it
            await UploadDriveDocumentAsync(result, image, destination);

            return(result);
            // Current, Drive does this with the upload (taking that out later)
            //using (var db = new ConnectDbContext(_writeDbConnect))
            //{
            //    // Create it
            //    db.FileDocuments.Add(result);

            //    // Add it to a folder
            //    db.FolderItems.Add(new FolderItem()
            //    {
            //        Id = KeyGen.NewGuid(),
            //        Folder = destination,
            //        FolderId = destination.Id,
            //        DocumentId = result.DocumentId
            //    });

            //    db.SaveChanges();
            //}
        }
Beispiel #14
0
        public async Task CreateAsync(Client client)
        {
            Ensure.That(client.Id == null, "Client Id is set internally when creating new clients");
            Ensure.NotNullOrEmpty(client.TenantKey);

            client.Id = KeyGen.NewGuid();

            // Initialize OIDC for this new client
            var tenant = await _tenantManager.CreateAsync(client.TenantKey, client.Name);

            var directory = await _directoryManager.CreateAsync(client.TenantKey, "Default User Directory");

            // create a new security pool mapped to the default directory
            var clientSecurityPool = await _poolManager.CreateTenantPoolAsync
                                     (
                client.TenantKey,
                client.Name + " Pool",
                new Identity.Models.Directory[] { directory }
                                     );

            // Create the Connect Client
            client.SecurityPoolId = clientSecurityPool.PoolId;

            if (client.AnniversaryDate == null)
            {
                client.AnniversaryDate = DateTime.UtcNow;
            }

            _db.Add(client);
            await _db.SaveChangesAsync();

            // Insert default roles
            await CreateDefaultClientLevelRoles(client);
        }
Beispiel #15
0
 private void btn_Ativar_Click(object sender, EventArgs e)
 {
     try
     {
         if (txt_Validacao.Text == KeyGen.Validador(lbl: lbl_Numero).ToString())
         {
             IntanciarKeyGenRepositorio();
             if (_keyGRepositorio.DeletarDatas() > 0)
             {
                 DialogMessage.MessageFullComButtonOkIconeDeInformacao("Serial correto, você tem mais 30 dias de uso.", "Aviso");
                 new frmLogin().Show();
                 this.Hide();
             }
             else
             {
                 DialogMessage.MessageFullComButtonOkIconeDeInformacao("Serial correto, mas ocorreu um problema de validação, contate o Administrador", "Aviso");
             }
         }
         else
         {
             DialogMessage.MessageFullComButtonOkIconeDeInformacao("Serial incorreto, tente novamente", "Aviso");
             FocarNoTxt();
         }
     }
     catch (CustomException erro)
     {
         DialogMessage.MessageFullComButtonOkIconeDeInformacao(erro.Message, "Aviso");
     }
     catch (Exception erro)
     {
         SaveErroInTxt.RecordInTxt(erro, this.GetType().Name);
         DialogMessage.MessageComButtonOkIconeErro(erro.Message, "Erro");
     }
 }
Beispiel #16
0
        public async Task <string> CreateAsync(Site site)
        {
            if (string.IsNullOrEmpty(site.Id))
            {
                site.Id = KeyGen.NewGuid();
            }

            // Configure the OIDC security pool for the site
            var client = await _clientManager.GetByIdAsync(site.ClientId);

            var directories = await _oidcDirectoryManager.GetDirectoriesAsync(client.TenantKey);

            var sitePool = await _oidcPoolManager.CreateChildPoolAsync
                           (
                client.SecurityPoolId,
                site.Title,
                directories
                           );

            site.SecurityPoolId = sitePool.PoolId;


            // Create the site
            _db.Sites.Add(site);

            await _db.SaveChangesAsync();

            return(site.Id);
        }
Beispiel #17
0
        public async Task AddDocumentAsync(TDocument document, IFolder folder)
        {
            Ensure.NotNull(document, $"{nameof(document)} cannot be null.");
            Ensure.NotNull(folder, $"{nameof(folder)} cannot be null.");

            var item = await GetItemAsync(document.DocumentId, folder.Id);

            if (item == null)
            {
                using (var db = new ConnectDbContext(_db))
                {
                    item = new FolderItem()
                    {
                        AllowComments   = true,
                        DocumentId      = document.DocumentId,
                        Folder          = folder as Folder,
                        FolderId        = folder.Id,
                        Id              = KeyGen.NewGuid(),
                        InheritSecurity = false,
                        InheritSharing  = false,
                        InheritTags     = false,
                        ItemStatus      = ModerationStatus.Approved
                    };

                    // No async, since we are in a lock
                    db.Entry(item).State = EntityState.Added;

                    await db.FolderItems.AddAsync(item);

                    db.SaveChanges();
                }
            }
        }
Beispiel #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR(hubOptions =>
            {
                hubOptions.EnableDetailedErrors = true;
                hubOptions.KeepAliveInterval    = System.TimeSpan.FromMinutes(1);
            });
            services.AddControllers().AddNewtonsoftJson(options =>
                                                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
            services.AddEntityFrameworkSqlServer()
            .AddDbContext <AppContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = Configuration.GetValue <string>("AuthOptions:issuer"),
                    ValidateAudience         = true,
                    ValidAudience            = Configuration.GetValue <string>("AuthOptions:audience"),
                    ValidateLifetime         = true,
                    IssuerSigningKey         = KeyGen.GetSymmetricSecurityKey(Configuration.GetValue <string>("AuthOptions:key")),
                    ValidateIssuerSigningKey = true,
                };
            });
        }
Beispiel #19
0
        /*
         * DecryptFromBytes(byte[] dataStructure, string pwd1, byte[] salt1, int myIterations)
         * Code here modified from: https://docs.microsoft.com/en-us/dotnet/api/
         *                              system.security.cryptography.aes?view=netframework-4.8
         * dataStructure : dataStruct : [metadata][hmac][iv][encrypted data]
         * pwd1 : the password from user
         * salt1 : random 8 bytes for master key
         * myIterations : num iterations from user
         * originalDataLength : data length before encryption to fix padding
         * output: []byte : trimmedDecrypted byte array  [ must trim due to padding ]
         */
        public static byte[] DecryptFromBytes(byte[] dataStructure, string pwd1, byte[] salt1, int myIterations, int originalDataLength, int metaDataLength, int encryptedDataLength, int IVLength, int macLength, int keySize, int hashAlgorithm)
        {
            // variables to return
            byte[] decrypted = new byte[encryptedDataLength];


            // Create an Aes object with the specified key and IV.
            using (Aes decAlg = Aes.Create())
            {
                KeyGen keyGen_Master = new KeyGen(pwd1, salt1, myIterations, keySize, hashAlgorithm);
                decAlg.Key = keyGen_Master.MasterKey;
                byte[] HMAC_Key = keyGen_Master.HMACKey;
                byte[] enc_Key  = keyGen_Master.EncryptionKey;
                decAlg.Padding = PaddingMode.PKCS7;

                // Create byte arrays to parse out data
                byte[] metaData            = new byte[metaDataLength];
                byte[] IV                  = new byte[decAlg.BlockSize / 8];
                byte[] encryptedData       = new byte[encryptedDataLength];
                byte[] storedHMAC          = new byte[macLength];
                byte[] combinedIVEncrypted = new byte[encryptedDataLength + IVLength];

                // Copy data to arrays
                Array.Copy(dataStructure, 0, metaData, 0, metaData.Length);
                Array.Copy(dataStructure, dataStructure.Length - encryptedDataLength - IVLength, IV, 0, IV.Length);
                Array.Copy(dataStructure, dataStructure.Length - encryptedDataLength, encryptedData, 0, encryptedData.Length);
                Array.Copy(dataStructure, dataStructure.Length - encryptedDataLength - IVLength, combinedIVEncrypted, 0, combinedIVEncrypted.Length);
                Array.Copy(dataStructure, metaDataLength, storedHMAC, 0, storedHMAC.Length);

                //verify signature
                verifyHMAC(HMAC_Key, storedHMAC, combinedIVEncrypted);

                // STUB FOR GRADING AND VERIFICAITON TODO: DELETE
                //Console.WriteLine("\nMetadata is {0}", Encoding.UTF8.GetString(metaData));
                //Console.WriteLine("\nParsed Decrypt IV {0}", Convert.ToBase64String(IV));
                //Console.WriteLine("Stubbing output encryptedData {0}", Convert.ToBase64String(encryptedData));

                //Use Streams to encrypt
                //TODO : moving cipher mode up causes decrypt difference.. find out why
                decAlg.IV   = IV;
                decAlg.Mode = CipherMode.CBC;
                using (var decryptor = decAlg.CreateDecryptor(enc_Key, decAlg.IV))
                {
                    using (MemoryStream ms = new MemoryStream(encryptedData))
                    {
                        using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                        {
                            cryptoStream.Read(decrypted, 0, decrypted.Length);
                            cryptoStream.Close();
                        } //end cryptostream
                        ms.Close();
                    }     //end memory stream
                }         //end decryptor
            }             //end aes decryption key
            //must trim due to padding
            byte[] trimmed = new byte[originalDataLength];
            Array.Copy(decrypted, 0, trimmed, 0, trimmed.Length);
            return(trimmed);
        }//end decrpypt from bytes
 internal static void Remove(IntPtr playlistPtr, IntPtr folderId, PlaylistType type)
 {
     lock (_instanceLock)
     {
         KeyGen key = new KeyGen(playlistPtr, folderId, type);
         _instances.Remove(key);
     }
 }
Beispiel #21
0
        private IEnumerable <Page> CreateSitePagesV0(Site site, IEnumerable <PageMaster> masterPages)
        {
            var    sitePages  = new List <Page>();
            string dataFolder = null;
            IList <SiteTemplatePage> pagesToSeed = null;

            // Setting pages & data path either from template (if supplied) or using defaults
            if (_siteTemplate.Pages != null)
            {
                pagesToSeed = _siteTemplate.Pages;
                dataFolder  = _coreOptions.FileSystemRoot + "\\" + _siteTemplate.DataFolder;
            }
            else
            {
                dataFolder  = _defaultDataFolder;
                pagesToSeed = GetDefaultPagesToSeed();
            }

            // Create Pages
            foreach (var seedInfo in pagesToSeed)
            {
                var master    = masterPages.First(x => x.TemplateId == seedInfo.Template);
                var seedFiles = seedInfo.SeedData?.Select(file => dataFolder + "\\" + file);

                var sitePage = new Page
                {
                    Id           = KeyGen.NewGuid(),
                    SiteId       = site.Id,
                    PageMasterId = master.Id,
                    Title        = seedInfo.Title,
                    Path         = seedInfo.Path,
                    Type         = PageType.Normal,
                    IsHomePage   = seedInfo.Path == "/"
                };

                _connectDb.Pages.Add(sitePage);
                _connectDb.SaveChanges();

                var version = _pageManager.CreateInitialVersion(sitePage, seedFiles).Result;

                // manually seed if no seed files were included
                if (seedFiles == null)
                {
                    if (_pageTemplates[0].Id == master.TemplateId)
                    {
                        ManuallySeedHomePage(sitePage, version);
                    }
                    else
                    {
                        ManuallySeedSecondaryPage(sitePage, version);
                    }
                }

                sitePages.Add(sitePage);
            }

            return(sitePages);
        }
        public void Sha256()
        {
            byte[] data = KeyGen.ASCIIEncoder("LJ Gomez");
            var    gg   = SHA256.MessageSHA256(data);

            var k = Convert.ToBase64String(gg);

            ;
        }
Beispiel #23
0
        private void CreateSiteNavigationV0(Site site, IEnumerable <Page> sitePages)
        {
            // Create the default site menu (scope = main)
            var navigationMenu = new NavigationMenu()
            {
                Id        = KeyGen.NewGuid().ToString(),
                Title     = "Top Navigation Menu",
                SiteId    = site.Id,
                Scope     = "main",
                MenuItems = new List <NavigationMenuItem>()
            };

            // create a link for each top level public page (not private)
            int order        = 1;
            var orderedPages = sitePages.Where(x =>
                                               x.ParentPageId == null && x.IsPrivate == false
                                               )
                               .OrderBy(x => x.Path)
                               .ThenBy(x => x.Title)
                               .ToList();


            foreach (var page in orderedPages)
            {
                var menuItem = new NavigationMenuItem
                {
                    Id          = KeyGen.NewGuid().ToString(),
                    Title       = page.Title,
                    ContentType = "PageLink",
                    ContentId   = page.Id,
                    Order       = order
                };

                navigationMenu.MenuItems.Add(menuItem);
                order += 1;
            }

            var isNotificationsEnabled = GetProductContext(site.ClientId).Features.Get(FeatureId.Notifications)?.GetSettingValue <bool>("enabled") ?? false;

            if (isNotificationsEnabled)
            {
                // adding a notify me link here temporarily
                var notifyMeLink = new NavigationMenuItem()
                {
                    Id          = KeyGen.NewGuid().ToString(),
                    Title       = "NotifyMe",
                    ContentType = NavigationMenuItemType.ExternalURL,
                    ExternalURL = "/sys/notifyme/start",
                    Order       = order
                };

                navigationMenu.MenuItems.Add(notifyMeLink);
            }

            _connectDb.NavigationMenu.Add(navigationMenu);
            _connectDb.SaveChanges();
        }
Beispiel #24
0
 private FolderCategory BuildFolderCategory(IFolder folder, Category category)
 {
     return(new FolderCategory
     {
         Id = KeyGen.NewGuid(),
         FolderId = folder.Id,
         CategoryId = category.Id
     });
 }
Beispiel #25
0
 private FolderTag BuildFolderTag(IFolder folder, string tag)
 {
     return(new FolderTag
     {
         Id = KeyGen.NewGuid(),
         FolderId = folder.Id,
         TagName = tag
     });
 }
Beispiel #26
0
 public override Int32 GetHashCode()
 {
     return(KeyGen.WinBuildID
            (
                this.buildNumber,
                this.buildQfe,
                this.buildRevision ?? string.Empty,
                this.branchName
            ));
 }
Beispiel #27
0
 public AnnouncementWidget GetDefaultModel()
 {
     return(new AnnouncementWidget
     {
         Id = Guid.NewGuid().ToString("N"),
         Title = "Sample Announcement Posts",
         AnnouncementId = KeyGen.NewGuid(),
         CreateAnnouncement = true,
         PageSize = 5
     });
 }
Beispiel #28
0
 public NewsWidget GetDefaultModel()
 {
     return(new NewsWidget
     {
         Id = Guid.NewGuid().ToString("N"),
         Title = "Sample News Posts",
         NewsId = KeyGen.NewGuid(),
         CreateNews = true,
         PageSize = 5
     });
 }
Beispiel #29
0
            public override bool Equals(object obj)
            {
                if (obj == null)
                {
                    return(false);
                }
                var    comparer = EqualityComparer <object> .Default;
                KeyGen keyGen   = obj as KeyGen;

                return(keyGen != null && comparer.Equals(this.Item1, keyGen.Item1) && comparer.Equals(this.Item2, keyGen.Item2));
            }
 internal static void Delete(Playlist playlist, int position)
 {
     KeyGen key = new KeyGen(playlist, position);
     lock (tracksLock)
     {
         PlaylistTrack track = tracks[key];
         int count = track.RemRef();
         if (count == 0)
             tracks.Remove(key);
     }
 }
 internal static void Delete(IntPtr playlistPtr, IntPtr folderId, sp_playlist_type type)
 {
     lock (playlistsLock)
     {
         KeyGen key = new KeyGen(playlistPtr, folderId, type);
         ContainerPlaylist playlist = playlists[key];
         int count = playlist.RemRef();
         if (count == 0)
             playlists.Remove(key);
     }
 }
Beispiel #32
0
 public BlogWidget GetDefaultModel()
 {
     return(new BlogWidget
     {
         Id = Guid.NewGuid().ToString("N"),
         Title = "Sample Blog Posts",
         BlogId = KeyGen.NewGuid(),
         CreateBlog = true,
         PageSize = 5
     });
 }
 internal static IPlaylistTrack Get(Session session, Playlist playlist, IntPtr trackPtr, int position)
 {
     KeyGen key = new KeyGen(playlist, position);
     PlaylistTrack track;
     lock (tracksLock)
     {
         if (!tracks.ContainsKey(key))
         {
             tracks.Add(key, new PlaylistTrack(session, playlist, trackPtr, position));
         }
         track = tracks[key];
         track.AddRef();
     }
     return new PlaylistTrackWrapper(track);
 }
 internal static IContainerPlaylist Get(Session session, PlaylistContainer container, IntPtr playlistPtr, IntPtr folderId, sp_playlist_type type)
 {
     KeyGen key = new KeyGen(playlistPtr, folderId, type);
     ContainerPlaylist playlist;
     lock (playlistsLock)
     {
         if (!playlists.ContainsKey(key))
         {
             playlists.Add(key, new ContainerPlaylist(session, container, playlistPtr, folderId, type));
         }
         playlist = playlists[key];
         playlist.AddRef();
     }
     return new ContainerPlaylistWrapper(playlist);
 }
        internal static void Update(Playlist playlist, IEnumerable<int> moves = null, int movedTo = -1, IEnumerable<int> aditions = null, IEnumerable<int> removals = null)
        {
            Dictionary<int, int> moved = new Dictionary<int, int>();
            List<int> newTracks = new List<int>();
            List<int> toDel = new List<int>();
            int oldCount = playlistLengths[playlist];
            int count;
            int deleted;
            if (aditions != null)
            {
                count = aditions.Count();
                for (int i = aditions.First(); i < oldCount; i++)
                    moved.Add(i, i + count);
                foreach (int index in aditions)
                    newTracks.Add(index);
            }
            else if (removals != null)
            {
                deleted = 0;
                for (int i = 0; i < oldCount; i++)
                {
                    if (removals.Contains(i))
                    {
                        deleted++;
                        continue;
                    }
                    if (deleted > 0)
                    {
                        moved.Add(i, i - deleted);
                    }
                }
            }
            else if (moves != null && movedTo != -1)
            {
                deleted = 0;
                for (int i = 0; i < oldCount; i++)
                {
                    if (moves.Contains(i))
                    {
                        deleted++;
                        continue;
                    }
                    if (deleted > 0)
                    {
                        moved.Add(i, i - deleted);
                    }
                }
                count = moves.Count();
                for (int i = movedTo; i < oldCount; i++)
                {
                    if (moved.ContainsKey(i))
                        moved[i] += count;
                    else
                        moved.Add(i, i + count);
                }
                int i1 = 0;
                foreach (int index in moves)
                    if (moved.ContainsKey(index))
                        moved[index] = movedTo + (i1++);
                    else
                        moved.Add(index, movedTo + (i1++));
            }

            foreach (var itm in moved)
            {
                KeyGen kg = new KeyGen(playlist, itm.Key);
                if (tracks.ContainsKey(kg))
                {
                    PlaylistTrack track = tracks[kg];
                    tracks.Remove(kg);
                    track.position = itm.Value;
                    kg = new KeyGen(playlist, itm.Value);
                    tracks.Add(kg, track);
                }
            }
            foreach (var itm in toDel)
            {
                KeyGen kg = new KeyGen(playlist, itm);
                if (tracks.ContainsKey(kg))
                {
                    PlaylistTrack track = tracks[kg];
                    track.Dispose();
                    tracks.Remove(kg);
                }
            }
        }