public string doResourceAccess() { Console.WriteLine(classNameLog + "Do resource access"); currentlyAccessing = true; //clear permission, do request access //String nowResource; ResourceHandler resourceHandler = new ResourceHandler(); if (wantWrite) { Console.WriteLine(classNameLog + "Write random string to resource"); myString = resourceHandler.generateRandomString(); Console.WriteLine(classNameLog + "Random string generated => " + myString); finalString = resourceHandler.appendNewString(myIp, masterIp, myString); } else { Console.WriteLine(classNameLog + "Read shared string"); finalString = resourceHandler.readNewString(myIp, masterIp); } Console.WriteLine(classNameLog + "Resource value now => " + finalString); haveInterest = false; currentlyAccessing = false; return finalString; }
/// <summary> /// Image Handler /// </summary> /// <param name="dirName">dir Name</param> /// <param name="next">next</param> /// <param name="extensions">extensions</param> /// <returns></returns> public ImageHandler (string dirName, ResourceHandler next, params string[] extensions) : base(dirName, next) { this.extensions = extensions == null || !extensions.Any() ? new[] { ".gif", ".png", ".jpg", ".jpeg" } : extensions; }
/// <summary> /// Script Handler /// </summary> /// <param name="dirName">dir Name</param> /// <param name="next">next</param> /// <param name="extensions">extensions</param> /// <returns></returns> public ScriptHandler (string dirName, ResourceHandler next, params string[] extensions) : base(dirName, next) { this.extensions = extensions == null || !extensions.Any() ? new[] { ".js", ".css", ".axd" } : extensions; ; }
public CSharpServerImplementation() { myRegisterHandler = new RegisterHandler(); myElectionHelper = new ElectionHelper(); myRequestHandler = new RequestHandler(); myRequestCentralHandler = new RequestHandlerCentralized(); myResourceHandler = new ResourceHandler(); }
internal ContentHandler(GraphicsDevice graphicsDevice, SpriteBatch spriteBatch, Level level, Camera camera, ResourceHandler resourceHandler) { SpriteHandler = new SpriteHandler(); KeyboardHandler = new KeyboardHandler(); CursorHandler = new CursorHandler(); //EffectHandler = new EffectHandler(); ResourceHandler = resourceHandler; this.SpriteBatch = spriteBatch; this.Level = level; this.Camera = camera; this.graphicsDevice = graphicsDevice; }
/// <summary> /// Init handler. /// </summary> protected override void OnPreInit(EventArgs e) { if (!DebugHelper.DebugResources) { DisableDebugging(); } // Transfer the execution to the newsletter page if newsletter template string newsletterTemplateName = QueryHelper.GetString("newslettertemplatename", String.Empty); if (newsletterTemplateName != string.Empty) { Server.Transfer("~/CMSModules/Newsletters/CMSPages/GetCSS.aspx?newslettertemplatename=" + newsletterTemplateName); } // Process all other request with resource handler ResourceHandler handler = new ResourceHandler(); handler.ProcessRequest(Context); RequestHelper.EndResponse(); base.OnPreInit(e); }
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { //Notes: // - The 'host' portion is entirely ignored by this scheme handler. // - If you register a ISchemeHandlerFactory for http/https schemes you should also specify a domain name // - Avoid doing lots of processing in this method as it will affect performance. // - Use the Default ResourceHandler implementation var uri = new Uri(request.Url); var fileName = uri.AbsolutePath; //Load a file directly from Disk if (fileName.EndsWith("CefSharp.Core.xml", StringComparison.OrdinalIgnoreCase)) { //Convenient helper method to lookup the mimeType var mimeType = ResourceHandler.GetMimeType(".xml"); //Load a resource handler for CefSharp.Core.xml //mimeType is optional and will default to text/html return(ResourceHandler.FromFilePath("CefSharp.Core.xml", mimeType, autoDisposeStream: true)); } if (uri.Host == "cefsharp.com" && schemeName == "https" && (string.Equals(fileName, "/PostDataTest.html", StringComparison.OrdinalIgnoreCase) || string.Equals(fileName, "/PostDataAjaxTest.html", StringComparison.OrdinalIgnoreCase))) { return(new CefSharpSchemeHandler()); } if (string.Equals(fileName, "/EmptyResponseFilterTest.html", StringComparison.OrdinalIgnoreCase)) { return(ResourceHandler.FromString("", ".html")); } string resource; if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource)) { var fileExtension = Path.GetExtension(fileName); return(ResourceHandler.FromString(resource, includePreamble: true, mimeType: ResourceHandler.GetMimeType(fileExtension))); } return(null); }
/* * Handler for the browser register handler event. */ public void RegisterHandler(string url, ResourceHandler handler) { // No implementation required }
/// <summary> /// Html Agility Pack Loader /// </summary> /// <param name="resourceHandler">resource Handler</param> /// <returns></returns> public HtmlAgilityPackLoader(ResourceHandler resourceHandler = null) { this.resourceHandler = resourceHandler; }
private void UserLogin() { try { button_login.Enabled = false; //ProgressBar.Start(); //ProgressBar.Show(); var settingObject = System.Configuration.ConfigurationSettings.AppSettings; var company = settingObject["Company"]; var auth = new refUserAuth.IauthClient().login(txtUserName.Text.Trim(), txtPassword.Text.Trim(), int.Parse(company), "DuoSoftPhone"); var sip = ProfileManagementHandler.GetSipProfile(auth.SecurityToken, auth.guUserId); if (sip == null) { button_login.Enabled = true; //ProgressBar.Stop(); //ProgressBar.Hide(); txtPassword.Text = string.Empty; Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Fail to Get SIP Profile", Logger.LogLevel.Error); MessageBox.Show("Fail to Get SIP Profile", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var id = Guid.NewGuid().ToString(); var callBack = new ResourceHandler(auth.SecurityToken, auth.TenantID, auth.CompanyID); var ip = GetLocalIPAddress(); callBack.OnResourceRegistrationCompleted += (r) => { #region Resource Registration this.Invoke(new MethodInvoker(delegate { button_login.Enabled = true; //ProgressBar.Stop(); //ProgressBar.Hide(); txtPassword.Text = string.Empty; switch (r.Command) { case WorkflowResultCode.ACDS101: //- Agent sucessfully registered (ACDS101) Hide(); new FormDialPad(auth, id, sip, ip).ShowDialog(this); this.Close(); Environment.Exit(0); break; case WorkflowResultCode.ACDE101: //- Agent already registered with different IP (ACDE101) Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Agent already registered with different IP-ARDS Code : ACDE101", Logger.LogLevel.Info); MessageBox.Show("Agent already registered with different IP", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Login Fail-- ARDS not allow to Login. ARDS Code : " + r.Command, Logger.LogLevel.Info); MessageBox.Show("Login Fail", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } })); #endregion }; callBack.ResourceRegistration(auth, ip); } catch (Exception exception) { this.Invoke(new MethodInvoker(delegate { button_login.Enabled = true; //ProgressBar.Stop(); //ProgressBar.Hide(); txtPassword.Text = string.Empty; })); Logger.Instance.LogMessage(Logger.LogAppender.DuoDefault, "Login fail", exception, Logger.LogLevel.Error); MessageBox.Show("Login Fail", "Duo Dialer", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public pnlScsiInfo(ScsiInfo scsiInfo, string devicePath) { XamlReader.Load(this); this.scsiInfo = scsiInfo; Stream logo = ResourceHandler.GetResourceStream($"Aaru.Gui.Assets.Logos.Media.{scsiInfo.MediaType}.svg"); /* if(logo != null) * { * svgMediaLogo.SvgStream = logo; * svgMediaLogo.Visible = true; * } * else * {*/ logo = ResourceHandler.GetResourceStream($"Aaru.Gui.Assets.Logos.Media.{scsiInfo.MediaType}.png"); if (logo != null) { imgMediaLogo.Image = new Bitmap(logo); imgMediaLogo.Visible = true; } //} txtType.Text = scsiInfo.MediaType.ToString(); lblMediaSize.Text = $"Media has {scsiInfo.Blocks} blocks of {scsiInfo.BlockSize} bytes/each. (for a total of {scsiInfo.Blocks * scsiInfo.BlockSize} bytes)"; lblMediaSize.Visible = scsiInfo.Blocks != 0 && scsiInfo.BlockSize != 0; if (scsiInfo.MediaSerialNumber != null) { stkMediaSerial.Visible = true; var sbSerial = new StringBuilder(); for (int i = 4; i < scsiInfo.MediaSerialNumber.Length; i++) { sbSerial.AppendFormat("{0:X2}", scsiInfo.MediaSerialNumber[i]); } txtMediaSerial.Text = sbSerial.ToString(); } btnSaveReadMediaSerial.Visible = this.scsiInfo.MediaSerialNumber != null; btnSaveReadCapacity.Visible = this.scsiInfo.ReadCapacity != null; btnSaveReadCapacity16.Visible = this.scsiInfo.ReadCapacity16 != null; btnSaveGetConfiguration.Visible = this.scsiInfo.MmcConfiguration != null; btnSaveRecognizedFormatLayers.Visible = this.scsiInfo.RecognizedFormatLayers != null; btnSaveWriteProtectionStatus.Visible = this.scsiInfo.WriteProtectionStatus != null; tabMmc.Visible = btnSaveGetConfiguration.Visible || btnSaveRecognizedFormatLayers.Visible || btnSaveWriteProtectionStatus.Visible; if (this.scsiInfo.DensitySupportHeader.HasValue) { grpDensitySupport.Visible = true; txtDensitySupport.Text = DensitySupport.PrettifyDensity(scsiInfo.DensitySupportHeader); } if (this.scsiInfo.MediaTypeSupportHeader.HasValue) { grpMediumSupport.Visible = true; txtMediumSupport.Text = DensitySupport.PrettifyMediumType(scsiInfo.MediaTypeSupportHeader); } btnSaveDensitySupport.Visible = scsiInfo.DensitySupport != null; btnSaveMediumSupport.Visible = scsiInfo.MediaTypeSupport != null; tabSsc.Visible = grpDensitySupport.Visible || grpMediumSupport.Visible || btnSaveDensitySupport.Visible || btnSaveMediumSupport.Visible; var tabCompactDiscInfo = new tabCompactDiscInfo(); tabCompactDiscInfo.LoadData(scsiInfo.Toc, scsiInfo.Atip, scsiInfo.CompactDiscInformation, scsiInfo.Session, scsiInfo.RawToc, this.scsiInfo.Pma, this.scsiInfo.CdTextLeadIn, this.scsiInfo.DecodedToc, this.scsiInfo.DecodedAtip, this.scsiInfo.DecodedSession, this.scsiInfo.FullToc, this.scsiInfo.DecodedCdTextLeadIn, this.scsiInfo.DecodedCompactDiscInformation, this.scsiInfo.Mcn, this.scsiInfo.Isrcs); tabInfos.Pages.Add(tabCompactDiscInfo); var tabDvdInfo = new tabDvdInfo(); tabDvdInfo.LoadData(scsiInfo.MediaType, scsiInfo.DvdPfi, scsiInfo.DvdDmi, scsiInfo.DvdCmi, scsiInfo.HddvdCopyrightInformation, scsiInfo.DvdBca, scsiInfo.DvdAacs, this.scsiInfo.DecodedPfi); tabInfos.Pages.Add(tabDvdInfo); var tabXboxInfo = new tabXboxInfo(); tabXboxInfo.LoadData(scsiInfo.XgdInfo, scsiInfo.DvdDmi, scsiInfo.XboxSecuritySector, scsiInfo.DecodedXboxSecuritySector); tabInfos.Pages.Add(tabXboxInfo); var tabDvdWritableInfo = new tabDvdWritableInfo(); tabDvdWritableInfo.LoadData(scsiInfo.MediaType, scsiInfo.DvdRamDds, scsiInfo.DvdRamCartridgeStatus, scsiInfo.DvdRamSpareArea, scsiInfo.LastBorderOutRmd, scsiInfo.DvdPreRecordedInfo, scsiInfo.DvdrMediaIdentifier, scsiInfo.DvdrPhysicalInformation, scsiInfo.HddvdrMediumStatus, scsiInfo.HddvdrLastRmd, scsiInfo.DvdrLayerCapacity, scsiInfo.DvdrDlMiddleZoneStart, scsiInfo.DvdrDlJumpIntervalSize, scsiInfo.DvdrDlManualLayerJumpStartLba, scsiInfo.DvdrDlRemapAnchorPoint, scsiInfo.DvdPlusAdip, scsiInfo.DvdPlusDcb); tabInfos.Pages.Add(tabDvdWritableInfo); var tabBlurayInfo = new tabBlurayInfo(); tabBlurayInfo.LoadData(scsiInfo.BlurayDiscInformation, scsiInfo.BlurayBurstCuttingArea, scsiInfo.BlurayDds, scsiInfo.BlurayCartridgeStatus, scsiInfo.BluraySpareAreaInformation, scsiInfo.BlurayPowResources, scsiInfo.BlurayTrackResources, scsiInfo.BlurayRawDfl, scsiInfo.BlurayPac); tabInfos.Pages.Add(tabBlurayInfo); this.devicePath = devicePath; }
public OptionWindow() { InitializeComponent(); this.Icon = ResourceHandler.GetIcon("mono", 16, 16); GetButtonImages(); }
// Use this for initialization void Start() { rScript = gameObject.GetComponent<ResourceHandler> (); }
protected void OnMenuOpen(object sender, EventArgs e) { // TODO: Extensions var dlgOpenImage = new OpenFileDialog { Title = "Choose image to open" }; DialogResult result = dlgOpenImage.ShowDialog(this); if (result != DialogResult.Ok) { return; } var filtersList = new FiltersList(); IFilter inputFilter = filtersList.GetFilter(dlgOpenImage.FileName); if (inputFilter == null) { MessageBox.Show("Cannot open specified file.", MessageBoxType.Error); return; } try { IMediaImage imageFormat = ImageFormat.Detect(inputFilter); if (imageFormat == null) { MessageBox.Show("Image format not identified.", MessageBoxType.Error); return; } DicConsole.WriteLine("Image format identified by {0} ({1}).", imageFormat.Name, imageFormat.Id); try { if (!imageFormat.Open(inputFilter)) { MessageBox.Show("Unable to open image format", MessageBoxType.Error); DicConsole.ErrorWriteLine("Unable to open image format"); DicConsole.ErrorWriteLine("No error given"); return; } // TODO: SVG Stream logo = ResourceHandler. GetResourceStream($"DiscImageChef.Gui.Assets.Logos.Media.{imageFormat.Info.MediaType}.png"); var imageGridItem = new TreeGridItem { Values = new object[] { logo == null ? null : new Bitmap(logo), $"{Path.GetFileName(dlgOpenImage.FileName)} ({imageFormat.Info.MediaType})", dlgOpenImage.FileName, new pnlImageInfo(dlgOpenImage.FileName, inputFilter, imageFormat), inputFilter, imageFormat } }; List <Partition> partitions = Core.Partitions.GetAll(imageFormat); Core.Partitions.AddSchemesToStats(partitions); bool checkraw = false; List <string> idPlugins; IFilesystem plugin; PluginBase plugins = GetPluginBase.Instance; if (partitions.Count == 0) { DicConsole.DebugWriteLine("Analyze command", "No partitions found"); checkraw = true; } else { DicConsole.WriteLine("{0} partitions found.", partitions.Count); foreach (string scheme in partitions.Select(p => p.Scheme).Distinct().OrderBy(s => s)) { var schemeGridItem = new TreeGridItem { Values = new object[] { nullImage, // TODO: Add icons to partition schemes scheme } }; foreach (Partition partition in partitions. Where(p => p.Scheme == scheme).OrderBy(p => p.Start)) { var partitionGridItem = new TreeGridItem { Values = new object[] { nullImage, // TODO: Add icons to partition schemes $"{partition.Name} ({partition.Type})", null, new pnlPartition(partition) } }; DicConsole.WriteLine("Identifying filesystem on partition"); Core.Filesystems.Identify(imageFormat, out idPlugins, partition); if (idPlugins.Count == 0) { DicConsole.WriteLine("Filesystem not identified"); } else { DicConsole.WriteLine($"Identified by {idPlugins.Count} plugins"); foreach (string pluginName in idPlugins) { if (plugins.PluginsList.TryGetValue(pluginName, out plugin)) { plugin.GetInformation(imageFormat, partition, out string information, null); var fsPlugin = plugin as IReadOnlyFilesystem; if (fsPlugin != null) { Errno error = fsPlugin.Mount(imageFormat, partition, null, new Dictionary <string, string>(), null); if (error != Errno.NoError) { fsPlugin = null; } } var filesystemGridItem = new TreeGridItem { Values = new object[] { nullImage, // TODO: Add icons to filesystems plugin.XmlFsType.VolumeName is null ? $"{plugin.XmlFsType.Type}" : $"{plugin.XmlFsType.VolumeName} ({plugin.XmlFsType.Type})", fsPlugin, new pnlFilesystem(plugin.XmlFsType, information) } }; if (fsPlugin != null) { Statistics.AddCommand("ls"); filesystemGridItem.Children.Add(placeholderItem); } Statistics.AddFilesystem(plugin.XmlFsType.Type); partitionGridItem.Children.Add(filesystemGridItem); } } } schemeGridItem.Children.Add(partitionGridItem); } imageGridItem.Children.Add(schemeGridItem); } } if (checkraw) { var wholePart = new Partition { Name = "Whole device", Length = imageFormat.Info.Sectors, Size = imageFormat.Info.Sectors * imageFormat.Info.SectorSize }; Core.Filesystems.Identify(imageFormat, out idPlugins, wholePart); if (idPlugins.Count == 0) { DicConsole.WriteLine("Filesystem not identified"); } else { DicConsole.WriteLine($"Identified by {idPlugins.Count} plugins"); foreach (string pluginName in idPlugins) { if (plugins.PluginsList.TryGetValue(pluginName, out plugin)) { plugin.GetInformation(imageFormat, wholePart, out string information, null); var fsPlugin = plugin as IReadOnlyFilesystem; if (fsPlugin != null) { Errno error = fsPlugin.Mount(imageFormat, wholePart, null, new Dictionary <string, string>(), null); if (error != Errno.NoError) { fsPlugin = null; } } var filesystemGridItem = new TreeGridItem { Values = new object[] { nullImage, // TODO: Add icons to filesystems plugin.XmlFsType.VolumeName is null ? $"{plugin.XmlFsType.Type}" : $"{plugin.XmlFsType.VolumeName} ({plugin.XmlFsType.Type})", fsPlugin, new pnlFilesystem(plugin.XmlFsType, information) } }; if (fsPlugin != null) { Statistics.AddCommand("ls"); filesystemGridItem.Children.Add(placeholderItem); } Statistics.AddFilesystem(plugin.XmlFsType.Type); imageGridItem.Children.Add(filesystemGridItem); } } } } imagesRoot.Children.Add(imageGridItem); treeImages.ReloadData(); Statistics.AddMediaFormat(imageFormat.Format); Statistics.AddMedia(imageFormat.Info.MediaType, false); Statistics.AddFilter(inputFilter.Name); }
public frmMain(bool debug, bool verbose) { XamlReader.Load(this); lblError = new Label(); grdFiles = new GridView(); nullImage = null; ConsoleHandler.Init(); ConsoleHandler.Debug = debug; ConsoleHandler.Verbose = verbose; treeImagesItems = new TreeGridItemCollection(); treeImages.Columns.Add(new GridColumn { HeaderText = "Name", DataCell = new ImageTextCell(0, 1) }); treeImages.AllowMultipleSelection = false; treeImages.ShowHeader = false; treeImages.DataStore = treeImagesItems; // TODO: SVG imagesIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.inode-directory.png")); devicesIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.computer.png")); hardDiskIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-harddisk.png")); opticalIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-optical.png")); usbIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-removable-media-usb.png")); removableIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.drive-removable-media.png")); sdIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-flash-sd-mmc.png")); tapeIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-tape.png")); ejectIcon = new Bitmap(ResourceHandler. GetResourceStream("DiscImageChef.Gui.Assets.Icons.oxygen._32x32.media-eject.png")); imagesRoot = new TreeGridItem { Values = new object[] { imagesIcon, "Images" } }; devicesRoot = new TreeGridItem { Values = new object[] { devicesIcon, "Devices" } }; treeImagesItems.Add(imagesRoot); treeImagesItems.Add(devicesRoot); placeholderItem = new TreeGridItem { Values = new object[] { nullImage, "You should not be seeing this" } }; Closing += OnClosing; treeImagesMenu = new ContextMenu(); treeImagesMenu.Opening += OnTreeImagesMenuOpening; treeImages.ContextMenu = treeImagesMenu; }
private string GetMimeType(string fileName) { return(ResourceHandler.GetMimeType(System.IO.Path.GetExtension(fileName))); }
public InputProfile(string name) { Name = name; inputMappings = new ResourceHandler <InputMapping>(); }
public static Func <IResourceHandler> ForBytes(byte[] bytes, string mimeType) { return(() => ResourceHandler.FromByteArray(bytes, mimeType)); }
public static Func <IResourceHandler> ForString(string str, string mimeType) { return(() => ResourceHandler.FromString(str, mimeType: mimeType)); }
public static Func <IResourceHandler> ForString(string str) { return(() => ResourceHandler.FromString(str)); }
public SpriteAtlas() { entries = new ResourceHandler <SpriteAtlasEntry>(); images = new ResourceHandler <Texture2D>(); }
public static string RegisterResources(DefaultResourceHandlerFactory factory, string title) { if (factory == null) { return(null); } var previewPath = "http://test/resource/load/questionnaire_preview.html"; baseFilePath = Path.Combine(RetrieveAppLocation(), "Web"); Initialize(factory); var templateCollection = Directory.GetFiles(Path.Combine(baseFilePath, "templates"), "*.*", SearchOption.AllDirectories); foreach (var item in templateCollection) { factory.RegisterHandler(string.Format(CultureInfo.InvariantCulture, "{0}", item.Replace(baseFilePath, basePath).Replace("\\", "/")), ResourceHandler.FromFilePath(item)); } var htmlPage = GetQuestionnaireHtml(title); factory.RegisterHandler(previewPath, ResourceHandler.FromString(htmlPage)); ClearAll(); return(previewPath); }
protected override IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request) { return(ResourceHandler.FromStream(_stream, _contentType, true, _charSet)); }
private void Start() { _resources = FindObjectOfType <ResourceHandler>(); }
/// <summary> /// Default private constructor. /// </summary> private App() { // Create the resource handler Resources = new ResourceHandler(); // Create the handler collection Handlers = new RequestHandlerCollection(); }
IEnumerator SendCreateView() { if (m_IsCoroutineStarted) { yield break; } m_IsCoroutineStarted = true; if (string.IsNullOrEmpty(Page)) { throw new System.ApplicationException("The Page of a view must not be null or empty."); } if (ResourceHandlerFactoryFunc != null) { m_ResourceHandler = ResourceHandlerFactoryFunc(); } if (m_ResourceHandler == null) { Debug.LogWarning("Unable to create file handler using factory function! Falling back to default handler."); m_ResourceHandler = new UnityGTResourceHandler(); } ViewLoadPolicy policy = ViewLoadPolicy.VLP_UseCacheOrLoad; #if UNITY_EDITOR m_ResourcesInUse = new HashSet <string>(); m_ResourceHandler = new UnityGTResourceHandlerDecorator(m_ResourceHandler, this); if (AutoRefresh) { policy = ViewLoadPolicy.VLP_IgnoreCache; } #endif var viewInfo = new ViewInfo(); viewInfo.Width = (uint)this.m_Width; viewInfo.Height = (uint)this.m_Height; viewInfo.IsTransparent = this.m_IsTransparent; viewInfo.ViewListenerInstance = m_Listener; viewInfo.ResourceHandlerInstance = m_ResourceHandler; viewInfo.ClickThroughAlphaThreshold = ClickThroughThreshold; if (string.IsNullOrEmpty(InitialScript)) { View = m_UISystem.UISystem.CreateView(viewInfo, Page, policy); } else { View = m_UISystem.UISystem.CreateView(viewInfo, Page, InitialScript, policy); } RecreateViewTexture(m_Width, m_Height); View.SetNewRenderTarget(ViewTexture.GetNativeTexturePtr(), DepthTexture.GetNativeTexturePtr(), (uint)m_Width, (uint)m_Height, 1); CoherentUIGTRenderEvents.SendRenderEvent(CoherentRenderEventType.CreateViewRenderer, View.GetId()); while (ViewRenderer == null) { ViewRenderer = View.GetViewRenderer(); yield return(null); } AddViewRendererComponent(); }
public BrowserTabView() { InitializeComponent(); //browser.BrowserSettings.BackgroundColor = Cef.ColorSetARGB(0, 255, 255, 255); browser.RequestHandler = new RequestHandler(); //See https://github.com/cefsharp/CefSharp/issues/2246 for details on the two different binding options if (CefSharpSettings.LegacyJavascriptBindingEnabled) { browser.RegisterJsObject("bound", new BoundObject(), options: BindingOptions.DefaultBinder); } else { //Objects can still be pre registered, they can also be registered when required, see ResolveObject below //browser.JavascriptObjectRepository.Register("bound", new BoundObject(), isAsync:false, options: BindingOptions.DefaultBinder); } var bindingOptions = new BindingOptions() { Binder = BindingOptions.DefaultBinder.Binder, MethodInterceptor = new MethodInterceptorLogger() // intercept .net methods calls from js and log it }; //See https://github.com/cefsharp/CefSharp/issues/2246 for details on the two different binding options if (CefSharpSettings.LegacyJavascriptBindingEnabled) { browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject(), options: bindingOptions); } else { //Objects can still be pre registered, they can also be registered when required, see ResolveObject below //browser.JavascriptObjectRepository.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } //To use the ResolveObject below and bind an object with isAsync:false we must set CefSharpSettings.WcfEnabled = true before //the browser is initialized. CefSharpSettings.WcfEnabled = true; //If you call CefSharp.BindObjectAsync in javascript and pass in the name of an object which is not yet //bound, then ResolveObject will be called, you can then register it browser.JavascriptObjectRepository.ResolveObject += (sender, e) => { var repo = e.ObjectRepository; if (e.ObjectName == "boundAsync2") { repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } else if (e.ObjectName == "bound") { browser.JavascriptObjectRepository.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder); } else if (e.ObjectName == "boundAsync") { browser.JavascriptObjectRepository.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions); } }; browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) => { var name = e.ObjectName; Debug.WriteLine($"Object {e.ObjectName} was bound successfully."); }; browser.DisplayHandler = new DisplayHandler(); browser.LifeSpanHandler = new LifespanHandler(); browser.MenuHandler = new MenuHandler(); browser.AccessibilityHandler = new AccessibilityHandler(); var downloadHandler = new DownloadHandler(); downloadHandler.OnBeforeDownloadFired += OnBeforeDownloadFired; downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired; browser.DownloadHandler = downloadHandler; //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg var beachImageStream = new MemoryStream(); CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg); browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, ResourceHandler.GetMimeType(".jpg")); var dragHandler = new DragHandler(); dragHandler.RegionsChanged += OnDragHandlerRegionsChanged; browser.DragHandler = dragHandler; //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory(); //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler //browser.RequestContext = new RequestContext(new RequestContextHandler()); //NOTE - This is very important for this example as the default page will not load otherwise //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory()); //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread. //Cef.UIThreadTaskFactory.StartNew(delegate //{ // string errorMessage; // //Use this to check that settings preferences are working in your code // var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage); //}); browser.RenderProcessMessageHandler = new RenderProcessMessageHandler(); browser.LoadError += (sender, args) => { // Don't display an error for downloaded files. if (args.ErrorCode == CefErrorCode.Aborted) { return; } // Don't display an error for external protocols that we allow the OS to // handle. See OnProtocolExecution(). //if (args.ErrorCode == CefErrorCode.UnknownUrlScheme) //{ // var url = args.Frame.Url; // if (url.StartsWith("spotify:")) // { // return; // } //} // Display a load error message. var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>", args.FailedUrl, args.ErrorText, args.ErrorCode); args.Frame.LoadStringForUrl(errorBody, args.FailedUrl); }; CefExample.RegisterTestResources(browser); }
public BrowserTabView() { InitializeComponent(); browser.RequestHandler = new RequestHandler(); browser.RegisterJsObject("bound", new BoundObject(), BindingOptions.DefaultBinder); browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject()); // Enable touch scrolling - once properly tested this will likely become the default //browser.IsManipulationEnabled = true; browser.LifeSpanHandler = new LifespanHandler(); browser.MenuHandler = new MenuHandler(); browser.GeolocationHandler = new GeolocationHandler(); var downloadHandler = new DownloadHandler(); downloadHandler.OnBeforeDownloadFired += OnBeforeDownloadFired; downloadHandler.OnDownloadUpdatedFired += OnDownloadUpdatedFired; browser.DownloadHandler = downloadHandler; //Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg var beachImageStream = new MemoryStream(); CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg); browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, ResourceHandler.GetMimeType(".jpg")); var dragHandler = new DragHandler(); dragHandler.RegionsChanged += OnDragHandlerRegionsChanged; browser.DragHandler = dragHandler; //browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory(); //You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers //Also this is now the only way to access OnBeforePluginLoad - need to implement IRequestContextHandler //browser.RequestContext = new RequestContext(new RequestContextHandler()); //NOTE - This is very important for this example as the default page will not load otherwise //browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory()); //You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread. //Cef.UIThreadTaskFactory.StartNew(delegate //{ // string errorMessage; // //Use this to check that settings preferences are working in your code // var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage); //}); browser.RenderProcessMessageHandler = new RenderProcessMessageHandler(); browser.LoadError += (sender, args) => { // Don't display an error for downloaded files. if (args.ErrorCode == CefErrorCode.Aborted) { return; } // Don't display an error for external protocols that we allow the OS to // handle. See OnProtocolExecution(). //if (args.ErrorCode == CefErrorCode.UnknownUrlScheme) //{ // var url = args.Frame.Url; // if (url.StartsWith("spotify:")) // { // return; // } //} // Display a load error message. var errorBody = string.Format("<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>", args.FailedUrl, args.ErrorText, args.ErrorCode); args.Frame.LoadStringForUrl(errorBody, args.FailedUrl); }; CefExample.RegisterTestResources(browser); }
/// <summary> /// Gets the text content from a given path and processes it. Override this method if you want to implement custom logic when each file is loaded. /// </summary> /// <param name="path">The path from which to the content should be retrieved.</param> /// <returns>The processed text content of the given path, or null if it was not found.</returns> protected virtual string GetTextFromPath(string path) { if (path[0] == '/') { // This is a repository URL var fsPath = HostingEnvironment.MapPath(path); var fileNodeHead = NodeHead.Get(path); var fileNode = fileNodeHead != null && SecurityHandler.HasPermission(fileNodeHead, PermissionType.Open) ? Node.Load <File>(path) : null; System.IO.Stream stream = null; if ((WebApplication.DiskFSSupportMode == DiskFSSupportMode.Prefer || fileNode == null) && System.IO.File.Exists(fsPath)) { // If DiskFsSupportMode is Prefer and the file exists, or it's fallback but the node doesn't exist in the repo get it from the file system stream = new System.IO.FileStream(fsPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); } else if (path[0] == '/' && fileNode != null) { // If the node exists, get it from the repo stream = fileNode.Binary.GetStream(); } else if (path.StartsWith("/" + ResourceHandler.UrlPart + "/")) { // Special case, this is a resource URL, we will just render the resource script here var parsed = ResourceHandler.ParseUrl(path); if (parsed == null) { return(null); } var className = parsed.Item2; var culture = CultureInfo.GetCultureInfo(parsed.Item1); try { return(ResourceScripter.RenderResourceScript(className, culture)); } catch (Exception exc) { SnLog.WriteException(exc); return(null); } } try { return(stream != null?RepositoryTools.GetStreamString(stream) : null); } finally { if (stream != null) { stream.Dispose(); } } } if (path.StartsWith("http://") || path.StartsWith("https://")) { // This is a web URL try { HttpWebRequest req; if (PortalContext.IsKnownUrl(path)) { string url; var ub = new UriBuilder(path); var origHost = ub.Host; ub.Host = "127.0.0.1"; url = ub.Uri.ToString(); req = (HttpWebRequest)HttpWebRequest.Create(url); req.Host = origHost; } else { req = (HttpWebRequest)HttpWebRequest.Create(path); } req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; var res = req.GetResponse(); using (var st = res.GetResponseStream()) using (var stream = new System.IO.MemoryStream()) { st.CopyTo(stream); var arr = stream.ToArray(); var result = Encoding.UTF8.GetString(arr); return(result); } } catch (Exception exc) { SnLog.WriteException(exc, "Error during bundle request: ", EventId.Portal, properties: new Dictionary <string, object> { { "Path", path } }); return(null); } } return(null); }
/// <summary> /// If the file requested is within the rootFolder then a IResourceHandler reference to the file requested will be returned /// otherwise a 404 ResourceHandler will be returned. /// </summary> /// <param name="browser">the browser window that originated the /// request or null if the request did not originate from a browser window /// (for example, if the request came from CefURLRequest).</param> /// <param name="frame">frame that originated the request /// or null if the request did not originate from a browser window /// (for example, if the request came from CefURLRequest).</param> /// <param name="schemeName">the scheme name</param> /// <param name="request">The request. (will not contain cookie data)</param> /// <returns> /// A IResourceHandler /// </returns> protected virtual IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { if (this.schemeName != null && !schemeName.Equals(this.schemeName, StringComparison.OrdinalIgnoreCase)) { return(ResourceHandler.ForErrorMessage(string.Format("SchemeName {0} does not match the expected SchemeName of {1}.", schemeName, this.schemeName), HttpStatusCode.NotFound)); } var uri = new Uri(request.Url); if (this.hostName != null && !uri.Host.Equals(this.hostName, StringComparison.OrdinalIgnoreCase)) { return(ResourceHandler.ForErrorMessage(string.Format("HostName {0} does not match the expected HostName of {1}.", uri.Host, this.hostName), HttpStatusCode.NotFound)); } //Get the absolute path and remove the leading slash var asbolutePath = uri.AbsolutePath.Substring(1); ResourceLoader loader = null; //Search for ResourceLoader ID # int separator = asbolutePath.IndexOf("/"); int id; if ((separator > -1) && int.TryParse(asbolutePath.Substring(0, separator), out id)) { InteractiveCharts.ResourceLoaders.TryGetValue(id, out loader); asbolutePath = asbolutePath.Substring(separator + 1); //Adjust uri to only contain the file name now } // Get file properties string fileExtension = Path.GetExtension(asbolutePath); var mimeType = GetMimeTypeDelegate(fileExtension); Stream stream = null; // Check for resources that are loaded by the ResourceLoader if (loader != null) { if (asbolutePath == "config.js") { stream = loader.LoadConfig(); } else if (asbolutePath == "data.json") { stream = loader.LoadData(); } } // If no stream has been loaded yet, attempt to load from an internal assembly resource. if (stream == null) { try { var assembly = Assembly.GetExecutingAssembly(); stream = assembly.GetManifestResourceStream("InteractiveCharts.Resources." + asbolutePath.Replace('/', '.')); } catch (Exception) { stream = null; } } if (stream != null) { return(ResourceHandler.FromStream(stream, mimeType)); } else { return(ResourceHandler.ForErrorMessage("Resource Not Found - " + uri.AbsolutePath, HttpStatusCode.NotFound)); } }
void Start() { res = GameObject.FindGameObjectWithTag("resourceHandler").GetComponent <ResourceHandler>(); }
/** * class to handle async call back for centralized mutual exclusion * @author ukimiawz * */ //private class CallBack : AsyncCallback //{ // private String classNameLog = "callBack Centralized : "; // @Override // public void handleError(XmlRpcRequest arg0, Throwable arg1) // { // Console.WriteLine(classNameLog + "Centralized Async call failed"); // } // @Override // public void handleResult(XmlRpcRequest arg0, Object arg1) // { // Console.WriteLine(classNameLog + "Centralized Async call success"); // } //} /*==================== SLAVE SIDE ===================*/ /*** * * @param wantWrite - indicates whether the request is for write or read * @return */ public String startMessage(bool localWantWrite, bool isSignal) { Console.WriteLine(classNameLog + "Start mutual exclusion process"); masterIp = CSharpRpcServer.getIpMaster(); myIp = CSharpRpcServer.getMyIpAddress(); myKey = CSharpRpcServer.getMyPriority(); Console.WriteLine(classNameLog + "Master IP =>" + masterIp); Console.WriteLine(classNameLog + "My IP => " + myIp + " My key => " + myKey); if (!isSignal) { //start signal from client, inform others //contact all machines to start Dictionary<int, String> machines = CSharpRpcServer.getMachines(); Console.WriteLine(classNameLog + "Contacting all nodes " + machines); Object[] parameters = new Object[] { localWantWrite, true }; XmlRpcHelper.SendToAllMachinesAsync(machines, GlobalMethodName.requestCentralStartMessage, parameters); } Console.WriteLine(classNameLog + "Initiating resource handler. Want to write => " + localWantWrite); resourceHandler = new ResourceHandler(); wantWrite = localWantWrite; return sendRequest(localWantWrite); }
void Start() { resourceHandler = FindObjectOfType <ResourceHandler>(); gameManager = FindObjectOfType <GameManager>(); }
public CreateWindow(MainController controller) { InitializeComponent(); mainController = controller; this.Icon = ResourceHandler.GetIcon("mono", 16, 16); }
protected void grdRequestList_RowCommand(object sender, GridViewCommandEventArgs e) { int reqId = Convert.ToInt32(e.CommandArgument); if (e.CommandName == "checkReq") { hdnfReqId.Value = reqId.ToString(); //List<ResourceControl.Entity.Resource> resList = new List<ResourceControl.Entity.Resource>(); ResourceHandler rsh = new ResourceHandler(); RequestHandler requestHandler = new RequestHandler(); var requestDetails = requestHandler.GetRequestDetails(reqId); _resList = requestDetails.Status > 1 ? rsh.GetResourceListByStudentReqIDForAfterAccept(reqId) : rsh.ResourceSelectByReqStudentID(reqId); var resourceState = requestHandler.GetResourceStateForDefence(reqId); ViewState.Add("reqId", reqId); ViewState.Add("_resList", _resList); ViewState.Add("ResourceState", resourceState); grdResourceState.DataSource = resourceState; grdResourceState.DataBind(); if (drpRequestTypeList.SelectedIndex == 0) { drpCandidateResource.DataSource = _resList; drpCandidateResource.DataTextField = "name"; drpCandidateResource.DataValueField = "ID"; drpCandidateResource.DataBind(); drpCandidateResource.Items.Insert(0, new ListItem { Value = "0", Text = "انتخاب کنید..." }); dvOperation.Visible = true; // dvOperation1.Visible = true; dvSuggestResource.Visible = true; } else { dvOperation.Visible = false; // dvOperation1.Visible = false; dvSuggestResource.Visible = false; } if (drpRequestTypeList.SelectedIndex == 5) { dvOperation.Visible = false; // dvOperation1.Visible = false; } grdDateTime.EditIndex = -1; RequestDateTimeHandler rqdateTimeH = new RequestDateTimeHandler(); _dateTimeList = rqdateTimeH.GetDateTimeListByRequestId(reqId); grdDateTime.DataSource = _dateTimeList.OrderBy(c => c.Date); grdDateTime.DataBind(); lblRequestNumber.Text = requestDetails.ID.ToString(); lblIssuerName.Text = requestDetails.IssuerName.ToString(); // lblResh.Text = requestDetails.Nameresh.ToString(); lblDanesh.Text = requestDetails.Namedanesh.ToString(); string scrp = "function f(){$find(\"" + RadWindow1.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);"; ScriptManager.RegisterStartupScript(this.Page, GetType(), ClientID, scrp, true); } if (e.CommandName == "deny") { hdnfDenyReqId.Value = reqId.ToString(); string scrp = "function f(){$find(\"" + RadWindow2.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);"; ScriptManager.RegisterStartupScript(this.Page, GetType(), ClientID, scrp, true); } if (e.CommandName == "edit") { Response.Redirect("UserEditRequest.aspx?id=" + generaterandomstr() + "@A" + "0" + "-" + generaterandomstr() + "&reqId=" + e.CommandArgument); } if (e.CommandName == "History") { CommonBusiness cmb = new CommonBusiness(); var dtLog = cmb.GetUserAndStudentLogModifyId(int.Parse(e.CommandArgument.ToString()), 11); var myLog = RequestHandler.ConvertDataTableToList <logDetail>(dtLog).OrderBy(O => O.LogDate.ToGregorian()).ThenBy(x => x.LogTime.TimeToTicks()); lst_history.DataSource = myLog; lst_history.DataBind(); ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true); } if (e.CommandName == "showInfo") { #region ShowInfo hdnfReqId.Value = reqId.ToString(); RequestHandler rh = new RequestHandler(); GridViewRow curruntRow = (GridViewRow)(((Button)e.CommandSource).NamingContainer); imgStatus2.ImageUrl = ((Image)curruntRow.Cells[2].FindControl("imgStatus")).ImageUrl; var requestDetails = rh.GetRequestDetails(reqId); lblRequestId.Text = requestDetails.ID.ToString(); lblDarkhast.Text = requestDetails.CourseName; lbldateOfRequest.Text = requestDetails.Issue_time; RequestDateTimeHandler rqdateTimeH = new RequestDateTimeHandler(); _dateTimeList = rqdateTimeH.GetDateTimeListByRequestId(reqId); var dateTime = _dateTimeList.OrderBy(c => c.Date).FirstOrDefault(c => c.Date != null); if (dateTime != null) { lblRequest.Text = dateTime.Date; } //var requestDateTime = requestDetails.DateTimeRange.FirstOrDefault(c => c.Date != null); //if (requestDateTime != null) //{ // var firstOrDefault = requestDetails.DateTimeRange.FirstOrDefault(c => c.StartTime != 0).Date; // if (firstOrDefault != null) // lblRequest.Text = firstOrDefault; //} var startTime = _dateTimeList.FirstOrDefault(c => c.StartTime != 0); if (startTime != null) { lblTime1.Text = TimeSpan.FromTicks((long)startTime.StartTime).ToString().Substring(0, 5); } var endTime = _dateTimeList.FirstOrDefault(c => c.EndTime != 0); if (endTime != null) { lblTime2.Text = TimeSpan.FromTicks((long)endTime.EndTime).ToString().Substring(0, 5); } switch (requestDetails.Status) { case 0: lblStatue.Text = "درخواست استاد ثبت گردیده و در انتظار ارجاع هست"; break; case 1: lblStatue.Text = "درخواست ارجاع داده شده است"; break; case 2: lblStatue.Text = "درخواست شما مورد تایید واقع گردیده"; break; case 3: lblStatue.Text = "درخواست شما مورد تایید واقع نگردیده"; break; case 4: lblStatue.Text = "درخواست شما اطلاع رسانی گردیده است"; break; case 5: lblStatue.Text = "درخواست شما از دست رفته است"; break; } //lblTozieh.Text = requestDetails.Note; //blCapecity.Text = requestDetails.Capacity.ToString(); //lblLocation.Text = requestDetails.Location; //if (!string.IsNullOrEmpty(requestDetails.Answer_time)) //{ // if (requestDetails.Status == 2) // { // lblheader.Text = "زمان پاسخ به درخواست:"; // } // else // { // lblheader.Text = "زمان رد درخواست:"; // litDenyNot.Text = "علت رد درخواست:"; // } // lblheader.Visible = true; // lblDateOfResponse.Visible = true; // lblDateOfResponse.Text = requestDetails.Answer_time; // if (requestDetails.Status != 2) // { // litDenyNot.Visible = true; // lblDenyNot.Visible = true; // lblDenyNot.Text = requestDetails.Answernote; // } //} //else //{ // lblheader.Visible = false; // lblDateOfResponse.Visible = false; // litDenyNot.Visible = false; // lblDenyNot.Visible = false; //} var studentDefenceRequestList = rh.GetStudentDefenceRequest(requestDetails.IssuerID); var listOfDefenceRequest = RequestHandler.ConvertDataTableToList <StudentDefenceRequestDTO>(studentDefenceRequestList); var inCirculationRequest = listOfDefenceRequest.FirstOrDefault( x => x.isDeleted != true && x.RequestDate.StringPersianDateToGerogorianDate() >= DateTime.Now); if (inCirculationRequest == null) { inCirculationRequest = listOfDefenceRequest.OrderByDescending(x => x.ID).FirstOrDefault(); } if (inCirculationRequest.IsUseOwnSystem) { lblOwnSysytem.Text = "بله"; } else { lblOwnSysytem.Text = "خیر"; } if (inCirculationRequest.IsEquippingResource) { lblOnlineShow.Text = "بله"; } else { lblOnlineShow.Text = "خیر"; } if (!string.IsNullOrEmpty(inCirculationRequest.OnlineTeacherRole.Trim())) { lblOnlineDef.Text = "بله"; } else { lblOnlineDef.Text = "خیر"; } if (inCirculationRequest.FlagDoingMeetingOnline) { lblOnlineDoingMeeting.Text = "بله"; } else { lblOnlineDoingMeeting.Text = "خیر"; } //var requestDateTimes = _dateTimeList.OrderBy(d => d.Date); //if (requestDateTimes.Count() > 1) // tblRangeOfDate.Visible = true; //else // tblRangeOfDate.Visible = false; //if (requestDateTimes.Any()) //{ // tblRangeOfDate.Visible = true; // grdOldDateTime.DataSource = requestDateTimes; // grdOldDateTime.DataBind(); //} //var cth = new CategoryHandler(); //var categoryName = cth.GetCategoryList().FirstOrDefault(c => c.ID == requestDetails.CatID).Name; //lblPosition.Text = categoryName; //var opt = new OptionHandler(); // var optlist = opt.GetOptionListByCatID(requestDetails.CatID); //var rsopt = new Req_Opt_JuncHandler(); // var resOptJunlist = rsopt.GetReq_Opt_JuncListByReqID(requestDetails.ID); //var requestOption = new List<Option>(); //foreach (Req_Opt_Junc optJunc in resOptJunlist) //{ // foreach (var option in optlist) // { // if (optJunc.Opt_id == option.ID) // requestOption.Add(new Option { Name = option.Name }); // } //} ////grdFacilities.DataSource = requestOption; //grdFacilities.DataBind(); string scrp = "function f(){$find(\"" + RadWindow3.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);"; ScriptManager.RegisterStartupScript(this.Page, GetType(), ClientID, scrp, true); #endregion } }
bool IResourceHandler.ProcessRequest(IRequest request, ICallback callback) { // The 'host' portion is entirely ignored by this scheme handler. var uri = new Uri(request.Url); var fileName = uri.AbsolutePath; if (string.Equals(fileName, "/PostDataTest.html", StringComparison.OrdinalIgnoreCase)) { var postDataElement = request.PostData.Elements.FirstOrDefault(); var resourceHandler = (ResourceHandler)ResourceHandler.FromString("Post Data: " + (postDataElement == null ? "null" : postDataElement.GetBody())); stream = (MemoryStream)resourceHandler.Stream; mimeType = "text/html"; callback.Continue(); return(true); } if (string.Equals(fileName, "/PostDataAjaxTest.html", StringComparison.OrdinalIgnoreCase)) { var postData = request.PostData; if (postData == null) { var resourceHandler = (ResourceHandler)ResourceHandler.FromString("Post Data: null"); stream = (MemoryStream)resourceHandler.Stream; mimeType = "text/html"; callback.Continue(); } else { var postDataElement = postData.Elements.FirstOrDefault(); var resourceHandler = (ResourceHandler)ResourceHandler.FromString("Post Data: " + (postDataElement == null ? "null" : postDataElement.GetBody())); stream = (MemoryStream)resourceHandler.Stream; mimeType = "text/html"; callback.Continue(); } return(true); } if (string.Equals(fileName, "/EmptyResponseFilterTest.html", StringComparison.OrdinalIgnoreCase)) { stream = null; mimeType = "text/html"; callback.Continue(); return(true); } string resource; if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource)) { Task.Run(() => { using (callback) { var bytes = Encoding.UTF8.GetBytes(resource); stream = new MemoryStream(bytes); var fileExtension = Path.GetExtension(fileName); mimeType = ResourceHandler.GetMimeType(fileExtension); callback.Continue(); } }); return(true); } else { callback.Dispose(); } return(false); }
public static async void RegisterTestResources(IWebBrowser browser) { if (browser.ResourceRequestHandlerFactory == null) { browser.ResourceRequestHandlerFactory = new ResourceRequestHandlerFactory(); } var handler = browser.ResourceRequestHandlerFactory as ResourceRequestHandlerFactory; if (handler != null) { const string renderProcessCrashedBody = "<html><body><h1>Render Process Crashed</h1><p>Your seeing this message as the render process has crashed</p></body></html>"; handler.RegisterHandler(RenderProcessCrashedUrl, ResourceHandler.GetByteArray(renderProcessCrashedBody, Encoding.UTF8)); const string responseBody = "<html><body><h1>Success</h1><p>This document is loaded from a System.IO.Stream</p></body></html>"; handler.RegisterHandler(TestResourceUrl, ResourceHandler.GetByteArray(responseBody, Encoding.UTF8)); const string unicodeResponseBody = "<html><body>整体满意度</body></html>"; handler.RegisterHandler(TestUnicodeResourceUrl, ResourceHandler.GetByteArray(unicodeResponseBody, Encoding.UTF8)); if (string.IsNullOrEmpty(PluginInformation)) { var pluginBody = new StringBuilder(); pluginBody.Append("<html><body><h1>Plugins</h1><table>"); pluginBody.Append("<tr>"); pluginBody.Append("<th>Name</th>"); pluginBody.Append("<th>Description</th>"); pluginBody.Append("<th>Version</th>"); pluginBody.Append("<th>Path</th>"); pluginBody.Append("</tr>"); var plugins = await Cef.GetPlugins(); if (plugins.Count == 0) { pluginBody.Append("<tr>"); pluginBody.Append("<td colspan='4'>Cef.GetPlugins returned an empty list - likely no plugins were loaded on your system</td>"); pluginBody.Append("</tr>"); pluginBody.Append("<tr>"); pluginBody.Append("<td colspan='4'>You may find that NPAPI/PPAPI need to be enabled</td>"); pluginBody.Append("</tr>"); } else { foreach (var plugin in plugins) { pluginBody.Append("<tr>"); pluginBody.Append("<td>" + plugin.Name + "</td>"); pluginBody.Append("<td>" + plugin.Description + "</td>"); pluginBody.Append("<td>" + plugin.Version + "</td>"); pluginBody.Append("<td>" + plugin.Path + "</td>"); pluginBody.Append("</tr>"); } } pluginBody.Append("</table></body></html>"); PluginInformation = pluginBody.ToString(); } handler.RegisterHandler(PluginsTestUrl, ResourceHandler.GetByteArray(PluginInformation, Encoding.UTF8)); } }
void Start() { resources = GameObject.Find("ResourceContainer").GetComponent <ResourceHandler>(); }
private void GenerateServiceProxyCode(AssemblyBuilder assemblyBuilder, Type serviceType) { IResourceNameGenerator nameGenerator = assemblyBuilder.CodeDomProvider as IResourceNameGenerator; if (nameGenerator != null) { this.ResourceFullName = nameGenerator.GenerateResourceName(base.VirtualPath); } else { this.ResourceFullName = ResourceBuildProvider.GenerateTypeNameFromPath(base.VirtualPath); } // TODO: consolidate app relative path conversion // calculate the service end-point path string proxyPath = ResourceHandler.EnsureAppRelative(base.VirtualPath).TrimStart('~'); // build proxy from main service type JsonServiceDescription desc = new JsonServiceDescription(serviceType, proxyPath); JsonServiceProxyGenerator proxy = new JsonServiceProxyGenerator(desc); string proxyOutput = proxy.OutputProxy(false); proxyOutput = ScriptResourceCodeProvider.FirewallScript(proxyPath, proxyOutput, true); string debugProxyOutput = proxy.OutputProxy(true); debugProxyOutput = ScriptResourceCodeProvider.FirewallScript(proxyPath, debugProxyOutput, false); byte[] gzippedBytes, deflatedBytes; ResourceBuildProvider.Compress(proxyOutput, out gzippedBytes, out deflatedBytes); string hash = ResourceBuildProvider.ComputeHash(proxyOutput); // generate a service factory CodeCompileUnit generatedUnit = new CodeCompileUnit(); #region namespace ResourceNamespace CodeNamespace ns = new CodeNamespace(this.ResourceNamespace); generatedUnit.Namespaces.Add(ns); #endregion namespace ResourceNamespace #region public sealed class ResourceTypeName : JsonServiceInfo CodeTypeDeclaration resourceType = new CodeTypeDeclaration(); resourceType.IsClass = true; resourceType.Name = this.ResourceTypeName; resourceType.Attributes = MemberAttributes.Public | MemberAttributes.Final; resourceType.BaseTypes.Add(typeof(IJsonServiceInfo)); resourceType.BaseTypes.Add(typeof(IOptimizedResult)); ns.Types.Add(resourceType); #endregion public sealed class ResourceTypeName : CompiledBuildResult #region [BuildPath(virtualPath)] string virtualPath = base.VirtualPath; if (HttpRuntime.AppDomainAppVirtualPath.Length > 1) { virtualPath = virtualPath.Substring(HttpRuntime.AppDomainAppVirtualPath.Length); } virtualPath = "~" + virtualPath; CodeAttributeDeclaration attribute = new CodeAttributeDeclaration( new CodeTypeReference(typeof(BuildPathAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(virtualPath))); resourceType.CustomAttributes.Add(attribute); #endregion [BuildPath(virtualPath)] #region private static readonly byte[] GzippedBytes CodeMemberField field = new CodeMemberField(); field.Name = "GzippedBytes"; field.Type = new CodeTypeReference(typeof(byte[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; CodeArrayCreateExpression arrayInit = new CodeArrayCreateExpression(field.Type, gzippedBytes.Length); foreach (byte b in gzippedBytes) { arrayInit.Initializers.Add(new CodePrimitiveExpression(b)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static static readonly byte[] GzippedBytes #region private static readonly byte[] DeflatedBytes field = new CodeMemberField(); field.Name = "DeflatedBytes"; field.Type = new CodeTypeReference(typeof(byte[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; arrayInit = new CodeArrayCreateExpression(field.Type, deflatedBytes.Length); foreach (byte b in deflatedBytes) { arrayInit.Initializers.Add(new CodePrimitiveExpression(b)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static readonly byte[] DeflatedBytes #region string IOptimizedResult.Source { get; } // add a readonly property with the original resource source CodeMemberProperty property = new CodeMemberProperty(); property.Name = "Source"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return debugProxyOutput; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(debugProxyOutput))); resourceType.Members.Add(property); #endregion string IOptimizedResult.Source { get; } #region string IOptimizedResult.PrettyPrinted { get; } // add a readonly property with the debug proxy code string property = new CodeMemberProperty(); property.Name = "PrettyPrinted"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return ((IOptimizedResult)this).Source; } CodeExpression thisRef = new CodeCastExpression(typeof(IOptimizedResult), new CodeThisReferenceExpression()); CodePropertyReferenceExpression sourceProperty = new CodePropertyReferenceExpression(thisRef, "Source"); property.GetStatements.Add(new CodeMethodReturnStatement(sourceProperty)); resourceType.Members.Add(property); #endregion string IOptimizedResult.PrettyPrinted { get; } #region string IOptimizedResult.Compacted { get; } // add a readonly property with the proxy code string property = new CodeMemberProperty(); property.Name = "Compacted"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return proxyOutput; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(proxyOutput))); resourceType.Members.Add(property); #endregion string IOptimizedResult.Compacted { get; } #region byte[] IOptimizedResult.Gzipped { get; } // add a readonly property with the gzipped proxy code property = new CodeMemberProperty(); property.Name = "Gzipped"; property.Type = new CodeTypeReference(typeof(byte[])); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return GzippedBytes; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(this.ResourceTypeName), "GzippedBytes"))); resourceType.Members.Add(property); #endregion byte[] IOptimizedResult.Gzipped { get; } #region byte[] IOptimizedResult.Deflated { get; } // add a readonly property with the deflated proxy code property = new CodeMemberProperty(); property.Name = "Deflated"; property.Type = new CodeTypeReference(typeof(byte[])); property.PrivateImplementationType = new CodeTypeReference(typeof(IOptimizedResult)); property.HasGet = true; // get { return DeflatedBytes; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(this.ResourceTypeName), "DeflatedBytes"))); resourceType.Members.Add(property); #endregion byte[] IOptimizedResult.Deflated { get; } #region string IBuildResultMeta.Hash { get; } // add a readonly property with the hash of the resource data property = new CodeMemberProperty(); property.Name = "Hash"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return hash; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(hash))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.Hash { get; } #region string IBuildResultMeta.ContentType { get; } // add a readonly property with the MIME of the resource data property = new CodeMemberProperty(); property.Name = "ContentType"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return ScriptResourceCodeProvider.MimeType; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(ScriptResourceCodeProvider.MimeType))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.ContentType { get; } #region string IBuildResultMeta.FileExtension { get; } // add a readonly property with the extension of the resource data property = new CodeMemberProperty(); property.Name = "FileExtension"; property.Type = new CodeTypeReference(typeof(String)); property.PrivateImplementationType = new CodeTypeReference(typeof(IBuildResult)); property.HasGet = true; // get { return ScriptResourceCodeProvider.FileExt; } property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(ScriptResourceCodeProvider.FileExt))); resourceType.Members.Add(property); #endregion string IBuildResultMeta.FileExtension { get; } #region public Type IJrpcServiceInfo.ServiceType { get; } // add a static field with the service type property = new CodeMemberProperty(); property.Name = "ServiceType"; property.Type = new CodeTypeReference(typeof(Type)); property.Attributes = MemberAttributes.Public; property.ImplementationTypes.Add(new CodeTypeReference(typeof(IJsonServiceInfo))); property.HasGet = true; // get { return typeof(serviceType); } property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeOfExpression(serviceType.FullName))); resourceType.Members.Add(property); #endregion public Type IJrpcServiceInfo.ServiceType { get; } #region object IJrpcServiceInfo.CreateService(); CodeMemberMethod codeMethod = new CodeMemberMethod(); codeMethod.Name = "CreateService"; codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo)); codeMethod.ReturnType = new CodeTypeReference(typeof(Object)); // return new serviceType(); codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodeObjectCreateExpression(serviceType))); resourceType.Members.Add(codeMethod); #endregion object IJrpcServiceInfo.CreateService(); #region MethodInfo IJrpcServiceInfo.ResolveMethodName(string name); codeMethod = new CodeMemberMethod(); codeMethod.Name = "ResolveMethodName"; codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "name")); codeMethod.ReturnType = new CodeTypeReference(typeof(MethodInfo)); CodeVariableReferenceExpression nameParam = new CodeVariableReferenceExpression("name"); // if (String.IsNullOrEmpty(name)) { return null; } CodeConditionStatement nullCheck = new CodeConditionStatement(); nullCheck.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "IsNullOrEmpty", nameParam); nullCheck.TrueStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); codeMethod.Statements.Add(nullCheck); Dictionary <string, MethodInfo> methodMap = JsonServiceBuildProvider.CreateMethodMap(serviceType); foreach (string name in methodMap.Keys) { CodeConditionStatement nameTest = new CodeConditionStatement(); // if (String.Equals(name, methodName)) { ... } nameTest.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "Equals", nameParam, new CodePrimitiveExpression(name)); // this.ServiceType CodePropertyReferenceExpression serviceTypeRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ServiceType"); // method name CodePrimitiveExpression methodNameRef = new CodePrimitiveExpression(methodMap[name].Name); // this.ServiceType.GetMethod(methodNameRef) CodeMethodInvokeExpression methodInfoRef = new CodeMethodInvokeExpression(serviceTypeRef, "GetMethod", methodNameRef); // return MethodInfo; nameTest.TrueStatements.Add(new CodeMethodReturnStatement(methodInfoRef)); codeMethod.Statements.Add(nameTest); } codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null))); resourceType.Members.Add(codeMethod); #endregion MethodInfo IJrpcServiceInfo.ResolveMethodName(string name); #region string[] IJrpcServiceInfo.GetMethodParams(string name); codeMethod = new CodeMemberMethod(); codeMethod.Name = "GetMethodParams"; codeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IJsonServiceInfo)); codeMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "name")); codeMethod.ReturnType = new CodeTypeReference(typeof(String[])); CodeVariableReferenceExpression nameParam2 = new CodeVariableReferenceExpression("name"); // if (String.IsNullOrEmpty(name)) { return new string[0]; } CodeConditionStatement nullCheck2 = new CodeConditionStatement(); nullCheck2.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "IsNullOrEmpty", nameParam); nullCheck2.TrueStatements.Add(new CodeMethodReturnStatement(new CodeArrayCreateExpression(typeof(String[]), 0))); codeMethod.Statements.Add(nullCheck2); foreach (MethodInfo method in methodMap.Values) { string[] paramMap = JsonServiceBuildProvider.CreateParamMap(method); if (paramMap.Length < 1) { continue; } CodeConditionStatement nameTest = new CodeConditionStatement(); // if (String.Equals(name, method.Name)) { ... } nameTest.Condition = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(String)), "Equals", nameParam2, new CodePrimitiveExpression(method.Name)); // = {...} CodePrimitiveExpression[] paramList = new CodePrimitiveExpression[paramMap.Length]; for (int i = 0; i < paramMap.Length; i++) { paramList[i] = new CodePrimitiveExpression(paramMap[i]); } // new string[] = {...} CodeArrayCreateExpression paramArray = new CodeArrayCreateExpression(typeof(String[]), paramList); // return string[]; nameTest.TrueStatements.Add(new CodeMethodReturnStatement(paramArray)); codeMethod.Statements.Add(nameTest); } codeMethod.Statements.Add(new CodeMethodReturnStatement(new CodeArrayCreateExpression(typeof(String[]), 0))); resourceType.Members.Add(codeMethod); #endregion string[] IJrpcServiceInfo.GetMethodParams(string name); if (this.VirtualPathDependencies.Count > 0) { resourceType.BaseTypes.Add(typeof(IDependentResult)); #region private static readonly string[] Dependencies field = new CodeMemberField(); field.Name = "Dependencies"; field.Type = new CodeTypeReference(typeof(string[])); field.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; arrayInit = new CodeArrayCreateExpression(field.Type, this.VirtualPathDependencies.Count); foreach (string key in this.VirtualPathDependencies) { arrayInit.Initializers.Add(new CodePrimitiveExpression(key)); } field.InitExpression = arrayInit; resourceType.Members.Add(field); #endregion private static readonly string[] Dependencies #region IEnumerable<string> IDependentResult.VirtualPathDependencies { get; } // add a readonly property returning the static data property = new CodeMemberProperty(); property.Name = "VirtualPathDependencies"; property.Type = new CodeTypeReference(typeof(IEnumerable <string>)); property.PrivateImplementationType = new CodeTypeReference(typeof(IDependentResult)); property.HasGet = true; // get { return Dependencies; } property.GetStatements.Add(new CodeMethodReturnStatement( new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(resourceType.Name), "Dependencies"))); resourceType.Members.Add(property); #endregion IEnumerable<string> IDependentResult.VirtualPathDependencies { get; } } // Generate _ASP FastObjectFactory assemblyBuilder.GenerateTypeFactory(this.ResourceFullName); assemblyBuilder.AddCodeCompileUnit(this, generatedUnit); }
void Start() { rb = GetComponent <Rigidbody>(); rh = GameObject.FindGameObjectWithTag("resourceHandler").GetComponent <ResourceHandler>(); }