displaying search result of database stored images without file extension - javascript

I have an autocomplete search box that culled up the thumbnail of images stored in the database. The problem is that the .jpg extension shows up each times the image name appears in the autocomplete search box. Is there anyway I can modify these codes to prevent the .jpg extension from appearing? Below is my existing code using javascript and ashx.
Thank you in advance!
the aspx:
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID%>").autocomplete("Search.ashx", {
width: 200,
formatItem: function (data, i, n, value) {
return "<img style = 'width:50px;height:50px' src= 'Images/" + value.split(",")[1] + "'/> " + value.split(",")[0];
},
formatResult: function (data, value) {
return value.split(",")[0];
}
});
});
</script>
<style type="text/css">
.Gridview {
font-family: Verdana;
font-size: 10pt;
font-weight: normal;
color: black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
Search here:
<asp:TextBox ID="txtSearch" runat="server" />
<br />
</div>
<div>
<asp:FileUpload ID="fileuploadimages" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
<div>
</div>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</form>
</body>
</html>
the ashx:
public class Search : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string searchText = context.Request.QueryString["q"];
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("select ID,ImageName,ImagePath from ImagesPath where ImageName Like #Search + '%'", connection);
cmd.Parameters.AddWithValue("#Search", searchText);
StringBuilder sb = new StringBuilder();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
sb.Append(string.Format("{0},{1}{2}", dr["ImageName"], dr["ImageName"], Environment.NewLine));
}
}
connection.Close();
context.Response.Write(sb.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
}

Do a search and replace, either in the ashx
dr["ImageName"].ToString().Replace(".jpg", "");
Or in the database
select ID, REPLACE(ImageName, '.jpg', '') AS ImageName, ImagePath from ImagesPath
Or if you have more than one extension, you can also do this
Path.GetFileNameWithoutExtension(dr["ImageName"].ToString())
This filters out the extension of every file, and the path should it be present:
string file = #"c:\folder\testFile.jpg";
string result = Path.GetFileNameWithoutExtension(file);
//result: testFile
Translated to your snippet it would look something like this.
while (dr.Read())
{
string file = Path.GetFileNameWithoutExtension(dr["ImageName"].ToString());
sb.Append(string.Format("{0},{1}{2}", file, file, Environment.NewLine));
}

Related

Is it possible to get javascript data from web to application

I need to get a list of innerHTML strings from a website (for example facebook) to my .NET application.
Is there a way to get results from the following function into my application (i would put this data into a list) :
var data = new Array();
for(i=0; i<document.getElementsByClassName("class-name").length;i++)
data.push(document.getElementsByClassName("class-name")[i].innerHTML);
The code above outputs exactly the data i need, now my question is if it's possible to somehow get this data into my c# list?
This is how I'd like it to look :
var JS_DATA = data; //get the js array as a variable
static List<string> data = new List<string>(); //make a new list
foreach (string str in JS_DATA)
data.Add(String.Format("{0}", str)); //add the whole js array to the list
Here is an example:
see hidden Field array_store
Client side:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var array_store;
window.onload = function () {
array_store = document.getElementById("array_store");
document.getElementById("array_disp").innerHTML = array_store.value;
};
function UpdateArray() {
var arr;
if (array_store.value == "") {
arr = new Array();
} else {
arr = array_store.value.split(",");
}
arr.push((arr.length + 1).toString());
array_store.value = arr.join(",");
};
</script>
</head>
<body>
<form id="form1" runat="server">
<span id="array_disp"></span>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="UpdateArray()" />
<input type="hidden" id="array_store" name = "ArrayStore" value = '<%=this.ArrayStore %>' />
</form>
</body>
</html>
C#:
protected string ArrayStore = "";
protected void Page_Load(object sender, EventArgs e)
{
this.ArrayStore = Request.Form["ArrayStore"];
}

Calling C# COM Object from javascript fails

I'm trying to call a COM C# Object from javascript code and get an object that doesn't contain the COM object functions.
I created a setup project for the C# COM library. The library is signed for COM interop, and the setup project output is signed for COM register on the machine it deployed at.
I see that the TLB is properly exported.
C# Code:
using System;
using System.Runtime.InteropServices;
namespace YaronTestCOM
{
[Guid("BD145EEC-ACAC-4FDB-B766-0F15CE07990F")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IComEvents))]
public class YaronComObject : IComObject, IObjectSafety
{
[ComVisible(false)]
public delegate void YaronFirstEventHandler(string args);
public event YaronFirstEventHandler YaronFirstEvent;
public int YaronFirstComCommand(string arg)
{
if (YaronFirstEvent != null)
YaronFirstEvent(arg);
return (int)DateTime.Now.Ticks;
}
public void Dispose()
{
}
}
[Guid("A3576AA4-9DE0-422D-BAA3-3FFB862E8007")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[ComVisible(true)]
public interface IComObject
{
[DispId(0x10000001)]
int YaronFirstComCommand(string arg);
[DispId(0x10000002)]
void Dispose();
}
[Guid("B551EC8B-4D19-4781-938C-9E50E70D37CD")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComEvents
{
[DispId(0x00000001)]
void YaronFirstEvent(string args);
}
}
HTML+Javascrip Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<object id="publisher" name="publisher" classid="clsid:BD145EEC-ACAC-4FDB-B766-0F15CE07990F"></object>
<title>Sender Test</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var msgTxt = $("#msgTxt");
$("#btnSend").click(function () {
var msg = msgTxt.val();
//publisher.YaronFirstComCommand is undefined!!!
var result = publisher.YaronFirstComCommand(msg);
alert('The message ' + msg + 'has been sent and returned ' + result);
});
});
</script>
</head>
<body>
<div>
<input type='text' id='msgTxt' />
<input type='button' value='Send Message' id='btnSend' />
</div>
</body>
Any ideas?

push message from code behind

when I use from javascript works perfectly but when I click link button nothing happens. how can I fix pushing message from code behind?
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
protected void LinkButton1_Click(object sender, EventArgs e)
{
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.Send("asf", "111");
}
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
[assembly: OwinStartup(typeof(signalRtest.Startup))]
namespace signalRtest
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}

how to display G map by repeater and markers from database

I want to display google map inside repeater from database values comes, i searched on google and reached to this result but not working with me i don't know if it have something missing or not can you help me please.
<body>
<form id="form1" runat="server">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<asp:Literal runat="server" ID="Literal1"></asp:Literal>
<script type="text/javascript">
var markers = [
<asp:Repeater ID="rptMarkers" runat="server">
<ItemTemplate>
{
"title": '<%# Eval("City") %>',
"lat": '<%# Eval("Latitude") %>',
"lng": '<%# Eval("Longitude") %>'
}
</ItemTemplate>
<SeparatorTemplate>
,
</SeparatorTemplate>
</asp:Repeater>
];
</script>
</body>
Here my code behind aspx.cs,
public class Markers
{
public string City { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
void GetData(string strRsult)
{
XmlDataDocument xmlDataDoc = new XmlDataDocument();
xmlDataDoc.LoadXml(strRsult);
Literal1.Text = "<script type=\"text/javascript\">var markers = [";
foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
{
if (n.HasChildNodes)
{
List<Markers> markers = new List<Markers>();
foreach (XmlNode childNode in n)
{
if (childNode.Name == "GEOData")
{
Literal1.Text += "title: '" + childNode.Attributes["City"].Value + "', lat: '" + childNode.Attributes["Longitude"].Value + "', lng: '" + childNode.Attributes["Latitude"].Value + "'}";
}
}
Literal1.Text += "];</script>";
}
}
XML file
- <AVSearch_PropertyDetails RequestedCurrency="EUR">
- <Property IDHotel="10000" PropertyCode="10000" Hotelname="REZ:Online HOTEL" StarCategory="0" ImageIdentifier="RHN_10000" NumberOfRooms="80" CheckinTime="00:00" CheckoutTime="23:59" Email="info#r-h-n.com" Status="0" StatusInfo="">
- <GEOData CountryCode="DE" CountryName="Germany" City="Duesseldorf" IDCity="32" Zip="40472" Street="Wanheimer Street 45" Longitude="6.7932130" Latitude="51.2871870">
- <Distances>
<Distance Type="1" Distance="0.50" />
<Distance Type="2" Distance="1.81" />
</Distances>
</GEOData>
- <Descriptions>
<Description IDLanguage="4" IDType="1" Text="This is the test hotel used for testing and debugging purposes only. Please do not book this hotel." />
<Description IDLanguage="4" IDType="4" Text="This is a testhotel" />
<Description IDLanguage="4" IDType="3" Text="Terms & conditions EN" />
</Descriptions>
`
Download Google Map DLL in your project from codeplex GoogleMapControl.
Register DLL in your page:
<%# Register Assembly="Artem.Google" Namespace="Artem.Google.UI" TagPrefix="artem" %>
Here is the steps to create Google Map dynamically in repeater control.
First download Artem.Google.dll from this link and put down DLL in bin folder.
ASPX Page Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="GmapRepeater.aspx.cs" Inherits="GmapRepeater" %>
<!DOCTYPE html>
<%# Register Assembly="Artem.Google" Namespace="Artem.Google.UI" TagPrefix="artem" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:Repeater ID="rptMarkers" runat="server" OnItemDataBound="rptMarkers_ItemDataBound">
<ItemTemplate>
<artem:GoogleMap ID="GMap" runat="server"></artem:GoogleMap>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
ASPX.CS Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Artem.Google.UI;
public partial class GmapRepeater : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
protected void rptMarkers_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Markers loData = (Markers)e.Item.DataItem;
GoogleMap GMap = (GoogleMap)e.Item.FindControl("GMap");
GMap.MapType = Artem.Google.UI.MapType.Roadmap;
GMap.ApiVersion = "v2";
GMap.Latitude = Convert.ToDouble(loData.Latitude);
GMap.Longitude = Convert.ToDouble(loData.Longitude);
GMap.Zoom = 18;
GMap.EnableMapTypeControl = false;
GMap.Height = 200;
GMap.Width = 195;
Marker loMarker = new Marker();
loMarker.Position.Latitude = Convert.ToDouble(loData.Latitude);
loMarker.Position.Longitude = Convert.ToDouble(loData.Longitude);
loMarker.Clickable = true;
loMarker.Info = "Marker Information";
loMarker.Title = "Title of your Marker";
loMarker.Visible = true;
GMap.Markers.Add(loMarker);
}
}
private void GetData()
{
XmlDataDocument xmlDataDoc = new XmlDataDocument();
xmlDataDoc.Load(Server.MapPath("~/Files/XMLFile.xml"));
List<Markers> markers = new List<Markers>();
foreach (XmlNode n in xmlDataDoc.DocumentElement.GetElementsByTagName("Property"))
{
if (n.HasChildNodes)
{
foreach (XmlNode childNode in n)
{
if (childNode.Name == "GEOData")
{
Markers loObj = new Markers();
loObj.City = Convert.ToString(childNode.Attributes["City"].Value);
loObj.Longitude = Convert.ToString(childNode.Attributes["Longitude"].Value);
loObj.Latitude = Convert.ToString(childNode.Attributes["Latitude"].Value);
markers.Add(loObj);
}
}
}
}
if (markers != null && markers.Count > 0)
{
rptMarkers.DataSource = markers;
rptMarkers.DataBind();
}
}
}
Markers Entity Class:
public class Markers
{
public string City { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
Please let me know if you have any questions.

jquery or javascript - add text from text editor into a variable

I have a webpage with a textbox named "title" and a text editor window that represents content.
I have this javascript variable:
var article = {"title" : "I am a title", "content" : "I am the content"};
I must admit and I've never ran into this kind of array before in javascript, that's why I need help.
Here's my code of the HTML page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
...
<script type="text/javascript">
var article = {"title" : "I am a title", "content" : "I am the content"};
</script>
</head>
<body>
<form name="myForm" method="post">
<label>Title:</label><br />
<input id="myTitle"></input><br /><br />
<label>Content:</label><br />
<textarea id="myContent" name="myContent" rows="15" cols="80" style="width: 80%">
</textarea><br /><br />
<input type="submit" value="save" />
</form>
</body>
</html>
What I need to add to the webpage functionality is this:
When page loads, put in the title textbox and inside the textarea (where the text editor is) the values in the article variable (in this case "I am a title" in the title, and "I am the content" in the editor).
Once I change the values inside those textbox and textarea, the variable itself should be updated to what I've written.
Unfortunately for me, I have never ran into this kind of variable, so I'd be glad for some guidance.
It is a good choice to use knockout for this. First of all I would recommend you to read documentation of knockout: http://knockoutjs.com/documentation/introduction.html
To track object status you should use ko.observable. Put the following code to the bottom of the page:
<script type="text/javascript">
var article = {
title: ko.observable("I am a title"),
content: ko.observable("I am the content")
};
ko.applyBindings(article);
</script>
And update your form as follow:
<form name="myForm" method="post">
<label>Title:</label><br />
<input id="myTitle" data-bind="value: title"></input>
<br /><br />
<label>Content:</label><br />
<textarea id="myContent" data-bind="value: content" name="myContent" rows="15" cols="80" style="width: 80%">
</textarea><br /><br />
<input type="submit" value="save" />
</form>
Here is working fiddle: http://jsfiddle.net/8gJAZ/
EDIT:
Also don't forget to add reference to knockout library.
<script src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.0.js' type='text/javascript'></script>
Try this:
var article = {
"title": "I am a title",
"content": "I am the content"
};
$('#myTitle').val(article.title);
$('#myContent').val(article.content);
$('#target').click(function() {
article.title = $('#myTitle').val();
article.content = $('#myContent').val();
alert(article.title + '\n' + article.content);
return false;
});​
DEMO HERE
If your only problem is "how to use object". You can use it by:
var title = article.title;
var content = article.content;
I prefer using closures for this purpose. You can use public members commented below by dot syntax. You may also want to extend and add functionality.
var Article = (function() {
var title = "";
var content = "";
function setOrUpdateValues(t, c) {
title = (t !== null) ? t : title;
content = (c !== null) ? c : content;
}
function getValues() {
return {
title: title,
content: content
}
}
function setTitle(t) {
title = t;
}
function setContent(c) {
content = c;
}
function getTitle() {
return title;
}
function getContent() {
return content;
}
// public members
return {
title: title,
content: content,
getValues: getValues,
setOrUpdateValues: setOrUpdateValues,
updateTitle: setTitle,
updateContent: setContent,
getTitle: getTitle,
getContent: getContent
}
}());
// usage
Article.setOrUpdateValues("title", "content");
printValues();
Article.updateTitle("updated title");
printValues();
Article.setOrUpdateValues(null, "newContent");
printValues();
function printValues() {
var values = Article.getValues();
console.log("title: " + values.title + ", content: " + values.content);
}

Categories

Resources