2sxc - Access an adam file by unique identifier - razor

I need to access an ID to an adam file setup like this:
MyDocument is the field name, where users can load an image or whatever.
In a list style view, users will click a link that activates a detail view for that image.
The link will be something like mysite.com/mytab/detailsforfile/fileId
The details view will parse the fileId and load the image.
So, two questions:
How can I access an ID for that adam file that later allows me to load that file based on that id?
How can I access the URL of the file based on the ID created?
Is the native DNN file: 123 the only way? Or does 2sxc or adam have some specific ids?
Edit:
A practical example would probably help:
This list view will have:
#foreach(var car in eCars) {
<div>
<strong>#car.Name</strong>
<img class="img-fluid" src="#car.carImageOne">
See full image...
<img class="img-fluid" src="#car.carImageTwo">
See full image...
</div>
}
And the details view:
#{
var qsImageId = Request.QueryString["whatever"];
//cast and double check the qs int
var imageURL = ??; // How do I get the file url based on the id?
}
<div>
//embed nice frame, ads, whatever
<img class="img-fluid" src="#imageURL">
</div>

The IDs are normal IDs from Dnn/Oqtane
To get the "raw" data use the Get method, and set convertLinks: false - see
https://docs.2sxc.org/api/dot-net/ToSic.Sxc.Data.IDynamicEntity.html#ToSic_Sxc_Data_IDynamicEntity_Get_System_String_System_String_System_String_System_Boolean_System_Nullable_System_Boolean__
To then get the file id back could be challenging. The 2sxc APIs aren't for public use and could change, so probably best to use DNN APIs to get it.
Alternative is to pass the entity-id to the details page, and there just get the entity and work with that - which is probably much easier.

To get the file ID I used this:
var getFile = AsAdam(Entity, "field").Files as System.Collections.Generic.IEnumerable<dynamic>;
get fileId = getFile.First().FileId;
To get the url from the id:
var myFile = FileManager.Instance.GetFile(FileId);
var myurl = FileManager.Instance.GetUrl(myFile);

Related

External image using img src not allowing integer parameter

I am trying to get an image from an external source in Play Framework. When working with just the string this works fine, but I need to pass to the controller an Integer also but this always give me a not applicable to String error. I think this is because of the img src html tag I am using. item.Myjob is the string and works fine by itself, item.MyItem is the integer
<img src ="#routes.ImagesController.getImage(item.MyJob,Item.MyItem)"/>
My plan is to pass the parameters to the image controller from the parameters I have to make up the path and the image file name and then return the image. Or any other advice on how this can be achieved. Thanks
Why you want to do this?
Why not pass a list of items with their image ids, and a for loop; if you want to get the list of items and their images? Something like:
//In controller
case class Item (name: String, picId: Int, whateverElse: Any)
//In your views
#(items: List[Item])
#for(item <- items){
#item.name
<img src="whateverPath/#item.picId">
}
or...
In a case you have a small application and unique items, you could simply make the image ids the same as items' names; so you don't need to look for it.

How to add images in an html file?

Anytime I have read an article on html and images, I have seen an anchor tag like this:
<img src="http://www.tizag.com/pics/htmlT/sunset.gif" />
However, in my case I have stored the image in AWS-S3 and I am reading image from S3. This, I do not upfront have a path like "http://www.tizag.com/pics/htmlT/sunset.gif"
So what is the most common technique to embed image in the html page when image is stored in S3, and the path to image is not known ?
In case my question is confusing, I will ask it differently.
I am building a project, which is simple. Whenever user is logged in he gets a page saying "Welcome" and below welcome note is is profile picture.
But, assume I have 10 users, each of these 10 users will have a different URL to the image.
eg:
<img src = "http:bucket.amazonaws.com/USER1'> for user 1
<img src = "http:bucket.amazonaws.com/USER2'> for user 2
and so on.
So the image I will display is not known until run-time and path to image is dependent on who logs in.
How to make my HTML page smart so that the image src is not a constant and can be made flexible depending on who logs in ?
SOLUTION IN JSP, WHICH I COULD DO, THANKS TO SO MANY ANSWERS:
<body>
<% String url = (String)request.getAttribute("url"); %>
<img src = <%= url %>></img>
</body>
This JSP code is called from the servlet.
request.setAttribute("url", "URL to image.");
RequestDispatcher view = request.getRequestDispatcher("URLImage.jsp");
view.forward(request, response);
You require some kind of server side programming language to generate the the paths for the image dynamically for each user. Anyway you do have a setup for the users to login. For that, I believe you have some kind of framework in some server side scripting language like PHP(Laravel, Wordpress, CodeIgniter), Java(Spring), Ruby(Rails), Python(Django).
So when a user logs in, your login script should validate the user and you will render a particular html page. And you should show the name of the user and a particular image. In PHP or Ruby on Rails you can embed the actual PHP code or ruby code in HTML.
In PHP, like this :
<html>
<head> </head>
<body>
<!-- say PHP Session varibale contains the logged in user's name & bucket name -->
<img src="<?php echo "https://"+ $_SESSION["bucket_name"] +".amazonaws.com/"+$_SESSION["username"] ?>" />
</body>
</html>
In Ruby on Rails, like this:
<html>
<head> </head>
<body>
<!-- say Ruby - Rails controller passes #username & #bucketname to view -->
<img src="<%= "https://"+ #bucketname +".amazonaws.com/" + #username %>" />
</body>
</html>
In Python - Django, like this :
<html>
<head> </head>
<body>
<!-- In Python - Django Suppose you pass context variables username & bucketname to template -->
<img src="https://{{ bucketname }}.amazonaws.com/{{ username }}" />
</body>
</html>
So what I would suggest is, you get familiar with the server side scripting language that you intend to use or are already using and manipulate the url to be generated based on logged in user accordingly.
If your bucket was named my-bucket and the image file was named my-image.png, then the format for the url would be http://my-bucket.s3.amazonaws.com/my-image.png.
In order to access the file though, you need to have a policy attached to your bucket that allows anyone to access the file. Below is a policy that works for this example.
{
"Id": "some-policy-id",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "some-statement-id",
"Principal": "*",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::my-bucket/my-image.png"
}]
}
See the docs for more information about accessing a bucket.
Also note that the bucket name must be DNS compatible for this to work. See here under Rules for Bucket Naming.
My suggestion is:
<img src = "http:bucket.amazonaws.com/USER1'> for user 1
<img src = "http:bucket.amazonaws.com/USER2'> for user 2
according to your examples in user1 and user2 having same path is http:bucket.amazonaws.com/ make it common for all and put variable after that and according to your user id fetch image from there.
like <img src = "http:bucket.amazonaws.com/<?php echo $userimg; ?>'
or fetch img path from database according to users
You can use javascript / jQuery:
<script type="text/javascript">
$(document).ready(function(){
var userName = getUserNameValue;
document.getElementById("<%= loginImg.ClientID %>").src = "http:bucket.amazonaws.com/" + userName;
});
</script>
with html:
<img id="loginImg" src="default.img" />
You should be able to handle this like a simple 'insert your name here' kind of Hello World exercise.
Since the user is logged in, you should have at least some sort of information from the user, or can get it - username, first/last name, uniqueID, etc. Ideally when the user logs in, your server will provide you with an image filename, but whatever.
Store that uniqueID into a variable in your JS. This will be used to build your URL in JS.
Then, have the root path of your images in a separate variable.
var uniqueID = 'avatar_e2fbfbcbb52d_128'; // from login
var urlPrefix = 'http://www.tizag.com/pics/htmlT/';
var imageURL = urlPrefix + uniqueID + '.gif';
var imgNode = document.createElement("IMG");
imgNode.src = imageURL;
document.getElementById('imageDiv').appendChild(imgNode);
Then, in your HTML,
<div id='imageDiv></div>
I can tell you the approach since you don't have a code to edit or look into.
You can have an ajax call to your server once the user logged in, get the image URL from there or if you are having any back-end language then get the url from there.
Now the hard part, assigning the URL to the img source tag, so if you are doing the ajax call just store the data(URL) into the JavaScript variable and give img src as that variable, if you are doing it using server side language then also you can do the same, different languages have different way to do it and you need to google it out, or you can have the hidden field with id, assign that hidden field that value (URL) in your JSP or ASP page and use that in the img src.
Hope the approach works. I am a dot net developer and you are java developer so can't tell you the exact code.
Its very simple just try this out. I have added your image path just run this code.
<!DOCTYPE html>
<html>
<body>
<h2>Spectacular Mountain</h2>
<img src="http://www.tizag.com/pics/htmlT/sunset.gif" style="width:304px;height:228px;">
</body>
</html>

Edit CSS Using Razor/Sitecore

We have a component that contains a background image. Our front-end guy needs it to be loaded through CSS (i.e. background: url(/*path here*/)...). The following is a possible solution we came up with:
#string src = // Get image path from Sitecore().Field("Picture");
<div style="background: url(#src) left top no-repeat;"> ... </div>
However, there are two problems with this approach:
It makes it very difficult for the content editor to swap out the image. They will have to manually change it through edit item.
It feels like a hack/workaround.
So the question is as follows: Is there a way to edit the CSS of an element through Razor/Sitecore? Specifically, the background: field.
I had a similar case and I used :
<footer class="layout_footer" style="background-color: #Model.BackgroundColor">
on view rendering (cshtml file)
And on the model we have :
public string BackgroundColor
{
get
{
Sitecore.Data.Fields.ImageField imgField =((Sitecore.Data.Fields.ImageField)item.Fields["BackgroundImage"]);
return Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem);
}
}
For editing this field in page editor you can use Sitecore Field Editor from a command : http://blog.istern.dk/2012/05/21/running-sitecore-field-editor-from-a-command/
Check for edit mode, and display in edit mode a editable field. Also create a Custom Experience Button from the Field Editor Button Type. You can also display. See User friendly developing with the Sitecore Experience Editor
#string src = // Get image path from Sitecore().Field("Picture");
<div style="background: url(#src) left top no-repeat;">
#if (IsInEditingMode)
{
<h3>Backgroiund Picture: #Editable(m => m.Picture)</h3>
}
</div>
There is no Sitecore extension method which will do this out of the box (i.e. #Html.Sitecore().Field("fieldName") will not work here as it would render the entire image tag (also a load of other non-image markup in page editor mode) as you probably know.
The method that #sitecore climber mentions is useful for controller renderings (or view renderings with a custom RenderingModel). If you want to stick with simple view renderings (i.e. not create a RenderingModel) then you could create a Html extension method which can be re-used on any view rendering. This could be something like the following:
public string ImageFieldSrc(this SitecoreHelper sitecoreHelper, string fieldName, Item item = null)
{
if (item == null) {
item = sitecoreHelper.CurrentItem;
}
var imageField = new ImageField(item.Fields[fieldName]);
var mediaItem = imageField.MediaItem;
var mediaUrl = MediaManager.GetMediaUrl(mediaItem);
mediaUrl = HashingUtils.ProtectAssetUrl(mediaUrl); //if you want to use media request protection (adding the hash onto the end of the URL, use this line
return mediaUrl;
}
It's worth noting that if you are using Sitecore 7.5 or above there is a feature to protect media URLs with a hash to prevent malicious DoS type attacks described in this blog post by Adam Najmanowicz.
In summary; if you are using Sitecore 7.5+ and you use media hashing then you will need to call HashingUtils.ProtectAssetUrl on the media URL if it is to respect size parameters.

pChart:render the image to browser and embed in html

I have a class name 'MonthReport.class.php' and its structure like the following:
class MonthReport{
.....
//some member variables
public function pieChart(){
........
//the image data comes from mysql and data belongs to a specified user
$myPicture->Stroke();
}
public function lineChart(){
........
//the image data comes from mysql and data belongs to a specified user
$myPicture->Stroke();
}
public function render html(){
$html.=str1<<<
.....
//some html code
str1;
$html.=<<<str2
<img src="$this->pieChart()" /> //can not work
str2;
}
}
when I call the pieChart() function with this in the place src it will overwrites my entire page and just shows the image.how can I do this?
I try to render the image in a separate page but the image need some specified user data eg.'userId'.in others words when i new a object, it specify the userId,so I can not render the image in a separate page.
sorry for my bad english!but I need your help!thanks in advancd!
Your question is a little unclear but if your problem is what I am assuming it to be, then I used to have similar issues (Graphic created that is just an image with all of the rest of my page content not displaying). My solution was to generate a temporary image using pchart then embed that file in the html
$myfilename = "temp_image.png"; // temp file name
$myPicture = new pImage(700,500,$myData);
// other image creation code....
$myPicture->Render($myfilename); // generate image "temp_image.png"
$image_html = '<img src="' . $myfilename . '">'; //generate the link
print("$htmlline");
Again there is some guesswork going on here as your question is unclear. The above works for me though and enables me to embed an image created on the fly by pChart into my php pages.

How to Get Image From <img src=""> Tag?

When I want to render a picture, I send a request to the server with the associated picture to render. What's odd is how it's returned:
<img src="https://blargh.com/displayTemplate?templateid=template1">
Where that link is supposed to be the image data.
Using this, how can I transform that into an image that I can display to the user? This is for a facebook app, I can't just embed the HTML. It needs to be displayed inside my AS App as a Bitmap or Sprite or anything, really. Trying to convert it to a Bitmap or BitmapData have failed...
The only other information I can give is that my templateLoader is a Loaderand its .data is supposed to carry the HTML.
Something like this:
var data:String = '<img src="https://blargh.com/displayTemplate?templateid=template1">';
// grab the src attribute
var url:Array = data.match(/<img src=\"(.*?)\">/);
if (url.length > 1){
var loader:Loader = new Loader();
loader.load(new URLRequest(url[1]));
addChild(loader);
}
Use e4x. I'm not sure if you're getting a string or the result format on your service call is already XML, but if it's a string, you'd do something like this:
var imgXML:XML = XML(yourString);//yourString contains <img src="https://blargh.com/displayTemplate?templateid=template1">
link = imgXML.#src;
Then, look at the code Zevan posted for how to use a Loader if you're using just AS, or use it as the source for an Image control in Flex.
Looks like the server is providing you with a link that dynamically looks up the image based on the GET data you're passing to the server (the ?templateid=template1). Too bad you didn't paste in the real link so that this theory could be proven. Take the real link and copy out the http:// portion, enter it into your browser and if the image appears then this is indeed the case.
If this is true, then you want to extract the link from the tag. You could do this with a regular expression, like so:
/\?)"(.?)"(.*)/
If you ran that regex against the full tag like you've provided above, then capture group 2 will contain just the HTTP link. You can then use a Loader object to fetch the image so you're actually downloading and presenting the binary image data instead of embedding HTML.
If you're going to be using Regex in AS3, then you absolutely must have the RegExr tool by grantskinner.com: http://gskinner.com/RegExr/desktop/.
Also, to get the data from capture group 2 we do this:
var imageTag:String = '<img src="https://blargh.com/displayTemplate?templateid=template1">'
var myHttpRegex:Regex = /\<img(.*?)"(.*?)"(.*)/;
var result:Object;
result = myHttpRegex.exec(imageTag);
if(result != null) {
var imgUrl:String = result[1];
}
Code is untested, but the concept is there.