Add code in page base to header C# - c#

I have the following code in my MasterPageBase.cs file:
protected override void OnLoad(EventArgs e)
{
string url = Request.Path;
var page = _ContentPageRepository.GetContentPageByUrl(url, ConfigurationManager.GetSiteID());
if (page != null)
{
PageBase.SetTitle(page.Title);
PageBase.SetDescription(page.Description);
PageBase.SetKeywords(page.Keywords);
}
else
{
this.ProcessSiteMap();
}
this.AddGACode();
base.OnLoad(e);
}
I need this.AddGACode(); to get added to the head section of the page, but when I view the source of the page as I am running the solution, I see that this is adding it to the body section of the page.
I have tried Page.Header.Controls.Add(AddGACode()); and get the following errors:
The best overloaded method match has some invalid arguments and cannot convert from 'void' to 'System.Web.UI.Control'
What can I do to get this code added to the head? TIA
EDIT: Request to see the AddGACode method:
private void AddGACode()
{
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
if (!ConfigurationManager.EnableUniversalGATracking)
{
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\">");
csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
}
else
{
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<!-- Universal GA Code --><script type=\"text/javascript\">");
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
}
}
}
EDIT:
This code is in the AddGACode method. There is still this.AddGACode(); in the OnLoad of the page that seems to duplicate the code with this edit, but both codes will disappear if I delete this.AddGACode(); from OnLoad
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<!-- Universal GA Code --><script type=\"text/javascript\">");
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
LiteralControl lc = new LiteralControl(csText.ToString());
Page.Header.Controls.Add(lc);

This adds the script into the head tag:
LiteralControl lt = new LiteralControl("<script type='text/javascript'>alert('test');</script>");
Header.Controls.Add(lt);
UPDATE
LiteralControl lt = new LiteralControl(AddGACode());
Header.Controls.Add(lt);
...
private string AddGACode()
{
var result = string.Empty;
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\">");
if (!ConfigurationManager.EnableUniversalGATracking)
{
csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
}
else
{
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
}
csText.Append("</script>");
result = csText.ToString();
}
return result;
}

I'd keep your markup, in this instance your ga scripts, on mastpage itself. In the head tag add two literals, gaGaq and gaUniversal an then use you logic to contol the visibility of them.
<head runat="server"><script type="text\javascript">
<asp:Literal id="gaGaq" runat="server">
<!-- Put you gaq code here-->
<!-- Keep {0} as a place holder for gaqCode -->
</script>
</asp:Literal>
<asp:Literal id="gaUniveral" runat="server">
<script type="text\javascrtip">
<!-- Put you universal code here-->
<!-- Keep {0} as a place holder for gaqCode -->
</script>
</asp:Literal>
</head>
C#
private void AddGACode()
{
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
if(ConfigurationManager.EnableUniversalGATracking)
{
//Set gaCode
gaUniversal.Text = string.Fomat(gaUniveral.Text, gaCode);
}
else
{
//Set gaCode
gaGaq.Text = string.Format(ga.Text, gaCode);
}
gaUniversal.Visible = ConfigurationManager.EnableUniversalGATracking;
gaGaq.Visible = !ConfigurationManager.EnableUniversalGATracking;
}
else
{
//Hide Both literals if no gaCode
gaUniversal.Visible = gaGaq.Visible = false;
}
}
You could also look at putting all this into a custom control. If you're interested in taking that route I wrote a blog article on exactly that for the gaq style google analytics so I could drop it onto my many asp.net websites. The code in that article owuld need to be modified to suite your needs but should be enough to get you stared.

Related

Connect Local AD with C# .Net Webform

Having trouble understanding this error below in vs.net.
I'm trying to grab a logged in user account on the domain and allow them to be able to edit their phone number.
Another guy setup the AD Access, but I can't event get a logged in user name.
Pasted the code VS.NET errors on every time with the exception that I found in an online article and worked for everyone else except me.
I've verified it works using powershell but I could use some help.
THANKS!!!
//parse the current user's logon name as search key
string sFilter = String.Format(
"(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))",
User.Identity.Name.Split(new char[] { '\\' })[1]
);
Exception User-Unhandled
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
<%# Import Namespace="System.DirectoryServices.ActiveDirectory" %>
<%# Import Namespace="System.DirectoryServices.AccountManagement" %>
<!DOCTYPE html>
<head>
<script language="c#" runat="server">
static string adsPath = "LDAP://dc=DOMAIN,dc=com";
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
SearchResult sr = FindCurrentUser(new string[] { "allowedAttributesEffective" });
if (sr == null)
{
msg.Text = "User not found...";
return;
}
int count = sr.Properties["allowedAttributesEffective"].Count;
if (count > 0)
{
int i = 0;
string[] effectiveAttributes = new string[count];
foreach (string attrib in sr.Properties["allowedAttributesEffective"])
{
effectiveAttributes[i++] = attrib;
}
sr = FindCurrentUser(effectiveAttributes);
foreach (string key in effectiveAttributes)
{
string val = String.Empty;
if (sr.Properties.Contains(key))
{
val = sr.Properties[key][0].ToString();
}
GenerateControls(key, val, parent);
}
}
}
else
{
UpdateControls();
}
}
private SearchResult FindCurrentUser(string[] attribsToLoad)
{
//parse the current user's logon name as search key
string sFilter = String.Format(
"(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))",
User.Identity.Name.Split(new char[] { '\\' })[1]
);
DirectoryEntry searchRoot = new DirectoryEntry(
adsPath,
null,
null,
AuthenticationTypes.Secure
);
using (searchRoot)
{
DirectorySearcher ds = new DirectorySearcher(
searchRoot,
sFilter,
attribsToLoad,
SearchScope.Subtree
);
ds.SizeLimit = 1;
return ds.FindOne();
}
}
private void GenerateControls(string attrib, string val, Control parent)
{
parent.Controls.Add(new LiteralControl("<div>"));
TextBox t = new TextBox();
t.ID = "c_" + attrib;
t.Text = val;
t.CssClass = "txt";
Label l = new Label();
l.Text = attrib;
l.AssociatedControlID = t.ID;
l.CssClass = "lbl";
parent.Controls.Add(l);
parent.Controls.Add(t);
parent.Controls.Add(new LiteralControl("</div>"));
}
private void UpdateControls()
{
SearchResult sr = FindCurrentUser(new string[] { "cn" });
if (sr != null)
{
using (DirectoryEntry user = sr.GetDirectoryEntry())
{
foreach (string key in Request.Form.AllKeys)
{
if (key.StartsWith("c_"))
{
string attrib = key.Split(new char[] { '_' })[1];
string val = Request.Form[key];
if (!String.IsNullOrEmpty(val))
{
Response.Output.Write("Updating {0} to {1}<br>", attrib, val);
user.Properties[attrib].Value = val;
}
}
}
user.CommitChanges();
}
}
btnSubmit.Visible = false;
Response.Output.Write("<br><br>< Back", Request.Url);
}
</script>
<style>
.lbl
{
margin-left: 25px;
clear: left;
width: 250px;
}
.txt
{
width: 250px;
}
</style>
</head>
<body>
<form id="main" runat="server">
Data for user:
<%=User.Identity.Name%>
<br>
<br>
<asp:Label ID="msg" runat="server" />
<asp:Panel ID="parent" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Update" />
</form>
</body>
</html>

How can I scan a document using ASP.net MVC 5 with the help of Twain

Please help me out by sharing the step by step procedure to achieve the scanning functionality using Twain in ASP.Net MVC5. Thank you
Solution is here:
In ASP.Net/Core Project you send message to call winform project:
var start = function () {
var i = 0;
var wsImpl = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://localhost:8181/');
ws.onmessage = function (e) {
$('#submit').hide();
$('#scanBtn').hide();
$('.loader').show();
if (typeof e.data === "string") {
//IF Received Data is String
}
else if (e.data instanceof ArrayBuffer) {
//IF Received Data is ArrayBuffer
}
else if (e.data instanceof Blob) {
i++;
var f = e.data;
f.name = "File" + i;
storedFiles.push(f);
formdata.append(f.name, f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div class=\"col-sm-2 text-center\"
style=\"border: 1px solid black; margin-left: 2px;\"><img
height=\"200px\" width=\"200px\" src=\"" + e.target.result + "\"
data-file='" + f.name + "' class='selFile' title='Click to
remove'><br/>" + i + "</div>";
selDiv.append(html);
$('#submit').show();
$('#scanBtn').show();
$('.loader').hide();
}
reader.readAsDataURL(f);
}
};
ws.onopen = function () {
//Do whatever u want when connected succesfully
};
ws.onclose = function () {
$('.dalert').modal('show');
};
}
window.onload = start;
function scanImage() {
ws.send("1100");
};
https://javascript.info/websocket
In Winforms Project you scan document and send graphic data back to Asp.Net/Core project:
public partial class Form1 : Form
{
ImageCodecInfo _tiffCodecInfo;
TwainSession _twain;
bool _stopScan;
bool _loadingCaps;
List allSockets;
WebSocketServer server;
public Form1()
{
InitializeComponent();
if (NTwain.PlatformInfo.Current.IsApp64Bit)
{
Text = Text + " (64bit)";
}
else
{
Text = Text + " (32bit)";
}
foreach (var enc in ImageCodecInfo.GetImageEncoders())
{
if (enc.MimeType == "image/tiff") { _tiffCodecInfo = enc; break; }
}
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
allSockets = new List<IWebSocketConnection>();
server = new WebSocketServer("ws://0.0.0.0:8181");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine("Open!");
allSockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>
{
if (message == "1100")
{
this.Invoke(new Action(()=> {
this.WindowState = FormWindowState.Normal;
}));
}
};
});
}
Link to project.
https://github.com/mgriit/ScanAppForWeb
You can remake this project, as you want.
At this moment, none of the browsers support scanning out of the box. You need to use a third-party library (not part of Microsoft's .NET core components). Below example uses Scanner.js, which is a product offered by our company:
Enable Scanning from TWAIN Scanners to ASP.NET Pages: Step by Step
Below steps use Scanner.js as example; they may differ for other products.
1) Include the scanning library in your HTML code:
<script type="text/javascript" src="//asprise.azureedge.net/scannerjs/scanner.js"></script>
2) Add a button to trigger the scanning process:
function scanToJpg() {
scanner.scan(displayImagesOnPage,
{
"twain_cap_setting" : {
"ICAP_PIXELTYPE" : "TWPT_RGB", // Color
"ICAP_XRESOLUTION" : "100", // DPI: 100
"ICAP_YRESOLUTION" : "100",
"ICAP_SUPPORTEDSIZES" : "TWSS_USLETTER" // Paper size: TWSS_USLETTER, TWSS_A4, ...
},
"output_settings" :
[
{
"type" : "return-base64",
"format" : "jpg"
}
]
}
);
}
3) Handle the scan result - display, upload, etc.
Below code creates an img element for each image scanned to display on the current web page:
/** Processes the scan result */
function displayImagesOnPage(successful, mesg, response) {
var scannedImages = scanner.getScannedImage(response, true, false); // returns an array of ScannedImage
for(var i = 0; (scannedImages instanceof Array) && i < scannedImages.length; i++) {
var scannedImage = scannedImages[i];
processScannedImage(scannedImage);
}
}
/** Images scanned so far. */
var imagesScanned = [];
/** Processes a ScannedImage */
function processScannedImage(scannedImage) {
imagesScanned.push(scannedImage);
var elementImg = createDomElementFromModel( {
'name': 'img',
'attributes': {
'class': 'scanned',
'src': scannedImage.src
}
});
document.getElementById('images').appendChild(elementImg);
}
For examples of scanning into PDF formats and direct uploading, please visit the code repository: https://github.com/Asprise/scannerjs.javascript-scanner-access-in-browsers-chrome-ie.scanner.js

html agility pack function scraping

I have a problem as I am new in html agility pack. What I'm looking for is function from the page. The code below. I want to just take out a function named getDirections then replace start koniec and then repaste it into webpage again, then display it in my app. One question again, is there need to create two html files? Firt static, which never changes, just to load code, and second to display it? As I have to always replace start koniec? Thanks for help and advice!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Find directions</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var end;
var start;
function getMap()
{
map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: ''});
alert('');
getDirections();
}
function getDirections()
{
start= 'start'; end= 'koniec';
map.getCredentials(callRouteService);
}
function callRouteService(credentials)
{
var routeRequest = 'http://dev.virtualearth.net/REST/v1/Routes?wp.0=' + start + '&wp.1=' + end + '&routePathOutput=Points&output=json&jsonp=routeCallback&key=' + credentials;
var mapscript = document.createElement('script');
mapscript.type = 'text/javascript';
mapscript.src = routeRequest;
document.getElementById('myMap').appendChild(mapscript);
}
function routeCallback(result)
{
var output = document.getElementById("output");
if (output)
{
while (output.hasChildNodes()) {
output.removeChild(output.lastChild);
}
var resultsHeader = document.createElement("h5");
var resultsList = document.createElement("ol");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
}
if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0)
{
//resultsHeader.innerHTML = "Bing Maps REST Route API <br/> Route from " + result.resourceSets[0].resources[0].routeLegs[0].startLocation.name + " to " + result.resourceSets[0].resources[0].routeLegs[0].endLocation.name;
var resultsListItem = null;
//for (var i = 0; i < result.resourceSets[0].resources[0].routeLegs[0].itineraryItems.length; ++i)
//{
//resultsListItem = document.createElement("li");
//resultsList.appendChild(resultsListItem);
//resultStr = result.resourceSets[0].resources[0].routeLegs[0].itineraryItems[i].instruction.text;
//resultsListItem.innerHTML = resultStr;
//}
var bbox = result.resourceSets[0].resources[0].bbox;
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
map.setView({ bounds: viewBoundaries});
var routeline = result.resourceSets[0].resources[0].routePath.line; var routepoints = new Array();
for (var i = 0; i < routeline.coordinates.length; i++)
{
routepoints[i]=new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
}
var routeshape = new Microsoft.Maps.Polyline(routepoints, {strokeColor:new Microsoft.Maps.Color(200,0,0,200)});
var startPushpinOptions = {anchor: new Microsoft.Maps.Point(10, 32) };
var startPin= new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(routeline.coordinates[0][0], routeline.coordinates[0][1]), startPushpinOptions);
var endPushpinOptions = {anchor: new Microsoft.Maps.Point(10, 32)};
var endPin= new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(routeline.coordinates[routeline.coordinates.length-1][0], routeline.coordinates[routeline.coordinates.length-1][1]), endPushpinOptions);
map.entities.push(startPin);
map.entities.push(endPin);
map.entities.push(routeshape);
}
else
{
if (typeof(result.errorDetails) != 'undefined')
{
resultsHeader.innerHTML = result.errorDetails[0];
}
alert("No Route found");
}
}
</script>
</head>
<body onload="getMap();">
<div id='myMap' style="position:relative; width:400px; height:400px;"></div>
<div id="output"></div>
</body>
</html>

Grab information from database and insert into drop down list dynamically

I have a little website where I am trying to grab a certain column from the database(SQL Server Management Studio) and insert these values into a drop down list.
My HTML code loads a simple page with a drop down list.
<html>
<body onload = "Location();">
<h4>Home Page</h4>
CompanyName
<select id="company" name="C1" >
<option>Pick A Location</option>
</select>
</body>
<html>
Before my JavaScript function does any "work" it navigates to a c# page. I debugged the c# code and it does output correctly. It shows:
"<root>\n<CompanyName>\n\t<option>AAA</option>\n\t<option>BBB</option>\n\t<option>CCC</option>\n\t<option>DDD</option>\n\t<option>EEE</option>\n\t<option>FFF</option>\n\t<option>GGG</option>\n\t<option>HHH</option>\n</CompanyName>\n</root>"
which is just the columns from the database that I need to input into the drop down list.
The javascript function is supposed to grab this chunk of code and dive into the option section and put each option into the drop down list one by one. For some reason between navigating from the c# page to the javaScript page, i lose the xml information. Is there something that I am missing or is there something incorrect? Thank you.
function Location() {
$.ajax({
url: "Test.aspx",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
}).done(function (data) {
if (console && console.log) {
xml = data;
xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
var settingHTML = "";
settingHTML += "<option value = 'null' > Pick a Location </option>";
$xml.find('root').each(function () {
$xml.find('CompanyName').each(function () {
// one at a time
$(this).children().each(function () {
settingHTML += "<option value='" + $(this).text() + "' >" + $(this).text() + "</option>";
});
});
});
$("#company").html(settingHTML);
}
});
}
I am also going to add my c# code as it seems that it could be the way I am returning the string possibly
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string root = "<root>\n";
root += fill_company();
root += "</root>";
Response.Write(root);
}
protected string fill_company()
{
OdbcDataReader reader;
string myConnString = "DSN=DevSql12-1;";
OdbcConnection conn = new OdbcConnection(myConnString);
OdbcCommand mycommand = new OdbcCommand();
mycommand.Connection = conn;
conn.Open();
mycommand.CommandText = "SELECT CompanyName FROM [PS_Settings].[cams].[Client];";
reader = mycommand.ExecuteReader();
string CompanyLocation = "";
CompanyLocation += "<CompanyName>\n";
object[] meta = new object[1];
bool read;
if (reader.Read() == true)
{
do
{
int NumberOfColumns = reader.GetValues(meta);
for (int i = 0; i < NumberOfColumns; i++)
{
CompanyLocation += "\t<option>" + meta[i].ToString() + "</option>\n";
}
read = reader.Read();
} while (read == true);
}
CompanyLocation += "</CompanyName>\n";
return CompanyLocation;
}
}
The issue was that I didn't show the actual output (wasn't actually AAA, BBB), but the reason for my error is because one of the options had an '&', and I forgot to escape it.

Why can't JQuery load my resource?

I have the following script in an page called ajax.aspx page:
<script type="text/javascript">
$(document).ready(function () {
var nameFoundMessage = $('#nameFoundMessage');
var nameInput = $('#name');
nameFoundMessage.hide();
nameInput.blur(function () {
if ($(this).val()) {
$.getJSON('Services/ArtistFound.aspx?' + escape($(this).val()), function (results) {
if (results.available) {
if (nameFoundMessage.is(':visible')) {
nameFoundMessage.html('The name was found');
}
}
else {
nameFoundMessage.show();
nameFoundMessage.html('The name was not found');
}
});
}
});
});
</script>
The page has an input field with an id of "name" and when I blur off of that it goes into a service folder which has another aspx page ArtistFound.aspx and in that Page load, I have the following:
Response.ContentType = "application/json";
string name = Request.QueryString.ToString();
string output = string.Empty;
name = db.Names.Single(x => x.Name== name).Name;
if(name == null)
{
output = "{available:false}";
}
else
{
output = "{available:true}";
}
Response.Write(output);
}
When I run the page and blur off the input, it says the following:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I have tried ../Services/ArtistFound.aspx... and /Services/ArtistFound.aspx..., but it still gives me the same error.
You want:
name = db.Names.FirstOrDefault(x => x.Name== name);
if(name != null && name.Name != null)
{
output = "{available:true}";
}
else
{
output = "{available:false}";
}
This will return null if it is not found rather than throwing an exception like Single() does.
I would also recommend you use an ASHX handler rather than an ASPX page to do this call.
To do this you just add a 'Generic Handler' file in visual studio then you can put replace the ProcessRequest method with this:
public void ProcessRequest(HttpContext context)
{
string name = context.Request.QueryString.ToString();
string output = string.Empty;
name = db.Names.FirstOrDefault(x => x.Name == name);
if (name != null && name.Name != null)
{
output = "{available:true}";
}
else
{
output = "{available:false}";
}
context.Response.ContentType = "application/json";
context.Response.Write(output);
}

Categories

Resources