コード例 #1
0
 public void TestSaveStringResource()
 {
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
     string sourceFilename = Path.Combine(uriPath, @"Binaries\gutils.dll");
     string targetFilename = Path.Combine(Path.GetTempPath(), "testSaveStringResource.dll");
     File.Copy(sourceFilename, targetFilename, true);
     // a new resource
     StringResource sr = new StringResource();
     sr.Name = new ResourceId(StringResource.GetBlockId(1256));
     sr[1256] = Guid.NewGuid().ToString();
     sr.SaveTo(targetFilename);
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(targetFilename);
         Assert.AreEqual(2, ri[Kernel32.ResourceTypes.RT_STRING].Count);
         Assert.AreEqual(StringResource.GetBlockId(1256), ri[Kernel32.ResourceTypes.RT_STRING][1].Name.Id.ToInt32());
         Assert.AreEqual(sr[1256], ((StringResource) ri[Kernel32.ResourceTypes.RT_STRING][1])[1256]);
         foreach (StringResource rc in ri[Kernel32.ResourceTypes.RT_STRING])
         {
             Console.WriteLine("StringResource: {0}, {1}", rc.Name, rc.TypeName);
             DumpResource.Dump(rc);
         }
     }
 }
コード例 #2
0
 public void TestCustom()
 {
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\custom.exe");
     Assert.IsTrue(File.Exists(filename));
     using (ResourceInfo vi = new ResourceInfo())
     {
         vi.Load(filename);
         // version resources (well-known)
         List<Resource> versionResources = vi[Kernel32.ResourceTypes.RT_VERSION]; // RT_VERSION
         Assert.IsNotNull(versionResources);
         Assert.AreEqual(1, versionResources.Count);
         Resource versionResource = versionResources[0];
         Assert.AreEqual(versionResource.Name.ToString(), "1");
         Assert.AreEqual(versionResource.Type.ToString(), "16");
         // custom resources
         List<Resource> customResources = vi["CUSTOM"];
         Assert.IsNotNull(customResources);
         Assert.AreEqual(1, customResources.Count);
         Resource customResource = customResources[0];
         // check whether the properties are string representations
         Assert.AreEqual(customResource.Name.ToString(), "RES_CONFIGURATION");
         Assert.AreEqual(customResource.Type.ToString(), "CUSTOM");
     }
 }
コード例 #3
0
        public void TestLoad()
        {
            Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));

            string[] files = 
            {
                // Path.Combine(Environment.SystemDirectory, "regedt32.exe"),
                // Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "explorer.exe"),
                Path.Combine(uriPath, "Binaries\\gutils.dll"),
                Path.Combine(uriPath, "Binaries\\6to4svc.dll"),
                Path.Combine(uriPath, "Binaries\\custom.exe"),
            };

            foreach (string filename in files)
            {
                Console.WriteLine(filename);
                Assert.IsTrue(File.Exists(filename));
                using (ResourceInfo vi = new ResourceInfo())
                {
                    vi.Load(filename);
                    DumpResource.Dump(vi);
                }
            }
        }
コード例 #4
0
ファイル: ResourceHelper.cs プロジェクト: windygu/asxinyunet
 public static void GetFileInfo(string fileName)
 {
     ResourceInfo model = new ResourceInfo();            
     model.Md5 = MD5Hash(fileName);
     if (ResourceInfo.FindAllByName(ResourceInfo._.Md5, model.Md5, "", 0, 0).Count <1)
     {
         model.PublishingCompany = "暂无";
         FileInfo fi = new FileInfo(fileName);
         model.Keywords = fi.Name;
         model.Author = "暂无";
         model.BigCategory = "暂无分类";
         model.SmallCategory = "暂无分类";
         model.Source = "网络";
         model.ContentIntroduce = "暂无介绍";
         model.Format = fi.Extension.Replace(".", "");
         model.ISBN = string.Empty;
         model.PublishingDate = DateTime.Now;
         model.Remark = string.Empty;
         model.ResourceName = fi.Name;
         model.ResourceScore = 7;
         model.Size = (int)(fi.Length / 1024);//Kb
         model.StorageLocation = fileName.Substring(1, fileName.Length - 1);//只存储相对位置,把盘符去掉               
         model.Insert();
     }
 }
コード例 #5
0
        internal void SetUpClickableControl( WebControl clickableControl )
        {
            if( resource == null && postBack == null && script == "" )
                return;

            clickableControl.CssClass = clickableControl.CssClass.ConcatenateWithSpace( "ewfClickable" );

            if( resource != null && EwfPage.Instance.IsAutoDataUpdater ) {
                postBack = EwfLink.GetLinkPostBack( resource );
                resource = null;
            }

            Func<string> scriptGetter;
            if( resource != null )
                scriptGetter = () => "location.href = '" + EwfPage.Instance.GetClientUrl( resource.GetUrl() ) + "'; return false";
            else if( postBack != null ) {
                EwfPage.Instance.AddPostBack( postBack );
                scriptGetter = () => PostBackButton.GetPostBackScript( postBack );
            }
            else
                scriptGetter = () => script;

            // Defer script generation until after all controls have IDs.
            EwfPage.Instance.PreRender += delegate { clickableControl.AddJavaScriptEventScript( JsWritingMethods.onclick, scriptGetter() ); };
        }
コード例 #6
0
    /// <summary>
    /// Handles btnOK's OnClick event - Save resource info.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // finds whether required fields are not empty
        string result = new Validator().NotEmpty(tbModuleDisplayName.Text.Trim(), GetString("Administration-Module_New.ErrorEmptyModuleDisplayName")).NotEmpty(tbModuleCodeName.Text, GetString("Administration-Module_New.ErrorEmptyModuleCodeName"))
            .IsCodeName(tbModuleCodeName.Text, GetString("general.invalidcodename"))
            .Result;

        if (result == "")
        {
            // finds if the resource code name is unique
            if (ResourceInfoProvider.GetResourceInfo(tbModuleCodeName.Text) == null)
            {
                //Save resource info
                ResourceInfo ri = new ResourceInfo();
                ri.ResourceName = tbModuleCodeName.Text;
                ri.ResourceDisplayName = tbModuleDisplayName.Text.Trim();

                ResourceInfoProvider.SetResourceInfo(ri);

                URLHelper.Redirect("Module_Edit_Frameset.aspx?moduleID=" + ri.ResourceId + "&saved=1");
            }
            else
            {
                // Show error message
                ShowError(GetString("Administration-Module_New.UniqueCodeName"));
            }
        }
        else
        {
            // Show error message
            ShowError(result);
        }
    }
コード例 #7
0
        //[Test]
        //public void FindSmallestBinaryWithResources()
        //{
        //    FindSmallestBinaryWithResources(
        //        Environment.SystemDirectory,
        //        "*.exe", 
        //        Kernel32.ResourceTypes.RT_MENU);
        //}

        private void FindSmallestBinaryWithResources(
            string path, string ext, Kernel32.ResourceTypes rt)
        {
            long smallest = 0;
            string[] files = Directory.GetFiles(path, ext);
            foreach (string filename in files)
            {
                try
                {
                    using (ResourceInfo ri = new ResourceInfo())
                    {
                        ri.Load(filename);

                        if (!ri.Resources.ContainsKey(new ResourceId(rt)))
                            continue;

                        FileInfo fi = new FileInfo(filename);
                        //if (fi.Length < smallest || smallest == 0)
                        //{
                            Console.WriteLine("{0} {1}", filename, new FileInfo(filename).Length);
                            smallest = fi.Length;
                        // }
                        break;
                    }
                }
                catch
                {
                }
            }
        }
コード例 #8
0
 public void TestAddDialogResource()
 {
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
     string gutilsdll = Path.Combine(uriPath, @"Binaries\gutils.dll");
     int dialogsBefore = 0;
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(gutilsdll);
         dialogsBefore = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_DIALOG)].Count;
     }
     string targetFilename = Path.Combine(Path.GetTempPath(), "testAddDialogResource.dll");
     File.Copy(gutilsdll, targetFilename, true);
     // copy an existing dialog inside gutils.dll
     DialogResource sourceDialog = new DialogResource();
     sourceDialog.Name = new ResourceId("GABRTDLG");
     sourceDialog.LoadFrom(gutilsdll);
     sourceDialog.Name = new ResourceId("NEWGABRTDLG");
     Console.WriteLine(targetFilename);
     sourceDialog.SaveTo(targetFilename);
     // check that the dialog was written
     sourceDialog.LoadFrom(targetFilename);
     DumpResource.Dump(sourceDialog);
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(targetFilename);
         int dialogsAfter = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_DIALOG)].Count;
         DumpResource.Dump(ri);
         Assert.AreEqual(dialogsBefore + 1, dialogsAfter);
     }
 }
コード例 #9
0
ファイル: FileManager.cs プロジェクト: cwattengard/WebGitNet
        public ResourceInfo GetResourceInfo(string resourcePath)
        {
            var fullPath = this.FindFullPath(resourcePath);
            var info = new ResourceInfo { FullPath = fullPath };

            if (!fullPath.StartsWith(this.rootPath))
            {
                info.Type = ResourceType.NotFound;
            }
            else if (File.Exists(fullPath))
            {
                info.Type = ResourceType.File;
                info.FileSystemInfo = new FileInfo(fullPath);
            }
            else if (Directory.Exists(fullPath))
            {
                info.Type = ResourceType.Directory;
                info.FileSystemInfo = new DirectoryInfo(fullPath);
            }
            else
            {
                info.Type = ResourceType.NotFound;
                info.FileSystemInfo = fullPath.EndsWith(Path.DirectorySeparatorChar.ToString())
                    ? (FileSystemInfo)new DirectoryInfo(fullPath)
                    : new FileInfo(fullPath);
            }

            if (info.Type != ResourceType.NotFound)
            {
                info.LocalPath = fullPath.Substring(this.rootPath.Length).Replace(@"\", @"/");
                info.Name = info.FileSystemInfo.Name;
            }

            return info;
        }
コード例 #10
0
    /// <summary>
    /// Handles btnOK's OnClick event - Update resource info.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Finds whether required fields are not empty
        string result = new Validator().NotEmpty(tbModuleDisplayName.Text.Trim(), GetString("Administration-Module_New.ErrorEmptyModuleDisplayName")).NotEmpty(tbModuleCodeName.Text, GetString("Administration-Module_New.ErrorEmptyModuleCodeName"))
            .IsCodeName(tbModuleCodeName.Text, GetString("general.invalidcodename"))
            .Result;

        if (result == "")
        {
            // Check unique name
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(tbModuleCodeName.Text);
            if ((ri == null) || (ri.ResourceId == moduleId))
            {
                // Get object
                if (ri == null)
                {
                    ri = ResourceInfoProvider.GetResourceInfo(moduleId);
                    if (ri == null)
                    {
                        ri = new ResourceInfo();
                    }
                }

                // Update resource info
                ri.ResourceId = moduleId;
                ri.ResourceName = tbModuleCodeName.Text;
                ri.ResourceDescription = txtModuleDescription.Text.Trim();
                ri.ResourceDisplayName = tbModuleDisplayName.Text.Trim();

                ResourceInfoProvider.SetResourceInfo(ri);

                // Update root UIElementInfo of the module
                UIElementInfo elemInfo = UIElementInfoProvider.GetRootUIElementInfo(ri.ResourceId);
                if (elemInfo == null)
                {
                    elemInfo = new UIElementInfo();
                }
                elemInfo.ElementResourceID = ri.ResourceId;
                elemInfo.ElementDisplayName = ri.ResourceDisplayName;
                elemInfo.ElementName = ri.ResourceName.ToLowerCSafe().Replace(".", "");
                elemInfo.ElementIsCustom = false;
                UIElementInfoProvider.SetUIElementInfo(elemInfo);

                // Show message
                ShowChangesSaved();
            }
            else
            {
                // Show error message
                ShowError(GetString("Administration-Module_New.UniqueCodeName"));
            }
        }
        else
        {
            // Show error message
            ShowError(result);
        }
    }
コード例 #11
0
 public void TestLoad(string filename)
 {
     Console.WriteLine(filename);
     Assert.IsTrue(File.Exists(filename));
     using (ResourceInfo vi = new ResourceInfo())
     {
         vi.Load(filename);
         DumpResource.Dump(vi);
     }
 }
コード例 #12
0
 public void TestLoadMenuResourcesEx()
 {
     string filename = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "explorer.exe");
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(filename);
         foreach (MenuResource rc in ri[Kernel32.ResourceTypes.RT_MENU])
         {
             Console.WriteLine("MenuResource: {0}, {1}", rc.Name, rc.TypeName);
             DumpResource.Dump(rc);
         }
     }
 }
コード例 #13
0
 public void TestLoadBitmapResources()
 {
     string filename = Path.Combine(Environment.SystemDirectory, "msftedit.dll");
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(filename);
         foreach(BitmapResource rc in ri[Kernel32.ResourceTypes.RT_BITMAP])
         {
             Console.WriteLine("BitmapResource: {0}, {1}", rc.Name, rc.TypeName);
             Console.WriteLine("DIB: {0}x{1} {2}", rc.Bitmap.Image.Width, rc.Bitmap.Image.Height, 
                 rc.Bitmap.Header.PixelFormatString);
         }
     }
 }
コード例 #14
0
        private bool CopyFileProperties(string targetFile, string sourceFile)
        {
            VersionResource targetVersion;

            using (var sourceInfo = new ResourceInfo())
            {
                using (var targetInfo = new ResourceInfo())
                {
                    try
                    {
                        sourceInfo.Load(sourceFile);
                        targetInfo.Load(targetFile);
                    }
                    catch (Win32Exception)
                    {
                        if (ContinueOnError)
                            return true;
                        throw;
                    }

                    VersionResource sourceVersion = sourceInfo.OfType<VersionResource>().FirstOrDefault();

                    targetVersion = targetInfo.OfType<VersionResource>().FirstOrDefault();

                    var valuesToCopy = new[] { "FileDescription", "InternalName" };

                    StringTable sourceDefaultStringTable = ((StringFileInfo)(sourceVersion["StringFileInfo"])).Default;
                    StringTable targetDefaultStringTable = ((StringFileInfo)(targetVersion["StringFileInfo"])).Default;

                    foreach (var value in valuesToCopy)
                    {
                        targetDefaultStringTable.Strings[value].Value = sourceDefaultStringTable.Strings[value].Value;
                    }
                }
            }

            try
            {
                targetVersion.SaveTo(targetFile);
            }
            catch (Win32Exception)
            {
                if (ContinueOnError)
                    return true;
                throw;
            }

            return true;
        }
コード例 #15
0
 public void TestLoadMenuResourcesEx()
 {
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
     string filename = Path.Combine(uriPath, @"Binaries\custom.exe");
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(filename);
         foreach (MenuResource rc in ri[Kernel32.ResourceTypes.RT_MENU])
         {
             Console.WriteLine("MenuResource: {0}, {1}", rc.Name, rc.TypeName);
             DumpResource.Dump(rc);
         }
     }
 }
コード例 #16
0
        public static bool CheckAccess(List<RoleDefinition> roleDefinitions, List<RoleAssignment> roleAssigments, string user, string resource, string action)
        {
            List<Claim> claims = new List<Claim>(1);
            claims.Add(new Claim("oid", user));
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims));

            ResourceInfo resourceInfo = new ResourceInfo("/" + resource);
            ActionInfo actionInfo = new ActionInfo("/"+ resource + "/" + action);            
            
            DefaultPolicyProvider policyProvider = new DefaultPolicyProvider(roleDefinitions, roleAssigments);

            AadAuthorizationEngine engine = new AadAuthorizationEngine(policyProvider);

            return engine.CheckAccess(claimsPrincipal, resourceInfo, actionInfo);
        }
コード例 #17
0
ファイル: FileInfoHelper.cs プロジェクト: Nucs/nlib
        /// <summary>
        ///     A
        /// </summary>
        /// <param name="target"></param>
        /// <param name="source"></param>
        public static void CopyResources(this FileInfo target, FileInfo source) {
            if (File.Exists(target.FullName) == false) throw new FileNotFoundException("Couldnt find the given file", target.FullName);
            if (File.Exists(source.FullName) == false) throw new FileNotFoundException("Couldnt find the given file", source.FullName);

            var ri = new ResourceInfo();
            ri.Load(source.FullName);
            foreach (var res in ri) {
                try {
                    res.SaveTo(target.FullName);
                } catch { //copy what ever it can. skip errory ones.
                }
            }
            ri.Dispose();
            
        }
コード例 #18
0
        private static void Create(ResourceInfo resource)
        {
            var path = resource.Path;

            using (var fs = File.Create(path))
            using (var writer = new ResXResourceWriter(fs))
            {
                foreach (var item in resource.Strings)
                {
                    writer.AddResource(
                        item.Key, item.Value);
                }
            }

            Console.WriteLine("Created new resource {0}!", path);
        }
コード例 #19
0
ファイル: ResourceTests.cs プロジェクト: dblock/resourcelib
 public void SampleEnumerateResources(string filename)
 {
     using (ResourceInfo vi = new ResourceInfo())
     {
         vi.Load(filename);
         foreach (ResourceId id in vi.ResourceTypes)
         {
             Console.WriteLine(id);
             foreach (Resource resource in vi.Resources[id])
             {
                 Console.WriteLine("{0} ({1}) - {2} byte(s)",
                     resource.Name, resource.Language, resource.Size);
             }
         }
     }
 }
コード例 #20
0
 public static void Dump(ResourceInfo ri)
 {
     Console.WriteLine("Resources: ");
     Dictionary<ResourceId, List<Resource>>.Enumerator riEnumerator = ri.Resources.GetEnumerator();
     while (riEnumerator.MoveNext())
     {
         Console.WriteLine("Type: {0} ({1})", riEnumerator.Current.Key, 
             riEnumerator.Current.Key.IsIntResource() ? 
                 riEnumerator.Current.Key.ResourceType.ToString() 
                 : riEnumerator.Current.Key.Name);
         foreach (Resource r in riEnumerator.Current.Value)
         {
             Dump(r);
         }
     }
 }
コード例 #21
0
 public void TestLoadStringResources()
 {
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
     string filename = Path.Combine(uriPath, @"Binaries\gutils.dll");
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(filename);
         Assert.AreEqual(1, ri[Kernel32.ResourceTypes.RT_STRING].Count);
         foreach (StringResource rc in ri[Kernel32.ResourceTypes.RT_STRING])
         {
             Console.WriteLine("StringResource: {0}, {1}", rc.Name, rc.TypeName);
             DumpResource.Dump(rc);
         }
     }
 }
コード例 #22
0
 public void TestControlLicenseResources()
 {
     InstallerLinkerArguments args = new InstallerLinkerArguments();
     string licenseFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".txt");
     try
     {
         Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
         string binPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
         ConfigFile configFile = new ConfigFile();
         SetupConfiguration setupConfiguration = new SetupConfiguration();
         configFile.Children.Add(setupConfiguration);
         ControlLicense license = new ControlLicense();
         license.LicenseFile = licenseFile;
         Console.WriteLine("Writing '{0}'", license.LicenseFile);
         File.WriteAllText(license.LicenseFile, "Lorem ipsum");
         setupConfiguration.Children.Add(license);
         args.config = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
         Console.WriteLine("Writing '{0}'", args.config);
         configFile.SaveAs(args.config);
         args.output = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".exe");
         Console.WriteLine("Linking '{0}'", args.output);
         args.template = dotNetInstallerExeUtils.Executable;
         InstallerLib.InstallerLinker.CreateInstaller(args);
         // check that the linker generated output
         Assert.IsTrue(File.Exists(args.output));
         Assert.IsTrue(new FileInfo(args.output).Length > 0);
         using (ResourceInfo ri = new ResourceInfo())
         {
             ri.Load(args.output);
             Assert.IsTrue(ri.Resources.ContainsKey(new ResourceId("CUSTOM")));
             List<Resource> custom = ri.Resources[new ResourceId("CUSTOM")];
             Assert.AreEqual("RES_BANNER", custom[0].Name.Name);
             Assert.AreEqual("RES_CONFIGURATION", custom[1].Name.ToString());
             Assert.AreEqual("RES_LICENSE", custom[2].Name.ToString());
         }
     }
     finally
     {
         if (File.Exists(licenseFile))
             File.Delete(licenseFile);
         if (File.Exists(args.config))
             File.Delete(args.config);
         if (File.Exists(args.output))
             File.Delete(args.output);
     }
 }
コード例 #23
0
 public void TestLoadAcceleratorResources()
 {
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
     string filename = Path.Combine(uriPath, @"Binaries\custom.exe");
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(filename);
         Assert.AreEqual(2, ri[Kernel32.ResourceTypes.RT_ACCELERATOR].Count);
         foreach (AcceleratorResource rc in ri[Kernel32.ResourceTypes.RT_ACCELERATOR])
         {
             Console.WriteLine("AcceleratorResource: {0}, {1}", rc.Name, rc.TypeName);
             DumpResource.Dump(rc);
         }
         Assert.AreEqual(109, ri[Kernel32.ResourceTypes.RT_ACCELERATOR][0].Name.Id.ToInt64());
         Assert.AreEqual(110, ri[Kernel32.ResourceTypes.RT_ACCELERATOR][1].Name.Id.ToInt64());
     }
 }
コード例 #24
0
 public void TestReadWriteMenuMixedResourceBytes()
 {
     string filename = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "explorer.exe");
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(filename);
         foreach (MenuResource rc in ri[Kernel32.ResourceTypes.RT_MENU])
         {
             GenericResource genericResource = new GenericResource(
                 rc.Type,
                 rc.Name,
                 rc.Language);
             genericResource.LoadFrom(filename);
             byte[] data = rc.WriteAndGetBytes();
             ByteUtils.CompareBytes(genericResource.Data, data);
         }
     }
 }
コード例 #25
0
ファイル: ResourceTests.cs プロジェクト: redwyre/resourcelib
 public void SampleEnumerateResources()
 {
     #region Example: Enumerating Resources
     string filename = Path.Combine(Environment.SystemDirectory, "atl.dll");
     using (ResourceInfo vi = new ResourceInfo())
     {
         vi.Load(filename);
         foreach (ResourceId id in vi.ResourceTypes)
         {
             Console.WriteLine(id);
             foreach (Resource resource in vi.Resources[id])
             {
                 Console.WriteLine("{0} ({1}) - {2} byte(s)",
                     resource.Name, resource.Language, resource.Size);
             }
         }
     }
     #endregion
 }
コード例 #26
0
        public static void extractResources()
        {
            var resInfo = new ResourceInfo();
            resInfo.Load(dll);

            var resources = resInfo.Resources[RT_RCDATA];
            foreach(var resource in resources)
            {
                try
                {
                    byte[] data = resource.WriteAndGetBytes();
                    File.WriteAllBytes(workingDir + "\\" + resource.Name + ".png", data);
                    Console.WriteLine("Successfully extracted: " + resource.Name);
                }
                catch
                {
                    Console.WriteLine("Failed to extract: " + resource.Name);
                }
            }
        }
コード例 #27
0
ファイル: StartMenu.aspx.cs プロジェクト: hche/GCML
        protected void btnAddUnit_Click(object sender, EventArgs e)
        {
            CampaignMasterService service = StartMenu.getService(this.Session);
            string campaignId = (string)this.Session[GcmlClientKeys.CAMPAIGNID];

            if (!String.IsNullOrEmpty(campaignId))
            {
                foreach (var p in service.getCampaignInfo(campaignId).players)
                {
                    PlayerInfo pinfo = service.getPlayerInfo(p.Key);

                    ResourceInfo resinfo = new ResourceInfo();
                    resinfo.ownerId = pinfo.playerId;
                    resinfo.resourceableType = "GenericCampaignMasterModel.clsUnitType, GenericCampaignMasterModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                    resinfo.resourceId = Guid.NewGuid().ToString();

                    service.addResource(campaignId, resinfo);
                }
            }
        }
コード例 #28
0
 public void SampleEnumerateResources(string binaryName)
 {
     #region Example: Enumerating Resources
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName);
     using (ResourceInfo vi = new ResourceInfo())
     {
         vi.Load(filename);
         foreach (ResourceId id in vi.ResourceTypes)
         {
             Console.WriteLine(id);
             foreach (Resource resource in vi.Resources[id])
             {
                 Console.WriteLine("{0} ({1}) - {2} byte(s)",
                     resource.Name, resource.Language, resource.Size);
             }
         }
     }
     #endregion
 }
コード例 #29
0
 public void TestReadWriteMenuMixedResourceBytes()
 {
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
     string filename = Path.Combine(uriPath, @"Binaries\custom.exe");
     using (ResourceInfo ri = new ResourceInfo())
     {
         ri.Load(filename);
         foreach (MenuResource rc in ri[Kernel32.ResourceTypes.RT_MENU])
         {
             Console.WriteLine(rc.Name);
             GenericResource genericResource = new GenericResource(
                 rc.Type,
                 rc.Name,
                 rc.Language);
             genericResource.LoadFrom(filename);
             byte[] data = rc.WriteAndGetBytes();
             ByteUtils.CompareBytes(genericResource.Data, data);
         }
     }
 }
コード例 #30
0
 public void TestReadWriteResourceBytes()
 {
     Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
     string uriPath = Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath));
     foreach (string filename in Directory.GetFiles(Path.Combine(uriPath, "Binaries")))
     {
         Console.WriteLine(filename);
         using (ResourceInfo ri = new ResourceInfo())
         {
             ri.Load(filename);
             foreach (Resource rc in ri)
             {
                 Console.WriteLine("Resource: {0} - {1}", rc.TypeName, rc.Name);
                 GenericResource genericResource = new GenericResource(rc.Type, rc.Name, rc.Language);
                 genericResource.LoadFrom(filename);
                 byte[] data = rc.WriteAndGetBytes();
                 ByteUtils.CompareBytes(genericResource.Data, data);
             }
         }
     }
 }
            /// <summary>
            /// 初始化资源组集合的新实例。
            /// </summary>
            /// <param name="resourceGroups">资源组集合。</param>
            /// <param name="resourceInfos">资源信息引用。</param>
            public ResourceGroupCollection(ResourceGroup[] resourceGroups, Dictionary <ResourceName, ResourceInfo> resourceInfos)
            {
                if (resourceGroups == null || resourceGroups.Length < 1)
                {
                    throw new GameFrameworkException("Resource groups is invalid.");
                }

                if (resourceInfos == null)
                {
                    throw new GameFrameworkException("Resource infos is invalid.");
                }

                int lastIndex = resourceGroups.Length - 1;

                for (int i = 0; i < lastIndex; i++)
                {
                    if (resourceGroups[i] == null)
                    {
                        throw new GameFrameworkException(Utility.Text.Format("Resource group index '{0}' is invalid.", i));
                    }

                    for (int j = i + 1; j < resourceGroups.Length; j++)
                    {
                        if (resourceGroups[i] == resourceGroups[j])
                        {
                            throw new GameFrameworkException(Utility.Text.Format("Resource group '{0}' duplicated.", resourceGroups[i].Name));
                        }
                    }
                }

                if (resourceGroups[lastIndex] == null)
                {
                    throw new GameFrameworkException(Utility.Text.Format("Resource group index '{0}' is invalid.", lastIndex));
                }

                m_ResourceGroups        = resourceGroups;
                m_ResourceInfos         = resourceInfos;
                m_ResourceNames         = new HashSet <ResourceName>();
                m_TotalLength           = 0L;
                m_TotalCompressedLength = 0L;

                List <ResourceName> cachedResourceNames = new List <ResourceName>();

                foreach (ResourceGroup resourceGroup in m_ResourceGroups)
                {
                    resourceGroup.InternalGetResourceNames(cachedResourceNames);
                    foreach (ResourceName resourceName in cachedResourceNames)
                    {
                        ResourceInfo resourceInfo = null;
                        if (!m_ResourceInfos.TryGetValue(resourceName, out resourceInfo))
                        {
                            throw new GameFrameworkException(Utility.Text.Format("Resource info '{0}' is invalid.", resourceName.FullName));
                        }

                        if (m_ResourceNames.Add(resourceName))
                        {
                            m_TotalLength           += resourceInfo.Length;
                            m_TotalCompressedLength += resourceInfo.CompressedLength;
                        }
                    }
                }
            }
コード例 #32
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Handle the preselection
        preselectedItem = QueryHelper.GetString(this.QueryParameterName, "");
        if (preselectedItem.StartsWith("cms.", StringComparison.InvariantCultureIgnoreCase))
        {
            preselectedItem = preselectedItem.Substring(4);
        }

        uniMenu.HighlightItem = preselectedItem;

        // If element name is not set, use root module element
        string elemName = this.ElementName;

        if (String.IsNullOrEmpty(elemName))
        {
            elemName = this.ModuleName.Replace(".", "");
        }

        // Get the UI elements
        DataSet ds = UIElementInfoProvider.GetChildUIElements(this.ModuleName, elemName);

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            FilterElements(ds);

            int count = ds.Tables[0].Rows.Count;
            string[,] groups = new string[count, 4];

            // Prepare the list of elements
            int i = 0;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string url = ValidationHelper.GetString(dr["ElementTargetURL"], "");

                if (url.EndsWith("ascx"))
                {
                    groups[i, 1] = url;
                }
                else
                {
                    groups[i, 3] = ValidationHelper.GetString(dr["ElementID"], "");
                }

                groups[i, 2] = "ContentMenuGroup";
                groups[i, 0] = ResHelper.LocalizeString(ValidationHelper.GetString(dr["ElementCaption"], ""));

                i++;
            }

            uniMenu.Groups = groups;

            // Button created & filtered event handler
            if (OnButtonCreated != null)
            {
                uniMenu.OnButtonCreated += new CMSAdminControls_UI_UniMenu_UniMenu.ButtonCreatedEventHandler(uniMenu_OnButtonCreated);
            }
            if (OnButtonFiltered != null)
            {
                uniMenu.OnButtonFiltered += new CMSAdminControls_UI_UniMenu_UniMenu.ButtonFilterEventHandler(uniMenu_OnButtonFiltered);
            }
        }

        // Add editing icon in development mode
        if (SettingsKeyProvider.DevelopmentMode && CMSContext.CurrentUser.IsGlobalAdministrator)
        {
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(this.ModuleName);
            if (ri != null)
            {
                ltlAfter.Text += UIHelper.GetResourceUIElementsLink(this.Page, ri.ResourceId);
            }
        }
    }
コード例 #33
0
ファイル: SelectSitePublish.cs プロジェクト: Yellllllow/swb
        protected virtual void SelectSitePublish_ValidateStep(object sender, CancelEventArgs e)
        {
            if (selectWebPage.SelectedWebPage != null)
            {
                WebPageInfo webpage = selectWebPage.SelectedWebPage.WebPageInfo;
                if (!OfficeApplication.OfficeDocumentProxy.canPublishToResourceContent(type.ToString(), webpage))
                {
                    MessageBox.Show(this, "No tiene permisos para publicar en esta página", this.Wizard.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                    return;
                }
                this.Wizard.Data[WEB_PAGE] = webpage;
                String version        = this.Wizard.Data[SelectVersionToOpen.VERSION].ToString();
                string repositoryName = this.Wizard.Data[SelectVersionToPublish.REPOSITORY_ID_NAME].ToString();
                string contentID      = this.Wizard.Data[SelectVersionToPublish.CONTENT_ID_NAME].ToString();
                if (m_title == null || m_description == null)
                {
                    m_title       = this.Wizard.Data[TitleAndDescription.TITLE].ToString();
                    m_description = this.Wizard.Data[TitleAndDescription.DESCRIPTION].ToString();
                }
                PropertyInfo[] properties = OfficeApplication.OfficeDocumentProxy.getResourceProperties(document.reporitoryID, document.contentID);
                String[]       values     = null;
                if (properties == null || properties.Length == 0)
                {
                    values = new String[0];
                }
                else
                {
                    values = (String[])this.Wizard.Data[ViewProperties.VIEW_PROPERTIES_VALUES];
                }
                ResourceInfo portletInfo = OfficeApplication.OfficeDocumentProxy.publishToResourceContent(repositoryName, contentID, version, m_title, m_description, webpage, properties, values);
                if (OfficeApplication.OfficeDocumentProxy.needsSendToPublish(portletInfo))
                {
                    DialogResult res = MessageBox.Show(this, "Para activar el contenido, se necesita que sea autorizado primero\r\n¿Desea enviar el contenido a autorizar?", this.Wizard.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (res == DialogResult.Yes)
                    {
                        FormSendToAutorize formSendToAutorize = new FormSendToAutorize(portletInfo);
                        formSendToAutorize.ShowDialog();
                        if (formSendToAutorize.DialogResult == DialogResult.OK)
                        {
                            OfficeApplication.OfficeDocumentProxy.sendToAuthorize(portletInfo, formSendToAutorize.pflow, formSendToAutorize.textBoxMessage.Text);
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "Para activar el contenido deberá enviar primero esta publicación a autorizar", this.Wizard.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    DialogResult res = MessageBox.Show(this, "¿Desea activar el contenido?", this.Wizard.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (res == DialogResult.Yes)
                    {
                        OfficeApplication.OfficeDocumentProxy.activateResource(portletInfo, true);
                        MessageBox.Show(this, "Se ha publicado correctamente el contenido en la página web", this.Wizard.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                this.Wizard.Close();
            }
            else
            {
                MessageBox.Show(this, "¡Debe indicar una página web", "Seleccionar página web", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
        }
コード例 #34
0
ファイル: QueueNotifier.cs プロジェクト: zi-yu/orionsbelt
        /// <summary>Verifica se h comandos para executar</summary>
        protected override void OnLoad(EventArgs args)
        {
            ResourceInfo resource = Manager.getResourceInfo(Category);

            checkEvents(resource);
        }
コード例 #35
0
 /// <summary>
 /// Sets this text box up for AJAX auto-complete.
 /// </summary>
 public void SetupAutoComplete(ResourceInfo service, AutoCompleteOption option)
 {
     autoCompleteService = service;
     autoCompleteOption  = option;
 }
コード例 #36
0
    private void Command()
    {
        _field.text += _input.text + "\n";

        if (_input.text.Contains(_save))
        {
            string t_saveInput = _input.text.Replace(_save, "");
            t_saveInput = t_saveInput.TrimEnd();
            if (t_saveInput == "")
            {
                _field.text += new NullReferenceException() + "\n";
                return;
            }

            _dataManager.GenerateSave(t_saveInput.ToUpper());
            _input.text  = "";
            _field.text += "Succesfull. \n";
        }
        else if (_input.text == _godmode)
        {
            ResourceManager t_resourceManager = ResourceManager.Instance;
            _field.text           += "Succesfully initiated godmode. \n";
            t_resourceManager.Wood = 100000;
            t_resourceManager.Rock = 100000;

            SceneManager   t_sceneManager   = SceneManager.Instance;
            DataReferences t_dataReferences = t_sceneManager.DataReferences;

            ResourceInfo t_resourceInfo = t_dataReferences.FindElement <ResourceInfo>("RESOURCE_DATA");
            t_resourceInfo.Wood = 100000;
            t_resourceInfo.Rock = 100000;

            t_resourceInfo.Save();
        }
        else if (_input.text == _exit)
        {
            Application.Quit();
        }
        else if (_input.text == _pause)
        {
            UIManager t_uiManager = UIManager.Instance;

            t_uiManager.SetTimeScale(0);
            t_uiManager.ClosePrompt();
            t_uiManager.LockCursor(true);
            t_uiManager.CommandsOpened = !t_uiManager.CommandsOpened;
        }
        else if (_input.text == _unpause)
        {
            UIManager t_uiManager = UIManager.Instance;

            t_uiManager.SetTimeScale(1);
            t_uiManager.ClosePrompt();
            t_uiManager.LockCursor(true);
            t_uiManager.CommandsOpened = !t_uiManager.CommandsOpened;
        }
        else
        {
            _field.text += new InvalidOperationException() + "\n";
        };
    }
コード例 #37
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Logging out of Facebook
        if (QueryHelper.GetInteger("logout", 0) > 0)
        {
            btnSignOut_Click(this, EventArgs.Empty);
        }
        btnSignOut.OnClientClick = FacebookConnectHelper.FacebookConnectInitForSignOut(CMSContext.CurrentSiteName, LiteralScript);

        this.LabelMessage.Text    = GetString("CMSMessages.AccessDenied");
        this.titleElem.TitleText  = GetString("CMSDesk.AccessDenied");
        this.titleElem.TitleImage = GetImageUrl("Others/Messages/denied.png");

        // If specification parameters given, display custom message
        string resourceName = QueryHelper.GetString("resource", null);
        int    nodeId       = QueryHelper.GetInteger("nodeid", 0);
        string message      = QueryHelper.GetText("message", null);

        if (!String.IsNullOrEmpty(resourceName))
        {
            // Access denied to resource
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(resourceName);
            if (ri != null)
            {
                this.titleElem.TitleText = String.Format(GetString("CMSSiteManager.AccessDeniedOnResource"), ri.ResourceDisplayName);
            }
        }
        else if (nodeId > 0)
        {
            // Access denied to document
            TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
            TreeNode     node = tree.SelectSingleNode(nodeId);
            if (node != null)
            {
                this.titleElem.TitleText = String.Format(GetString("CMSSiteManager.AccessDeniedOnNode"), HTMLHelper.HTMLEncode(node.DocumentName));
            }
        }
        else if (!String.IsNullOrEmpty(message))
        {
            // Custom message
            this.LabelMessage.Text = ResHelper.LocalizeString(message);
        }

        // Add missing permission name message
        string permission = QueryHelper.GetText("permission", null);

        if (!String.IsNullOrEmpty(permission))
        {
            this.LabelMessage.Text = String.Format(GetString("CMSSiteManager.AccessDeniedOnPermissionName"), permission);
        }

        // Display SignOut button
        if (CMSContext.CurrentUser.IsAuthenticated())
        {
            if (!RequestHelper.IsWindowsAuthentication())
            {
                this.btnSignOut.Visible = true;
            }
        }
        else
        {
            this.btnLogin.Visible = true;
        }

        this.lnkGoBack.Text = GetString("CMSDesk.GoBack");
    }
コード例 #38
0
ファイル: VesselState.cs プロジェクト: vosechu/MechJeb2
        public void Update(Vessel vessel)
        {
            if (vessel.rigidbody == null)
            {
                return;                           //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions.
            }
            //if (vessel.packed) return;

            // To investigate some strange error
            if ((vessel.mainBody == null || (object)(vessel.mainBody) == null) && counter == 0)
            {
                if ((object)(vessel.mainBody) == null)
                {
                    MechJebCore.print("vessel.mainBody is proper null");
                }
                else
                {
                    MechJebCore.print("vessel.mainBody is Unity null");
                }

                counter = counter++ % 100;
            }


            time   = Planetarium.GetUniversalTime();
            deltaT = TimeWarp.fixedDeltaTime;

            CoM = vessel.findWorldCenterOfMass();
            up  = (CoM - vessel.mainBody.position).normalized;

            Rigidbody rigidBody = vessel.rootPart.rigidbody;

            if (rigidBody != null)
            {
                rootPartPos = rigidBody.position;
            }

            north                 = Vector3d.Exclude(up, (vessel.mainBody.position + vessel.mainBody.transform.up * (float)vessel.mainBody.Radius) - CoM).normalized;
            east                  = vessel.mainBody.getRFrmVel(CoM).normalized;
            forward               = vessel.GetTransform().up;
            rotationSurface       = Quaternion.LookRotation(north, up);
            rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);

//            velocityVesselOrbit = vessel.orbit.GetVel();
//            velocityVesselOrbitUnit = velocityVesselOrbit.normalized;
//            velocityVesselSurface = velocityVesselOrbit - vessel.mainBody.getRFrmVel(CoM);
//            velocityVesselSurfaceUnit = velocityVesselSurface.normalized;
            velocityMainBodySurface = rotationSurface * vessel.srf_velocity;

            horizontalOrbit   = Vector3d.Exclude(up, vessel.obt_velocity).normalized;
            horizontalSurface = Vector3d.Exclude(up, vessel.srf_velocity).normalized;

            angularVelocity = Quaternion.Inverse(vessel.GetTransform().rotation) * vessel.rigidbody.angularVelocity;

            radialPlusSurface = Vector3d.Exclude(vessel.srf_velocity, up).normalized;
            radialPlus        = Vector3d.Exclude(vessel.obt_velocity, up).normalized;
            normalPlusSurface = -Vector3d.Cross(radialPlusSurface, vessel.srf_velocity.normalized);
            normalPlus        = -Vector3d.Cross(radialPlus, vessel.obt_velocity.normalized);

            gravityForce = FlightGlobals.getGeeForceAtPosition(CoM);
            localg       = gravityForce.magnitude;

            speedOrbital.value           = vessel.obt_velocity.magnitude;
            speedSurface.value           = vessel.srf_velocity.magnitude;
            speedVertical.value          = Vector3d.Dot(vessel.srf_velocity, up);
            speedSurfaceHorizontal.value = Vector3d.Exclude(up, vessel.srf_velocity).magnitude; //(velocityVesselSurface - (speedVertical * up)).magnitude;
            speedOrbitHorizontal         = (vessel.obt_velocity - (speedVertical * up)).magnitude;

            vesselHeading.value = rotationVesselSurface.eulerAngles.y;
            vesselPitch.value   = (rotationVesselSurface.eulerAngles.x > 180) ? (360.0 - rotationVesselSurface.eulerAngles.x) : -rotationVesselSurface.eulerAngles.x;
            vesselRoll.value    = (rotationVesselSurface.eulerAngles.z > 180) ? (rotationVesselSurface.eulerAngles.z - 360.0) : rotationVesselSurface.eulerAngles.z;

            altitudeASL.value = vessel.mainBody.GetAltitude(CoM);
            //RaycastHit sfc;
            //if (Physics.Raycast(CoM, -up, out sfc, (float)altitudeASL + 10000.0F, 1 << 15))
            //{
            //    altitudeTrue.value = sfc.distance;
            //}
            //else if (vessel.mainBody.pqsController != null)
            //{
            //    // from here: http://kerbalspaceprogram.com/forum/index.php?topic=10324.msg161923#msg161923
            //    altitudeTrue.value = vessel.mainBody.GetAltitude(CoM) - (vessel.mainBody.pqsController.GetSurfaceHeight(QuaternionD.AngleAxis(vessel.mainBody.GetLongitude(CoM), Vector3d.down) * QuaternionD.AngleAxis(vessel.mainBody.GetLatitude(CoM), Vector3d.forward) * Vector3d.right) - vessel.mainBody.pqsController.radius);
            //}
            //else
            //{
            //    altitudeTrue.value = vessel.mainBody.GetAltitude(CoM);
            //}

            //double surfaceAltitudeASL = altitudeASL - altitudeTrue;

            double surfaceAltitudeASL = vessel.mainBody.pqsController != null ? vessel.pqsAltitude : 0d;

            altitudeTrue.value = altitudeASL - surfaceAltitudeASL;

            altitudeBottom = altitudeTrue;
            foreach (Part p in vessel.parts)
            {
                if (p.collider != null)
                {
                    Vector3d bottomPoint   = p.collider.ClosestPointOnBounds(vessel.mainBody.position);
                    double   partBottomAlt = vessel.mainBody.GetAltitude(bottomPoint) - surfaceAltitudeASL;
                    altitudeBottom = Math.Max(0, Math.Min(altitudeBottom, partBottomAlt));
                }
            }

            double atmosphericPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody);

            if (atmosphericPressure < vessel.mainBody.atmosphereMultiplier * 1e-6)
            {
                atmosphericPressure = 0;
            }
            atmosphericDensity      = FlightGlobals.getAtmDensity(atmosphericPressure);
            atmosphericDensityGrams = atmosphericDensity * 1000;

            orbitApA.value      = vessel.orbit.ApA;
            orbitPeA.value      = vessel.orbit.PeA;
            orbitPeriod.value   = vessel.orbit.period;
            orbitTimeToAp.value = vessel.orbit.timeToAp;
            if (vessel.orbit.eccentricity < 1)
            {
                orbitTimeToPe.value = vessel.orbit.timeToPe;
            }
            else
            {
                orbitTimeToPe.value = -vessel.orbit.meanAnomaly / (2 * Math.PI / vessel.orbit.period);
            }
            orbitLAN.value = vessel.orbit.LAN;
            orbitArgumentOfPeriapsis.value = vessel.orbit.argumentOfPeriapsis;
            orbitInclination.value         = vessel.orbit.inclination;
            orbitEccentricity.value        = vessel.orbit.eccentricity;
            orbitSemiMajorAxis.value       = vessel.orbit.semiMajorAxis;
            latitude.value  = vessel.mainBody.GetLatitude(CoM);
            longitude.value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM));

            if (vessel.mainBody != Planetarium.fetch.Sun)
            {
                Vector3d delta = vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + 1) - vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() - 1);
                Vector3d plUp  = Vector3d.Cross(vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime()) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime()), vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4)).normalized;
                angleToPrograde = MuUtils.ClampDegrees360((((vessel.orbit.inclination > 90) || (vessel.orbit.inclination < -90)) ? 1 : -1) * ((Vector3)up).AngleInPlane(plUp, delta));
            }
            else
            {
                angleToPrograde = 0;
            }

            mainBody = vessel.mainBody;

            radius = (CoM - vessel.mainBody.position).magnitude;

            mass = massDrag = torqueThrustPYAvailable = 0;
            thrustVectorLastFrame   = new Vector3d();
            thrustVectorMaxThrottle = new Vector3d();
            thrustVectorMinThrottle = new Vector3d();
            torqueAvailable         = new Vector3d();
            rcsThrustAvailable      = new Vector6();
            rcsTorqueAvailable      = new Vector6();
            ctrlTorqueAvailable     = new Vector6();

            EngineInfo einfo = new EngineInfo(CoM);
            IntakeInfo iinfo = new IntakeInfo();

            parachutes = new List <ModuleParachute>();

            var rcsbal = vessel.GetMasterMechJeb().rcsbal;

            if (vessel.ActionGroups[KSPActionGroup.RCS] && rcsbal.enabled)
            {
                Vector3d rot = Vector3d.zero;
                foreach (Vector6.Direction dir6 in Enum.GetValues(typeof(Vector6.Direction)))
                {
                    Vector3d dir = Vector6.directions[dir6];
                    double[] throttles;
                    List <RCSSolver.Thruster> thrusters;
                    rcsbal.GetThrottles(dir, out throttles, out thrusters);
                    if (throttles != null)
                    {
                        for (int i = 0; i < throttles.Length; i++)
                        {
                            if (throttles[i] > 0)
                            {
                                Vector3d force = thrusters[i].GetThrust(dir, rot);
                                rcsThrustAvailable.Add(vessel.GetTransform().InverseTransformDirection(dir * Vector3d.Dot(force * throttles[i], dir)));
                            }
                        }
                    }
                }
            }

            hasMFE = false;

            foreach (Part p in vessel.parts)
            {
                if (p.IsPhysicallySignificant())
                {
                    double partMass = p.TotalMass();
                    mass     += partMass;
                    massDrag += partMass * p.maximum_drag;
                }

                if (vessel.ActionGroups[KSPActionGroup.RCS] && !rcsbal.enabled)
                {
                    foreach (ModuleRCS pm in p.Modules.OfType <ModuleRCS>())
                    {
                        double   maxT         = pm.thrusterPower;
                        Vector3d partPosition = p.Rigidbody.worldCenterOfMass - CoM;

                        if ((pm.isEnabled) && (!pm.isJustForShow))
                        {
                            foreach (Transform t in pm.thrusterTransforms)
                            {
                                Vector3d thrusterThrust = vessel.GetTransform().InverseTransformDirection(-t.up.normalized) * pm.thrusterPower;
                                rcsThrustAvailable.Add(thrusterThrust);
                                Vector3d thrusterTorque = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, thrusterThrust));
                                rcsTorqueAvailable.Add(thrusterTorque);
                            }
                        }
                    }
                }

                if (p is ControlSurface)
                {
                    Vector3d       partPosition = p.Rigidbody.worldCenterOfMass - CoM;
                    ControlSurface cs           = (p as ControlSurface);
                    Vector3d       airSpeed     = vessel.srf_velocity + Vector3.Cross(cs.Rigidbody.angularVelocity, cs.transform.position - cs.Rigidbody.position);
                    // Air Speed is velocityVesselSurface
                    // AddForceAtPosition seems to need the airspeed vector rotated with the flap rotation x its surface
                    Quaternion airSpeedRot   = Quaternion.AngleAxis(cs.ctrlSurfaceRange * cs.ctrlSurfaceArea, cs.transform.rotation * cs.pivotAxis);
                    Vector3    ctrlTroquePos = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(airSpeedRot * airSpeed)));
                    Vector3    ctrlTroqueNeg = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(Quaternion.Inverse(airSpeedRot) * airSpeed)));
                    ctrlTorqueAvailable.Add(ctrlTroquePos);
                    ctrlTorqueAvailable.Add(ctrlTroqueNeg);
                }

                if (p is CommandPod)
                {
                    torqueAvailable += Vector3d.one * Math.Abs(((CommandPod)p).rotPower);
                }

                foreach (VesselStatePartExtension vspe in vesselStatePartExtensions)
                {
                    vspe(p);
                }

                foreach (PartModule pm in p.Modules)
                {
                    if (!pm.isEnabled)
                    {
                        continue;
                    }

                    if (pm is ModuleReactionWheel)
                    {
                        ModuleReactionWheel rw = (ModuleReactionWheel)pm;
                        // I had to remove the test for active in .23 since the new ressource system reply to the RW that
                        // there is no energy available when the RW do tiny adjustement.
                        // I replaceed it with a test that check if there is electricity anywhere on the ship.
                        // Let's hope we don't get reaction wheel that use something else
                        //if (rw.wheelState == ModuleReactionWheel.WheelState.Active && !rw.stateString.Contains("Not enough"))
                        if (rw.wheelState == ModuleReactionWheel.WheelState.Active && vessel.HasElectricCharge())
                        {
                            torqueAvailable += new Vector3d(rw.PitchTorque, rw.RollTorque, rw.YawTorque);
                        }
                    }
                    else if (pm is ModuleEngines)
                    {
                        einfo.AddNewEngine(pm as ModuleEngines);
                    }
                    else if (pm is ModuleEnginesFX)
                    {
                        einfo.AddNewEngine(pm as ModuleEnginesFX);
                    }
                    else if (pm is ModuleResourceIntake)
                    {
                        iinfo.addIntake(pm as ModuleResourceIntake);
                    }
                    else if (pm is ModuleParachute)
                    {
                        parachutes.Add(pm as ModuleParachute);
                    }
                    else if (pm is ModuleControlSurface)
                    {
                        // TODO : Tweakable for ignorePitch / ignoreYaw  / ignoreRoll
                        ModuleControlSurface cs           = (pm as ModuleControlSurface);
                        Vector3d             partPosition = p.Rigidbody.worldCenterOfMass - CoM;

                        Vector3d airSpeed = vessel.srf_velocity + Vector3.Cross(cs.part.Rigidbody.angularVelocity, cs.transform.position - cs.part.Rigidbody.position);

                        Quaternion airSpeedRot = Quaternion.AngleAxis(cs.ctrlSurfaceRange * cs.ctrlSurfaceArea, cs.transform.rotation * Vector3.right);

                        Vector3 ctrlTroquePos = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(airSpeedRot * airSpeed)));
                        Vector3 ctrlTroqueNeg = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(Quaternion.Inverse(airSpeedRot) * airSpeed)));
                        ctrlTorqueAvailable.Add(ctrlTroquePos);
                        ctrlTorqueAvailable.Add(ctrlTroqueNeg);
                    }

                    if (pm.ClassName == "ModuleEngineConfigs" || pm.ClassName == "ModuleHybridEngine" || pm.ClassName == "ModuleHybridEngines")
                    {
                        hasMFE = true;
                    }

                    foreach (VesselStatePartModuleExtension vspme in vesselStatePartModuleExtensions)
                    {
                        vspme(pm);
                    }
                }
            }

            // Consider all the parachutes
            {
                bool tempParachuteDeployed = false;
                foreach (ModuleParachute p in parachutes)
                {
                    if (p.deploymentState == ModuleParachute.deploymentStates.DEPLOYED || p.deploymentState == ModuleParachute.deploymentStates.SEMIDEPLOYED)
                    {
                        tempParachuteDeployed = true;
                        break;
                    }
                }
                this.parachuteDeployed = tempParachuteDeployed;
            }

            torqueAvailable += Vector3d.Max(rcsTorqueAvailable.positive, rcsTorqueAvailable.negative);   // Should we use Max or Min ?
            torqueAvailable += Vector3d.Max(ctrlTorqueAvailable.positive, ctrlTorqueAvailable.negative); // Should we use Max or Min ?

            thrustVectorMaxThrottle += einfo.thrustMax;
            thrustVectorMinThrottle += einfo.thrustMin;
            thrustVectorLastFrame   += einfo.thrustCurrent;
            torqueThrustPYAvailable += einfo.torqueThrustPYAvailable;

            if (thrustVectorMaxThrottle.magnitude == 0 && vessel.ActionGroups[KSPActionGroup.RCS])
            {
                rcsThrust = true;
                thrustVectorMaxThrottle += (Vector3d)(vessel.transform.up) * rcsThrustAvailable.down;
            }
            else
            {
                rcsThrust = false;
            }

            // Convert the resource information from the einfo and iinfo format
            // to the more useful ResourceInfo format.
            resources = new Dictionary <int, ResourceInfo>();
            foreach (var info in einfo.resourceRequired)
            {
                int id  = info.Key;
                var req = info.Value;
                resources[id] = new ResourceInfo(
                    PartResourceLibrary.Instance.GetDefinition(id),
                    req.requiredLastFrame,
                    req.requiredAtMaxThrottle,
                    iinfo.getIntakes(id));
            }

            int intakeAirId = PartResourceLibrary.Instance.GetDefinition("IntakeAir").id;

            intakeAir           = 0;
            intakeAirNeeded     = 0;
            intakeAirAtMax      = 0;
            intakeAirAllIntakes = 0;
            if (resources.ContainsKey(intakeAirId))
            {
                intakeAir           = resources[intakeAirId].intakeProvided;
                intakeAirAllIntakes = resources[intakeAirId].intakeAvailable;
                intakeAirNeeded     = resources[intakeAirId].required;
                intakeAirAtMax      = resources[intakeAirId].requiredAtMaxThrottle;
            }

            angularMomentum = new Vector3d(angularVelocity.x * MoI.x, angularVelocity.y * MoI.y, angularVelocity.z * MoI.z);

            inertiaTensor = new Matrix3x3();
            foreach (Part p in vessel.parts)
            {
                if (p.Rigidbody == null)
                {
                    continue;
                }

                //Compute the contributions to the vessel inertia tensor due to the part inertia tensor
                Vector3d   principalMoments = p.Rigidbody.inertiaTensor;
                Quaternion princAxesRot     = Quaternion.Inverse(vessel.GetTransform().rotation) * p.transform.rotation * p.Rigidbody.inertiaTensorRotation;
                Quaternion invPrincAxesRot  = Quaternion.Inverse(princAxesRot);

                for (int i = 0; i < 3; i++)
                {
                    Vector3d iHat = Vector3d.zero;
                    iHat[i] = 1;
                    for (int j = 0; j < 3; j++)
                    {
                        Vector3d jHat = Vector3d.zero;
                        jHat[j]              = 1;
                        inertiaTensor[i, j] += Vector3d.Dot(iHat, princAxesRot * Vector3d.Scale(principalMoments, invPrincAxesRot * jHat));
                    }
                }

                //Compute the contributions to the vessel inertia tensor due to the part mass and position
                double  partMass     = p.TotalMass();
                Vector3 partPosition = vessel.GetTransform().InverseTransformDirection(p.Rigidbody.worldCenterOfMass - CoM);

                for (int i = 0; i < 3; i++)
                {
                    inertiaTensor[i, i] += partMass * partPosition.sqrMagnitude;

                    for (int j = 0; j < 3; j++)
                    {
                        inertiaTensor[i, j] += -partMass * partPosition[i] * partPosition[j];
                    }
                }
            }

            MoI             = new Vector3d(inertiaTensor[0, 0], inertiaTensor[1, 1], inertiaTensor[2, 2]);
            angularMomentum = inertiaTensor * angularVelocity;
        }
コード例 #39
0
    /// <summary>
    /// Generates the permission matrix for the current group.
    /// </summary>
    private void CreateMatrix()
    {
        // Get group resource info
        if (resGroups == null)
        {
            resGroups = ResourceInfoProvider.GetResourceInfo("CMS.Groups");
        }

        if (resGroups != null)
        {
            group = GroupInfoProvider.GetGroupInfo(GroupID);

            // Get permissions for the current group resource
            DataSet permissions = PermissionNameInfoProvider.GetResourcePermissions(resGroups.ResourceID);
            if (DataHelper.DataSourceIsEmpty(permissions))
            {
                ShowInformation(GetString("general.emptymatrix"));
            }
            else
            {
                TableRow headerRow = new TableRow();
                headerRow.TableSection = TableRowSection.TableHeader;
                headerRow.CssClass     = "unigrid-head";

                TableHeaderCell newHeaderCell = new TableHeaderCell();
                newHeaderCell.CssClass = "first-column";
                headerRow.Cells.Add(newHeaderCell);

                foreach (string permission in allowedPermissions)
                {
                    DataRow[] drArray = permissions.Tables[0].DefaultView.Table.Select("PermissionName = '" + permission + "'");
                    if (drArray.Length > 0)
                    {
                        DataRow dr = drArray[0];
                        newHeaderCell          = new TableHeaderCell();
                        newHeaderCell.CssClass = "matrix-header";
                        newHeaderCell.Text     = dr["PermissionDisplayName"].ToString();
                        newHeaderCell.ToolTip  = dr["PermissionDescription"].ToString();

                        headerRow.Cells.Add(newHeaderCell);
                    }
                    else
                    {
                        throw new Exception("[Security matrix] Column '" + permission + "' cannot be found.");
                    }
                }
                tblMatrix.Rows.Add(headerRow);

                // Render group access permissions
                object[,] accessNames = new object[5, 2];
                accessNames[0, 0]     = GetString("security.nobody");
                accessNames[0, 1]     = SecurityAccessEnum.Nobody;
                accessNames[1, 0]     = GetString("security.allusers");
                accessNames[1, 1]     = SecurityAccessEnum.AllUsers;
                accessNames[2, 0]     = GetString("security.authenticated");
                accessNames[2, 1]     = SecurityAccessEnum.AuthenticatedUsers;
                accessNames[3, 0]     = GetString("security.groupmembers");
                accessNames[3, 1]     = SecurityAccessEnum.GroupMembers;
                accessNames[4, 0]     = GetString("security.authorizedroles");
                accessNames[4, 1]     = SecurityAccessEnum.AuthorizedRoles;

                TableRow newRow = null;

                TableCell newCell;
                for (int access = 0; access <= accessNames.GetUpperBound(0); access++)
                {
                    SecurityAccessEnum currentAccess = ((SecurityAccessEnum)accessNames[access, 1]);

                    // Generate cell holding access item name
                    newRow           = new TableRow();
                    newCell          = new TableCell();
                    newCell.CssClass = "matrix-header";
                    newCell.Text     = accessNames[access, 0].ToString();
                    newRow.Cells.Add(newCell);

                    // Render the permissions access items
                    int permissionIndex = 0;
                    for (int permission = 0; permission < (tblMatrix.Rows[0].Cells.Count - 1); permission++)
                    {
                        newCell          = new TableCell();
                        newCell.CssClass = "matrix-cell";

                        // Check if the currently processed access is applied for permission
                        bool isAllowed = CheckPermissionAccess(currentAccess, permission, tblMatrix.Rows[0].Cells[permission + 1].Text);

                        // Disable column in roles grid if needed
                        if ((currentAccess == SecurityAccessEnum.AuthorizedRoles) && !isAllowed)
                        {
                            gridMatrix.DisableColumn(permissionIndex);
                        }

                        // Insert the radio button for the current permission
                        var radio = new CMSRadioButton
                        {
                            Checked = isAllowed,
                            Enabled = Enabled,
                        };
                        radio.Attributes.Add("onclick", ControlsHelper.GetPostBackEventReference(this, permission + ";" + Convert.ToInt32(currentAccess)));
                        newCell.Controls.Add(radio);

                        newRow.Cells.Add(newCell);
                        permissionIndex++;
                    }

                    // Add the access row to the table
                    tblMatrix.Rows.Add(newRow);
                }

                // Hide if no roles available
                headTitle.Visible = gridMatrix.HasData;
            }
        }
    }
コード例 #40
0
                public static LoadDependencyAssetTask Create(string assetName, int priority, ResourceInfo resourceInfo, string[] dependencyAssetNames, LoadResourceTaskBase mainTask, object userData)
                {
                    LoadDependencyAssetTask loadDependencyAssetTask = ReferencePool.Acquire <LoadDependencyAssetTask>();

                    loadDependencyAssetTask.Initialize(assetName, null, priority, resourceInfo, dependencyAssetNames, userData);
                    loadDependencyAssetTask.m_MainTask = mainTask;
                    loadDependencyAssetTask.m_MainTask.TotalDependencyAssetCount++;
                    return(loadDependencyAssetTask);
                }
コード例 #41
0
    protected void Page_Load(object sender, EventArgs e)
    {
        bool displayNone = false;
        bool currentIsCustomizedOfInstalled = false;

        elementInfo = UIContext.EditedObject as UIElementInfo;

        if (elementInfo != null && elementInfo.ElementID > 0)
        {
            ParentID       = elementInfo.ElementParentID;
            PageTemplateID = elementInfo.ElementPageTemplateID;

            EditForm.FieldControls["ElementPageTemplateID"].SetValue("ItemGuid", elementInfo.ElementGUID);
            EditForm.FieldControls["ElementPageTemplateID"].SetValue("ItemName", elementInfo.ElementDisplayName);

            // Exclude current element and children from dropdown list
            EditForm.FieldControls["ElementParentID"].SetValue("WhereCondition", "ElementIDPath NOT LIKE N'" + elementInfo.ElementIDPath + "%'");

            // Enable editing only for current module. Disable for root
            EditForm.Enabled = ((!UIElementInfoProvider.AllowEditOnlyCurrentModule || (ResourceID == elementInfo.ElementResourceID) && elementInfo.ElementIsCustom) &&
                                (elementInfo.ElementParentID != 0));

            // Allow global application checkbox only for applications
            if (!elementInfo.IsApplication && !elementInfo.ElementIsGlobalApplication)
            {
                EditForm.FieldsToHide.Add("ElementIsGlobalApplication");
                EditForm.FieldsToHide.Add(nameof(UIElementInfo.ElementRequiresGlobalAdminPriviligeLevel));
            }

            // Show info for customized elements
            ResourceInfo ri = ResourceInfo.Provider.Get(elementInfo.ElementResourceID);
            if (ri != null)
            {
                if (elementInfo.ElementIsCustom && !ri.ResourceIsInDevelopment)
                {
                    currentIsCustomizedOfInstalled = true;
                    ShowInformation(GetString("module.customeleminfo"));
                }
            }
        }
        // New item
        else
        {
            isNew = true;
            if (!RequestHelper.IsPostBack())
            {
                EditForm.FieldControls["ElementFromVersion"].Value = CMSVersion.GetVersion(true, true, false, false);
            }

            // Predefine current resource if is in development
            ResourceInfo ri = CurrentResourceInfo;
            if ((ri != null) && ri.ResourceIsInDevelopment)
            {
                EditForm.FieldControls["ElementResourceID"].Value = ResourceID;
            }
            // Display none if is under not-development resource
            else
            {
                displayNone = true;
            }

            EditForm.FieldControls["ElementParentID"].Value = ParentID;
            EditForm.FieldsToHide.Add("ElementParentID");

            var parent = UIElementInfo.Provider.Get(ParentID);
            if ((parent == null) || (parent.ElementLevel != 2) || !parent.IsInAdministrationScope)
            {
                EditForm.FieldsToHide.Add("ElementIsGlobalApplication");
                EditForm.FieldsToHide.Add(nameof(UIElementInfo.ElementRequiresGlobalAdminPriviligeLevel));
            }
        }

        // Allow only modules in development mode
        FormEngineUserControl resourceCtrl = EditForm.FieldControls["ElementResourceID"];

        if (resourceCtrl != null)
        {
            resourceCtrl.SetValue("DisplayOnlyModulesInDevelopmentMode", true);
        }

        // Disable form and add customize button if element is not custom and not development mode
        if (!SystemContext.DevelopmentMode && (elementInfo != null) && (ResourceID == elementInfo.ElementResourceID) && !elementInfo.ElementIsCustom && (elementInfo.ElementParentID != 0))
        {
            ICMSMasterPage master = Page.Master as ICMSMasterPage;
            if (master != null)
            {
                master.HeaderActions.AddAction(new HeaderAction
                {
                    Text          = GetString("general.customize"),
                    CommandName   = "customize",
                    OnClientClick = "if (!confirm(" + ScriptHelper.GetString(ResHelper.GetString("module.customizeconfirm")) + ")) { return false; }"
                });

                master.HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;
            }

            EditForm.Enabled = false;
        }

        if (resourceCtrl != null)
        {
            // Display all modules in disabled UI
            if (!EditForm.Enabled)
            {
                resourceCtrl.SetValue("DisplayOnlyModulesInDevelopmentMode", false);
            }
            // Display all modules in customized element but do not allow change the module
            else if (currentIsCustomizedOfInstalled)
            {
                resourceCtrl.SetValue("DisplayOnlyModulesInDevelopmentMode", false);
                resourceCtrl.Enabled = false;
            }

            // Display none if needed
            resourceCtrl.SetValue("DisplayNone", displayNone);
        }
    }
コード例 #42
0
 private static string ToFileName(ResourceInfo type)
 {
     return($"{type.Id}.schema");
 }
コード例 #43
0
ファイル: RecipeUI.cs プロジェクト: JackSouthard1/Etherium
    void LoadRecipe()
    {
        for (int x = 0; x < 2; x++)
        {
            for (int y = 0; y < 2; y++)
            {
                if (x < Crafting.instance.recipes [curRecipe].resources.GetLength(0) && y < Crafting.instance.recipes [curRecipe].resources.GetLength(1))
                {
                    Crafting.Stack curStack = Crafting.instance.recipes [curRecipe].resources [x, y];
                    tiles [x, y].color      = (curStack.tileType != ResourceInfo.ResourceType.None) ? ResourceInfo.GetInfoFromType(curStack.tileType).colorDark : defaultTileColor;
                    resources [x, y].sprite = ResourceInfo.GetInfoFromType(curStack.resourceType).sprite;
                    numbers [x, y].text     = curStack.count.ToString();
                    resources [x, y].gameObject.SetActive(true);
                }
                else
                {
                    tiles [x, y].color = defaultTileColor;
                    resources [x, y].gameObject.SetActive(false);
                    numbers [x, y].text = "";
                }
            }
        }

        recipeName.text = Crafting.instance.recipes [curRecipe].name;
    }
コード例 #44
0
 public LoadSceneTask(string sceneAssetName, ResourceInfo resourceInfo, string[] dependencyAssetNames, string[] scatteredDependencyAssetNames, string resourceChildName, LoadSceneCallbacks loadSceneCallbacks, object userData)
     : base(sceneAssetName, "", resourceInfo, dependencyAssetNames, scatteredDependencyAssetNames, resourceChildName, userData)
 {
     m_LoadSceneCallbacks = loadSceneCallbacks;
 }
コード例 #45
0
 public LoadDependencyAssetTask(string assetName, int priority, ResourceInfo resourceInfo, string[] dependencyAssetNames, LoadResourceTaskBase mainTask, object userData)
     : base(assetName, null, priority, resourceInfo, dependencyAssetNames, userData)
 {
     m_MainTask = mainTask;
     m_MainTask.TotalDependencyAssetCount++;
 }
コード例 #46
0
ファイル: Kitchen.cs プロジェクト: alee74/ClassAdventureGame
 void DailyConsumption()
 {
     ResourceInfo.addWaterStock(-waterConsumption);
     ResourceInfo.addFoodStock(-foodConsumption);
 }
    /// <summary>
    /// PreRender action on which security settings are set.
    /// </summary>
    private void Page_PreRender(object sender, EventArgs e)
    {
        if ((Form == null) || !mDocumentSaved)
        {
            return;
        }

        TreeNode editedNode = Form.EditedObject as TreeNode;

        // Create or rebuild department content index
        CreateDepartmentContentSearchIndex(editedNode);

        if ((editedNode == null) || !editedNode.NodeIsACLOwner)
        {
            return;
        }

        ForumInfo        fi = ForumInfoProvider.GetForumInfo("Default_department_" + editedNode.NodeGUID, SiteContext.CurrentSiteID);
        MediaLibraryInfo mi = MediaLibraryInfoProvider.GetMediaLibraryInfo("Department_" + editedNode.NodeGUID, SiteContext.CurrentSiteName);

        // Check if forum of media library exists
        if ((fi == null) && (mi == null))
        {
            return;
        }

        // Get allowed roles ID
        int         aclID     = ValidationHelper.GetInteger(editedNode.GetValue("NodeACLID"), 0);
        DataSet     listRoles = AclItemInfoProvider.GetAllowedRoles(aclID, NodePermissionsEnum.Read, "RoleID");
        IList <int> roleIds   = null;


        if (!DataHelper.DataSourceIsEmpty(listRoles))
        {
            roleIds = DataHelper.GetIntegerValues(listRoles.Tables[0], "RoleID") as List <int>;
        }

        // Set permissions for forum
        if (fi != null)
        {
            // Get resource object
            ResourceInfo resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");

            // Get permissions IDs
            var forumPermissions = PermissionNameInfoProvider.GetPermissionNames()
                                   .Column("PermissionID")
                                   .WhereEquals("ResourceID", resForums.ResourceID)
                                   .WhereNotEquals("PermissionName", CMSAdminControl.PERMISSION_READ)
                                   .WhereNotEquals("PermissionName", CMSAdminControl.PERMISSION_MODIFY);

            // Delete old permissions apart attach file permission
            ForumRoleInfoProvider.DeleteAllRoles(new WhereCondition().WhereEquals("ForumID", fi.ForumID).WhereIn("PermissionID", forumPermissions));

            // Set forum permissions
            ForumRoleInfoProvider.SetPermissions(fi.ForumID, roleIds, forumPermissions.Select(p => p.PermissionId).ToArray());

            // Log staging task
            SynchronizationHelper.LogObjectChange(fi, TaskTypeEnum.UpdateObject);
        }

        // Set permissions for media library
        if (mi == null)
        {
            return;
        }

        // Get resource object
        ResourceInfo resMediaLibs = ResourceInfoProvider.GetResourceInfo("CMS.MediaLibrary");

        // Get permissions IDs
        var where = new WhereCondition()
                    .WhereEquals("ResourceID", resMediaLibs.ResourceID)
                    .And()
                    .Where(new WhereCondition()
                           .WhereEquals("PermissionName", "LibraryAccess")
                           .Or()
                           .WhereEquals("PermissionName", "FileCreate"));

        DataSet     dsMediaLibPerm         = PermissionNameInfoProvider.GetPermissionNames().Where(where).Column("PermissionID");
        IList <int> mediaLibPermissionsIds = null;

        if (!DataHelper.DataSourceIsEmpty(dsMediaLibPerm))
        {
            mediaLibPermissionsIds = DataHelper.GetIntegerValues(dsMediaLibPerm.Tables[0], "PermissionID");
        }

        var deleteWhere = new WhereCondition()
                          .WhereEquals("LibraryID", mi.LibraryID)
                          .WhereIn("PermissionID", mediaLibPermissionsIds);

        // Delete old permissions only for Create file and See library content permissions
        MediaLibraryRolePermissionInfoProvider.DeleteAllRoles(deleteWhere.ToString(true));

        MediaLibraryRolePermissionInfoProvider.SetPermissions(mi.LibraryID, roleIds, mediaLibPermissionsIds);

        // Log staging task;
        SynchronizationHelper.LogObjectChange(mi, TaskTypeEnum.UpdateObject);
    }
コード例 #48
0
    /// <summary>
    /// Initializes the controls.
    /// </summary>
    private void SetupControl()
    {
        mQueryName = GetString("queryedit.newquery");

        DataClassInfo queryClass = null;

        // If the existing query is being edited
        if (QueryID > 0)
        {
            // Get information on existing query
            Query = QueryInfoProvider.GetQueryInfo(QueryID);
            if (Query != null)
            {
                queryClass = DataClassInfoProvider.GetDataClassInfo(Query.ClassID);
                ClassName  = queryClass.ClassName;
                QueryName  = Query.QueryName;

                if (!RequestHelper.IsPostBack())
                {
                    // Fills form with the existing query information
                    LoadValues();
                    txtQueryText.Focus();
                }
            }
        }
        else if (ClassID > 0)
        {
            // New query is being created
            Query      = new QueryInfo();
            queryClass = DataClassInfoProvider.GetDataClassInfo(ClassID);
            ClassName  = queryClass.ClassName;

            if (!RequestHelper.IsPostBack())
            {
                ucSelectString.Value = queryClass.ClassConnectionString;
            }

            txtQueryName.Focus();
        }

        plcLoadGeneration.Visible = SystemContext.DevelopmentMode;

        // Ensure generate button and custom checkbox for default queries
        if (SqlGenerator.IsSystemQuery(QueryName))
        {
            btnGenerate.Visible = true;
        }

        // Initialize the validator
        RequiredFieldValidatorQueryName.ErrorMessage = GetString("queryedit.erroremptyqueryname");

        if (ShowHelp)
        {
            DisplayHelperTable();
        }

        // Filter available only when creating new query in dialog mode
        plcDocTypeFilter.Visible = filter.Visible = DialogMode && !EditMode;

        // Set filter preselection
        if (plcDocTypeFilter.Visible)
        {
            filter.SelectedValue = QueryHelper.GetString("selectedvalue", null);
            filter.FilterMode    = QueryInfo.OBJECT_TYPE;
        }

        // Hide header actions when creating new query in dialog mode
        if ((DialogMode && !EditMode) || !Visible)
        {
            mCurrentMaster.HeaderActions.ActionsList.Clear();
        }

        txtQueryName.Enabled = !DialogMode || !EditMode;

        // Set dialog's content panel CSS class
        if (DialogMode)
        {
            Panel pnlContent = EditMode ? mCurrentMaster.PanelContent : pnlContainer;
            pnlContent.CssClass = "PageContent";
        }

        ResourceInfo resource = ResourceInfoProvider.GetResourceInfo(ModuleID);

        if ((resource != null) && !resource.IsEditable && (QueryID > 0))
        {
            if ((queryClass != null) && !queryClass.ClassShowAsSystemTable)
            {
                // Disable customization for module not in development and not customizable class
                pnlCustomization.StopProcessing = true;
                HeaderAction save = HeaderActions.ActionsList.FirstOrDefault(a => a is SaveAction);
                if (save != null)
                {
                    save.Enabled = false;
                    ShowInformation(GetString("cms.query.customization.disabled"));
                }
            }
            else
            {
                // Enable customization system tables in modules not in development
                pnlCustomization.HeaderActions       = HeaderActions;
                pnlCustomization.MessagesPlaceHolder = MessagesPlaceHolder;
            }
        }
        else
        {
            // Normal processing for new queries and queries in document types etc.
            pnlCustomization.StopProcessing = true;
        }
    }
コード例 #49
0
        private async Task SychronizeFolder(ResourceInfo resourceInfo)
        {
            if (resourceInfo == null)
            {
                return;
            }

            var syncInfo = SyncDbUtils.GetFolderSyncInfoByPath(resourceInfo.Path);

            try
            {
                Task <ContentDialogResult> firstRunDialog = null;
                StorageFolder folder;
                if (syncInfo == null)
                {
                    // try to Get parent or initialize
                    syncInfo = SyncDbUtils.GetFolderSyncInfoBySubPath(resourceInfo.Path);

                    if (syncInfo == null)
                    {
                        // Initial Sync
                        syncInfo = new FolderSyncInfo()
                        {
                            Path = resourceInfo.Path
                        };

                        var folderPicker = new FolderPicker()
                        {
                            SuggestedStartLocation = PickerLocationId.Desktop
                        };

                        folderPicker.FileTypeFilter.Add(".txt");
                        var newFolder = await folderPicker.PickSingleFolderAsync();

                        if (newFolder == null)
                        {
                            return;
                        }

                        StorageApplicationPermissions.FutureAccessList.AddOrReplace(syncInfo.AccessListKey, newFolder);
                        var subElements = await newFolder.GetItemsAsync();

                        var client = await ClientService.GetClient();

                        var remoteElements = await client.List(resourceInfo.Path);

                        if (subElements.Count > 0 && remoteElements.Count > 0)
                        {
                            var dialogNotEmpty = new ContentDialog
                            {
                                Title   = _resourceLoader.GetString("SyncFoldersNotEmptyWarning"),
                                Content = new TextBlock()
                                {
                                    Text         = _resourceLoader.GetString("SyncFoldersNotEmptyWarningDetail"),
                                    TextWrapping = TextWrapping.WrapWholeWords,
                                    Margin       = new Thickness(0, 20, 0, 0)
                                },
                                PrimaryButtonText   = _resourceLoader.GetString("OK"),
                                SecondaryButtonText = _resourceLoader.GetString("Cancel")
                            };

                            var dialogResult = await _dialogService.ShowAsync(dialogNotEmpty);

                            if (dialogResult != ContentDialogResult.Primary)
                            {
                                return;
                            }
                        }

                        folder = newFolder;
                        SyncDbUtils.SaveFolderSyncInfo(syncInfo);
                        StartDirectoryListing(); // This is just to update the menu flyout - maybe there is a better way

                        var dialog = new ContentDialog
                        {
                            Title   = _resourceLoader.GetString("SyncStarted"),
                            Content = new TextBlock
                            {
                                Text         = _resourceLoader.GetString("SyncStartedDetail"),
                                TextWrapping = TextWrapping.WrapWholeWords,
                                Margin       = new Thickness(0, 20, 0, 0)
                            },
                            PrimaryButtonText = _resourceLoader.GetString("OK")
                        };
                        firstRunDialog = _dialogService.ShowAsync(dialog);
                    }
                    else
                    {
                        var subPath    = resourceInfo.Path.Substring(syncInfo.Path.Length);
                        var tempFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(syncInfo.AccessListKey);

                        foreach (var foldername in subPath.Split('/'))
                        {
                            if (foldername.Length > 0)
                            {
                                tempFolder = await tempFolder.GetFolderAsync(foldername);
                            }
                        }
                        folder = tempFolder;
                    }
                }
                else
                {
                    folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(syncInfo.AccessListKey);

                    // TODO catch exceptions
                }

                var service = new SyncService(folder, resourceInfo, syncInfo, _resourceLoader);
                await service.StartSync();

                if (firstRunDialog != null)
                {
                    await firstRunDialog;
                }
            }
            catch (Exception e)
            {
                // ERROR Maybe AccessList timed out.
                Debug.WriteLine(e.Message);
            }
        }
コード例 #50
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int moduleId = QueryHelper.GetInteger("moduleid", 0);
        int parentId = QueryHelper.GetInteger("parentId", 0);

        ScriptHelper.RegisterJQuery(Page);

        // Use images according to culture
        if (CultureHelper.IsUICultureRTL())
        {
            uniTree.LineImagesFolder = GetImageUrl("RTL/Design/Controls/Tree", false, false);
        }
        else
        {
            uniTree.LineImagesFolder = GetImageUrl("Design/Controls/Tree", false, false);
        }

        if (!RequestHelper.IsPostBack())
        {
            // Get module root element
            UIElementInfo elemInfo = UIElementInfoProvider.GetRootUIElementInfo(moduleId);
            if (elemInfo != null)
            {
                uniTree.SelectPath = elemInfo.ElementIDPath;
                uniTree.ExpandPath = elemInfo.ElementIDPath + "/";
                menuElem.Value     = elemInfo.ElementID + "|" + elemInfo.ElementParentID;
            }
            else
            {
                // Get current resource
                ResourceInfo resInfo = ResourceInfoProvider.GetResourceInfo(moduleId);
                if (resInfo != null)
                {
                    // Create new UI element
                    elemInfo = new UIElementInfo();
                    elemInfo.ElementResourceID  = moduleId;
                    elemInfo.ElementDisplayName = resInfo.ResourceDisplayName;
                    elemInfo.ElementName        = resInfo.ResourceName.ToLowerCSafe().Replace(".", "");
                    elemInfo.ElementIsCustom    = false;

                    UIElementInfoProvider.SetUIElementInfo(elemInfo);
                    uniTree.SelectPath = elemInfo.ElementIDPath;
                    uniTree.ExpandPath = elemInfo.ElementIDPath;
                    menuElem.Value     = elemInfo.ElementID + "|0";
                }
            }
        }

        menuElem.ResourceID   = moduleId;
        menuElem.AfterAction += new OnActionEventHandler(menuElem_AfterAction);

        // Create and set UIElements provider
        UniTreeProvider elementProvider = new UniTreeProvider();

        elementProvider.ObjectType        = "CMS.UIElement";
        elementProvider.DisplayNameColumn = "ElementDisplayName";
        elementProvider.IDColumn          = "ElementID";
        elementProvider.LevelColumn       = "ElementLevel";
        elementProvider.OrderColumn       = "ElementOrder";
        elementProvider.ParentIDColumn    = "ElementParentID";
        elementProvider.PathColumn        = "ElementIDPath";
        elementProvider.ValueColumn       = "ElementID";
        elementProvider.ChildCountColumn  = "ElementChildCount";
        elementProvider.WhereCondition    = "ElementResourceID = " + moduleId;
        elementProvider.Columns           = "ElementID,ElementLevel,ElementOrder,ElementParentID,ElementIDPath,ElementChildCount,ElementDisplayName";

        uniTree.UsePostBack     = false;
        uniTree.ProviderObject  = elementProvider;
        uniTree.ExpandTooltip   = GetString("general.expand");
        uniTree.CollapseTooltip = GetString("general.collapse");

        uniTree.NodeTemplate         = "<span id=\"node_##NODEID##\" onclick=\"SelectNode(##NODEID##,##PARENTNODEID##," + moduleId + "); return false;\" name=\"treeNode\" class=\"ContentTreeItem\"><span class=\"Name\">##NODENAME##</span></span>";
        uniTree.SelectedNodeTemplate = "<span id=\"node_##NODEID##\" onclick=\"SelectNode(##NODEID##,##PARENTNODEID##," + moduleId + "); return false;\" name=\"treeNode\" class=\"ContentTreeItem ContentTreeSelectedItem\"><span class=\"Name\">##NODENAME##</span></span>";

        if (!RequestHelper.IsPostBack())
        {
            string selectedPath = QueryHelper.GetString("path", String.Empty);
            int    elementId    = QueryHelper.GetInteger("elementId", 0);

            if (!string.IsNullOrEmpty(selectedPath))
            {
                uniTree.SelectPath = selectedPath;
            }

            if (elementId > 0)
            {
                menuElem.ElementID = elementId;
                menuElem.ParentID  = parentId;
                menuElem.Value     = elementId + "|" + parentId;
            }
        }

        // Load data
        uniTree.ReloadData();

        string script = "var frameURL = '" + ResolveUrl("~/CMSModules/Modules/Pages/Development/Module_UI_EditFrameset.aspx") + "';";

        script += "var newURL = '" + ResolveUrl("~/CMSModules/Modules/Pages/Development/Module_UI_New.aspx") + "';";
        script += "var postParentId = " + parentId + ";";

        ltlScript.Text = ScriptHelper.GetScript(script);
    }
コード例 #51
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterJQuery(Page);

        SitePanel.Visible                = ShowHeaderPanel && ShowSiteSelector;
        ActionsPanel.Visible             = ShowHeaderPanel && !SitePanel.Visible;
        plcActionSelectionScript.Visible = ShowHeaderPanel && !ShowSiteSelector;
        plcSelectionScript.Visible       = !plcActionSelectionScript.Visible;

        if (RootCategory != null)
        {
            string levelWhere = (MaxRelativeLevel <= 0 ? "" : " AND (CategoryLevel <= " + (RootCategory.CategoryLevel + MaxRelativeLevel) + ")");
            // Restrict CategoryChildCount to MaxRelativeLevel. If level < MaxRelativeLevel, use count of non-group children.
            string levelColumn = "CASE CategoryLevel WHEN " + MaxRelativeLevel + " THEN 0 ELSE  (SELECT COUNT(*) AS CountNonGroup FROM CMS_SettingsCategory AS sc WHERE (sc.CategoryParentID = CMS_SettingsCategory.CategoryID) AND (sc.CategoryIsGroup = 0)) END AS CategoryChildCount";

            // Create and set category provider
            UniTreeProvider provider = new UniTreeProvider();
            provider.RootLevelOffset   = RootCategory.CategoryLevel;
            provider.ObjectType        = "CMS.SettingsCategory";
            provider.DisplayNameColumn = "CategoryDisplayName";
            provider.IDColumn          = "CategoryID";
            provider.LevelColumn       = "CategoryLevel";
            provider.OrderColumn       = "CategoryOrder";
            provider.ParentIDColumn    = "CategoryParentID";
            provider.PathColumn        = "CategoryIDPath";
            provider.ValueColumn       = "CategoryID";
            provider.ChildCountColumn  = "CategoryChildCount";
            provider.ImageColumn       = "CategoryIconPath";

            provider.WhereCondition = "((CategoryIsGroup IS NULL) OR (CategoryIsGroup = 0)) " + levelWhere;
            if (!ShowEmptyCategories)
            {
                var where = "CategoryID IN (SELECT CategoryParentID FROM CMS_SettingsCategory WHERE (CategoryIsGroup = 0) OR (CategoryIsGroup = 1 AND CategoryID IN (SELECT KeyCategoryID FROM CMS_SettingsKey WHERE ISNULL(SiteID, 0) = 0 AND ISNULL(KeyIsHidden, 0) = 0";
                if (SiteID > 0)
                {
                    where += " AND KeyIsGlobal = 0";
                }
                where += ")))";
                provider.WhereCondition = SqlHelper.AddWhereCondition(provider.WhereCondition, where);
            }
            provider.Columns = "CategoryID, CategoryName, CategoryDisplayName, CategoryLevel, CategoryOrder, CategoryParentID, CategoryIDPath, CategoryIconPath, CategoryResourceID, " + levelColumn;

            if (String.IsNullOrEmpty(JavaScriptHandler))
            {
                Tree.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS## ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME##');\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
                Tree.NodeTemplate         = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS##\" onclick=\"SelectNode('##NODECODENAME##');\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
            }
            else
            {
                Tree.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS## ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME##'); if (" + JavaScriptHandler + ") { " + JavaScriptHandler + "('##NODECODENAME##',##NODEID##, ##SITEID##, ##PARENTID##, ##RESOURCEID##); }\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
                Tree.NodeTemplate         = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS##\" onclick=\"SelectNode('##NODECODENAME##'); if (" + JavaScriptHandler + ") { " + JavaScriptHandler + "('##NODECODENAME##',##NODEID##, ##SITEID##, ##PARENTID##, ##RESOURCEID##); }\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
            }

            Tree.UsePostBack    = false;
            Tree.ProviderObject = provider;
            Tree.ExpandPath     = RootCategory.CategoryIDPath;

            Tree.OnNodeCreated += Tree_OnNodeCreated;
        }

        GetExpandedPaths();

        NewItemButton.ToolTip      = GetString("settings.newelem");
        DeleteItemButton.ToolTip   = GetString("settings.deleteelem");
        MoveUpItemButton.ToolTip   = GetString("settings.modeupelem");
        MoveDownItemButton.ToolTip = GetString("settings.modedownelem");

        // Create new element javascript
        NewItemButton.OnClientClick = "return newItem();";

        // Confirm delete
        DeleteItemButton.OnClientClick = "if(!deleteConfirm()) { return false; }";

        var isPostback = RequestHelper.IsPostBack();

        if (!isPostback)
        {
            Tree.ReloadData();

            if (QueryHelper.GetBoolean("reloadtreeselect", false))
            {
                var category = SettingsCategoryInfoProvider.GetSettingsCategoryInfo(CategoryID);
                // Select requested category
                RegisterSelectNodeScript(category);
            }
        }

        if (ShowSiteSelector)
        {
            if (!isPostback)
            {
                if (QueryHelper.Contains("selectedSiteId"))
                {
                    // Get from URL
                    SiteID             = QueryHelper.GetInteger("selectedSiteId", 0);
                    SiteSelector.Value = SiteID;
                }
            }
            else
            {
                SiteID = ValidationHelper.GetInteger(SiteSelector.Value, 0);
            }

            // Style site selector
            SiteSelector.SetValue("AllowGlobal", true);
            SiteSelector.SetValue("GlobalRecordValue", 0);

            bool reload = QueryHelper.GetBoolean("reload", true);

            // URL for tree selection
            string script = "var categoryURL = '" + UIContextHelper.GetElementUrl(ModuleName.CMS, "Settings.Keys") + "';\n";
            script += "var doNotReloadContent = false;\n";

            // Select category
            SettingsCategoryInfo sci = SettingsCategoryInfoProvider.GetSettingsCategoryInfo(CategoryID);
            if (sci != null)
            {
                // Stop reloading of right frame, if explicitly set
                if (!reload)
                {
                    script += "doNotReloadContent = true;";
                }
                script += SelectAtferLoad(sci.CategoryIDPath, sci.CategoryName, sci.CategoryID, sci.CategoryParentID);
            }

            ScriptHelper.RegisterStartupScript(Page, typeof(string), "SelectCat", ScriptHelper.GetScript(script));
        }
        else
        {
            ResourceInfo resource = ResourceInfoProvider.GetResourceInfo(ModuleID);

            StringBuilder sb = new StringBuilder();
            sb.Append(@"
var frameURL = '", UIContextHelper.GetElementUrl(ModuleName.CMS, "EditSettingsCategory", false), @"';
var rootId = ", (RootCategory != null ? RootCategory.CategoryID : 0), @";
var selectedModuleId = ", ModuleID, @";
var developmentMode = ", SystemContext.DevelopmentMode ? "true" : "false", @";
var resourceInDevelopment = ", (resource != null) && resource.ResourceIsInDevelopment ? "true" : "false", @";
var postParentId = ", CategoryID, @";

function newItem() {
    var hidElem = document.getElementById('" + hidSelectedElem.ClientID + @"');
    var ids = hidElem.value.split('|');
    if (window.parent != null && window.parent.frames['settingsmain'] != null) {
        window.parent.frames['settingsmain'].location = '" + ResolveUrl("~/CMSModules/Modules/Pages/Settings/Category/Edit.aspx") + @"?moduleid=" + ModuleID + @"&parentId=' + ids[0];
    } 
    return false;
}

function deleteConfirm() {
    return confirm(" + ScriptHelper.GetString(GetString("settings.categorydeleteconfirmation")) + @");
}
");

            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "setupTreeScript", ScriptHelper.GetScript(sb.ToString()));
        }
    }
コード例 #52
0
    protected void Page_Load(object sender, EventArgs e)
    {
        CurrentUserInfo currentUser = CMSContext.CurrentUser;

        // Fill the menu with UIElement data for specified module
        if (!String.IsNullOrEmpty(this.ModuleName) & (currentUser != null))
        {
            DataSet dsModules = UIElementInfoProvider.GetUIMenuElements(ModuleName);

            List <object[]> categoriesTmp = new List <object[]>();

            if (!DataHelper.DataSourceIsEmpty(dsModules))
            {
                foreach (DataRow drModule in dsModules.Tables[0].Rows)
                {
                    UIElementInfo moduleElement = new UIElementInfo(drModule);

                    // Proceed if user has permissions for this UI element
                    if (currentUser.IsAuthorizedPerUIElement(this.ModuleName, moduleElement.ElementName))
                    {
                        // Category title
                        string categoryTitle = ResHelper.LocalizeString(moduleElement.ElementDisplayName);

                        // Category name
                        string categoryName = ResHelper.LocalizeString(moduleElement.ElementName);

                        // Category URL
                        string categoryUrl = CMSContext.ResolveMacros(URLHelper.EnsureHashToQueryParameters(moduleElement.ElementTargetURL));

                        // Category image URL
                        string categoryImageUrl = this.GetImagePath(moduleElement.ElementIconPath.Replace("list.png", "module.png"));
                        if (!FileHelper.FileExists(categoryImageUrl))
                        {
                            categoryImageUrl = this.GetImagePath("CMSModules/module.png");
                        }

                        // Category tooltip
                        string categoryTooltip = ResHelper.LocalizeString(moduleElement.ElementDescription);

                        // Category actions
                        DataSet dsActions = UIElementInfoProvider.GetChildUIElements(moduleElement.ElementID);

                        List <string[]> actionsTmp = new List <string[]>();

                        foreach (DataRow drAction in dsActions.Tables[0].Rows)
                        {
                            UIElementInfo actionElement = new UIElementInfo(drAction);

                            // Proceed if user has permissions for this UI element
                            if (currentUser.IsAuthorizedPerUIElement(this.ModuleName, actionElement.ElementName))
                            {
                                actionsTmp.Add(new string[] { ResHelper.LocalizeString(actionElement.ElementDisplayName), CMSContext.ResolveMacros(URLHelper.EnsureHashToQueryParameters(actionElement.ElementTargetURL)) });
                            }
                        }

                        int actionsCount = actionsTmp.Count;

                        string[,] categoryActions = new string[actionsCount, 2];

                        for (int i = 0; i < actionsCount; i++)
                        {
                            categoryActions[i, 0] = actionsTmp[i][0];
                            categoryActions[i, 1] = actionsTmp[i][1];
                        }

                        CategoryCreatedEventArgs args = new CategoryCreatedEventArgs(moduleElement, categoryName, categoryTitle, categoryUrl, categoryImageUrl, categoryTooltip, categoryActions);

                        // Raise additional initialization events for this category
                        if (this.CategoryCreated != null)
                        {
                            this.CategoryCreated(this, args);
                        }

                        // Add to categories, if further processing of this category was not cancelled
                        if (!args.Cancel)
                        {
                            categoriesTmp.Add(new object[] { args.CategoryTitle, args.CategoryName, args.CategoryURL, args.CategoryImageURL, args.CategoryTooltip, args.CategoryActions });
                        }
                    }
                }
            }

            int categoriesCount = categoriesTmp.Count;

            object[,] categories = new object[categoriesCount, 6];

            for (int i = 0; i < categoriesCount; i++)
            {
                categories[i, 0] = categoriesTmp[i][0];
                categories[i, 1] = categoriesTmp[i][1];
                categories[i, 2] = categoriesTmp[i][2];
                categories[i, 3] = categoriesTmp[i][3];
                categories[i, 4] = categoriesTmp[i][4];
                categories[i, 5] = categoriesTmp[i][5];
            }
            if (categoriesCount > 0)
            {
                this.panelMenu.Categories   = categories;
                this.panelMenu.ColumnsCount = this.ColumnsCount;
            }
            else
            {
                RedirectToUINotAvailable();
            }

            // Add editing icon in development mode
            if (SettingsKeyProvider.DevelopmentMode && currentUser.IsGlobalAdministrator)
            {
                ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(this.ModuleName);
                if (ri != null)
                {
                    ltlAfter.Text += "<div class=\"AlignRight\">" + UIHelper.GetResourceUIElementsLink(this.Page, ri.ResourceId) + "</div>";
                }
            }
        }
    }
コード例 #53
0
 protected override Task OnReferencedRNameChangedOverride(ResourceInfo referencedResInfo, EngineNS.RName newRName, EngineNS.RName oldRName)
 {
     throw new NotImplementedException();
 }
コード例 #54
0
    /// <summary>
    /// Handles btnOK's OnClick event - Update resource info.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // finds whether required fields are not empty
        string result = new Validator().NotEmpty(tbModuleDisplayName.Text.Trim(), GetString("Administration-Module_New.ErrorEmptyModuleDisplayName")).NotEmpty(tbModuleCodeName.Text, GetString("Administration-Module_New.ErrorEmptyModuleCodeName"))
                        .IsCodeName(tbModuleCodeName.Text, GetString("general.invalidcodename"))
                        .Result;

        if (this.chkShowInDevelopment.Checked && String.IsNullOrEmpty(this.txtResourceUrl.Text.Trim()))
        {
            result = GetString("module_edit.emptyurl");
        }

        if (result == "")
        {
            // Check unique name
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(tbModuleCodeName.Text);
            if ((ri == null) || (ri.ResourceId == moduleId))
            {
                // Get object
                if (ri == null)
                {
                    ri = ResourceInfoProvider.GetResourceInfo(moduleId);
                    if (ri == null)
                    {
                        ri = new ResourceInfo();
                    }
                }

                //Update resource info
                ri.ResourceId          = moduleId;
                ri.ResourceName        = tbModuleCodeName.Text;
                ri.ResourceDescription = txtModuleDescription.Text.Trim();
                ri.ResourceDisplayName = tbModuleDisplayName.Text.Trim();

                ri.ShowInDevelopment = chkShowInDevelopment.Checked;
                ri.ResourceUrl       = (ri.ShowInDevelopment ? txtResourceUrl.Text : "");
                pnlResourceUrl.Style.Add("display", (ri.ShowInDevelopment ? "block" : "none"));

                ResourceInfoProvider.SetResourceInfo(ri);

                // Update root UIElementInfo of the module
                UIElementInfo elemInfo = UIElementInfoProvider.GetRootUIElementInfo(ri.ResourceId);
                if (elemInfo == null)
                {
                    elemInfo = new UIElementInfo();
                }
                elemInfo.ElementResourceID  = ri.ResourceId;
                elemInfo.ElementDisplayName = ri.ResourceDisplayName;
                elemInfo.ElementName        = ri.ResourceName.ToLower().Replace(".", "");
                elemInfo.ElementIsCustom    = false;
                UIElementInfoProvider.SetUIElementInfo(elemInfo);

                lblInfo.Visible = true;
                lblInfo.Text    = GetString("General.ChangesSaved");
            }
            else
            {
                lblInfo.Visible  = false;
                lblError.Visible = true;
                lblError.Text    = GetString("Administration-Module_New.UniqueCodeName");
            }
        }
        else
        {
            lblInfo.Visible  = false;
            lblError.Visible = true;
            lblError.Text    = result;
        }
    }
コード例 #55
0
 public bool HasResource(ResourceInfo resourceInfo)
 {
     return(_stockpileBlocks.Any(_ => _.HasResource(resourceInfo.Id)));
 }
コード例 #56
0
 public ResourceInfoData(ResourceInfo owner, HexSpan span)
     : base(DataKind.ResourceInfo, span) => Owner = owner;
コード例 #57
0
 public bool Equals(ResourceInfo other)
 {
     return(resourceName == other.resourceName && resourcePath == other.resourcePath);
 }
コード例 #58
0
 public UnicodeNameAndOffsetData(ResourceInfo owner, Bit7String bit7String)
     : base(DataKind.UnicodeNameAndOffset, HexSpan.FromBounds(bit7String.FullSpan.Start, bit7String.FullSpan.End + 4))
 {
     Owner      = owner;
     Bit7String = bit7String;
 }
コード例 #59
0
 protected void Initialize(string assetName, Type assetType, int priority, ResourceInfo resourceInfo, string[] dependencyAssetNames, object userData)
 {
     Initialize(++s_Serial, priority);
     m_AssetName            = assetName;
     m_AssetType            = assetType;
     m_ResourceInfo         = resourceInfo;
     m_DependencyAssetNames = dependencyAssetNames;
     m_UserData             = userData;
 }
コード例 #60
0
ファイル: SchemaLoader.cs プロジェクト: dwalu/LevelEditor
        protected override void ParseAnnotations(
            XmlSchemaSet schemaSet,
            IDictionary <NamedMetadata, IList <XmlNode> > annotations)
        {
            base.ParseAnnotations(schemaSet, annotations);

            foreach (var kv in annotations)
            {
                DomNodeType nodeType = kv.Key as DomNodeType;
                if (nodeType == null || kv.Value.Count == 0)
                {
                    continue;
                }

                // create a hash of hidden attributes
                HashSet <string> hiddenprops = new HashSet <string>();
                foreach (XmlNode xmlnode in kv.Value)
                {
                    if (xmlnode.LocalName == "scea.dom.editors.attribute")
                    {
                        XmlAttribute hiddenAttrib = xmlnode.Attributes["hide"];
                        if (hiddenAttrib != null && hiddenAttrib.Value == "true")
                        {
                            XmlAttribute nameAttrib = xmlnode.Attributes["name"];
                            string       name       = (nameAttrib != null) ? nameAttrib.Value : null;
                            if (!string.IsNullOrWhiteSpace(name))
                            {
                                hiddenprops.Add(name);
                            }
                        }
                    }
                }
                if (hiddenprops.Count > 0)
                {
                    nodeType.SetTag(HiddenProperties, hiddenprops);
                }

                PropertyDescriptorCollection localDescriptor      = nodeType.GetTagLocal <PropertyDescriptorCollection>();
                PropertyDescriptorCollection annotationDescriptor = Sce.Atf.Dom.PropertyDescriptor.ParseXml(nodeType, kv.Value);

                // if the type already have local property descriptors
                // then add annotation driven property descriptors to it.
                if (localDescriptor != null)
                {
                    foreach (System.ComponentModel.PropertyDescriptor propDecr in annotationDescriptor)
                    {
                        localDescriptor.Add(propDecr);
                    }
                }
                else
                {
                    localDescriptor = annotationDescriptor;
                }

                if (localDescriptor.Count > 0)
                {
                    nodeType.SetTag <PropertyDescriptorCollection>(localDescriptor);
                }


                // process annotations resourceReferenceTypes.
                XmlNode rfNode = FindElement(kv.Value, Annotations.ReferenceConstraint.Name);
                if (rfNode != null)
                {
                    HashSet <string> extSet = null;
                    string           exts   = FindAttribute(rfNode, Annotations.ReferenceConstraint.ValidResourceFileExts);
                    if (!string.IsNullOrWhiteSpace(exts))
                    {
                        exts = exts.ToLower();
                        char[] sep = { ',' };
                        extSet = new HashSet <string>(exts.Split(sep, StringSplitOptions.RemoveEmptyEntries));
                    }
                    else if (m_gameEngine != null)
                    {
                        string       restype = FindAttribute(rfNode, Annotations.ReferenceConstraint.ResourceType);
                        ResourceInfo resInfo = m_gameEngine.Info.ResourceInfos.GetByType(restype);
                        if (resInfo != null)
                        {
                            extSet = new HashSet <string>(resInfo.FileExts);
                        }
                    }

                    if (extSet != null)
                    {
                        nodeType.SetTag(Annotations.ReferenceConstraint.ValidResourceFileExts, extSet);
                    }
                }

                // todo use schema annotation to mark  Palette types.
                XmlNode xmlNode = FindElement(kv.Value, "scea.dom.editors");
                if (xmlNode != null)
                {
                    string name              = FindAttribute(xmlNode, "name");
                    string description       = FindAttribute(xmlNode, "description");
                    string image             = FindAttribute(xmlNode, "image");
                    string category          = FindAttribute(xmlNode, "category");
                    string menuText          = FindAttribute(xmlNode, "menuText");
                    NodeTypePaletteItem item = new NodeTypePaletteItem(nodeType, name, description, image, category,
                                                                       menuText);
                    nodeType.SetTag <NodeTypePaletteItem>(item);
                }
            }
        }