I'm pulling Waypoints data from Google Maps API V3.
I have 3 Textbox with data: Lat and Lng, corresponding to 3 locations
Page1.aspx
<div id="map"></div>
<asp:TextBox ID="textbox1" AutoPostBack="true" ... runat="server"></asp:TextBox>
<asp:TextBox ID="textbox2" AutoPostBack="true" ... runat="server"></asp:TextBox>
<asp:TextBox ID="textbox3" AutoPostBack="true" ... runat="server"></asp:TextBox>
Page1.aspx.cs
protected void LoadWaypoints()
{
string textone = textbox1.Text; //lat,lng
string texttwo = textbox2.Text; //lat,lng
string textthree = textbox3.Text; //lat,lng
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + textone + "&destination="+ texttwo + "&waypoints=" + textthree + "&key=" + keyAPIGoogleMaps + "&mode=driving";
WebClient client = new WebClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string result = client.DownloadString(url);
}
I got the result from string result
However how can I display it outside in <div id="map"></div>. It will look like this:
I searched on stackoverflow but it only shows results from retrieving data from javascript. However I want to retrieve the data using the code in codebehind c#.
I still don't know how. Looking forward to everyone's help. Thank you!
Related
I'm creating a asp.net website for showing up rss feed from BBC, I'm doing exactly as i want that i m showing the rss feed on asp:DataList but my problem is that i dont want to show feed directly from a XML document, i want to store it firstly to my database and then show it to my website using Datalist. My older code is
<asp:DataList ID="DataList1" runat="server" DataSourceID="XmlDataSource1">
<ItemTemplate>
<div class="jumbotron">
<h2><%# XPath("title") %></h2>
<br />
<h3><%# XPath("pubDate") %></h3>
<br />
<h3><%# XPath("description") %></h3>
<br />
<asp:Repeater runat="server" ID="_subitemsRepeater"
EnableViewState="false"
DataSource='<%# XPathSelect("media:thumbnail", XmlNamespaceManager) %>'>
<ItemTemplate>
<img src="<%# ((System.Xml.XmlNode)Container.DataItem).Attributes["url"].Value %>" />
<br />
</ItemTemplate>
</asp:Repeater>
<br />
<a class="btn btn-primary btn-lg" target="_blank" href="<%# XPath("link") %>">Read More On This Story</a>
</div>
<hr />
</ItemTemplate>
</asp:DataList>
<asp:XmlDataSource ID="XmlDataSource1" runat="server"
DataFile="http://feeds.bbci.co.uk/news/education/rss.xml"
XPath="rss/channel/item" />
C# Code is in page load
public partial class _Default : Page
{
protected XmlNamespaceManager XmlNamespaceManager { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
XmlNamespaceManager = new XmlNamespaceManager(XmlDataSource1.GetXmlDocument().NameTable);
XmlNamespaceManager.AddNamespace("media", "http://search.yahoo.com/mrss/");
}
}
and my new code is:
FileWebRequest rssFeed = (FileWebRequest)WebRequest.Create(FeedURL);
// DataSet rssData = new DataSet();
//read the xml from the stream of the web request
XDocument xd = XDocument.Load(rssFeed.GetResponse().GetResponseStream());
XNamespace media = "http://feeds.mashable.com/Mashable?format=xml";
foreach (var feed in xd.Descendants("item"))
{
string title = feed.Element("title").Value.ToString();
string description = feed.Element("description").Value.ToString();
string link = feed.Element("link").Value.ToString();
DateTime pubdate = DateTime.Parse(feed.Element("pubDate").Value);
string thumb = (string)feed.Element(media + "thumbnail") != null ? (string)feed.Element(media + "thumbnail").Attribute("url").Value.ToString() : "file:///c:/No_Image.png";
string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
SqlConnection NewCon = new SqlConnection(connection);
NewCon.Open();
SqlCommand NewCMD = new SqlCommand(TableName + "_Proc", NewCon);
NewCMD.CommandType = CommandType.StoredProcedure;
NewCMD.Parameters.AddWithValue("#title", title);
NewCMD.Parameters.AddWithValue("#description", description);
NewCMD.Parameters.AddWithValue("#link", link);
NewCMD.Parameters.AddWithValue("#pubdate", pubdate);
NewCMD.Parameters.AddWithValue("#thumb", thumb);
NewCMD.ExecuteNonQuery();
NewCon.Close();
}
in this code the problem is with images that it returns me the NoImage.jpg every time I'm connected to the internet. I think there is no problem with NameSpace too.
I'm doing it because if the feed server or news server shutdown or not respond then my website not effected so. Anybody know how resolve this issue?. Any help will be greatly appreciated. thanks !
I want display student information and student image on my web page while selecting student Id from drop down list. Given below code is used for displaying information and image. But the image is not showing properly. Please check the code and out put screen.
Code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.TextBoxTableTableAdapter tx;
tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
DataTable dt = new DataTable();
dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"].ToString());
TextBox2.Text = (row["SecondName"].ToString());
byte[] barrImg = (byte[])row["StudImage"];
string base6=Convert.ToBase64String(barrImg);
Image1.ImageUrl = "data:image/jpeg;base6," + base6;
}
}
SQL Query:
SELECT FirstName, SecondName, StudentImage FROM TextBoxTable WHERE (Id = #Id)
Aspx Source:
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Image ID="Image1" runat="server" />
</div>
Data base:
OutPut:
base64 instead of base6 ???
Image1.ImageUrl = "data:image/jpeg;base64," + base6;
I am trying to set a background image in a repeater programmatically. Variations of the following have not worked, including trying to set the url in the div, not the jquery function:
The JQuery function:
var getBackgroundImage = function (imagePath) {
var backgroundImage = 'url(' + iipServ + '?FIF=/IIPServer/images/' + imagePath + '&WID=40&CVT=PNG' + ')';
return backgroundImage;
};
The ASP page:
<asp:Repeater ID="docResults" runat="server" ItemType="ArchiveViewer.Models.Document"
SelectMethod="GetSearchResults" >
<ItemTemplate>
<div class="result" data-docid="<%#:Item.DocumentId %>"
data-imageDir="<%#:Item.FolderPath %>"
data-objData="<%#:Item.JSONPath %>"
style="<%= getBackgroundImage(Item.Pages.First().ImagePath) %> ">
<%#:Item.Metadata.Title %>
</div>
</ItemTemplate>
</asp:Repeater>
Can this be done? How?
Thank you!
EDIT: Each div has its own image. I'm getting the URL from the server.
EDIT 2: I am not instead of using a jquery function, am using a web method in my code behind:
[WebMethod]
public string getBackgroundImage(string path)
{
string iipServer = ConfigurationManager.ConnectionStrings["iipServer"].ConnectionString;
string urlString = "background-image : url('" + iipServer + "?FIF=/IIPServer/images/" +
path + "&WID=40&CVT=PNG)'";
System.Diagnostics.Debug.WriteLine(urlString);
return urlString;
}
In the ASPX page:
style="background-image : <%=getBackgroundImage(Item.Pages.First().ImagePath) %>">
In the code behind:
public string getBackgroundImage(string iipServ, string path)
{
return "url('" + iipServ + "?FIF=/IIPServer/images/" + path + "&WID=40&CVT=PNG)'";
}
It's not clear what iipServ is and where to take it from. Just pass it to the C# function along the path.
You should remove the JS function, this will be all server-side.
pid: Your answer is almost correct, but the compiler didn't like it. It helped me figure out how to do it correctly, though. Thank you.
In case it helps someone else, here is how I fixed this issue:
My ASPX page:
<ItemTemplate>
<div class="result" data-docid="<%#:Item.DocumentId %>"
data-imageDir="<%#:Item.FolderPath %>" data-objData="<%#:Item.JSONPath %>"
style="<%#: getBackgroundImage(Item.Pages.First().ImagePath) %>" >
<%#:Item.Metadata.Title %>
</div>
</ItemTemplate>
And my code behind:
[WebMethod]
public string getBackgroundImage(string path)
{
string iipServer = ConfigurationManager.ConnectionStrings["iipServer"].ConnectionString;
string urlString = #"background-image:url("
+ iipServer + "?FIF=/IIPServer/images/" +
path + "&WID=40&CVT=PNG)";
return urlString;
}
So I've been looking into Braintree Payments for a couple of days now. I love the architecture, concept, etc. After looking through the documentation and the .NET walk-throughs I've noticed that all of the examples for .NET are in MVC3. I am trying to integrate Braintree into my current .NET Web Application using regular web forms.
My goal is to have a normal web form post back to the payment page with both customer data and card data. The card data should be encrypted using their Braintree.js. That way I can send everything over to Braintree for processing including the encrypted card data.
The form would look something like this:
<p>
<label>Card Number</label>
<asp:TextBox ID="number" AutoCompleteType="Disabled" MaxLength="20" Width="150" data-encrypted-name="number" runat="server" />
</p>
<p>
<label>CVV</label>
<asp:TextBox ID="cvv" AutoCompleteType="Disabled" MaxLength="4" Width="50" data-encrypted-name="cvv" runat="server" />
</p>
<p>
<label>Expiration (MM/YYYY)</label>
<asp:TextBox ID="month" AutoCompleteType="Disabled" MaxLength="2" data-encrypted-name="month" runat="server" />
/
<asp:TextBox ID="year" AutoCompleteType="Disabled" MaxLength="4" data-encrypted-name="year" runat="server" />
</p>
<asp:Button ID="btnSubmit" Text="SUBMIT" runat="server" />
<script type="text/javascript" src="https://js.braintreegateway.com/v1/braintree.js"></script>
<script type="text/javascript">
var braintree = Braintree.create("MyClientSideKey");
braintree.onSubmitEncryptForm('braintree-payment-form');
</script>
Then in the code-behind I would set the Form.Action, Form.Method and Form.ID as follows:
protected void Page_Load(object sender, EventArgs e)
{
Form.Action = "CreateTransaction()";
Form.Method = "POST";
Form.ID = "braintree-payment-form";
}
So then hopefully when the user submits the form it hits the "CreateTransaction()" member along with the encrypted card data in the "collection" parameter like this:
[HttpPost]
public ActionResult CreateTransaction(FormCollection collection)
{
TransactionRequest request = new TransactionRequest
{
Amount = 1000.0M,
CreditCard = new TransactionCreditCardRequest
{
Number = collection["number"],
CVV = collection["cvv"],
ExpirationMonth = collection["month"],
ExpirationYear = collection["year"]
},
Options = new TransactionOptionsRequest
{
SubmitForSettlement = true
}
};
Result<Transaction> result = Constants.Gateway.Transaction.Sale(request);
return null;
}
When I take this approach the form never posts back to the "CreateTransaction()" member. What am I missing? Can this be done using regular old web forms?
OK, so after LOTS of experimenting and shooting in the dark for a bit I was able to get this the Braintree.js to encrypt the data before passing it to my server. From there I am able to us the code behind to handle the payment processing.
Here is the ASP.NET web form that I'm using:
Card Number
<p>
<label>CVV</label>
<asp:TextBox ID="txtCVV" AutoCompleteType="Disabled" MaxLength="4" Width="50" data-encrypted-name="cvv" runat="server" />
</p>
<p>
<label>Expiration (MM/YYYY)</label>
<asp:TextBox ID="txtMonth" AutoCompleteType="Disabled" MaxLength="2" data-encrypted-name="month" runat="server" />
/
<asp:TextBox ID="txtYear" AutoCompleteType="Disabled" MaxLength="4" data-encrypted-name="year" runat="server" />
</p>
<asp:Button ID="btnSubmit" Text="SUBMIT" runat="server" />
<script type="text/javascript" src="https://js.braintreegateway.com/v1/braintree.js"></script>
<script type="text/javascript">
var braintree = Braintree.create("YOURKEYHERE");
braintree.onSubmitEncryptForm('braintree-payment-form');
</script>
Please take note of a few key details here:
I am using server controls. Not simple HTML tags.
braintree.js will encrypt any field that has the "data-encrypted-name" attribute.
The "data-encrypted-name" attribute does NOT need to be the same
as the control's ID attribute.
The braintree.js script is posting to the
"braintree-payment-form" form.
So when I click Submit button this form will naturally post back. The particular form that I'm using has a master page, so I need to alter the Form.ID in the Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
//Adjust the properties of the form itself as this
//form has a master page.
Form.ID = "braintree-payment-form";
//Wire up the click event
btnSubmit.Click += btnSubmit_Click;
}
In the click event handler I am then able to extract the encrypted values from the Request.Form object and then submit the transaction request to the Braintree Gateway:
void btnSubmit_Click(object sender, EventArgs e)
{
//--------------------------------------------------------------------------------------------------
//Extract encrypted values from the Request.Form object
//braintree.js has encrypted these values before placing them in
//the Request object.
//--------------------------------------------------------------------------------------------------
string number = Request.Form["number"].ToString();
string cvv = Request.Form["cvv"].ToString();
string month = Request.Form["month"].ToString();
string year = Request.Form["year"].ToString();
//--------------------------------------------------------------------------------------------------
//Gateway
//This is the Braintree Gateway that we will use to post the transaction
//to. This is included here in the example but should be extracted out
//into some static class somewhere. Possibly in another layer.
//--------------------------------------------------------------------------------------------------
BraintreeGateway Gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
PublicKey = "YOURPUBLICKEYHERE",
PrivateKey = "YOURPRIVATEKEYHERE",
MerchantId = "YOURMERCHANTIDHERE"
};
//--------------------------------------------------------------------------------------------------
//Transaction Request
//This is the actual transaction request that we are posting to the
//Braintree gateway. The values for number, cvv, month and year have
//been encrypted above using the braintree.js. If you were to put a
//watch on the actual server controls their ".Text" property is blank
//at this point in the process.
//--------------------------------------------------------------------------------------------------
TransactionRequest transactionRequest = new TransactionRequest
{
Amount = 100.00M,
CreditCard = new TransactionCreditCardRequest
{
Number = number,
CVV = cvv,
ExpirationMonth = month,
ExpirationYear = year,
}
};
//--------------------------------------------------------------------------------------------------
//Transaction Result
//Here we are going to post our information, including the encrypted
//values to Braintree.
//--------------------------------------------------------------------------------------------------
Result<Transaction> result = Gateway.Transaction.Sale(transactionRequest);
}
OK, so this is a very basic example of how to post a transaction to Braintree. However it solves the first big hurdle that I have with getting the card data to be encrypted before it gets to my server. Hope this helps...
I am trying to provide alternate image as some of the images are corrupt and do not get display, I tried with js but no success, so need help and suggestions on how to do the same. the scenario is on page load the information of students get bound to DataList and on the basis of it image is pulled from another table by GetImage class but the problem is some images are corrupt so I want to display another dummy image. I changed BG image using CSS but its not as expected.
<asp:DataList ID="DataList1" CssClass="slider" r RepeatColumns="6" RepeatDirection="Vertical" runat="server" OnEditCommand="DataList1_EditCommand" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<ul>
<li><a class="info" href="#">
<asp:ImageButton CssClass="imagetest" AlternateText=" " ID="Image1" name="mybutton" runat="server" Width="140" Height="140" CommandName="image" OnLoad="changeImage();" CommandArgument="image" CausesValidation="false" ImageUrl='<%# "GetImage.aspx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>'
</li>
</ul>
</ItemTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
string city = Request.QueryString["city"];
string RollNo = Request.QueryString["RollNo"];
string state = Request.QueryString["state"];
string fname = Request.QueryString["fname"];
string lname = Request.QueryString["lname"];
DataAccess dao = new DataAccess();
dao.openConnection();
byte[] arr = dao.GetPicture(city, RollNo, state, fname, lname);
//Response.BinaryWrite(arr);
try
{
Response.BinaryWrite(arr);
}
catch (Exception) { }
}
You can use the onerror of the image and show an alternative image if not loaded.
Here is a basic example with one img tag, on asp.net you can place similar the onerror call
<img id="one" src="image.gif" onerror="imgError(this)">
and the javascript
function imgError(me)
{
// place here the alternative image
var AlterNativeImg = "/images/emptyimage.gif";
// to avoid the case that even the alternative fails
if(AlterNativeImg != me.src)
me.src = AlterNativeImg;
}
and live: http://jsfiddle.net/DxN69/2/
and also http://jsfiddle.net/DxN69/3/
and final: http://jsfiddle.net/DxN69/4/
on asp.net image button
you simple add the onerror="imgError(this)" on your asp.net tag as:
<asp:ImageButton ID="ImageButton1" runat="server" onclick="ImageButton1_Click" ImageUrl="image.jpg" onerror="imgError(this)" />
even if the image button is rendered as input the final result is the same.
image send from code behind
after your last update is clear that you have make a big mistake trying to send a page as an image, and you did not even change the ContentType of it. So use a handler, eg make a new handler named loadImage.ashx and there write your code as:
public void ProcessRequest(HttpContext context)
{
// this is a header that you can get when you read the image
context.Response.ContentType = "image/jpeg";
// cache the image - 24h example
context.Response.Cache.SetExpires(DateTime.Now.AddHours(24));
context.Response.Cache.SetMaxAge(new TimeSpan(24, 0, 0));
// render direct
context.Response.BufferOutput = false;
// load here the image as you do
....
// the size of the image
context.Response.AddHeader("Content-Length", imageData.Length.ToString());
// and send it to browser
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
and your call will be something like:
<asp:ImageButton CssClass="imagetest" AlternateText=" " ID="Image1" name="mybutton" runat="server" Width="140" Height="140" CommandName="image" OnLoad="changeImage();" CommandArgument="image" CausesValidation="false" ImageUrl='<%# "loadImage.ashx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>'
now here you can double check if the image exist and send some default image if not exist.
<img src="images.png" onerror="this.onerror=null;this.src='default.png'">
I would preffer to set imageURL property for the default image you want to display. If the image is exists in database record then replace the imageURL with that record else keep it as it is.
Just do using onerror event
<img src="image.gif" onerror="alert('The image could not be loaded.')">
Instead of creating a server side image button why you just not create an html image with a link, that acts as an image button.
<a class="info" href="#">
<img src="<%# GetImage.aspx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>" onerror="this.src='<%=Page.ResolveClientUrl("~/images/emptyimage.gif") %>'" alt="" class="imagetest" />
</a>