Hosting a webService in Sharepoint - c#
I'm loosing my mind with an issue about hosting wcf in SharePoint. I'm not able to reach my webservice, I saw on it on my SharePoint site but when I'm clicking on it I have an error message
Edit: I delete my public key to be sure that the problem doensn't come from here
So i have my ASP.NET Web Application which is called: Foo.PS2016.PSIExtension
With its iservice and Service (Very simple one):
Iservice:
namespace Foo.PS2016.PSIExtension
{
[ServiceContract]
interface IService
{
[OperationContract]
bool isAlive();
}
}
Service:
namespace Foo.PS2016.PSIExtension
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
internal class Service : IService
{
public bool isAlive()
{
return (true);
}
}
}
its Service.svc:
<%# ServiceHost Language="C#" Debug="true" Service="Foo.PS2016.PSIExtension.Service" %>
and its webservice:
<?xml version="1.0" encoding="utf-8"?>
<!--
-->
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://sfd-2016-01/sites/pwa/" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
and I have my SharePoint solution with its folder ISAPI=>PSI=>Foo.PS2016.PSIExtension.svc :
The Version, culture and PublicKey comes from a powershell command from the file: Foo.PS2016.PSIExtension.dll
So I have been stucking on this issue since this morning so if someone has some ideas to help me
So this is the result of my ajax call:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:o="urn:schemas-microsoft-com:office:office" lang="en-us" dir="ltr">
<head><meta name="GENERATOR" content="Microsoft SharePoint" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta http-equiv="Expires" content="0" /><meta http-equiv="X-UA-Compatible" content="IE=8"/><meta name="ROBOTS" content="NOHTMLINDEX" /><title>
Error
</title><link rel="stylesheet" type="text/css" href="/_layouts/15/1033/styles/corev15.css?rev=i237P0%2BWmCDIsNnTvKWmyg%3D%3DTAG0"/>
<link rel="stylesheet" type="text/css" href="/_layouts/15/1033/styles/error.css?rev=uLsAgejtz6uU3M4tXKgEfA%3D%3DTAG0"/>
<script type="text/javascript" src="/_layouts/15/1033/initstrings.debug.js?rev=FPxEulJ9Nz3gxtb2SaxF6g%3D%3DTAG0"></script>
<script type="text/javascript" src="/_layouts/15/init.debug.js?rev=2nn1mwPjUX5aE85AUUjDGw%3D%3DTAG0"></script>
<script type="text/javascript" src="/ScriptResource.axd?d=GIJq-Z4bxUgQ1eeUBIHs5TQTn3kW6sT7yUXQTl4rpjULIbN8l-8p5XVhLDaSql7d5A-3pUW-QYv9cNcSN8liy_MdG4bV-tm3jPg_qX7_SzwnVcDWWxcD7gCBFnjOMi41nNZ1dTrbIXVUnjy2b65YO3EoqipnBU5ZsFUeYIzPrruiuztdGyeUat-m3R42Mv8a0&t=2a48f442"></script>
<script type="text/javascript" src="/_layouts/15/blank.js?rev=Y52JlQQL8Ld7e28E1u1PXw%3D%3DTAG0"></script>
<script type="text/javascript" src="/ScriptResource.axd?d=DtxdsIxZ13GzDhO3js7m9Y5qqFa6jCdy5nWUs3QtO0OiymWNuz8ei7lyf7bZCIumCWC3yWeU3nI7HsPj_4MfIjnCYUbbGjzuUKdAGAG2R016R_w2gdgT06fcxkcT6lssmCtiM7sqvDESEv9aa4lcHigN66DWM8TOlx0fEEBwiQpwSE8NNqGUPcIkkyx2wGxEmyZMGotZO6OcGHT_8EAtNg2&t=2a48f442"></script>
<script type="text/javascript">RegisterSod("require.js", "\u002f_layouts\u002f15\u002frequire.js?rev=\u00252BRRfOnYW0VaAgSoCgcIN8Q\u00253D\u00253DTAG0");</script>
<script type="text/javascript">RegisterSod("strings.js", "\u002f_layouts\u002f15\u002f1033\u002fstrings.debug.js?rev=ClRR65\u00252FJrktrUN4XIKIREQ\u00253D\u00253DTAG0");</script>
<script type="text/javascript">RegisterSod("sp.res.resx", "\u002f_layouts\u002f15\u002f1033\u002fsp.res.js?rev=MbB92HT8biYuFa\u00252B1vTMilA\u00253D\u00253DTAG0");</script>
<script type="text/javascript">RegisterSod("sp.runtime.js", "\u002f_layouts\u002f15\u002fsp.runtime.debug.js?rev=Vehk\u00252FiThFRjckdql8i15Ag\u00253D\u00253DTAG0");RegisterSodDep("sp.runtime.js", "sp.res.resx");</script>
<script type="text/javascript">RegisterSod("sp.js", "\u002f_layouts\u002f15\u002fsp.debug.js?rev=fIEkblNHoC3DmVwyA9fW7Q\u00253D\u00253DTAG0");RegisterSodDep("sp.js", "sp.runtime.js");RegisterSodDep("sp.js", "sp.ui.dialog.js");RegisterSodDep("sp.js", "sp.res.resx");</script>
<script type="text/javascript">RegisterSod("sp.init.js", "\u002f_layouts\u002f15\u002fsp.init.debug.js?rev=r7eoFYyCjoRR1v71zF6w6A\u00253D\u00253DTAG0");</script>
<script type="text/javascript">RegisterSod("sp.ui.dialog.js", "\u002f_layouts\u002f15\u002fsp.ui.dialog.debug.js?rev=JWExCHnIyo1aEflEW9vZxQ\u00253D\u00253DTAG0");RegisterSodDep("sp.ui.dialog.js", "sp.init.js");RegisterSodDep("sp.ui.dialog.js", "sp.res.resx");</script>
<script type="text/javascript">RegisterSod("core.js", "\u002f_layouts\u002f15\u002fcore.debug.js?rev=uhz\u00252B5jl6DViyR8K7N2onWQ\u00253D\u00253DTAG0");RegisterSodDep("core.js", "strings.js");</script>
<script type="text/javascript">RegisterSod("foldhyperlink.js", "\u002f_layouts\u002f15\u002ffoldhyperlink.debug.js?rev=hsjDlc\u00252BMqWuhI3IZAGCRqQ\u00253D\u00253DTAG0");</script>
<meta name="Robots" content="NOINDEX " />
<meta name="SharePointError" content="0" />
<link rel="shortcut icon" href="/_layouts/15/images/favicon.ico?rev=40" type="image/vnd.microsoft.icon" /></head>
<body id="ms-error-body" onload="if (typeof(_spBodyOnLoadWrapper) != 'undefined') _spBodyOnLoadWrapper();">
<form method="post" action="./error.aspx?ErrorText=The+type+%27Test.PS2016.PSIExtension.Service%2c+Test.PS2016.PSIExtension%2c+Version%3d1.0.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3dnull%27%2c+provided+as+the+Service+attribute+value+in+the+ServiceHost+directive%2c+or+provided+in+the+configuration+element+system.serviceModel%2fserviceHostingEnvironment%2fserviceActivations+could+not+be+found." id="aspnetForm" onsubmit="if (typeof(_spFormOnSubmitWrapper) != 'undefined') {return _spFormOnSubmitWrapper();} else {return true;}">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTMxMjY5NDA5NQ9kFgJmD2QWAgIBD2QWAgIDD2QWAgIJD2QWAgIBD2QWBAIDDw8WAh4HVmlzaWJsZWhkZAIHD2QWAgIBDw8WAh4XTGlua1RpdGxlV2hlbkZvbGRDbG9zZWQFEVRlY2huaWNhbCBEZXRhaWxzZBYIZg9kFgICAQ8PZBYCHgdvbmNsaWNrBcgBRW5zdXJlU2NyaXB0UGFyYW1zKCdmb2xkaHlwZXJsaW5rLmpzJywgJ1RvZ2dsZUZvbGRUZXh0JywgJzYzYzE2ZTE0ZDczZjQ1ODE4YTRlNmU4YjNmODY2Zjg4JywgJ2N0bDAwX1BsYWNlSG9sZGVyTWFpbl9Gb2xkTGlua19fbW9yZURldGFpbHNMaW5rJywgJ1RlY2huaWNhbCBEZXRhaWxzJywgJ1RlY2huaWNhbCBEZXRhaWxzJyk7O3JldHVybiBmYWxzZTsWAgIBDw8WAh4EVGV4dAURVGVjaG5pY2FsIERldGFpbHMWBB4EaHJlZgUBIx8CBRtQcmV2ZW50RGVmYXVsdE5hdmlnYXRpb24oKTtkAgUPDxYCHwBoZGQCCQ8PFgIfAwU0Q29ycmVsYXRpb24gSUQ6IDZiMDc1ZTllLWUxZmQtMTBhYy04N2FkLTI3M2U4NTIyYjZmYmRkAgsPDxYCHwMFI0RhdGUgYW5kIFRpbWU6IDQvMTYvMjAxOCAxOjQ5OjMyIFBNZGRk/Ntc91GhLAEgVx/VJMcHSI1WvxzG6XMahftfMlC9Lxc=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/WebResource.axd?d=kqzbgiHYRPrIk2c8aGZXXtswgMsrN6SqxII1hyFPNd1D82NA8x9uOyjyzjXfPaUCFQZbznkKisM-JIwuoGt2n00XLarOKlQh2_rmdbXjf981&t=636160876665894255" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var g_presenceEnabled = true;
var g_wsaEnabled = false;
var g_correlationId = '6b075e9e-e1fd-10ac-87ad-273e8522b6fb';
var g_wsaQoSEnabled = false;
var g_wsaQoSDataPoints = [];
var g_wsaRUMEnabled = false;
var g_wsaLCID = 1033;
var g_wsaListTemplateId = null;
var g_wsaSiteTemplateId = 'STS#0';
var _fV4UI=true;var _spPageContextInfo = {webServerRelativeUrl: "\u002f", webAbsoluteUrl: "http:\u002f\u002fsfd-2016-01", siteAbsoluteUrl: "http:\u002f\u002fsfd-2016-01", serverRequestPath: "\u002f_layouts\u002f15\u002ferror.aspx", layoutsUrl: "_layouts\u002f15", webTitle: "Root Site Collection", webTemplate: "1", tenantAppVersion: "2395466148", isAppWeb: false, webLogoUrl: "_layouts\u002f15\u002fimages\u002fsiteicon.png", webLanguage: 1033, currentLanguage: 1033, currentUICultureName: "en-US", currentCultureName: "en-US", clientServerTimeDelta: new Date("2018-04-16T11:49:32.8917464Z") - new Date(), updateFormDigestPageLoaded: new Date("2018-04-16T11:49:32.8917464Z"), siteClientTag: "0$$16.0.4507.1000", crossDomainPhotosEnabled:false, webUIVersion:15, webPermMasks:{High:2147483647,Low:4294967295}, pagePersonalizationScope:1,userId:1073741823,userLoginName:"SHAREPOINT\\system", systemUserKey:"S-1-0-0", alertsEnabled:true, siteServerRelativeUrl: "\u002f", allowSilverlightPrompt:'True', isSiteAdmin: true};Flighting.ExpFeatures = [480215056,1880287568,1561350208,302071836,3212816,69473024,4194310,-2113396707,268502022,-872284160,1049232,-2147421952,65536,65536,2097472,917504,-2147474174,1372324107,67108882,0,0,-2147483648,2097152,0,0,32768,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32768];//]]>
</script>
<script src="/_layouts/15/blank.js?rev=Y52JlQQL8Ld7e28E1u1PXw%3D%3DTAG0" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
if (typeof(DeferWebFormInitCallback) == 'function') DeferWebFormInitCallback();//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="F3F6CE2F" />
</div>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ctl00$ScriptManager', 'aspnetForm', [], [], [], 90, 'ctl00');
//]]>
</script>
<div id="ms-error-header" class="ms-pr">
<h1 class="ms-core-pageTitle">
<div id="ctl00_PlaceHolderPageTitleInTitleArea_ErrorPageTitlePanel">
Sorry, something went wrong
</div>
</h1>
<div>
</div>
</div>
<div id="ms-error">
<div id="ms-error-top">
</div>
<div id="ms-error-content">
<div id="ms-error-error-content">
<div id="DeltaPlaceHolderMain">
<div>
<span id="ctl00_PlaceHolderMain_LabelMessage">The type 'Test.PS2016.PSIExtension.Service, Test.PS2016.PSIExtension, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.</span>
</div>
<div id="ctl00_PlaceHolderMain_FoldPanel" class="ms-error-detailsFold">
<div id="ctl00_PlaceHolderMain_FoldLink_foldLinkWrapper">
<div id="ctl00_PlaceHolderMain_FoldLink_foldLinkPanel" class="ms-foldHyperLink-panel" onclick="EnsureScriptParams('foldhyperlink.js', 'ToggleFoldText', '63c16e14d73f45818a4e6e8b3f866f88', 'ctl00_PlaceHolderMain_FoldLink__moreDetailsLink', 'Technical Details', 'Technical Details');;return false;">
<a id="ctl00_PlaceHolderMain_FoldLink__moreDetailsLink" class="ms-commandLink ms-floatLeft" href="#" onclick="PreventDefaultNavigation();">Technical Details</a>
<div class="ms-clear"></div>
</div>
</div><div class="ms-hide" id="63c16e14d73f45818a4e6e8b3f866f88">
<div>
<p>
<span class="ms-descriptiontext">
</span>
</p>
<p>
<span class="ms-descriptiontext">
<div id="ctl00_PlaceHolderMain_FoldLink_WSSEndUser_troubleshootingPanel">
<span id="ctl00_PlaceHolderMain_FoldLink_helptopic_WSSEndUser_troubleshooting"><a title="Troubleshoot issues with Microsoft SharePoint Foundation. - Opens in new window" href="javascript:HelpWindowKey('WSSEndUser_troubleshooting')">Troubleshoot issues with Microsoft SharePoint Foundation.</a></span>
</div>
</span>
</p>
<p>
<span id="ctl00_PlaceHolderMain_FoldLink_RequestGuidText" class="ms-metadata">Correlation ID: 6b075e9e-e1fd-10ac-87ad-273e8522b6fb</span>
</p>
<p>
<span id="ctl00_PlaceHolderMain_FoldLink_DateTimeText" class="ms-metadata">Date and Time: 4/16/2018 1:49:32 PM</span>
</p>
</div>
</div>
</div>
<div class="ms-error-techMsg">
<hr />
</div>
<script type="text/javascript">// <![CDATA[
var gearPage = document.getElementById('ms-loading-box');
if(null != gearPage)
{
gearPage.parentNode.removeChild(gearPage);
document.title = "Error";
}
function _spBodyOnLoad()
{
var intialFocus = (document.getElementById("ctl00_PlaceHolderMain_FoldLink__moreDetailsLink"));
try
{
intialFocus.focus();
}
catch(ex)
{
}
}
function _onmessage(e)
{
if (e && window.JSON)
{
var origin = e.origin;
var data = e.data;
if (window.console && window.console.log)
{
console.log("ErrorPage.OnMessage: Origin=" + origin + ", Data=" + data);
}
var requestInfo = JSON.parse(data);
if (requestInfo && (requestInfo.command == 'Ping' || requestInfo.command == 'Query'))
{
var requestGuidElem = (document.getElementById("ctl00_PlaceHolderMain_FoldLink_RequestGuidText"));
var responseInfo = {};
responseInfo.command = requestInfo.command;
responseInfo.postMessageId = requestInfo.postMessageId;
responseInfo.responseAvailable = false;
responseInfo.errorCode = -1007;
var errorMessage;
if (requestGuidElem)
{
errorMessage = requestGuidElem.textContent;
if (typeof(errorMessage) == "undefined")
{
errorMessage = requestGuidElem.innerText;
}
}
if (typeof(errorMessage) == "undefined")
{
errorMessage = "Error";
}
responseInfo.errorMessage = errorMessage;
if (window.parent && window.parent.postMessage)
{
data = JSON.stringify(responseInfo);
if (window.console && window.console.log)
{
console.log("ErrorPage.PostMessage: Origin=" + origin + ", Data=" + data);
}
window.parent.postMessage(data, origin);
}
}
}
}
if (window.addEventListener) {
window.addEventListener('message', _onmessage, false);
}
else if (window.attachEvent) {
window.attachEvent('onmessage', _onmessage);
}
// ]]>
</script>
</div>
</div>
<div id="ms-error-gobackcont" class="ms-calloutLink">
Go back to site
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
var g_MinimalDownload = true;var g_WebServerRelativeUrl = "/";var _spFullDownloadList = ['closeconnection', 'download', 'signout', 'xlviewer', 'wordviewer', 'wordeditor', 'powerpoint', 'powerpointframe', 'onenote', 'visiowebaccess', 'storefront', 'wopiframe', 'appredirect', 'wfstart', 'developertools'];
//]]>
</script>
</form>
</body>
</html>
Change your .svc file to:
<%# ServiceHost Language="C#" Debug="true"
Service="Foo.PS2016.PSIExtension.Service, $SharePoint.Project.AssemblyFullName$"
CodeBehind="Service.cs"
Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
MultipleBaseAddressWebServiceHostFactory creates configuration dynamically so you can get rid of your web.config modifications and you will have your REST endpoint working out-of-the-box after deployment.
and decorate your interface methods with WebGet attribute:
[WebGet(UriTemplate = "isAlive", BodyStyle = WebMessageBodyStyle.Bare)]
and additionally (not necessarily) add BasicHttpBindingServiceMetadataExchangeEndpointAttribute to your class
As I said in comments, this tutorial goes through all actions step by step so use it!
Related
Cross-Origin Request Blocked - .net Web API and JS AJAX
I'm attempting to use Ajax to capture a submit event and then send the form elements formatted as JSON to a asp.net Web API 2. I am using the latest version of FireFox. Ad blocker is disabled. I have an SSL on both origin and destination. I have followed the steps in this guide to Enable cross-origin requests. https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api I have tested that my form with out javascript can send to the API no problem and recieve results. I have also tested using Postman. I would like to capture the response from the API and show it in an alert message. here is a screen shot of the error in the browser https://imgur.com/a/3wM7M1Y here is a screen shot from postman of the server response confirming it accepts all https://imgur.com/a/1MZ9dGE Here is my HTML ` <!DOCTYPE html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TLogin</title> <link rel="stylesheet" href="CSS/main.css"> <script src="JS/main.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { var form = $('#login_form')[0]; form.onsubmit = function (e) { var data = $("#login_form :input").serializeArray(); console.log(data); $.ajax({ type: 'POST', url: "https://api.website.org/api/users/login", xhrFields: { withCredentials: false }, data: data, processData: false, contentType: "application/json; charset=utf-8", success: function (data) { alert(data); }, error: function (xhrRequest, status, error) { alert(JSON.stringify(xhrRequest)); } }); return false; } }); </script> </head> <html> <body> <form id="login_form"> <div class="master_container"> <div id="views_container" class="clear"> <div class="view_container"> <span>Username :</span> <input type="text" id="username" name="username"> </div> <div class="view_container"> <span>Password :</span> <input type="password" id="password" name="password"> </div> <div class="view_container"> <input id="ip" type="hidden" value="myip" /> <input type="submit" id="Button_Login" value="Login" /> </div> <div class="view_container"> </div> </div> </div> </form> </body> </html> ` Here is my API Controller Info ` [EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "*", SupportsCredentials = false)] public class UsersController : ApiController { //user login [Route("api/Users/Login")] [HttpPost] public UsersSession Login(Users users) { UsersSession UsersSession = new UsersSession(); UsersSession.result = new Result(); try { if (users != null && !string.IsNullOrWhiteSpace(users.username) && !string.IsNullOrWhiteSpace(users.password)) { var v_meta_list = new List<string>(); var v_search_results = new List<string>(); v_meta_list.Add("username=" + users.username); v_meta_list.Add("password=" + users.password); v_search_results = CL_db.db_search("4", v_meta_list, true); if (v_search_results != null && v_search_results.Count > 0) { UsersSession.userid = v_search_results[0]; UsersSession.result.result = true; UsersSession.result.message = "success"; } else { UsersSession.result.result = false; UsersSession.result.message = "Invalid user"; } } else { UsersSession.result.result = false; UsersSession.result.message = "Please enter username and password"; } } catch (Exception ex) { UsersSession.result.result = false; UsersSession.result.message = "Error occurred: " + ex.Message.ToString(); } return UsersSession; } } Here is the web.config <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="*" /> <add name="Access-Control-Allow-Methods" value="*" /> </customHeaders> </httpProtocol> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer> `
So the issue was that I had the cors stuff defined in too many locations. The solution was simply to only have the code for the WebApiConfig.cs I removed the code from the web.config and the controller.
Download a file from azure devops server writes wrong data to the file
I am trying to download a SQL file from azure devops server using the API, but an html page source code with signout link is copied to the file. C# Code var personalaccesstoken = "wwwwwwwwwwwwwwwwwwy47b7ugkz32bubi64bw7fqdyfpa"; var url = $"https://dev.azure.com/OrgTest/ABCProject/_apis/git/repositories/e9e2f082-99999iii-dummy-869b0bcc737a/items?path=/Versiondata/Datfile/ABC.sql&includeContent=true&api-version=5.1"; var request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = "VSTS-Get"; request.Headers.Set(HttpRequestHeader.Authorization, "Bearer " + personalaccesstoken); request.ContentType = "application/json"; request.Method = "GET"; request.AllowAutoRedirect = true; var response = (HttpWebResponse)request.GetResponse(); using (var responseStream = response.GetResponseStream()) { using (var filestream = File.Create(System.IO.Path.Combine("D:\\testFolder\\", "ABC.sql"))) { responseStream.CopyTo(filestream); } } Unfortunately I am getting below html content in file Content Output file <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="en-US"> <head><title> Azure DevOps Services | Sign In </title><meta http-equiv="X-UA-Compatible" content="IE=11; IE=10; IE=9; IE=8" /> <link rel="SHORTCUT ICON" href="/favicon.ico"/> <link data-bundlelength="508967" data-bundlename="commoncss" data-highcontrast="/_static/tfs/M172_20200708.14/_cssbundles/HighContrast/vss-bundle-commoncss-vbprQZmxiRGQT6OOu7QI7gB_rewyS40Ce_ulm1Fh3rQQ=" data-includedstyles="jQueryUI-Modified;Core;Splitter;PivotView" href="/_static/tfs/M172_20200708.14/_cssbundles/Default/vss-bundle-commoncss-v18eOGnLpZpVm7mtRF63HJdB9wzrq2LZpAxko9qNRfdY=" rel="stylesheet" /> <link data-bundlelength="116304" data-bundlename="viewcss" data-highcontrast="/_static/tfs/M172_20200708.14/_cssbundles/HighContrast/vss-bundle-viewcss-vv48rOLU2KepPSTALtsmN5-gXtibzGGwjVnS2QIkrRI4=" data-includedstyles="VSS.Controls" href="/_static/tfs/M172_20200708.14/_cssbundles/Default/vss-bundle-viewcss-vDH9dOETFqT44jZvM_rX-2sP7DneEj_u8KJJ1u7Bcr3I=" rel="stylesheet" /> <!--UxServices customizations --> <link href="/_static/tfs/M172_20200708.14/_content/Authentication.css" type="text/css" rel="stylesheet" /> </head> <body class="platform"> <script type="text/javascript"> var __vssPageContext = {"webContext":{"user":{"id":"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa","name":"Anonymous","email":"","uniqueName":"TEAM FOUNDATION\\Anonymous"},"host":{"id":"7d0cc8e9-39e8-4313-9ff3-23ace0f8f4cf","name":"TEAM FOUNDATION","uri":"https://spsprodweu4.vssps.visualstudio.com/","relativeUri":"/","hostType":"deployment","scheme":"https","authority":"spsprodweu4.vssps.visualstudio.com"}},"moduleLoaderConfig":{"baseUrl":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/","paths":{"Profile/Scripts/Resources":"en-US","VSS/Resources":"en-US","Account/Scripts/Resources":"en-US","UserManagement/Scripts/Resources":"en-US","Authentication/Scripts/Resources":"en-US"},"map":{},"contributionPaths":{"VSS":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/VSS","pathType":"default"},"VSS/Resources":{"value":"en-US","pathType":"resource"},"q":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/q","pathType":"default"},"knockout":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/knockout","pathType":"default"},"mousetrap":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/mousetrap","pathType":"default"},"mustache":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/mustache","pathType":"default"},"react":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/react.15.3","pathType":"default"},"react-dom":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/react-dom.15.3","pathType":"default"},"react-transition-group":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/react-transition-group.15.3","pathType":"default"},"jQueryUI":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/jQueryUI","pathType":"default"},"jquery":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/jquery","pathType":"default"},"OfficeFabric":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/OfficeFabric","pathType":"default"},"tslib":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/tslib","pathType":"default"},"#uifabric":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/#uifabric","pathType":"default"},"VSSUI":{"value":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/VSSUI","pathType":"default"}},"shim":{"jquery":{"deps":[],"exports":"jQuery"}},"waitSeconds":30},"coreReferences":{"stylesheets":[{"url":"/_static/tfs/M172_20200708.14/_cssbundles/Default/vss-bundle-ext-core-css-vQ8Us1s7UaJe7EYaHu4abPhUIoy4VkQeq0UCGlmbyyiE=","highContrastUrl":null,"isCoreStylesheet":true}],"scripts":[{"identifier":"JQuery","url":"/_static/3rdParty/_scripts/jquery-2.2.4.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"JQueryXDomain","url":"/_static/3rdParty/_scripts/jquery.xdomainrequest.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"Promise","url":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/promise.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"GlobalScripts","url":"/_static/tfs/M172_20200708.14/_scripts/TFS/min/global-scripts.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M172_20200708.14/_scripts/TFS/pre-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false},{"identifier":"AMDLoader","url":"/_static/3rdParty/_scripts/require.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M172_20200708.14/_scripts/TFS/post-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false}],"coreScriptsBundle":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-basejs-v9GpWWBnsWqhM23ijhK2HfAqLowTXGUqZLDRsBCZbkfY=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},"extensionCoreReferences":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-ext-core-vXmFrbZVv9in776dlqjrJLCGMci5PQIF14Ug3E2n2Ku0=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true}},"webAccessConfiguration":{"isHosted":true,"paths":{"rootPath":"/","staticContentRootPath":"/","staticContentVersion":"M172_20200708.14","resourcesPath":"/_static/tfs/M172_20200708.14/_content/","staticRootTfs":"/_static/tfs/M172_20200708.14/","cdnFallbackStaticRootTfs":"/_static/tfs/M172_20200708.14/","staticRoot3rdParty":"/_static/3rdParty/"},"api":{"webApiVersion":"1","areaPrefix":"_","controllerPrefix":""},"mailSettings":{"enabled":false},"registryItems":{}},"microsoftAjaxConfig":{"cultureInfo":{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":1,"PercentNegativePattern":1,"NegativeInfinitySymbol":"-∞","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"∞","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"‰","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"0001-01-01T00:00:00","MaxSupportedDateTime":"9999-12-31T23:59:59.9999999","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM d, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM d, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM d","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy'-'MM'-'dd'T'HH':'mm':'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy'-'MM'-'dd HH':'mm':'ss'Z'","YearMonthPattern":"MMMM yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]},"numberShortForm":{"QuantitySymbols":["K","M","B"],"NumberGroupSize":1000,"ThousandSymbol":"K"},"eras":null}},"timeZonesConfiguration":{},"featureAvailability":{"featureStates":{"VisualStudio.Services.Contribution.EnableOnPremUnsecureBrowsers":false,"VisualStudio.Service.WebPlatform.ClientErrorReporting":false,"Microsoft.VisualStudio.Services.Gallery.Client.UseCdnAssetUri":false,"VisualStudio.Services.WebAccess.SubresourceIntegrity":false,"VisualStudio.Services.IdentityPicker.ReactProfileCard":true}},"appInsightsConfiguration":{"enabled":false,"instrumentationKey":"00000000-0000-0000-0000-000000000000","insightsScriptUrl":null},"diagnostics":{"sessionId":"f6a1e2ac-a812-49e0-9d52-d7ee7f8143d0","activityId":"f6a1e2ac-a812-49e0-9d52-d7ee7f8143d0","bundlingEnabled":true,"webPlatformVersion":"M172","serviceVersion":"Dev18.M172.1 (build: AzureDevOps_M172_20200708.14)"},"navigation":{"topMostLevel":"deployment","area":"","currentController":"Signin","currentAction":"Index","routeId":"LegacyWebAccessRoute","routeValues":{"controller":"Signin","action":"Index"}},"globalization":{"explicitTheme":"","theme":"Default","culture":"en-US","timezoneOffset":0,"timeZoneId":"UTC"},"serviceInstanceId":"951917ac-a960-4999-8464-e3f0aa25b381","hubsContext":{},"serviceLocations":{"locations":{"951917ac-a960-4999-8464-e3f0aa25b381":{"Application":"https://spsprodweu4.vssps.visualstudio.com/","Deployment":"https://spsprodweu4.vssps.visualstudio.com/"}}}};</script><script type="text/javascript"> var __cultureInfo = __vssPageContext.microsoftAjaxConfig.cultureInfo;</script> <script type="text/javascript">if (window.performance && window.performance.mark) { window.performance.mark('startLoadBundleOuter-basejs'); }</script> <script data-bundlelength="125076" data-bundlename="basejs" src="/_public/_Bundling/Content?bundle=vss-bundle-basejs-v9GpWWBnsWqhM23ijhK2HfAqLowTXGUqZLDRsBCZbkfY=" type="text/javascript"></script> <script type="text/javascript">if (window.performance && window.performance.mark) { window.performance.mark('endLoadBundleOuter-basejs'); }</script> <script type="text/javascript"> require.config(__vssPageContext.moduleLoaderConfig);</script> <input name="__RequestVerificationToken" type="hidden" value="NczcE2VqtZurcha-i70MYWJmzvklYWzgZmMOD4_U9KGkpElkwsliaVLxrc5SUWZXGi0kzpaOtqckBS6JZEDleh7ctQA1" /><input name="__RequestVerificationToken2" type="hidden" value="__RequestVerificationToken209a26724-ac5a-4587-887f-60eb94fca407" /> <div class="account signin main-container hide"> <div class="page-content"> <div class="header-section" role="banner"> <link rel="stylesheet" type="text/css" href="/_static/tfs/M172_20200708.14/_content/Combined.css"> <div id="ux-header" class="FF ltr vsIntegrate" xmlns="http://www.w3.org/1999/xhtml"> <span id="isMobile"></span> <div class="upperBand"> <div class="upperBandContent"> <div class="left"></div> <div class="right"> <div class="profileImage"></div> <div id="signIn"> <a class=":SignedOutProfileElement: createProfileLink" href="/go/profile" title="Anonymous">Anonymous</a> <a class="scarabLink" href="/_signout">Sign out</a> </div> </div> <div class="clear-both"></div> </div> </div> </div> </div> <div class="content-section" role="main"> <div class="signin-main-content"> <noscript> <span class="error">Microsoft Internet Explorer's Enhanced Security Configuration is currently enabled on your environment. This enhanced level of security prevents our web integration experiences from displaying or performing correctly. To continue with your operation please disable this configuration or contact your administrator.</span> </noscript> <div class="provider-control"> <script class="options" defer="defer" type="application/json">{"providerOptions":{"force":false,"orgIdAuthUrl":"https://login.microsoftonline.com/c627bf07-e774-48cd-9e33-eeeed30d747b/oauth2/authorize?client_id=499b84ac-1321-427f-aa17-267ca6975798\u0026site_id=501454\u0026response_mode=form_post\u0026response_type=code+id_token\u0026redirect_uri=https%3A%2F%2Fspsprodweu4.vssps.visualstudio.com%2F_signedin\u0026nonce=15b49048-8f5c-43a8-8e2d-77067ccdbc15\u0026state=realm%3Ddev.azure.com%26reply_to%3Dhttps%253A%252F%252Fdev.azure.com%252FOrgnatinTest%252FAIProject%252F_apis%252Fgit%252Frepositories%252Fe9e2f082-6f6d-4cfd-a7af-869b0bcc737a%252Fitems%253Fpath%253D%25252FV4.1.0.0%25252FDB%25252FDWH%25252FDWH%25252FDWH%25252FAMF.sql%2526includeContent%253Dtrue%2526api-version%253D5.1%26ht%3D2%26hid%3D750bf9a1-4ded-4c22-89dd-a2740fccd529%26nonce%3D15b49048-8f5c-43a8-8e2d-77067ccdbc15\u0026resource=https%3A%2F%2Fmanagement.core.windows.net%2F\u0026cid=15b49048-8f5c-43a8-8e2d-77067ccdbc15\u0026wsucxt=1","user":null,"signInContext":"eyJodCI6MiwiaGlkIjoiMTY0NmI1NzMtNjNhOS00MzYyLWE0MjItYzA0MzEyYTI4MjU3IiwicXMiOnsicmVhbG0iOiJkZXYuYXp1cmUuY29tIiwicmVwbHlfdG8iOiJodHRwczovL2Rldi5henVyZS5jb20vUGF0aFNvbHV0aW9uc1Rlc3QvQUlQcm9qZWN0L19hcGlzL2dpdC9yZXBvc2l0b3JpZXMvZTllMmYwODItNmY2ZC00Y2ZkLWE3YWYtODY5YjBiY2M3MzdhL2l0ZW1zP3BhdGg9JTJGVjQuMS4wLjAlMkZEQiUyRkRXSCUyRkRXSCUyRkRXSCUyRkFNRi5zcWwmaW5jbHVkZUNvbnRlbnQ9dHJ1ZSZhcGktdmVyc2lvbj01LjEiLCJodCI6IjIiLCJoaWQiOiI3NTBiZjlhMS00ZGVkLTRjMjItODlkZC1hMjc0MGZjY2Q1MjkiLCJub25jZSI6IjE1YjQ5MDQ4LThmNWMtNDNhOC04ZTJkLTc3MDY3Y2NkYmMxNSJ9LCJyciI6IiIsInZoIjoiIiwiY3YiOiIiLCJjcyI6IiJ90"}}</script> </div> </div> </div> </div> <script type="text/javascript">if (window.performance && window.performance.mark) { window.performance.mark('startLoadBundleOuter-common'); }</script> <script data-bundlelength="205378" data-bundlename="common" data-includedscripts="VSS/Bundling" src="/_public/_Bundling/Content?bundle=vss-bundle-common-v_Ss9wqVqy_aJagjjTroIfzbnjzMUeKzN0KlnLkpPbLw=" type="text/javascript"></script> <script type="text/javascript">if (window.performance && window.performance.mark) { window.performance.mark('endLoadBundleOuter-common'); }</script> <script type="text/javascript">if (window.performance && window.performance.mark) { window.performance.mark('startLoadBundleOuter-view'); }</script> <script data-bundlelength="157426" data-bundlename="view" data-includedscripts="Authentication/Scripts/SPS.Authentication.Controls;Authentication/Scripts/SPS.Authentication" src="/_public/_Bundling/Content?bundle=vss-bundle-view-vip8jjFGoJo8AL2ac18TvWQ8inaN47zLqW97-Gn61kAs=" type="text/javascript"></script> <script type="text/javascript">if (window.performance && window.performance.mark) { window.performance.mark('endLoadBundleOuter-view'); }</script> <script type="text/javascript"> if (window.performance && window.performance.mark) { window.performance.mark('requireStart'); } require(["Authentication/Scripts/SPS.Authentication.Controls","Authentication/Scripts/SPS.Authentication"], function(){ if (window.performance && window.performance.mark) { window.performance.mark('requireEnd'); } window.requiredModulesLoaded=true; }); </script> </body> </html> I tried to download from downlink. I am facing the same issue. Should we add authorization to the application on development in Azure DevOps server?
Finally I found solution to this issue.Here we are trying to use Personal access token(PAT).In order to use PAT for authentication we have to use authorization as "Basic" instead of "Bearer".More over instead of adding PAT alone to the Request header we have to use combination of username and PAT.Say base-64-encoded-string of username:PAT. Required Code Change var personalaccesstoken = "wwwwwwwwwwwwwwwwwwy47b7ugkz32bubi64bw7fqdyfpa"; var base64Creds = Convert.ToBase64String(Encoding.ASCII.GetBytes("SPabbbal#ABCTech.com:"+ personalaccesstoken)); request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + base64Creds); thank you for support.
Your PAT token is your username+password with scopes (permissions) applied. So when calling with the bearer token, the syntax for the token is a Base64 encoded string of the username:token. Because the token represents the user, the username isn’t specified, so you specify an empty string instead. From: Use a PAT in your code public static async void GetBuilds() { try { var personalaccesstoken = "PATFROMWEB"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String( System.Text.ASCIIEncoding.ASCII.GetBytes( string.Format("{0}:{1}", "", personalaccesstoken)))); using (HttpResponseMessage response = client.GetAsync( "https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.0").Result) { response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
ASP tags not recognized in Visual Studio 2012
I have created a simple ASP.NET project in VS 2012 but it is not recognizing AJAX Control Toolkit controls...I have downloaded and added ACT to my toolbox. I have referenced the DLLs in the build on the project page...the solution doesn't understand what the prefix asp on the dropdown control is... Update! The issue is not with " or '. Update 2! Changed the web.config and refactored the the code behind a little bit but still get asp prefix unrecognized... Error Solution Explorer web.config <?xml version="1.0"?> <configuration> <!-- For a description of web.config changes for .NET 4.5 see http://go.microsoft.com/fwlink/?LinkId=235367. The following attributes can be set on the <httpRuntime> tag. <system.Web> <httpRuntime targetFramework="4.5" /> </system.Web> --> <system.web> <compilation debug="true" targetFramework="4.5"/> <httpRuntime/> <pages> <controls> <add tagPrefix="ajax" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit"/> </controls> </pages> </system.web> <appSettings> <!-- add folder path here--> <add key="ediConfigPath" value="~/"/> </appSettings> <connectionStrings> <add name="cmsDB3ConnectStr" connectionString="xkcd" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration> aspx page <%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>xkcdCoder</title> <link type="text/css" rel="stylesheet" href="Content/bootstrap.min.css" /> <link type="text/css" rel="stylesheet" href="Content/style.css" /> </head> <body> <form id="form1" runat="server"> <nav id="navbar" class="navbar navbar-default navbar-fixed-top"> <a id="product" class="navbar-brand">xkcdCoder > TransCodes</a> <img id="logo" class="navbar-brand" src="/content/img/xkcd_logo2.png" alt="" /> </nav> <section class="login-sect"> <asp:dropdownlist id="ddHospitals" runat="server" datatextfield='<%#Eval("Custom")%>' datavaluefield='<%#Eval("Custom")%>' xmlns:asp="#unknown"> </asp:dropdownlist> <div class="give-me-space"> <div class="give-me-space">TranCode</div> <input type="text" /> </div> <div class="give-me-space"> <div class="give-me-space">TranDescr</div> <input type="text" /> </div> <div class="give-me-space"> <div class="give-me-space">PosTranCode</div> <input type="text" /> </div> <div class="give-me-space"> <div class="give-me-space">NegTranCode</div> <input type="text" /> </div> <button type="button" title="Submit" class="action-button">Add Code</button> </section> <script src="scripts/jquery-1.9.1.min.js"></script> <script src="scripts/bootstrap.min.js"></script> <script src="Scripts/xkcdCoder.js"></script> </form> </body> </html> code behind using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; public partial class _Default : System.Web.UI.Page { public DataSet GetItems() { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cmsDB3ConnectStr"].ConnectionString); SqlCommand cmd = new SqlCommand("getFacilitiesAll", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); try { con.Open(); da.Fill(ds); con.Close(); } catch (Exception ex) { string err = ex.ToString(); //write error message } return ds; } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { return; //This will make sure that only once the below code will be executed. } else { ddHospitals.DataSource = GetItems(); ddHospitals.DataBind(); } } }
Jquery .show hides again after postback
I have an UL that I control using hide and show. The problem is that when I click on level1 it shows level2 for only a moment before it disappears, I believe this is because of a postback or something. The functionality works but it just doesnt stay like it. I need to be able to toggle the items in the list to show and hide them. <script> $(function(){ $('.level2').hide(); $('.level3').hide(); $('.level1').click(function () { $('.level2').show(); return false; $('level2').click(function () { $('.level3').show(); return false; $(this).find('ul').slideToggle(); }); }) } ) </script> HTML: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script> <title></title> <link href="styles/Menu.css" rel="stylesheet" /> <script type="text/javascript"> function openNewWin(url) { var x = window.open(url, 'mynewwin', 'toolbar=no,directories=no,location=no,menubar=no,left=0,top=0,resizable=no,status=no'); x.focus(); } </script> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <link rel="stylesheet" href="/resources/demos/style.css"/> <script> $(function(){ $('.level2').hide(); $('.level3').hide(); $('.level1').click(function () { $('.level2').show(); return false; $('level2').click(function () { $('.level3').show(); return false; $(this).find('ul').slideToggle(); }); }) } ) </script> </head> <body> <form id="form1" runat="server"> <div id="menu" class="MenuBar"> <asp:Menu ID="Menu1" runat="server" CssClass="mainmenu" StaticDisplayLevels="3" Target="_blank" StaticEnableDefaultPopOutImage="False" StaticSubMenuIndent="0px" > <LevelMenuItemStyles> <asp:MenuItemStyle CssClass="level1"/> <asp:MenuItemStyle CssClass="level2"/> <asp:MenuItemStyle CssClass="level3" /> <asp:MenuItemStyle CssClass="level4" /> </LevelMenuItemStyles> <StaticMenuItemStyle CssClass="staticItem" /> </asp:Menu> </div> </form> </body> </html>
google maps API v3 doen't respond
I'm new here. I'm trying to make an application that calculates distance and driving time between two adresses using google maps API. My problem is that google DirectionsService() doesn't seem to respond. and I can't figure it out. I have been trying to figure it out for one week now. I hope you guys can help. the problems seems to be in gmapApi.js here is my code. Default.aspx <%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function postbackObj() { var orig = document.getElementById('<%= txbOrigin.ClientID %>').value; var dist = document.getElementById('<%= txbDestination.ClientID %>').value; var temp = showLocation(orig, dist); __doPostBack('gmAPIObj',temp); } </script> <script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript">< /script> <script type="text/javascript" src="gmapApi.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txbOrigin" Text="" runat="server" /> <asp:TextBox ID="txbDestination" Text="" runat="server" /> <asp:Button ID="btnSubmit" runat="server" Text="Search" OnClientClick="postbackObj()"/> <p> < asp:Label runat="server" ID="lblPrint" /> </p> </div> </form> </body> </html> gmapApi.js function showLocation(orig, dist) { var directionService = new google.maps.DirectionsService(); var t = ""; var request = { origin: orig, destination: dist, travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionService.route(request, function (response, status) { if (status != google.maps.DirectionsStatus.OK) { alert(status + " \nreq. failed."); } else { t = request.origin + ';' + request.destination + ';' + response.routes[0].legs[0].distance.value + ';' + response.routes[0].legs[0].duration.value; } }); return t; } the response variable is null and the status variable is emptystring in the directionService.route(request, function (response, status) I have tried to change to without lock. And I have tried to place the tags in the body tag without lock. the rendered html code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title> </title> <script type="text/javascript"> function postbackObj() { var orig = document.getElementById('txbOrigin').value; var dist = document.getElementById('txbDestination').value; var temp = showLocation(orig, dist); __doPostBack('gmAPIObj',temp); } </script> <script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script> <script type="text/javascript" src="gmapApi.js"></script> </head> <body> <form method="post" action="Default.aspx" id="form1"> <div class="aspNetHidden"> <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /> <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MjMyMzMwNTZkZHxi8IJlhy7bL8nAZqZfL2Vh4Yr8uF80ja6jX9Ypc87B" /> </div> <script type="text/javascript"> //<![CDATA[ var theForm = document.forms['form1']; if (!theForm) { theForm = document.form1; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]> </script> <div class="aspNetHidden"> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBALsorucDwLTmobsAwK0weWLAwLCi9reA32PxME86E6mQhRTgBkF7cdktbiURIpf/IzKvAs5PHwI" /> </div> <div> <input name="txbOrigin" type="text" value="tilst" id="txbOrigin" /> <input name="txbDestination" type="text" value="aarhus" id="txbDestination" /> <input type="submit" name="btnSubmit" value="Search" onclick="postbackObj();" id="btnSubmit" /> <p> <span id="lblPrint"></span> </p> </div> </form> </body> </html> thanks in advance.
requesting the directionService is an asynchronous process, your variable t inside the function showLocation will not be modified by the call of directionService.route() call __doPostBack('gmAPIObj',t) from within the successfull callback of directionService.route() instead. function postbackObj() { var orig = document.getElementById('txbOrigin').value; var dist = document.getElementById('txbDestination').value; showLocation(orig, dist); } //----- function showLocation(orig, dist) { var directionService = new google.maps.DirectionsService(); var t = ""; var request = { origin: orig, destination: dist, travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionService.route(request, function (response, status) { if (status != google.maps.DirectionsStatus.OK) { alert(status + " \nreq. failed."); } else { t = request.origin + ';' + request.destination + ';' + response.routes[0].legs[0].distance.value + ';' + response.routes[0].legs[0].duration.value; __doPostBack('gmAPIObj',t); } }); }