Ok am am very new to Umbraco/C# and what I am trying to do is loop through a custom media type to build banners for the home page of my application and the #bannerUrl always returns the images property id and not the file path to the resource. How would you go about retrieving the image file path from a custom media type created in Umbraco.
See code for example:
var mediaFolder = Umbraco.Media(mediaFolderId);
var banners = mediaFolder.Children();
foreach (var banner in banners)
{
var bannerUrl = banner.image;
<div style="background-image:url(#bannerUrl);"></div>
}
The variable bannerUrl always returns the image id by default and not the file path for the URL. How can I get the file path working? When inspecting the contents of the banner object in the debugger in VS I notice of the Url property has the following error:
Url = 'banner.Url' threw an exception of type 'System.NotSupportedException'
You would of though I could use something along the .Url lines but that dose not seem to work, so any suggestions how I would go about getting the URL the image property in Umbraco using the Dynamic way.
Thanks.
Solutioin if anyone happens to stumbles upon this:
var bannerId = Umbraco.Media(banner.image); //banner.image is the property id.
var bannerUrl = bannerId.Url;
To do the same within an MVC controller / API Contoller once you have the "media ID" you can also use the UmbracoHelper.
var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
var image = umbracoHelper.Media(mediaID); // mediaID = the (int)ID of the media
var imageURL = image.url; // imageURL now has the site root relative path of the media item
It's much better to use strongly typed models in Umbraco nowadays:
var bannerMediaItem = Umbraco.TypedMedia(banner.image); //banner.image is the property id.
var bannerUrl = bannerMediaItem.Url;
Related
i could successfully add bugs into TFS programmatically,
var tfsURI = new Uri("http://test:8080/tfs");
var networkCredential1 = new NetworkCredential("test", "test!");
ICredentials credential = (ICredentials)networkCredential1;
Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(credential);
VssCredentials vssCredentials = new VssCredentials(winCred);
using (TfsTeamProjectCollection collection = new TfsTeamProjectCollection(tfsURI, vssCredentials))
{
collection.EnsureAuthenticated();
WorkItemStore workItemStore = collection.GetService<WorkItemStore>();
Project teamProject = workItemStore.Projects["Test"];
WorkItemType workItemType = teamProject.WorkItemTypes["Bug"];
WorkItem Defect = new WorkItem(workItemType);
FileInfo fi = new FileInfo(#"C:\\Document.docx");
Attachment tfsAttachment = new Attachment(fi.FullName);
Defect.Attachments.Add(tfsAttachment);
Defect.Title = "Testing from VS to TFS Bug";
Defect.Description = "Testing from VS to entered Bug in to TFS.";
Defect.Fields["Assigned To"].Value = "Test";
Defect.Save();
}
I have Newly Created WorkItem ID. Defect.ID provides me workitemID.
How can i get the URL of newly created WOrkItem by passing ID.
Let Me know if any API available? i need HTML Link of Newly created WorkItem so that anyone when click on URL, created WorkItem will be Open.
You could use Rest API to directly return a single work item
GET https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=5.1
However this will only get a url to the json data for the bug created, not the URL of the HTML page of the bug. Such as below output that I got
https://tfsurl:8080/_apis/wit/workItems/workitemID
When I load the above link in browser, I got JSON data, instead of the HTML page for the work item I created.
Guess you want to fetch the url of HTML in web portal.
https://tfsurl:8080/tfs/DefaultCollection/PatrickProject/_workitems/edit/172/
In my case it was this and here DefaultCollection is the collection name and the PatrickProject is the project name. I used this url and got rid of the id '172' in this case and use the ID of newly created work item. This would return the URL to go to the work item HTML page.
So it's a fixed format, if you have Newly Created WorkItem ID and collection name , project name, you just need to follow above format and change the last value of work item ID. That's it , ignore of which work item type you created.
Hope this Helps!
I found solution after lots of research, may help to someone in future:
var tfsURI = new Uri("http://test:8080/tfs");
var networkCredential1 = new NetworkCredential("test", "test!");
ICredentials credential = (ICredentials)networkCredential1;
Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(credential);
VssCredentials vssCredentials = new VssCredentials(winCred);
using (TfsTeamProjectCollection collection = new TfsTeamProjectCollection(tfsURI, vssCredentials))
{
collection.EnsureAuthenticated();
TswaClientHyperlinkService hyperlinkService =
collection.GetService<TswaClientHyperlinkService>();
String TFSurl = hyperlinkService.GetWorkItemEditorUrl(17648).ToString(); //17648 WorkItem ID
}
Im trying to move a file from one folder to another using the Google Drive API v3. I found documentation how to this here. I used the .NET sample code from the documentation page and created a method that looks like this:
public ActionResult MoveFile(string fileToMove, string destination)
{
DriveService service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = <USER CREDENTIAL>,
ApplicationName = "APPNAME"
});
var searchFiles = service.Files.List();
searchFiles.Corpus = FilesResource.ListRequest.CorpusEnum.User;
searchFiles.Q = "name = '" + fileToMove + "'";
searchFiles.Fields = "files(*)";
string fileToMoveId = searchFiles.Execute().Files[0].Id;
searchFiles.Q = "name = '" + destination + "'";
string destinationId = searchFiles.Execute().Files[0].Id;
//Code used from documentation
// Retrieve the existing parents to remove
var getRequest = service.Files.Get(fileToMoveId);
getRequest.Fields = "parents";
var file = getRequest.Execute();
var previousParents = String.Join(",", file.Parents);
// Move the file to the new folder
var updateRequest = service.Files.Update(file, fileToMoveId);
updateRequest.Fields = "id, parents";
updateRequest.AddParents = destinationId;
updateRequest.RemoveParents = previousParents;
file = updateRequest.Execute();
return RedirectToAction("Files", new {folderId = destinationId});
}
When I execute this code I get the following error:
The parents field is not directly writable in update requests. Use the
addParents and removeParents parameters instead.
The error doesn't really makes sense to me because this code sample came from the documentation page itself. I can't figure out what other paramters they mean. What addParents and removeParents parameters do they mean? Are updateRequest.AddParents and updateRequest.RemoveParents not the right parameters?
Ok here is the problem.
var updateRequest = service.Files.Update(file, fileToMoveId);
The method is requiring that you send a body of a file to be updated. This normally makes sense as any changes you want to make you can add to the body.
Now the problem you are having is that you got your file from a file.get. Which is totally normal. This is how you should be doing it. THe problem is there are some fields in that file that you cant update. So by sending the full file the API is rejecting your update. If you check Files: update under Request body you will see which fiends are updateable.
Issue:
Now this is either a problem with the client library or the API I am going to have to track down a few people at Google to see which is the case.
Fix:
I did some testing and sending an empty file object as the body works just fine. The file is moved.
var updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileToMove.Id);
updateRequest.AddParents = directoryToMove.Id;
updateRequest.RemoveParents = fileToMove.Parents[0];
var movedFile = updateRequest.Execute();
This method works well when working in your own drive, but not in a team drive where a file (folder) can only have 1 parent strictly. I do not have the solution in a team drive
I've been able to integrate some scheduled web service calls into my Umbraco site that uses the response from the web service to update some of the content on my site. I can now handle text and some various other content but my main query is how should I deal with images that are delivered from the web service in byte[] format?
For a little context, the site I am developing uses web service calls to retreive the details of a product which users of our desktop software have created on their machine. Each of these products is pulled via a web service call into my Umbraco site and created as an individual product page under the parent node of products.
Products > Product
Each product has several properties such as an ID, a name, notes and a collection of images. Once I have called my web service I am creating these pages using the following code:
//Construct Service Request
svc = new StaticDataWebServiceSoapClient();
var response = svc.GetProducts(ref compressionSoapHeader,ref managedUserHeader);
//Umbraco Content Services
int rootID = 1117;
IContentService cs = ApplicationContext.Current.Services.ContentService;
var remove = cs.GetChildren(rootID).Where(x => x.ContentType.Alias == "product");
foreach (var child in remove)
{
cs.Delete(child);
}
foreach(var product in response){
var item = cs.CreateContent(product.ContinentName, rootID, "product");
//Set the properties using the SetValue method, passing in the alias of the property and the value to assign to it
item.SetValue("continentId", product.Id);
item.SetValue("continentName", product.ProductName);
item.SetValue("continentNotes", product.Notes);
foreach (var image in product.Images)
{
??? destination.SetValue("ProductImages", image._Image); ???
image.Caption;
image.FileName;
image.ImageId;
image.KeywordID;
}
cs.SaveAndPublishWithStatus(item);
}
As you can see from the code, each product has several images associated with it that I would also like to pull into the site and associate with the product page that is being created. How would I go about doing this? Would I need to use the Media Service and a specific datatype or would this structure fit easily into a multiple media picker?
You may find it easiest to loop through the images once you've retrieved them and create a new Media item for each of them, and then associate them with the product using a property based on something like the Multiple Media Picker datatype as you noted.
Because this data type stores it's values as a comma separated list of id's you could use something like the following:
// Setup
IContentService cs = ApplicationContext.Current.Services.ContentService;
var mediaService = ApplicationContext.Current.Services.MediaService;
int mediaRootId = 1111; // Replace with the id of your media parent folder
// Replace the image looping logic with the following:
// MultiMediaPicker stores it's values as a commma separated string of ids.
string imageIds = string.Empty;
foreach (var image in product.Images)
{
var fileName = image.FileName; // Assumes no path information, just the file name
var ext = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
if (!UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles.Contains(ext))
{
var mediaType = Constants.Conventions.MediaTypes.File;
if (UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes.Contains(ext))
mediaType = Constants.Conventions.MediaTypes.Image;
var f = mediaService.CreateMedia(fileName, mediaRootId, mediaType);
// Assumes the image._Image is a Stream - you may have to do some extra work here...
f.SetValue(Constants.Conventions.Media.File, fileName, (Stream)image._Image); // Real magic happens here.
mediaService.Save(f);
imageIds += (imageIds.Length > 0 ? "," : "") + f.Id;
}
}
// Get the relevant property on the new item and save the image list to it.
var imagesProp = item.Properties.Where(p => p.Alias == "productImages").FirstOrDefault();
imagesProp.Value = imageIds;
Note - I haven't tested this code out, so ymmv.
I would like to know the page views for a certain page/url only.
Is there a way to add the url to the Google query? Baseurl doesn't seem to work.
DataQuery PageViewQuery = new DataQuery(DataFeedUrl)
{
Ids = ProfileID,
Dimensions = "ga:date",
Metrics = "ga:pageviews",
Sort = "ga:date",
GAStartDate = (DateTime.Now).AddDays(-7).ToString("yyyy-MM-dd"),
GAEndDate = (DateTime.Now).ToString("yyyy-MM-dd")
};
You might try ga:pagePath (plus ga:hostname if you need to retrieve a full URL), or if you have unique page titles ga:pageTitle should be a valid workaround.
Full documentation of dimensions and metric is here: https://developers.google.com/analytics/devguides/reporting/core/dimsmets.
I'm forming a newsletter with links to various html modules within my DNN website. I have access to each of their ModuleID's and I'm wanting to use that to get the url. The current approach (made by a third party developer) worked, but only to a degree. The url's are incorrectly formed when the Modules are located deeper in the website.
For example module located at www.website.com/website/articles.aspx is works fine, but a module located www.website.com/website/articles/subarticles.aspx won't. I know this is because the url is incorrectly formed.
Here's the current code:
DotNetNuke.Entities.Modules.ModuleController objModCtrlg = new DotNetNuke.Entities.Modules.ModuleController();
DotNetNuke.Entities.Modules.ModuleInfo dgfdgdg = objModCtrlg.GetModule(ContentMID);
TabController objtabctrll = new TabController();
TabInfo objtabinfoo = objtabctrll.GetTab(tabidfrcontent);
string tabnamefremail= objtabinfoo.TabName;
moduletitlefrEmail = dgfdgdg.ModuleTitle;
string readmorelinkpath = basePath + "/" + tabnamefremail + ".aspx";
ContentMID is the current module ID I'm looking at. I've tried to use Globals.NavigateURL, but that always crashes with Object reference not set to an instance of an object. error. Same thing when I use objtabinfoo.FullUrl so I'm currently at a loss as to how I get the specific modules URL.
EDIT: Here's some more code as to how the tabId is retrieved.
IDictionary<int, TabInfo> dicTabInfo12 = new Dictionary<int, TabInfo>();
ContentMID = Convert.ToInt32(dsNewsList.Tables[0].Rows[i]["ModuleID"]);
dicTabInfo12 = objTabctrl.GetTabsByModuleID(ContentMID);
if (dicTabInfo12.Count > 0)
{
string tester = ""; //Debug
foreach (KeyValuePair<int, TabInfo> item1 in dicTabInfo12)
{
tabidfrcontent = item1.Key;
}
}
You really should be using NavigateUrl to build the links ance if you have the tabid, you are golden.
string readMoreLinkPath = NavigateUrl(tabidfrcontent);
Nice and simple
Okay, colleague suggested this and it works great within a scheduler.
string linkPath = basePath + "/Default.aspx?TabID=" + tabID;
Will Navigate you to the correct tab ID. So this would be the best solution if you're forced to work within a scheduler where you can't use NavigateUrl without some major workarounds.