I'm using Google Maps v3 API to load a KML layer and want to be able to change the colour of the KML from its default blue without having to edit the KML file itself. Is this possible using JavaScript or some other means?
Unfortunately can't post a link, but it's pretty standard stuff.
var map = new google.maps.Map(document.getElementById("mymap"), { some options });
var regionLayer = new google.maps.KmlLayer("http://.../some.kml");
regionLayer.setMap(map);
From my understanding of the documentation, 'no', but it's not especially clear. I'm trying to do a similar thing (but update the colour of mouseover/mouseout).
The KML file is loaded by the Google servers, parsed and sent along to your javascript object to be applied to the map, so, by the time your javascript KMLLayer sees it, it's all sorted out.
You may be able to do something with Styles and styleUrl. This is supposed to allow you to set a number of different styles that can then be applied at runtime, however, I haven't got it working.
I have done this by creating a web service which reads in a KML file to a string, inserts a style section to the beginning of the KML string, and also a styleURL to each uniquely named placemark. It's fairly simple to amend the markup using a .net web service and write it back out to the server you have hosting the web service.
For example this uses a class which contains placemark IDs and a colour flag:
public string KMLStyler(string URL, string URLName, Data[] MyData)
{
try
{
ReadFile(URL);
string NewKML = ReadFile(URL);
string RedStyle = "<Style id=\"red\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F0000FF</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string BlackStyle = "<Style id=\"black\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F7F7F7F</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string GreenStyle = "<Style id=\"green\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F00FF00</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
string BlueStyle = "<Style id=\"blue\"><LineStyle><color>7F7F7F7F</color><width>2</width></LineStyle><PolyStyle><color>7F7F7F7F</color><fill>1</fill><outline>1</outline></PolyStyle></Style>";
//add styles to top
int EndID = 0;
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, RedStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, BlackStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, GreenStyle);
EndID = NewKML.IndexOf("</name>") + 7;
NewKML = NewKML.Insert(EndID, BlueStyle);
//add each style to each placemark
foreach (Data MyDataSingle in MyData)
{
int NamePos = NewKML.IndexOf(MyDataSingle.Name);
if (NamePos == -1) throw new Exception("Did not find '" + MyDataSingle.Name + "' within File");
NamePos += MyDataSingle.Name.Length + 7;
int MultiGeometryStartPos = NewKML.IndexOf("<MultiGeometry>", NamePos);
int MultiGeometryEndPos = NewKML.IndexOf("</MultiGeometry>", NamePos);
int PolygonStartPos = NewKML.IndexOf("<Polygon>", NamePos);
int InsertPos = 0;
if (MultiGeometryStartPos < PolygonStartPos)
{
if (MultiGeometryStartPos != -1)
{
InsertPos = MultiGeometryStartPos;
}
else
{
InsertPos = PolygonStartPos;
}
}
else
{
InsertPos = PolygonStartPos;
}
if (MyDataSingle.Red)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#red</styleUrl>");
}
if (MyDataSingle.Black)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#black</styleUrl>");
}
if (MyDataSingle.Green)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#green</styleUrl>");
}
if (MyDataSingle.Blue)
{
NewKML = NewKML.Insert(InsertPos, "<styleUrl>#blue</styleUrl>");
}
}
string NewFileName = WriteFile(NewKML, URLName);
return NewFileName;
}
catch (Exception ex)
{
return ex.ToString();
}
}
public string WriteFile(string KMLData, string URLName)
{
string FileName = "http:\\blah.co.uk\blah.kml";
StreamWriter writer = new StreamWriter("C:/inetpub/blah.kml");
writer.Write(KMLData);
writer.Flush();
writer.Close();
return FileName;
}
public string ReadFile(string URL)
{
string File = "";
StreamReader reader = new StreamReader(WebRequest.Create(URL).GetResponse().GetResponseStream());
string line;
while ((line = reader.ReadLine()) != null)
{
File += line;
}
return File;
}
Related
I'm trying to update my app to work with androids new scoped storage rules in Android 10 and up, but am having the hardest time with it. I know I need to rebuild my app with new versions of java, but I just want to get it to work while I study and learn enough to do so. In a nutshell, I really need help. I have read so many different ways to make scoped storage work, and everybody seems to be doing it differently.
Just for clarification, what I am trying to do with the uri is both display in an imageview, then upload to database.
This code is working to take a picture and select images and videos in android 9, but in android 10, it only works when camera component captures a picture or a video. When a user selects an image or video from file, it returns a null pointer exception. Because I am pretty sure the error is in how I am dealing with the different chooser intents, I have shown the on result code first.
I have been unable to find a clear example of how to retrieve a usable image or video uri in android 10. If anybody can help, I would really appreciate it. I know I have much to learn.
if ((new java.io.File(_filePath)).exists()){
} else {
_filePath = vidfile.getAbsolutePath();
if ((new java.io.File(_filePath)).exists()){
} else {
ArrayList<String> _filePath_1 = new ArrayList<>();
if (_data != null) {
if (_data.getClipData() != null) {
for (int _index = 0; _index < _data.getClipData().getItemCount(); _index++) {
ClipData.Item _item = _data.getClipData().getItemAt(_index);
_filePath_1.add(FileUtil.convertUriToFilePath(getApplicationContext(),
_item.getUri()));
}
}
else {
_filePath_1.add(FileUtil.convertUriToFilePath(getApplicationContext(),
_data.getData()));
}
}
_filePath = _filePath_1.get((int)0);
}
}
Just in case I am wrong, here is the code for the click event to launch the chooser...
SimpleDateFormat date1 = new SimpleDateFormat("yyyyMMdd_HHmmss");
String fileName1 = date1.format(new Date()) + ".jpg";
picfile = new
File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DCIM).getAbsolutePath() +
File.separator + fileName1);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri _uri_camr1 = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
_uri_camr1 = FileProvider.getUriForFile(getApplicationContext(),
getApplicationContext().getPackageName() + ".provider", picfile);
}
else {
_uri_camr1 = Uri.fromFile(picfile);
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, _uri_camr1);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
SimpleDateFormat date2 = new SimpleDateFormat("yyyyMMdd_HHmmss");
String fileName2 = date2.format(new Date()) + ".mp4";
vidfile = new
File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DCIM).getAbsolutePath() +
File.separator + fileName2);
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
Uri _uri_camr2 = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
_uri_camr2 = FileProvider.getUriForFile(getApplicationContext(),
getApplicationContext().getPackageName() + ".provider", vidfile);
}
else {
_uri_camr2 = Uri.fromFile(vidfile);
}
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, _uri_camr2);
takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent[] intentArray = new Intent[]{ takePictureIntent, takeVideoIntent};
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose an action");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, REQ_CD_CAMR);
try this code. it copies the selected file to scoped storage and gives you the final path of scoped storage from where you can access it. try it out & let me know if you face any problem.
android.net.Uri sharedFileUri = android.net.Uri.fromFile(new java.io.File(_filepath));
java.io.FileInputStream input = null;
java.io.FileOutputStream output = null;
try {
String filePath = new java.io.File(getCacheDir(), "tmp").getAbsolutePath();
android.os.ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(sharedFileUri, "rw");
if (pfd != null) {
java.io.FileDescriptor fd = pfd.getFileDescriptor();
input = new java.io.FileInputStream (fd);
output = new java.io.FileOutputStream (filePath);
int read;
byte[] bytes = new byte[4096];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
java.io.File sharedFile = new java.io.File(filePath);
String finalPath = sharedFile.getPath(); // this will provide you path to scoped storage. use this final path to access the selected file from scoped storage.
}
}catch(Exception ex) {
android.widget.Toast.makeText(this, ex.toString(), android.widget.Toast.LENGTH_SHORT).show();
} finally {
try {
input.close();
output.close();
} catch (Exception ignored) {
}
}
how to get the href value only from html anchor tag using C#
thank you
string ref="";
//i want get result from
//string ref like
//http://www.google.com
You could use a HTML parsing library such as Html Agility Pack. For example:
using System;
using HtmlAgilityPack;
class Program
{
static void Main()
{
var doc = new HtmlDocument();
doc.LoadHtml("");
var nodes = doc.DocumentNode.SelectNodes("a[#href]");
foreach (var node in nodes)
{
Console.WriteLine(node.Attributes["href"].Value);
}
}
}
If you want to do this without HtmlAgilityPack then you can do this using regular Expression :
string ref= #"test";
var regex = new Regex("<a [^>]*href=(?:'(?<href>.*?)')|(?:\"(?<href>.*?)\")", RegexOptions.IgnoreCase);
var urls = regex.Matches(ref).OfType<Match>().Select(m => m.Groups["href"].Value).SingleOrDefault();
Hope it helps you.
Using htmlagilitypack .
var url= #"<a href="http://stackoverflow.com" ></a>";
HtmlDocument document = new HtmlDocument();
document.LoadHtml(url);
var tempValue= document.DocumentNode.SelectSingleNode("//a");
var link= tempValue.Attributes["href"].Value;
If you need anchor link as well as the text of anchor then you can use below function which returns the list of string containing all anchors (URL;Text) within a HTML string.
public static List<string> ExtractLinks(string htmlString)
{
List<string> list = new List<string>();
string anchorStart = "<a";
string anchorEnd = "</a>";
string anchorText = string.Empty;
Regex regex = new Regex("(?:href)=[\"|']?(.*?)[\"|'|>]+", RegexOptions.Singleline | RegexOptions.CultureInvariant);
if (regex.IsMatch(htmlString))
{
foreach (Match match in regex.Matches(htmlString))
{
try
{
string strURL = match.Groups[1].Value; // should contain the HRF URL
int baseIndex = htmlString.IndexOf(strURL); // Get the Start Index of current URL.
// Start from baseindex and finc the fisrt instance of "<a" which should be the start of anchor
int anchorStartIndex = htmlString.LastIndexOf(anchorStart, baseIndex, StringComparison.CurrentCultureIgnoreCase);
// Find the end index of anchor
int anchorEndIndex = htmlString.IndexOf(anchorEnd, anchorStartIndex, StringComparison.CurrentCultureIgnoreCase);
// The actual anchor text would be found b/w ">" and "</a>" so need to find the index of ">"
int indexofanchorTextStart = htmlString.LastIndexOf(">", anchorEndIndex);
//find the substring b/w ">" and "</a>"
anchorText = htmlString.Substring(indexofanchorTextStart + 1, anchorEndIndex - indexofanchorTextStart - 1);
anchorText = HttpUtility.HtmlDecode(anchorText);
// get Full anchor from start to end
// string substringAheadAnchor = htmlString.Substring(anchorStartIndex, anchorEndIndex - anchorStartIndex + anchorEnd.Length + 1);
}
catch (Exception ex)
{
// Log Exception in parsing the anchor Text
}
if (!list.Contains(match.Groups[1].Value + ";" + anchorText))
{
list.Add(match.Groups[1].Value + ";" + anchorText);// Append URL and Text using semicolun as seperator.
}
}
}
return list;
}
I have two functions:
Function 1: ImageToByteArray: Is used to Convert an Image into a Byte Array and then Store in an Oracle Database, in a BLOB Field.
public byte[] ImageToByteArray(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
Function 2: ByteArrayToImage: Is used to Convert a Byte Array from the Database into an Image:
public System.Drawing.Image ByteArrayToImage(byte[] byteArray)
{
MemoryStream img = new MemoryStream(byteArray);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(img);
return returnImage;
}
In my Markup I have an Imgage Control:
<asp:Image ID="Image1" runat="server" />
In the Code Behind I want to Assign the Returned Value from Function 2 to (which is of type System.Drawing.Image) to the "image1" control which is of type (System.Web.UI.WebControls.Image).
Obviously I can't just assign:
image1 = ByteArrayToImage(byteArray);
because I'd get the following error: Cannot implicitly convert type 'System.Drawing.Image' to 'System.Web.UI.WebControls.Image'
Is there anyway to do this?
It looks like you just want a simple method to convert an image byte array into a picture. No problem. I found an article that helped me a lot.
System.Web.UI.WebControls.Image image = (System.Web.UI.WebControls.Image)e.Item.FindControl("image");
if (!String.IsNullOrEmpty(currentAd.PictureFileName))
{
image.ImageUrl = GetImage(currentAd.PictureFileContents);
}
else
{
image.Visible = false;
}
//The actual converting function
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
}
PictureFileContents is a Byte[] and that's what the function GetImage is taking as an object.
You can't. WebControls.Image is just a HTML container for an image url - you can't store the image data directly in it, you just store the reference (url) to an image file.
If you need to retrieve image data dynamically, the usual approach is to create an image handler that will handle the request and return the image as a stream that the browser can display.
See this question
I think it is possible and I hope it be helpful. My solution for this is here:
public System.Web.UI.WebControls.Image HexStringToWebControlImage(string hexString)
{
var imageAsString = HexString2Bytes(hexString);
MemoryStream ms = new MemoryStream();
ms.Write(imageAsString, 0, imageAsString.Length);
if (imageAsString.Length > 0)
{
var base64Data = Convert.ToBase64String(ms.ToArray());
return new System.Web.UI.WebControls.Image
{
ImageUrl = "data:image/jpg;base64," + base64Data
};
}
else
{
return null;
}
}
public byte[] HexString2Bytes(string hexString)
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
My question is image uploading , uploading and image load method are working perfect but im showing images below the upload control, after click upload button new image must be added to line.. what is the reason?
this is uploading code:
DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(#"~/Bailiffs/BailiffImages/"));
string cukurNumber = txtCukurNumber.Text;
int sequence = 0;
string fileName = string.Empty;
FileInfo[] fileInfos = directoryInfo.GetFiles(cukurNumber + "*");
if (afuImage.HasFile)
{
if (fileInfos.Length != 0)
{
for (int i = 0; i < fileInfos.Length; i++)
{
string fileNumber = fileInfos[i].Name.Substring(fileInfos[i].Name.LastIndexOf("-") + 1, fileInfos[i].Name.LastIndexOf(".") - fileInfos[i].Name.LastIndexOf("-") - 1);
sequence = int.Parse(fileNumber) + 1;
}
fileName = cukurNumber + "--" + sequence + ".jpg";
}
else
{
fileName = cukurNumber + "--1.jpg";
}
afuImage.PostedFile.SaveAs(Server.MapPath(#"/Bailiffs/BailiffImages/" + fileName));
CreateImages(); // recreates images
}
thx...
Use ajax to call a page method which retrieves the url of the image just uploaded and shows it in an img tag. Ajax and Jquery are your tools and friends.
I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.
I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.
What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.
The table is composed of just a few columns:
AjaxSavedDataID - int:
Primary key.
UserID - int:
Identify the user (easy enough).
PageName - varchar(100):
Necessary if you're working with multiple pages.
ControlID - varchar(100):
I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.
Value - varchar(MAX):
The value the user entered for a given field or control.
DateChanged - datetime:
The date the value was added or modified.
Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.
This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.
In case you're interested, here's the Javascript that allows auto-saving:
function getNewHTTPObject() {
var xmlhttp;
/** Special IE only code */
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end
#*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AjaxSend(url, myfunction) {
var xmlHttp = getNewHTTPObject();
url = url + "&_did=" + Date();
xmlHttp.open("GET", url, true);
var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4)
return;
var result = xmlHttp.responseText;
myfunction(result);
};
xmlHttp.send(null);
}
// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)
function ArrayContains(arr, value) {
for (i = 0; i < arr.length; i++) {
if (arr[i] == value)
return true;
}
return false;
}
function GetShortTime() {
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
a_p = "AM";
else
a_p = "PM";
if (curr_hour == 0)
curr_hour = 12;
else if (curr_hour > 12)
curr_hour = curr_hour - 12;
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
curr_min = "0" + curr_min;
return curr_hour + ":" + curr_min + " " + a_p;
}
function Saved(result) {
if (result == "OK") {
document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
document.getElementById("divAutoSaved").style.display = "";
}
else {
document.getElementById("divAutoSaved").innerHTML = result;
document.getElementById("divAutoSaved").style.display = "";
}
}
function getQueryString(name, defaultValue) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return defaultValue;
}
function urlencode(str) {
return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/#/g, '%40');
}
function AutoSave() {
if (SaveQueue.length > 0) {
var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");
for (i = 0; i < SaveQueue.length; i++) {
switch (document.getElementById(SaveQueue[i]).type) {
case "radio":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
break;
case "checkbox":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
default:
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
}
}
SaveQueue = [];
SaveQueueID = [];
AjaxSend(url, Saved);
}
}
function AddToQueue(elem, id) {
if (id == null || id.length == 0)
id = elem.id;
if (!ArrayContains(SaveQueueID, id)) {
SaveQueue[SaveQueue.length] = elem.id;
SaveQueueID[SaveQueueID.length] = id;
}
}
Add this to your page to make this work:
window.setInterval("AutoSave()", 5000);
And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:
onchange="AddToQueue(this)"
...or this for a RadioButtonList or CheckBoxList:
onchange="AddToQueue(this, '" + this.ClientID + "')"
I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.
Use the Timer class and the Tick method.