Wcf Rest Call HTTP/1.1 400 Bad Request or HTTP/1.1 404 Not Found - rest

I am having trouble while sending the request to a rest service. The service works fine on my desktop, but getting the following error when i host on the IIS.
HTTP/1.1 400 Bad Request when i use https
HTTP/1.1 404 Not Found when i use http
Here is my web.config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service
behaviorConfiguration="CoreService.DialService.DialServiceBehavior"
name="CoreService.DialService.TelephonyService">
<endpoint behaviorConfiguration="webBehavior" binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="CoreService.DialService.ITelephonyService"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="CoreService.DialService.DialServiceBehavior">
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true"/>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
maxMessagesToLog="3000" maxSizeOfMessageToLog="2000"/>
</diagnostics>
</system.serviceModel>
Service Contract
[WebInvoke(UriTemplate = "/Dial", Method = "POST", RequestFormat =
WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
Objects.Response.Telephony.DialResponse
Dial(Objects.Request.Telephony.DialRequest request);
Here is the client
DialRequest DialRequest = new DialRequest();
DialResponse DialResponse = new DialResponse();
DialRequest.ProjectID = "AMS0103300";
DialRequest.DialFromExtension = "1234";
DialRequest.OutDialCode = "51";
DialRequest.RequestBy = "HC User";
DialRequest.DialToPhoneNumber = "1234567890";
DialRequest.RequestDate = DateTime.Now;
DialRequest.ApplicationID = Guid.Parse("F5EE534B-B5ED-4ADD-B671-
CCF7C05057A7");
DataContractJsonSerializer ser =
new
DataContractJsonSerializer(typeof(Objects.Request.Telephony.DialRequest));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, DialRequest);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
var result = webClient.UploadString("https://test.xxxx.com/DialService/TelephonyService.svc/Dial","POST", data);
I have tried with different values in protocolMapping, but the results are same. Any help will be appreciated.

It seems to me that there are no errors in you project. Besides protocol mapping is the new feature in Net4.5, which could help us simplify settings.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/simplified-configuration
How to make WCF Service Use HTTPS protocol
There might be some small problems during the process of hosting the service on the IIS.
Could you access the WSDL page successfully?
Like the following form.
We might need to enable the WCF feature in the control panel.
I have made an example, wish it is useful to you.
Server-side (WCF service application).
IService1
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
[WebInvoke(UriTemplate ="/MyTest",Method ="POST",RequestFormat =WebMessageFormat.Json,ResponseFormat =WebMessageFormat.Json)]
string Test(CompositeType compositeType);
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
public override string ToString()
{
return $"The BoolValue is {boolValue}, StringValue is {stringValue}";
}
}
Service1.svc.cs
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public string Test(CompositeType compositeType)
{
return compositeType.ToString();
}
}
Web.config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="mybinding">
<security mode="Transport">
<transport clientCredentialType="None"></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
<add binding="webHttpBinding" scheme="https" bindingConfiguration="mybinding"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
IIS(new website)
Client(generate the data contract by adding service reference)
static void Main(string[] args)
{
//for validating the self-signed certificated.
ServicePointManager.ServerCertificateValidationCallback += delegate
{
return true;
};
ServiceReference1.CompositeType composite = new ServiceReference1.CompositeType()
{
StringValue = "Hello",
BoolValue = true
};
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServiceReference1.CompositeType));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, composite);
string data = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
WebClient webclient = new WebClient();
webclient.Headers["Content-type"] = "application/json";
webclient.Encoding = Encoding.UTF8;
var result = webclient.UploadString("https://localhost:8734/service1.svc/MyTest", "POST", data);
Console.WriteLine(result);
WebClient webclient2 = new WebClient();
webclient2.Headers["Content-type"] = "application/json";
webclient2.Encoding = Encoding.UTF8;
var result2 = webclient2.UploadString("http://localhost:8733/service1.svc/MyTest", "POST", data);
Console.WriteLine(result2);
}
Result.
Besides, PostMan is good choice to test Rest style service.
Feel free to let me know if the problem still exists.

Related

Authorization header in ServiceAuthorizationManager is null in second call

I have a WCF REST service which accepts xml data as input and returns some data too. To implement Basic Authentication i use ServiceAuthorizationManager. The CheckAccessCore method calls twice automatically. In first call authorization header in CheckAccessCore is correct, but in second call authorization header is null.
ServiceAuthorizationManager CheckAccessCore method
protected override bool CheckAccessCore(OperationContext operationContext)
{
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
var credentials = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(authHeader.Substring(6))).Split(':');
var user = new
{
Name = credentials[0],
Password = credentials[1]
};
if (user.Name == "test" && user.Password == "pass")
{
return true;
}
else
{
return false;
}
}
else
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm =\"CreditData\"");
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
WCF Web.config
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="RestBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Xml"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization serviceAuthorizationManagerType="CreditDataService.Authorization.CreditDataAuthorizationManager, CreditDataService" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="CreditDataService.Services.CreditData" behaviorConfiguration="">
<endpoint name="REST" behaviorConfiguration="RestBehavior" binding="webHttpBinding" contract="CreditDataService.Contracts.ICreditData"/>
</service>
</services>
<protocolMapping>
<add binding="webHttpBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
Client
private void button4_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:33016/Services/CreditData.svc");
byte[] bytes = System.Text.Encoding.UTF8.GetBytes("<Request><Firstname>John</Firstname><Lastname>Doe</Lastname><Pid>123456789</Pid></Request>");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
request.Method = "POST";
string credentials = "test:pass";
string enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
string auth = string.Format("{0} {1}", "Basic", enc);
request.Headers[HttpRequestHeader.Authorization] = auth;
Stream reqStream = request.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream respStream = response.GetResponseStream();
string respStr = new StreamReader(respStream).ReadToEnd();
MessageBox.Show(respStr);
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
MessageBox.Show(resp);
}
MessageBox.Show(ex.Message);
}
}
Without ServiceAuthorizationManager it works correctly.
Problem was webservice's method's UriTemplate. It was empty and when i was calling service there was happening redirecting to the same url only with slash. e.g. when i sent request to "http://localhost/myservice.svc" it was redirected to "http://localhost/myservice.svc/". This arose second request and exactly this second request had Authorization header null. When i added UriTemplate problem solved.

JAX-WS client, incorrect soap request - The markup in the document following the root element must be well-formed

I have generated a web service client using wsimport command line (JAX-WS) and generated Java objects using JAXB and separate XSD files.
But when I try to request, it gives following error from server side.
SAXException, cause: The markup in the document following the root element must be well-formed.
So I checked my soap request with a sample working soap message. Then I realized that there is a different between these two messages.
1. Sample working message.
<m:getMyDetail xmlns:m="http://axis.frontend.hi.example.net">
<MyDetailRQ xmlns="http://www.example.net/schemas/1005/06/messages"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.net/1005/06/messages ../xsd/MyDetailRQ.xsd"
version="2013/12">
2. Web service client generated soap message.
<ns3:getMyDetail xmlns:ns3="http://axis.frontend.hi.example.net" xmlns="http://www.
example.net/schemas/1005/06/messages" xmlns:ns2="http://www. example.net/wsdl/1005/06"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="MyDetailRQ">
As you can see, above expected MyDetailRQ wrapper tag element is missing but it generated as xsi:type="MyDetailRQ" attribute.
I’m not sure why this happen and how to fix this through my client project configurations.
Appreciate your help and advice.
Thanks
- Relevant WSDL part
<wsdl:types>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://axis.frontend.h1.example.com">
<element name="getMyDetail" type="xsd:anyType"/>
</schema>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.com/wsdl/2005/06">
<element name="getMyDetailReturn" type="xsd:anyType"/>
</schema>
</wsdl:types>
<wsdl:message name="getMyDetailRequest">
<wsdl:part element="tns1:getMyDetail" name="part"/>
</wsdl:message>
<wsdl:message name="getMyDetailResponse">
<wsdl:part element="impl:getMyDetailReturn" name="getMyDetailReturn"/>
</wsdl:message>
<wsdl:portType name="MyService">
<wsdl:operation name="getMyDetail">
<wsdl:input message="impl:getMyDetailRequest" name="getMyDetailRequest"/>
<wsdl:output message="impl:getMyDetailResponse" name="getMyDetailResponse"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="MyServiceSoapBinding" type="impl:MyService">
<wsdl:operation name="getMyDetail">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="getMyDetailRequest">
<wsdlsoap:body use="literal"/>
</wsdl:input>
<wsdl:output name="getMyDetailResponse">
<wsdlsoap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="MyServiceService">
<wsdl:port binding="impl:MyServiceSoapBinding" name="MyService">
<wsdlsoap:address location="http://interface.example.com/xmls/ws/MyService"/>
</wsdl:port>
</wsdl:service>
- Relevant XSD part
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://www.example.net/schemas/1005/06/messages" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.net/schemas/1005/06/messages" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:include schemaLocation="MyCommonTypes.xsd"/>
<xs:element name="MyDetailRQ">
- Relevant Java Object
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "MyDetailRQ", propOrder = {
"myCode"
})
#XmlRootElement(name = "MyDetailRQ")
public class MyDetailRQ
extends MainRequest
{
}
- web service client - service interface (Updated on 17-Oct-2014)
#WebService(name = "MyService", targetNamespace = "http://www.example.net/wsdl/1005/06")
#SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
#XmlSeeAlso({
com.myp.hi.frontend.axis.ObjectFactory.class,
com.myp.ObjectFactory.class
})
public interface MyService {
/**
*
* #param part
* #return
* returns java.lang.Object
*/
#WebMethod
#WebResult(name = "getMyDetailReturn", targetNamespace = "http://www.example.net/wsdl/1005/06", partName = "getMyDetailReturn")
public Object getMyDetail(
#WebParam(name = "getMyDetail", targetNamespace = "http://axis.frontend.hi.example.net", partName = "part")
Object part);
}
- ObjectFactory class (Updated on 17-Oct-2014)
#XmlRegistry
public class ObjectFactory {
private final static QName _GetMyDetail_QNAME = new QName("http://axis.frontend.hi.example.net", "getMyDetail");
public ObjectFactory() {
}
#XmlElementDecl(namespace = "http://axis.frontend.hi.example.net", name = "getMyDetail")
public JAXBElement<Object> createGetMyDetail(Object value) {
return new JAXBElement<Object>(_GetMyDetail_QNAME, Object.class, null, value);
}
}
-MyServiceService class (Updated on 17-Oct-2014)
#WebServiceClient(name = "MyServiceService", targetNamespace = "http://www.example.net/wsdl/1005/06", wsdlLocation = "http://interface.example.com/xmls/ws/MyService?wsdl")
#GZIP
public class MyServiceService
extends Service
{
private final static URL MYSERVICESERVICE_WSDL_LOCATION;
private final static WebServiceException MYSERVICESERVICE_EXCEPTION;
private final static QName MYSERVICESERVICE_QNAME = new QName("http://www.example.net/wsdl/1005/06", "MyServiceService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://interface.example.com/xmls/ws/MyService?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
MYSERVICESERVICE_WSDL_LOCATION = url;
MYSERVICESERVICE_EXCEPTION = e;
}
#WebEndpoint(name = "MyService")
public MyService getMyService() {
MyService port = super.getPort(new QName("http://www.example.net/wsdl/1005/06", "MyService"), MyService.class);
return port;
}
private static URL __getWsdlLocation() {
if (MYSERVICESERVICE_EXCEPTION!= null) {
throw MYSERVICESERVICE_EXCEPTION;
}
return MYSERVICESERVICE_WSDL_LOCATION;
}
}
- My Test class (Updated on 17-Oct-2014)
MyService myService = new MyServiceService().getMyService();
MyDetailRQ myDetailRQ = new MyDetailRQ();
myDetailRQ.setCredentials(credentials);
myDetailRQ.setLanguage("ENG");
myDetailRQ.setMyCode("52319");
MyDetailRS myDetailRS = (MyDetailRS) myService.getMyDetail(myService);
I have found a solution, but not sure whether perfect one.
What I have done is; pass a XML String to service and get response as a String from service.
Then manually do marshalling and un- marshalling.
See the example below.
MyService myService = new MyServiceService().getMyService();
MyDetailRQ myDetailRQ = new MyDetailRQ();
myDetailRQ.setCredentials(credentials);
myDetailRQ.setLanguage("ENG");
myDetailRQ.setMyCode("52319");
String requestStr = getStringFromJaxb(myDetailRQ.class, myDetailRQ);
String responseStr = (String) myService.getMyDetail(requestStr);
MyDetailRS myDetailRS = (MyDetailRS) getJaxbFromString(MyDetailRS.class, responseStr);
private static Object getJaxbFromString(Class<?> clazz, String xmlString) {
StringReader input = null;
Object o = null;
try {
input = new StringReader(xmlString);
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller um = context.createUnmarshaller();
o = um.unmarshal(input);
if (o instanceof JAXBElement)
o = ((JAXBElement<?>) o).getValue();
} catch (JAXBException e) {
e.printStackTrace();
} finally {
if (input != null)
input.close();
}
return o;
}
/**
* Helper method to get xml string from JAXB Object.
* #param clazz
* #param o
* #return
*/
private static String getStringFromJaxb(Class<?> clazz, Object o) {
String theXML = "";
try {
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller m = context.createMarshaller();
m.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE);
m.marshal(o, writer);
// output string to console
theXML = writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return theXML;
}

Element is not an instance of type

I am using Linq To XSD to send data over MSMQ. Here is my sending code
public void Send()
{
string criMessageQueuePath = ConfigurationManager.AppSettings["CRIMessageQueuePath"];
if (!MessageQueue.Exists(criMessageQueuePath))
{
MessageQueue.Create(criMessageQueuePath, false);
}
var messageQueue = new MessageQueue(criMessageQueuePath) { Label = "CRI Message Queue" };
messageQueue.Formatter = new XmlMessageFormatter(new[] { typeof(XML) });
var transaction = new MessageQueueTransaction();
transaction.Begin();
messageQueue.Send(CreateAuction(1), transaction);
messageQueue.Send(CreateAuction(2), transaction);
messageQueue.Send(CreateAuction(3), transaction);
messageQueue.Send(CreateAuction(4), transaction);
messageQueue.Send(CreateAuction(5), transaction);
transaction.Commit();
}
private XML CreateAuction(int id)
{
var message = new XML {id = id};
return message;
}
Here is my receiving code
public IEnumerable<string> Receive()
{
string criMessageQueuePath = ConfigurationManager.AppSettings["CRIMessageQueuePath"];
var messageQueue = new MessageQueue(criMessageQueuePath);
Message[] messages = messageQueue.GetAllMessages();
foreach (Message message in messages)
{
message.Formatter = new XmlMessageFormatter(new[] { typeof(XML) });
yield return message.Body.ToString();
}
messageQueue.Purge();
}
I've tried lots of variations of this code but can't figure out why I can't get a valid XML object out the other end.
Currently, my code is failing when I call it
static void Main()
{
var sender = new Sender.Sender();
sender.Send();
var receiver = new Receiver.Receiver();
foreach (var xml in receiver.Receive())
{
var typedXML = XML.Parse(xml);
Console.WriteLine(typedXML.id);
}
}
The line it fails on is var typedXML = XML.Parse(xml);. The error is
Element is not an instance of type Domain.XML
The XSD for the object is
<?xml version="1.0" encoding="Windows-1252"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="Domain">
<xs:element name="XML">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Looking at the value of xml on the line
var typedXML = XML.Parse(xml);
I can see that it generates this
"<XML>\r\n <XML xmlns=\"Domain\">\r\n <id>1</id>\r\n </XML>\r\n</XML>"
In other words it generates an additional xml node around the whole xml. If I remove this extra node in the debugger then it all works. what am I doing wrong?
This is the result of using hte XmlMessageFormatter as it serializes your object and wraps it in XML. I would suggest that you write your XML document directly to the BodyStream property instead.
var msg = new Message();
var writer = new StreamWriter(msg.BodyStream);
writer.Write(xmlDoc.ToString());
writer.Flush();
queue.Send(msg);
This way you have full Control over what is sent in your queue. The formatters are mostly there for legacy use and should not be used when sending XML documents as messages.

Not seeing roles on Principal in ASP.NET MVC 2 Application

I am writing an ASP.NET MVC 2 application and don't want to use ASP.NET Membership. I do want to use the Authorize attribute on the Controllers. What I have done so far is ...
Web.config
<roleManager enabled="true" />
<authentication mode="Forms">
<forms loginUrl="~/Authentication/Login" timeout="2880"/>
</authentication>
<authorization>
<allow users="*" /> /* This is for testing */
</authorization>
In my Global.asax
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Context.User = tcmPrincipal;
}
I am using a custom IIdentity so that I can add some custom properties in the future. To test this in my Controller action I did this ...
var testPrincipal = User;
I can see the custom Identity with all of the user information but there are no roles on principal object. Any help with what i have missed would be great. Thanks.
I believe you need a role provider. Much like how a Membership provider handles the membership of users, create, delete, validate, edit, in order to use roles, you need to use a RoleProvider (ASP.NET Implementing a Role Provider).
Which also requires enabling roles in the web.config, for example:
<roleManager enabled="enabled" defaultProvider="AspNetSqlRoleProvider">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="ApplicationServices"
applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider"
applicationName="/" />
</providers>
</roleManager>
This might be useful:
SO asp-net-mvc-roles-without-database-and-without-role-provider
As Might be:
ASP.NET 2.0, Custom Role assignment without a 'Role Provider'
UPDATE:
In the end I got this working by changing
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Context.User = tcmPrincipal;
}
to
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Thread.CurrentPrincipal = Context.User = tcmPrincipal;
}

Please help! unable to add performance counters - 'Add' button is disabled

I have created performance counters using Entlib 4.1 as below. When I open up the performon.exe and Add Counters - I can see the Performance Object I created, and the list of counters. However I can't add them becuse the Add button is disabled. Any suggessions?
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("You are about to install the performance counters");
InstallPerformaceCounters();
Console.ReadLine();
for (int i = 0; i < 100000; i++)
{
if (i % 3 == 2)
{
Thread.Sleep(100);
}
if (i % 5 == 2)
{
Thread.Sleep(1000);
}
PerformSearch(i);
}
Console.ReadLine();
}
private static void PerformSearch(int i)
{
Console.WriteLine(i);
}
private static void InstallPerformaceCounters()
{
try
{
PerformanceCountersInstaller installer = new PerformanceCountersInstaller(new SystemConfigurationSource());
IDictionary state = new System.Collections.Hashtable();
installer.Context = new InstallContext();
installer.Install(state);
installer.Commit(state);
Console.WriteLine("Performance counters have been successfully installed.");
}
catch (Exception ex)
{
throw ex;
}
}
}
////
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="policyInjection" type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration.PolicyInjectionSettings, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="instrumentationConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation.Configuration.InstrumentationConfigurationSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<policyInjection>
<policies>
<add name="Search">
<handlers>
<add categoryName="Search Performance Counters" instanceName="Default"
useTotalCounter="false" incrementNumberOfCalls="true" incrementCallsPerSecond="true"
incrementAverageCallDuration="true" incrementTotalExceptions="true"
incrementExceptionsPerSecond="true" type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.PerformanceCounterCallHandler, Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Performance Counters Handler" />
</handlers>
</add>
</policies>
</policyInjection>
<instrumentationConfiguration performanceCountersEnabled="true"
eventLoggingEnabled="false" wmiEnabled="false" applicationInstanceName="" />
</configuration>
This was my mistake. I need to run the app, particularly the methods that are decorated with those counters, so I could add the counters to the list.