I want to show products using TileView, but I do not show pictures when I give url. How can I overcome this problem?
private void tileView1_ItemCustomize(object sender, DevExpress.XtraGrid.Views.Tile.TileViewItemCustomizeEventArgs e)
{
TileView view = sender as TileView;
string ID = view.GetRowCellValue(e.RowHandle, "ID").ToString();.ToString();
string url = "http://webpage.com/images/"+ ID + ".jpg";
e.Item.Elements[6].ImageUri = url;
}
The simple answer to using URI is this:
e.Item.Elements[6].ImageUri = new Uri(url);
The problem in your case might be that the image must first be downloaded in order for the control to use it. So you're probably going to have to do something like this first:
https://stackoverflow.com/a/3615831/1633308
and then, instead of your URI being the web address, it would be the local image file (probably in temporary storage that you clean up later).
Related
I'm working on a simple portfolio project. I would like to show images on a webpage that logged in users can edit. My problem is in the [HttpPost] Edit, more specifically this part:
if (ModelState.IsValid)
{
//updating current info
inDb = ModelFactory<ArtSCEn>.GetModel(db, artSCEn.ArtSCEnID);
inDb.LastModified = DateTime.Now;
inDb.TechUsed = artSCEn.TechUsed;
inDb.DateOfCreation = artSCEn.DateOfCreation;
inDb.Description = artSCEn.Description;
inDb.ArtSC.LastModified = DateTime.Now;
//validating img
if (Validator.ValidateImage(img))
{
inDb.ImageString = Image.JsonSerialzeImage(img);
}
else
{
//return to the UI becuase we NEED a valid pic
return View(artSCEn);
}
db.Entry(inDb).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
//[PROBLEMATIC PART STARTS HERE]
//updating the pic on the server
//getting the string info
string userArtImgFolder = Server.MapPath($"~/Content/Images/Artistic/{inDb.ArtSC.PersonID}");
string imgNameOnServer = Path.Combine(
userArtImgFolder,
$"{inDb.ArtSC.PersonID}_{inDb.ArtSC.ArtSCID}_{inDb.ArtSCEnID}{Path.GetExtension(img.FileName)}");
//deleting previous pic
System.IO.File.Delete(imgNameOnServer);
//creating a new pic
Image.ResizePropotionatelyAndSave(img, Path.Combine(
userArtImgFolder,
$"{inDb.ArtSC.PersonID}_{inDb.ArtSC.ArtSCID}_{inDb.ArtSCEnID}{Path.GetExtension(img.FileName)}"));
return RedirectToAction("Edit", "Art", new { id = inDb.ArtSCID });
}
When I get back the new picture and I want to delete the previous, System.IO.File.Delete() always triggers an exception that it cannot access the resource, because someone else is holding onto it. Any idea what that might be?
Maybe it's something simple, I'm new to ASP, but just can't figure it out.
UPDATE
Following on the suggestions in the comments section, I checked the processes with a tool called Process Monitor and it seems that indeed IIS is locking the resource:
This one appears 2 more times in the logs, by the way.
Judging by the fact that the operation is CreateFileMapping, I guess it has to do with either Server.MapPath() or Path.Combine(), however, the Server is an IDisposable (being derived from Controller), so can that be the one I should deal with?
Also, the resource I'm trying to delete is an image used on the website, which might be a problem, but that section of the website is not shown during this process.
I found the solution building on the comment of #Diablo.
The IIS was indeed holding on to the resource, but Server.MapPath() or any of that code had nothing to do with it: it was the Edit view my page returning the data to. With the help of this SO answer, it turns out I was careless with a BitMap that I used without a using statement in the view to get some image stats. I updated the helper function with the following code:
public static float GetImageWidthFromPath(string imgAbsolutPath, int offset)
{
float width = 0;
using (Bitmap b = new Bitmap(imgAbsolutPath))
{
width = b.Width - offset;
}
return width;
}
Now IIS does not hold on to the resource and I can delete the file.
Edit: Sorry - now that I've understood the problem a bit better, I think my problem lies elsewhere
I have 2 asynchronus requests.
The first is this:
public void DownloadWebData(Uri apiUrl)
{
WebClient client = new WebClient();
client.DownloadDataCompleted += DownloadDataCompleted;
client.DownloadDataAsync(apiUrl);
}
public void DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
string result = System.Text.Encoding.UTF8.GetString (e.Result);
Uri downloadLink = (GetUri(result));
}
Basically it makes a simple url based API request to a remote webserver which returns some basic textual data over http. GetUri() just parses that data to extract an address from the data for an image to download.
I'm then using imageLoader in monotouch.dialog to download the image. All code is in the same class.
Edit: added the imageLoader code (I left the Console lines in because they serve reasonably well as comments).
public void downloadImage (Uri imageUri)
{
var tmp_img = ImageLoader.DefaultRequestImage (imageUri, this);
if (tmp_img != null)
{
adView.Image = tmp_img;
Console.WriteLine ("Image already cached, displaying");
}
else
{
adView.Image = UIImage.FromFile ("Images/downloading.jpg");
Console.WriteLine ("Image not cached. Using placeholder.");
}
}
public void UpdatedImage (System.Uri uri)
{
adView.Image = ImageLoader.DefaultRequestImage(uri, this);
}
You missed to check if e.Result actually contains something. The download might as well have failed and e.Result is null. Add some basic error handling to your code.
if you are using DownloadWebData inside a for loop, it will be better you generate seperate functions for DownloadDataCompleted event.
You can use anonymous function inside DownloadWebData().
client.DownloadDataCompleted +=(s,e)=>{
string result = System.Text.Encoding.UTF8.GetString (e.Result);
Uri downloadLink = (GetUri(result));
};
After realizing I was asking the wrong question, I finally figured it out here:
Hand back control to main UI thread to update UI after asynchronus image download
For my studying and university I have a project where I need to make an application using C# WPF. This application must allow me to select a path between two adresses and show the path on the map like google map.
How can I implement the google webservice API ? I am a bit lost with it and I don't understand how I can make my application and fit in the google map itself.
With this i must be able to calculate the distance as well.
This is what i have done with the webBrowser but it displays the whole website of google maps:
I know that the WebBrowser control can display the google maps but it doesnt actually work
This is my code actually
private void btnCharger_Click(object sender, RoutedEventArgs e)
{
//Use static or WebControl we don't know yet.
//This is the case we use webControl
string street = "";
string city = "";
string zipcode = "";
StringBuilder adresseQuery = new StringBuilder();
adresseQuery.Append("http://maps.google.com/maps?q=");
street = tbStreet.Text.Replace(" ", "+");
adresseQuery.Append(street + ",+");
city = tbCity.Text;
adresseQuery.Append(city + ",+");
zipcode = tbZipCode.Text;
webBrowser1.Navigate(adresseQuery.ToString());*/
}
So in this code i have created the adresse and sent it to the webbrowser through google maps. But is shows the whole google map page with the left bar and everything. I would like to only display the map ! How can i only display the map and not the bars present on the https://maps.google.com/
I have already checked this Link and am currently working on it but this is static.
For the part of routing/getting the directions (and for some of others functions you need as well), you can use a .NET wrapper around Google Maps API:
GoogleApi
google-maps
gmaps-api-net is outdated (at this time of answering) - the last update for the Directions API was made in 2016.
Usage example for GoogleApi:
using GoogleApi.Entities.Common;
using GoogleApi.Entities.Maps.Directions.Request;
using GoogleApi.Entities.Maps.Directions.Response;
public void GetRoute()
{
DirectionsRequest request = new DirectionsRequest();
request.Key = "AIzaSyAJgBs8LYok3rt15rZUg4aUxYIAYyFzNcw";
request.Origin = new Location("Brasov");
request.Destination = new Location("Merghindeal");
var response = GoogleApi.GoogleMaps.Directions.Query(request);
Console.WriteLine(response.Routes.First().Legs.First().DurationInTraffic);
Console.WriteLine(response.Routes.First().Legs.First().Distance);
Console.WriteLine(response.Routes.First().Legs.First().Steps);
}
I'm doing a school project, I need to make a simple web site, add google maps on it, read, lets say, 100 diffrent addresses from a text file and show those locations on google maps with markers.
Now I'm trying to add google maps to my ASP.net page with javascript which I saw on google maps tutorials. And there's that problem which I have to convert adresses to coordinates. So for that I'm using
function addAddressToMap(response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode that address");
}
else {
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(place.address + '<br>' + '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
}
}
// showLocation() is called when you click on the Search button
// in the form. It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
var address = "izmit";
var address2 = "ağrı";
geocoder.getLocations(address, addAddressToMap);
geocoder.getLocations(address2, addAddressToMap);
}
these functions and they are working fine. But my problem here is, I need to get these address informations from a text file. But to get them, I need to use a few diffrent codes. And I want to make it on the server side with C# codes. But I don't know how to write some codes on server side and then return something to HTML side as address. I hope you understand. Thank you for your helps.
Update:
Server code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterArrayDeclaration("Skills", "'asa'");
Page.ClientScript.RegisterArrayDeclaration("Skills", "'bell'");
Page.ClientScript.RegisterArrayDeclaration("Skills", "'C'");
Page.ClientScript.RegisterArrayDeclaration("Skills", "'C++'");
}
}
Client side:
function showLocation()
{
var address = "izmit";
var address2 = "ağrı";
geocoder.getLocations(Skills[0], addAddressToMap);
}
Now if I use "asa" instead of Skills[0] it will show the location and mark, but with Skills[0] it's not working. And thank you for your answer that was what I'm looking for.
even if I try var MyValue = Skills[0]; and then use MyValue instead of Skills[0] it's still not working
If I understood your question correctly, you want to create an array on the server side and read it in the client.
See this link for a tutorial on how to pass an array from the server to the client.
Basically, you want to use the ClientScriptManager.RegisterArrayDeclaration method to add values to the array.
You can then easily read it in javascript.
Server Side:
string arrayName = "MyArray";
Page.ClientScript.RegisterArrayDeclaration(arrayName , "'value1'");
Page.ClientScript.RegisterArrayDeclaration(arrayName , "'value2'");
Javascript on Client Side:
function readArray()
{
for (var i = 0; i < MyArray.length; i++)
{
//Reading Element From Array
var myValue = MyArray[i];
}
}
I am developing an online listen music website, on that I want to play song based on the user selection from gridview.right now I am using flash object for playing mp3 and video file this is running fine but its static path.how I can dynamically pass file URL of selected song on flash object.
waiting for your reply.
Using flashvars (requires reloading the page/SWF)
The easiest way would be to pass in the URL as a flashvar, e.g. via the querystring of the SWF file in your object/embed tag:
MyPlayer.swf?url=/path/to/song.mp3
The /path/to/song.mp3 can of course be printed by some server-side logic.
In Flash, you can then access the value of this variable using the LoaderInfo instance of the root:
var url : String = root.loaderInfo.parameters['url'];
If you want to provide a default for when no flashvar is specified, which is great for dev purposes especially, you can do this by using the || operator.
var url : String = root.loaderInfo.parameters['url'] || 'default.mp3';
This will use the specified URL if such exists, or else fall back to use default.mp3.
Using ExternalInterface & Javascript
If you don't want to reload the page, set up a javascript interface to your Flash player using ExternalInterface, e.g. like so:
if (ExternalInterface.available) {
ExternalInterface.addCallback('playUrl', playUrl);
}
function playUrl(url : String) : void {
// TODO: Add playback code here, e.g. using new Sound(url);
}
Then, from Javascript, you can do this:
var swf = document.getElementById('idOfSwfEmbed');
swf.playUrl('http://example.com/path/to/song.mp3');
This will invoke the ActionScript method playUrl() using the javascript API that was set up by ExternalInterface.addCallback().
I don't know .NET, so you'll need to figure out yourself how to invoke the playUrl() javascript method when a song is selected in your GridView.
If you use the <object /> tag to add the *.swf to the page:
Add following to the tag:
<object ...>
<param name="flashvars" value="path=<%# YOUR_PATH; %>">
</object>
And then inside the SWF:
var path:String = root.loaderInfo.parameters.path;
Hello friends i have got the answer for dynamically play the song.here is my code for this.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Play Now"))
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridCalls.Rows[index];
string songname = row.Cells[5].Text; // second column in the sql server database
StringBuilder str = new StringBuilder();
str.Append("<object width='300px' height='300px'>");
str.Append("<param name='autostart' value='true'>");
str.Append("<param name='src' value='songs/" + songname + "'>");
str.Append("<param name='autoplay' value='true'>");
str.Append("<param name='controller' value='true'>");
str.Append("<embed width='300px' height='300px' src='songs/" + songname + "' controller='true' autoplay='true' autostart='True' type='audio/wav' />");
str.Append("</object>");
LoadPlayer.Text = str.ToString();//here loadplayer is label control
}
}