public virtual void TestNodeContainerXML() { WebResource r = Resource(); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app = new MockApp(1); nmContext.GetApplications()[app.GetAppId()] = app; AddAppContainers(app); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app2 = new MockApp(2); nmContext.GetApplications()[app2.GetAppId()] = app2; AddAppContainers(app2); ClientResponse response = r.Path("ws").Path("v1").Path("node").Path("containers") .Accept(MediaType.ApplicationXml).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationXmlType, response.GetType()); string xml = response.GetEntity <string>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.NewInstance(); DocumentBuilder db = dbf.NewDocumentBuilder(); InputSource @is = new InputSource(); @is.SetCharacterStream(new StringReader(xml)); Document dom = db.Parse(@is); NodeList nodes = dom.GetElementsByTagName("container"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 4, nodes.GetLength ()); }
public virtual void TestNodesQueryNew() { WebResource r = Resource(); MockNM nm1 = rm.RegisterNode("h1:1234", 5120); MockNM nm2 = rm.RegisterNode("h2:1235", 5121); rm.SendNodeStarted(nm1); rm.NMwaitForState(nm1.GetNodeId(), NodeState.Running); rm.NMwaitForState(nm2.GetNodeId(), NodeState.New); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("nodes").QueryParam ("states", NodeState.New.ToString()).Accept(MediaType.ApplicationJson).Get <ClientResponse >(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length()); JSONObject nodes = json.GetJSONObject("nodes"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodes.Length() ); JSONArray nodeArray = nodes.GetJSONArray("node"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodeArray.Length ()); JSONObject info = nodeArray.GetJSONObject(0); VerifyNodeInfo(info, nm2); }
public void GetWebresourcesWithNoRootFolder() { // Arrange var config = new ConfigFile { webresources = new List <WebresourceDeployConfig> { new WebresourceDeployConfig { root = null, files = new List <WebResourceFile>() } }, filePath = @"C:\code\solution" }; var existingWebresource = new WebResource { DisplayName = "new_/js/somefile.js", Name = "new_/js/somefile.js" }; // Act var task = GetWebresourceTestTask(config, existingWebresource); // Assert // Check that there is a webresource matched with the correct path Assert.AreEqual(@"webresources\new_\js\somefile.js", config.webresources[0].files[0].file); Assert.AreEqual(@"new_/js/somefile.js", config.webresources[0].files[0].uniquename); }
public virtual void TestNodeAppsStateInvalidDefault() { WebResource r = Resource(); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app = new MockApp(1); nmContext.GetApplications()[app.GetAppId()] = app; AddAppContainers(app); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app2 = new MockApp("foo", 1234, 2); nmContext.GetApplications()[app2.GetAppId()] = app2; AddAppContainers(app2); try { r.Path("ws").Path("v1").Path("node").Path("apps").QueryParam("state", "FOO_STATE" ).Get <JSONObject>(); NUnit.Framework.Assert.Fail("should have thrown exception on invalid user query"); } catch (UniformInterfaceException ue) { ClientResponse response = ue.GetResponse(); NUnit.Framework.Assert.AreEqual(ClientResponse.Status.BadRequest, response.GetClientResponseStatus ()); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject msg = response.GetEntity <JSONObject>(); JSONObject exception = msg.GetJSONObject("RemoteException"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 3, exception.Length ()); string message = exception.GetString("message"); string type = exception.GetString("exception"); string classname = exception.GetString("javaClassName"); VerifyStateInvalidException(message, type, classname); } }
public static IEnumerable <ApiResource> GetApis(WebResource api) { return(new List <ApiResource> { new ApiResource { Name = api.Id, DisplayName = "API 1", Description = "The cool API you want to protect", ApiSecrets = new List <Secret> { new Secret(api.Secret.Sha256()) }, UserClaims = new List <string> { DomainClaimTypes.Role, DomainClaimTypes.TestUserId, DomainClaimTypes.LiveUserId, DomainClaimTypes.LiveEnabled, DomainClaimTypes.SomeClaim }, Scopes = new List <Scope> { new Scope(api.Id), // Should match name of ApiResource.Name new Scope { Name = DomainScopes.ApiKeys, DisplayName = "API Keys", Description = "Access to the API keys." } } } }); }
public virtual void TestNodeAppsState() { WebResource r = Resource(); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app = new MockApp(1); nmContext.GetApplications()[app.GetAppId()] = app; AddAppContainers(app); MockApp app2 = new MockApp("foo", 1234, 2); nmContext.GetApplications()[app2.GetAppId()] = app2; Dictionary <string, string> hash2 = AddAppContainers(app2); app2.SetState(ApplicationState.Running); ClientResponse response = r.Path("ws").Path("v1").Path("node").Path("apps").QueryParam ("state", ApplicationState.Running.ToString()).Accept(MediaType.ApplicationJson) .Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); JSONObject info = json.GetJSONObject("apps"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, info.Length()); JSONArray appInfo = info.GetJSONArray("app"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, appInfo.Length ()); VerifyNodeAppInfo(appInfo.GetJSONObject(0), app2, hash2); }
public void EnsureRegistered() { var webResourceId = WebResourceRepository.FirstOrDefault(r => r.Uuid == WebResourceUuids.Vk, r => r.Id); if (webResourceId == 0) { var resource = new WebResource { Uuid = WebResourceUuids.Vk, Name = WebResourceName, Url = WebResourceUrl, ImageUrl = WebResourceImageUrl }; WebResourceRepository.Save(resource); UnitOfWork.Commit(); webResourceId = resource.Id; } var isProviderRegistered = PersonMetaProviderRepository.Any(r => r.Uuid == PersonMetaProviderUuid); if (!isProviderRegistered) { PersonMetaProviderRepository.Save(new PersonMetaProvider { Uuid = PersonMetaProviderUuid, Name = typeof(VkWatch).FullName, WebResourceId = webResourceId }); UnitOfWork.Commit(); } }
public void LoadJsonTestIp() { var provider = new WebResource("http://ip.jsontest.com/"); var json = provider.Value; Console.WriteLine("JSON: {0}", json); Assert.IsNotNull(json); }
public void Download(WebResource resource) { logger.Info("Download: {0}", resource.AbsoluteUri); var request = WebRequest.Create(resource.AbsoluteUri); request.Timeout = Timeout; using (var response = request.GetResponse() as HttpWebResponse) { // just debug. LogHttpResponseHeaders(response); using (var webStream = response.GetResponseStream()) using (var localStream = resource.LocalResource.Create()) { int value; while (-1 < (value = webStream.ReadByte())) { localStream.WriteByte((byte)value); } } // TODO: what kind of the time is set? var downloadInfo = GetDownloadInfo(resource); downloadInfo.LastModified = response.LastModified.Ticks; } }
/// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/> /// <exception cref="System.Exception"/> public virtual void TestNodeHelper(string path, string media) { WebResource r = Resource(); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app = new MockApp(1); nmContext.GetApplications()[app.GetAppId()] = app; AddAppContainers(app); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app2 = new MockApp(2); nmContext.GetApplications()[app2.GetAppId()] = app2; AddAppContainers(app2); ClientResponse response = r.Path("ws").Path("v1").Path("node").Path(path).Accept( media).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); JSONObject info = json.GetJSONObject("containers"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, info.Length()); JSONArray conInfo = info.GetJSONArray("container"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 4, conInfo.Length ()); for (int i = 0; i < conInfo.Length(); i++) { VerifyNodeContainerInfo(conInfo.GetJSONObject(i), nmContext.GetContainers()[ConverterUtils .ToContainerId(conInfo.GetJSONObject(i).GetString("id"))]); } }
public virtual void TestJobsQueryState() { WebResource r = Resource(); // we only create 3 jobs and it cycles through states so we should have 3 unique states IDictionary <JobId, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job> jobsMap = appContext .GetAllJobs(); string queryState = "BOGUS"; JobId jid = null; foreach (KeyValuePair <JobId, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job> entry in jobsMap) { jid = entry.Value.GetID(); queryState = entry.Value.GetState().ToString(); break; } ClientResponse response = r.Path("ws").Path("v1").Path("history").Path("mapreduce" ).Path("jobs").QueryParam("state", queryState).Accept(MediaType.ApplicationJson) .Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length()); JSONObject jobs = json.GetJSONObject("jobs"); JSONArray arr = jobs.GetJSONArray("job"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, arr.Length()); JSONObject info = arr.GetJSONObject(0); Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job = appContext.GetPartialJob(jid); VerifyJobsUtils.VerifyHsJobPartial(info, job); }
public void LoadGoogle() { var provider = new WebResource("http://google.com"); var source = provider.Value; Console.WriteLine("Google.com Source: {0}", source); Assert.IsNotNull(source); }
private Guid CreateNewWebResource(string name, string displayName, string description, string extension, string solutionUniqueName) { WebResource webResource = new WebResource() { LogicalName = WebResource.EntityLogicalName, Attributes = { { WebResource.Schema.Attributes.displayname, displayName }, { WebResource.Schema.Attributes.name, name }, { WebResource.Schema.Attributes.webresourcetype, new OptionSetValue(WebResourceRepository.GetTypeByExtension(extension)) } } }; if (!string.IsNullOrEmpty(description)) { webResource.Attributes.Add(WebResource.Schema.Attributes.description, description); } CreateRequest request = new CreateRequest() { Target = webResource }; request.Parameters.Add("SolutionUniqueName", solutionUniqueName); CreateResponse response = (CreateResponse)_service.Execute(request); return(response.id); }
/// <summary> /// Uploads web resource /// </summary> /// <param name="webResource">Web resource to be updated</param> /// <param name="filePath">File with a content to be set for web resource</param> /// <returns>Returns true if web resource is updated</returns> private async Task <bool> UpdateWebResourceByFileAsync(WebResource webResource, string filePath) { var settings = await SettingsService.Instance.GetSettingsAsync(); var connections = settings.CrmConnections; var webResourceName = Path.GetFileName(filePath); await Logger.WriteLineAsync("Uploading " + webResourceName, connections.ExtendedLog); var project = await projectHelper.GetSelectedProjectAsync(); var projectRootPath = await projectHelper.GetProjectRootAsync(project); var localContent = FileHelper.GetEncodedFileContent(filePath); var remoteContent = webResource.Content; if (remoteContent.Length != localContent.Length || remoteContent != localContent) { await UpdateWebResourceByContentAsync(webResource, localContent); var relativePath = filePath.Replace(projectRootPath + "\\", ""); await Logger.WriteLineAsync(webResource.Name + " uploaded from " + relativePath, !connections.ExtendedLog); return(true); } else { await Logger.WriteLineAsync("Uploading of " + webResourceName + " was skipped: there aren't any change in the web resource", connections.ExtendedLog); await Logger.WriteLineAsync(webResourceName + " has no changes", !connections.ExtendedLog); return(false); } }
public virtual void TestPerUserResourcesJSON() { //Start RM so that it accepts app submissions rm.Start(); try { rm.SubmitApp(10, "app1", "user1", null, "b1"); rm.SubmitApp(20, "app2", "user2", null, "b1"); //Get JSON WebResource r = Resource(); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("scheduler/" ).Accept(MediaType.ApplicationJson).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); JSONObject schedulerInfo = json.GetJSONObject("scheduler").GetJSONObject("schedulerInfo" ); JSONObject b1 = GetSubQueue(GetSubQueue(schedulerInfo, "b"), "b1"); //Check users user1 and user2 exist in b1 JSONArray users = b1.GetJSONObject("users").GetJSONArray("user"); for (int i = 0; i < 2; ++i) { JSONObject user = users.GetJSONObject(i); NUnit.Framework.Assert.IsTrue("User isn't user1 or user2", user.GetString("username" ).Equals("user1") || user.GetString("username").Equals("user2")); user.GetInt("numActiveApplications"); user.GetInt("numPendingApplications"); CheckResourcesUsed(user); } } finally { rm.Stop(); } }
private void tv_DragOver(object sender, DragEventArgs e) { // Retrieve the current selected node var treeview = (TreeView)sender; var treeViewLocation = treeview.PointToScreen(Point.Empty); var currentNode = treeview.GetNodeAt(e.X - treeViewLocation.X, e.Y - treeViewLocation.Y); if (e.Data.GetDataPresent(DataFormats.FileDrop)) { var files = (string[])e.Data.GetData(DataFormats.FileDrop); // File must be an expected file format // or a folder bool isExtensionValid = files.All(f => WebResource.IsValidExtension(Path.GetExtension(f)) || File.GetAttributes(f).HasFlag(FileAttributes.Directory)); // Destination node must be a Root or Folder node bool isNodeValid = currentNode != null && (currentNode.ImageIndex <= 1 || currentNode.ImageIndex >= 14 && currentNode.ImageIndex <= 15); if (isNodeValid) { treeview.SelectedNode = currentNode; } e.Effect = files.Length > 0 && isExtensionValid && isNodeValid ? DragDropEffects.All : DragDropEffects.None; } else { e.Effect = DragDropEffects.None; } }
public virtual void TestNodes2XML() { rm.Start(); WebResource r = Resource(); rm.RegisterNode("h1:1234", 5120); rm.RegisterNode("h2:1235", 5121); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("nodes").Accept (MediaType.ApplicationXml).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationXmlType, response.GetType()); string xml = response.GetEntity <string>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.NewInstance(); DocumentBuilder db = dbf.NewDocumentBuilder(); InputSource @is = new InputSource(); @is.SetCharacterStream(new StringReader(xml)); Document dom = db.Parse(@is); NodeList nodesApps = dom.GetElementsByTagName("nodes"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodesApps.GetLength ()); NodeList nodes = dom.GetElementsByTagName("node"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 2, nodes.GetLength ()); rm.Stop(); }
public static async Task <Message> EditImage(this ITelegramClient bot, Message message, string imageUrl, string text = null, RequestItem item = null, InlineKeyboardMarkup replies = null) { var defaultPoster = Assembly.GetExecutingAssembly().GetResource("Assets.default_poster.png"); var image = await WebResource.Exists(imageUrl) ? new InputMedia(imageUrl) : new InputMedia(defaultPoster, "default_poster"); if (message.Type == MessageType.Photo) { return(await bot.Client.EditMessageMediaAsync( chatId : message.Chat, messageId : message.MessageId, media : new InputMediaPhoto(image) { Caption = item?.AsString(text) ?? text ?? message.Caption }, replyMarkup : replies )); } await bot.Client.DeleteMessageAsync(message.Chat, message.MessageId); return(await bot.Client.SendPhotoAsync( chatId : message.Chat, photo : image, caption : item?.AsString(text) ?? text ?? message.Text, replyMarkup : replies )); }
private bool Clean(WebResource resource) { try { if (this.connection.IsReady) { Log.Warning("Deleting {resource}", resource.Name); connection.Delete("webresource", resource.WebResourceId); return(true); } else { throw new Exception(this.connection.LastCrmError); } } catch (FaultException <OrganizationServiceFault> ex) { if (ex.Message.ToLower().Contains("does not exist")) { Log.Warning("File did not exist in CRM System."); return(true); } Log.Error(ex, "Failed"); return(false); } }
public void Download(WebResource resource) { logger.Info("Download: {0}", resource.AbsoluteUri); var request = WebRequest.Create(resource.AbsoluteUri); request.Timeout = Timeout; using (var response = request.GetResponse() as HttpWebResponse) { // just debug. LogHttpResponseHeaders(response); using (var webStream = response.GetResponseStream()) using (var localStream = resource.LocalResource.Create()) { int value; while (-1 < (value = webStream.ReadByte())) { localStream.WriteByte((byte) value); } } // TODO: what kind of the time is set? var downloadInfo = GetDownloadInfo(resource); downloadInfo.LastModified = response.LastModified.Ticks; } }
private void AddChangedResource(WebResource resource, string newContent) { var changedCrmResource = Clone(resource); changedCrmResource.Content = newContent; changedResources.Add(changedCrmResource); }
private void CreateFolderStructure(DirectoryNode parentNode, DirectoryInfo di, string sourceDirectory) { DirectoryNode parentNode1 = new DirectoryNode() { Name = parentNode.HasParent ? di.Name : "" }; parentNode1.SetParent(parentNode); foreach (DirectoryInfo directory in di.GetDirectories()) { this.CreateFolderStructure(parentNode1, directory, this.source); } foreach (FileInfo file in di.GetFiles("*.*", SearchOption.TopDirectoryOnly)) { if (this.GetTypeFromExtension(file.Extension) != -1) { WebResource webResource = new WebResource() { Name = parentNode1.Combine(file.Name), DisplayName = file.Name, WebResourceType = GetTypeFromExtension(file.Extension) }; parentNode1.Resources.Add(webResource); } } parentNode.Directories.Add(parentNode1); }
public List <WebResource> GetWebResourceFiles(string webResourcesRootPath, Parameters parameters) { var directoryInfo = new DirectoryInfo(webResourcesRootPath); var validExtensions = new[] { ".css", ".xml", ".gif", ".htm", ".html", ".ico", ".jpg", ".png", ".js", ".xap", ".xsl", ".xslt" }; var files = directoryInfo.GetFiles("*", SearchOption.AllDirectories).Where(f => validExtensions.Contains(f.Extension) && !parameters.IgnoreFiles.Contains(f.Name)); var webResourcesInfo = new List <WebResource>(); foreach (var file in files) { var type = file.Extension.Replace(".", string.Empty).ToLower(); var name = file.FullName.Replace(webResourcesRootPath, string.Empty).Replace("\\", "/"); if (!parameters.IncludeSlashAfterPrefix && name.StartsWith("/")) { name = name.Substring(1); } if (!parameters.IncludeExtensionInName) { var extension = file.Extension; name = name.Substring(0, name.Length - extension.Length); } name = parameters.PublisherPrefix + "_" + name; var webResource = new WebResource { FilePath = file.FullName, Name = name, DisplayName = file.Name, Type = GetWebResourceTypeByExtension(type) }; webResourcesInfo.Add(webResource); } return(webResourcesInfo); }
public async Task <string> getCompanyLogo() { SoapEntityRepository repo = SoapEntityRepository.GetService(); string logo = string.Empty; QueryExpression query = new QueryExpression(WebResource.EntityLogicalName); query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("content"); LinkEntity entityTypeTheme = new LinkEntity(WebResource.EntityLogicalName, Theme.EntityLogicalName, "webresourceid", "logoid", JoinOperator.Inner); entityTypeTheme.LinkCriteria.AddCondition("isdefaulttheme", ConditionOperator.Equal, true); query.LinkEntities.Add(entityTypeTheme); EntityCollection entitycol = repo.GetEntityCollection(query); if (entitycol != null && entitycol.Entities != null && entitycol.Entities.Count > 0) { WebResource logoResource = (WebResource)entitycol.Entities[0]; //logoResource.WebResourceId logo = logoResource.Content; } return(logo); }
public ResourceControl(WebResource resource) { InitializeComponent(); this.resource = resource; byte[] b = Convert.FromBase64String(resource.EntityContent); innerContent = Encoding.UTF8.GetString(b); originalContent = innerContent; innerType = Enumerations.WebResourceType.Resx; Stream stream = new MemoryStream(b); table = new DataTable(); table.Columns.Add(new DataColumn("Key")); table.Columns.Add(new DataColumn("Value")); Dictionary <string, string> resourceMap = new Dictionary <string, string>(); rsxr = new ResXResourceReader(stream); foreach (DictionaryEntry d in rsxr) { if (string.IsNullOrEmpty(d.Key?.ToString())) { continue; } table.Rows.Add(d.Key.ToString(), d.Value?.ToString()); } rsxr.Close(); dgv.DataSource = table; dgv.CellValueChanged += dgv_CellValueChanged; dgv.UserDeletedRow += dgv_UserDeletedRow;; }
public virtual void TestSingleNodeQueryStateLost() { WebResource r = Resource(); MockNM nm1 = rm.RegisterNode("h1:1234", 5120); MockNM nm2 = rm.RegisterNode("h2:1234", 5120); rm.SendNodeStarted(nm1); rm.SendNodeStarted(nm2); rm.NMwaitForState(nm1.GetNodeId(), NodeState.Running); rm.NMwaitForState(nm2.GetNodeId(), NodeState.Running); rm.SendNodeLost(nm1); rm.SendNodeLost(nm2); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("nodes").Path ("h2:1234").Accept(MediaType.ApplicationJson).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); JSONObject info = json.GetJSONObject("node"); string id = info.Get("id").ToString(); NUnit.Framework.Assert.AreEqual("Incorrect Node Information.", "h2:1234", id); RMNode rmNode = rm.GetRMContext().GetInactiveRMNodes()["h2"]; WebServicesTestUtils.CheckStringMatch("nodeHTTPAddress", string.Empty, info.GetString ("nodeHTTPAddress")); WebServicesTestUtils.CheckStringMatch("state", rmNode.GetState().ToString(), info .GetString("state")); }
private void DeployDirectory(OrganizationServiceContext ctx, string webresourceRoot, string directory, List <Guid> webresourcesToPublish, List <WebResource> curWebResources) { //_trace.WriteLine("DeployDirectory: " + directory); var webResSplit = webresourceRoot.Split('\\'); var fullPath = Path.Combine(webresourceRoot, directory); string[] fileEntries = Directory.GetFiles(directory); foreach (string fileName in fileEntries) { // Strip WebResource root from the filename string relativePathFileName = string.Join("\\", fileName.Split('\\').Skip(webResSplit.Count())); WebResourceFile file = new WebResourceFile { file = relativePathFileName }; DeployWebResource(ctx, webresourceRoot, webresourcesToPublish, file); WebResource webResourceListItem = curWebResources.FirstOrDefault(wr => wr.Name.ToLower() == relativePathFileName.ToLower().Replace("\\", "/")); if (webResourceListItem != null) { curWebResources.Remove(webResourceListItem); } } // Recurse into subdirectories of this directory. string[] subdirectoryEntries = Directory.GetDirectories(directory); foreach (string subdirectory in subdirectoryEntries) { DeployDirectory(ctx, webresourceRoot, subdirectory, webresourcesToPublish, curWebResources); } }
public DependencyDialog(WebResource resource, List <WebResource> allResources) { this.resource = resource; this.allResources = allResources; InitializeComponent(); }
public void RegisterWebResource(String uri, WebResourceInstance webresource) { WebResource res = dbcontext.WebResources.FirstOrDefault <WebResource>(s => s.Uri == uri); if (res == null) { if (webresource.Generator != null) { res = new WebResource { Uri = uri, Content = webresource.Generator.GetScriptText(), WebResourceType = WebResourceType.Script }; } else { res = new WebResource { Uri = uri, FileName = webresource.Uri, WebResourceType = WebResourceType.File }; } dbcontext.WebResources.Add(res); dbcontext.SaveChanges(); } else { Console.WriteLine("[x] Resource already exist"); } }
public virtual void TestQueryAll() { WebResource r = Resource(); MockNM nm1 = rm.RegisterNode("h1:1234", 5120); MockNM nm2 = rm.RegisterNode("h2:1235", 5121); MockNM nm3 = rm.RegisterNode("h3:1236", 5122); rm.SendNodeStarted(nm1); rm.SendNodeStarted(nm3); rm.NMwaitForState(nm1.GetNodeId(), NodeState.Running); rm.NMwaitForState(nm2.GetNodeId(), NodeState.New); rm.SendNodeLost(nm3); ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("nodes").QueryParam ("states", Joiner.On(',').Join(EnumSet.AllOf <NodeState>())).Accept(MediaType.ApplicationJson ).Get <ClientResponse>(); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject json = response.GetEntity <JSONObject>(); JSONObject nodes = json.GetJSONObject("nodes"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodes.Length() ); JSONArray nodeArray = nodes.GetJSONArray("node"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 3, nodeArray.Length ()); }
public void Test_AtLeastOne_GameScraped() { var scraperDataModel = new ScraperDataModel(); var logger = new Logger(); var webResource = new WebResource(new OnDataItemImpl(), logger); webResource.Initialize(scraperDataModel, null); webResource.CollectData(); Assert.NotNull(Test_PageScraper.NotEmptyGameData); Assert.False(Test_PageScraper.NotEmptyGameData.GameCountry.Equals(String.Empty)); Assert.False(Test_PageScraper.NotEmptyGameData.FirstTeam.Equals(String.Empty)); Assert.False(Test_PageScraper.NotEmptyGameData.GameDate.Equals(String.Empty)); Assert.False(Test_PageScraper.NotEmptyGameData.GameLeague.Equals(String.Empty)); Assert.False(Test_PageScraper.NotEmptyGameData.GameScore.Equals(String.Empty)); Assert.False(Test_PageScraper.NotEmptyGameData.GameTime.Equals(String.Empty)); Assert.False(Test_PageScraper.NotEmptyGameData.SecondTeam.Equals(String.Empty)); logger.LogInfo("Game Country: " + Test_PageScraper.NotEmptyGameData.GameCountry); logger.LogInfo("Game League: " + Test_PageScraper.NotEmptyGameData.GameLeague); logger.LogInfo("Game Date: " + Test_PageScraper.NotEmptyGameData.GameDate); logger.LogInfo("Game Time: " + Test_PageScraper.NotEmptyGameData.GameTime); logger.LogInfo("Game First Team: " + Test_PageScraper.NotEmptyGameData.FirstTeam); logger.LogInfo("Game Second Team: " + Test_PageScraper.NotEmptyGameData.SecondTeam); logger.LogInfo("Game Score: " + Test_PageScraper.NotEmptyGameData.GameScore); }
public static WebResource GetEmptyWebResource() { WebResource webResource = new WebResource(); webResource.WebResourceKey = Translate.It("None"); return(webResource); }
public virtual void TestNonexistNodeDefault() { rm.RegisterNode("h1:1234", 5120); rm.RegisterNode("h2:1235", 5121); WebResource r = Resource(); try { r.Path("ws").Path("v1").Path("cluster").Path("nodes").Path("node_invalid:99").Get <JSONObject>(); NUnit.Framework.Assert.Fail("should have thrown exception on non-existent nodeid" ); } catch (UniformInterfaceException ue) { ClientResponse response = ue.GetResponse(); NUnit.Framework.Assert.AreEqual(ClientResponse.Status.NotFound, response.GetClientResponseStatus ()); NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType() ); JSONObject msg = response.GetEntity <JSONObject>(); JSONObject exception = msg.GetJSONObject("RemoteException"); NUnit.Framework.Assert.AreEqual("incorrect number of elements", 3, exception.Length ()); string message = exception.GetString("message"); string type = exception.GetString("exception"); string classname = exception.GetString("javaClassName"); VerifyNonexistNodeException(message, type, classname); } finally { rm.Stop(); } }
/// <summary> /// Initializes a new instance of class UpdateForm /// </summary> /// <param name="script">Script to display or to create</param> /// <param name="service">Xrm Organization Service</param> public UpdateForm(WebResource script, IOrganizationService service) { InitializeComponent(); innerService = service; currentWebResource = script; FillControls(); }
public long GetLastModified(WebResource resource) { var request = WebRequest.Create(resource.AbsoluteUri); request.Timeout = Timeout; using (var response = request.GetResponse() as HttpWebResponse) { return response.LastModified.Ticks; } }
private void CreateButton_Click(object sender, RoutedEventArgs e) { CreatedWebResource = new WebResource() { Name = NameTextBox.Text, DisplayName = DisplayNameTextBox.Text, Description = DescriptionTextBox.Text, WebResourceType = new OptionSetValue((int.Parse(((ComboBoxItem)TypeComboBox.SelectedItem).Tag.ToString()))) }; Close(); }
private async void HandleWebResource(WebResource resource) { if (await CompatibilityManager.IsAvailableWebResource(resource.Path)) { if (this.OnWebsiteDisplayRequested != null) { await this.displayDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.OnWebsiteDisplayRequested(new Uri(resource.Path)); }); } } else { // give it to the agent? } }
DownloadInfo GetDownloadInfo(WebResource resource) { if (downloadInfoCollection.Contains(resource.AbsoluteUri)) { return downloadInfoCollection[resource.AbsoluteUri]; } else { var downloadInfo = new DownloadInfo(resource.AbsoluteUri); downloadInfoCollection.Add(downloadInfo); return downloadInfo; } }
void ResolveLocalResource(WebResource resource) { if (resource.LocalResource != null) return; var localUri = CreateLocalUri(resource.AbsoluteUri); resource.LocalResource = StorageResourceLoader.Instance.LoadResource(localUri) as StorageResource; }
private CreateRequest GetCreateWebResourceRequest(WebResource resource) { var createRequest = new CreateRequest { Target = resource }; if (!string.IsNullOrWhiteSpace(DefaultConfiguration.SolutionUniqueName)) { createRequest.Parameters.Add("SolutionUniqueName", DefaultConfiguration.SolutionUniqueName); } return createRequest; }
private CreateRequest GetCreateWebResourceRequest(string entityLogicalName, AttributeTemplate attributeTemplate) { var contents = CommonHelper.EncodeTo64(string.Format(DefaultConfiguration.WebResourceHtmlTemplate, attributeTemplate.DisplayName)); var webResource = new WebResource { Content = contents, DisplayName = attributeTemplate.DisplayNameShort, Description = attributeTemplate.Description, Name = entityLogicalName + "_" + attributeTemplate.LogicalName, LogicalName = WebResource.EntityLogicalName, WebResourceType = new OptionSetValue((int) Enums.WebResourceTypes.Html) }; var createRequest = new CreateRequest { Target = webResource }; if (!string.IsNullOrWhiteSpace(DefaultConfiguration.SolutionUniqueName)) { createRequest.Parameters.Add("SolutionUniqueName", DefaultConfiguration.SolutionUniqueName); } return createRequest; }
/// <summary> /// Set a resource to be used for the specified URL. /// Note that these resources are kept in the memory. /// If you need to handle a lot of custom web resources, /// subscribing to RequestHandler.GetResourceHandler /// and loading from disk on demand /// might be a better choice. /// </summary> /// <param name="url"></param> /// <param name="resource"></param> public void SetWebResource(string url, WebResource resource) { webResources[url] = resource; }
public object Load(WebResource resource, Type type) { ResolveLocalResource(resource); logger.Debug("Cache: {0}", resource.LocalResource.AbsoluteUri); // キャッシュが存在しない場合にのみ自動的にダウンロードを開始する。 // タイムスタンプ比較からの自動的なダウンロード可否判定を行わない。 // キャッシュが古い場合に最新をダウンロードするか否かは、ユーザ主導で決定する。 // なお、ゲームでは、Region の初回選択時に発生するダウンロードのみとし、 // ゲーム開始後に最新をダウンロードすることは想定しない。 // エディタでは、最新を確認した後、ユーザ判断により再ダウンロードが発生しうる。 if (!resource.LocalResource.Exists()) { logger.Debug("No cache exists."); Download(resource); } else { logger.Debug("Cache exists."); } return assetManager.Load(resource.LocalResource, type); }
private void CancelButton_Click(object sender, RoutedEventArgs e) { CreatedWebResource = null; Close(); }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// basic create, retrieve, update, and delete entity operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); //<snippetImportWebResources1> //Read the descriptive data from the XML file XDocument xmlDoc = XDocument.Load("../../ImportJob.xml"); //Create a collection of anonymous type references to each of the Web Resources var webResources = from webResource in xmlDoc.Descendants("webResource") select new { path = webResource.Element("path").Value, displayName = webResource.Element("displayName").Value, description = webResource.Element("description").Value, name = webResource.Element("name").Value, type = webResource.Element("type").Value }; // Loop through the collection creating Web Resources int counter = 0; foreach (var webResource in webResources) { //<snippetImportWebResources2> //Set the Web Resource properties WebResource wr = new WebResource { Content = getEncodedFileContents(@"../../" + webResource.path), DisplayName = webResource.displayName, Description = webResource.description, Name = _customizationPrefix + webResource.name, LogicalName = WebResource.EntityLogicalName, WebResourceType = new OptionSetValue(Int32.Parse(webResource.type)) }; // Using CreateRequest because we want to add an optional parameter CreateRequest cr = new CreateRequest { Target = wr }; //Set the SolutionUniqueName optional parameter so the Web Resources will be // created in the context of a specific solution. cr.Parameters.Add("SolutionUniqueName", _ImportWebResourcesSolutionUniqueName); CreateResponse cresp = (CreateResponse)_serviceProxy.Execute(cr); //</snippetImportWebResources2> // Capture the id values for the Web Resources so the sample can delete them. _webResourceIds[counter] = cresp.id; counter++; Console.WriteLine("Created Web Resource: {0}", webResource.displayName); } //</snippetImportWebResources1> DeleteRequiredRecords(promptforDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
private void AddNode(string[] nameParts, int index, object parent, WebResource wrObject) { if (index == 0) { if (((TreeView)parent).Nodes.Find(nameParts[index], false).Length == 0) { var node = new TreeNode(nameParts[index]); node.Name = node.Text; if (index == nameParts.Length - 1) { node.Tag = wrObject; int imageIndex = ((OptionSetValue)wrObject.WebResourceEntity["webresourcetype"]).Value + 1; node.ImageIndex = imageIndex; node.SelectedImageIndex = imageIndex; } else { node.ImageIndex = 0; node.SelectedImageIndex = 0; } TreeViewDelegates.AddNode((TreeView)parent, node); AddNode(nameParts, index + 1, node, wrObject); } else { AddNode(nameParts, index + 1, ((TreeView)parent).Nodes.Find(nameParts[index], false)[0], wrObject); } } else if (index < nameParts.Length) { if (((TreeNode)parent).Nodes.Find(nameParts[index], false).Length == 0) { var node = new TreeNode(nameParts[index]); node.Name = node.Text; if (index == nameParts.Length - 1) { node.Tag = wrObject; int imageIndex = ((OptionSetValue)wrObject.WebResourceEntity["webresourcetype"]).Value + 1; node.ImageIndex = imageIndex; node.SelectedImageIndex = imageIndex; } else { if (index == 0) { node.ImageIndex = 0; node.SelectedImageIndex = 0; } else { node.ImageIndex = 1; node.SelectedImageIndex = 1; } } TreeViewDelegates.AddNode((TreeNode)parent, node); AddNode(nameParts, index + 1, node, wrObject); } else { AddNode(nameParts, index + 1, ((TreeNode)parent).Nodes.Find(nameParts[index], false)[0], wrObject); } } }
private void tvWebResources_DragDrop(object sender, DragEventArgs e) { var errorList = new List<string>(); var tv = (TreeView)sender; Point location = tv.PointToScreen(Point.Empty); var currentNode = tvWebResources.GetNodeAt(e.X - location.X, e.Y - location.Y); var files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (var file in files) { var fi = new FileInfo(file); var tempNode = currentNode; string name = tempNode.Text; while (tempNode.Parent != null) { name = string.Format("{0}/{1}", tempNode.Parent.Text, name); tempNode = tempNode.Parent; } //Test valid characters if (WebResource.IsInvalidName(fi.Name)) { errorList.Add(file); } else { var webResource = new Entity("webresource"); webResource["content"] = Convert.ToBase64String(File.ReadAllBytes(file)); webResource["webresourcetype"] = new OptionSetValue(WebResource.GetTypeFromExtension(fi.Extension.Remove(0, 1))); webResource["name"] = string.Format("{0}/{1}", name, fi.Name); webResource["displayname"] = string.Format("{0}/{1}", name, fi.Name); var wr = new WebResource(webResource, file); var node = new TreeNode(fi.Name) { ImageIndex = WebResource.GetImageIndexFromExtension(fi.Extension.Remove(0, 1)) }; node.SelectedImageIndex = node.ImageIndex; node.Tag = wr; currentNode.Nodes.Add(node); currentNode.Expand(); } } if (errorList.Count > 0) { MessageBox.Show("Some file have not been added since their name does not match naming policy\r\n" + string.Join("\r\n", errorList)); } }
private void CreateWebResource(XElement webResourceInfo) { try { //Create the Web Resource. WebResource wr = new WebResource() { Content = getEncodedFileContents(ActivePackage.Attribute("rootPath").Value + webResourceInfo.Attribute("filePath").Value), DisplayName = webResourceInfo.Attribute("displayName").Value, Description = webResourceInfo.Attribute("description").Value, LogicalName = WebResource.EntityLogicalName, Name = GetWebResourceFullNameIncludingPrefix(webResourceInfo) }; wr.WebResourceType = new OptionSetValue((int)ResourceExtensions.ConvertStringExtension(webResourceInfo.Attribute("type").Value)); //Special cases attributes for different web resource types. switch (wr.WebResourceType.Value) { case (int)ResourceExtensions.WebResourceType.Silverlight: wr.SilverlightVersion = "4.0"; break; } // ActivePublisher.CustomizationPrefix + "_/" + ActivePackage.Attribute("name").Value + webResourceInfo.Attribute("name").Value.Replace("\\", "/"), Guid theGuid = _serviceProxy.Create(wr); //If not the "Default Solution", create a SolutionComponent to assure it gets //associated with the ActiveSolution. Web Resources are automatically added //as SolutionComponents to the Default Solution. if (ActiveSolution.UniqueName != "Default") { AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest(); scRequest.ComponentType = (int)componenttype.WebResource; scRequest.SolutionUniqueName = ActiveSolution.UniqueName; scRequest.ComponentId = theGuid; var response = (AddSolutionComponentResponse)_serviceProxy.Execute(scRequest); } } catch (Exception e) { AddMessage("Error: " + e.Message); return; } }
private void RetrieveWebResources(Guid solutionId, List<int> types) { EntityCollection scripts = wrManager.RetrieveWebResources(solutionId, types); foreach (Entity script in scripts.Entities) { var wrObject = new WebResource(script); string[] nameParts = script["name"].ToString().Split('/'); AddNode(nameParts, 0, tvWebResources, wrObject); } }
private void UpdateWebResource(XElement webResourceInfo, WebResource existingResource) { try { //These are the only 3 things that should (can) change. WebResource wr = new WebResource() { Content = getEncodedFileContents(ActivePackage.Attribute("rootPath").Value + webResourceInfo.Attribute("filePath").Value), DisplayName = webResourceInfo.Attribute("displayName").Value, Description = webResourceInfo.Attribute("description").Value }; wr.WebResourceId = existingResource.WebResourceId; _serviceProxy.Update(wr); } catch (Exception e) { AddMessage("Error: " + e.Message); return; } }
private void UpdateWebResource(OrganizationService orgService, WebResource choosenWebresource, string selectedFile) { choosenWebresource.Content = GetEncodedFileContents(selectedFile); var updateRequest = new UpdateRequest { Target = choosenWebresource }; orgService.Execute(updateRequest); }
private void CreateWebResources(Worksheet webresourceSheet, EntityTemplate entityTemplate, string excelFile, List<Exception> error, List<Exception> warning) { var xlsRange = webresourceSheet.UsedRange; for (var currentRow = webresourceTemplateFirstRow; currentRow < xlsRange.Rows.Count; currentRow++) { var logicalName = GetCellValueAsString(xlsRange, currentRow, webresourceLogicalNameColumn).Replace("\n", ""); var displayName = GetCellValueAsString(xlsRange, currentRow, webresourceDisplayNameColumn).Replace("\n", ""); var description = GetCellValueAsString(xlsRange, currentRow, webresourceDescriptionColumn).Replace("\n", ""); var type = GetCellValueAsString(xlsRange, currentRow, webresourceTypeColumn).Replace("\n", ""); var content = CommonHelper.EncodeTo64(GetCellValueAsString(xlsRange, currentRow, webresourceContentColumn)); var resourceType = CommonHelper.GetWebResourceType(type, excelFile, error, warning); if (resourceType < 0) { continue; } var webResource = new WebResource { Content = content, DisplayName = displayName, Description = description, Name = logicalName, LogicalName = WebResource.EntityLogicalName, WebResourceType = new OptionSetValue(resourceType) }; entityTemplate.WebResource = entityTemplate.WebResource ?? new List<WebResource>(); entityTemplate.WebResource.Add(webResource); } }