As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm looking for example of Silverlight 5 RIA services with authentication with active directory,
that can be downloaded and that works
Thanks in advance.
I have not found a complete downloadable example. The easiest way is to create a new Silverlight Business Application and then make the following changes to the 3 files specified (Web.config, App.xaml.cs, User.cs):
App.xaml.cs
Comment out (or remove) the following lines:
//webContext.Authentication = new FormsAuthentication();
Uncomment the following lines:
webContext.Authentication = new WindowsAuthentication();
User.cs
add the [ProfileUsage...] statement to the public partial class user so it looks like the following:
public partial class User : UserBase
{
[ProfileUsage(IsExcluded=true)] ///NEEDED FOR WINDOWS/ACTIVE DIRECTORY LOGON
public string FriendlyName { get; set; }
}
Web.config:
Comment out (or remove) the following lines:
<!--<authentication mode="Forms">
<forms name=".AuthenticationTest_ASPXAUTH" timeout="2880" />
</authentication>-->
Uncomment the following lines:
<authentication mode="Windows"/>
Comment out (or remove) the following lines:
<!--<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<clear />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<profile defaultProvider="DefaultProfileProvider">
<properties>
<add name="FriendlyName" />
</properties>
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>-->
<!--<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>-->
Add the following lines:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="winAuthBasicHTTPBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="AuthenticationTest.Web.AuthenticationServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<services>
<service behaviorConfiguration="AuthenticationTest.Web.AuthenticationServiceBehavior" name="System.Web.ApplicationServices.AuthenticationService">
<endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="winAuthBasicHTTPBinding"
contract="System.Web.ApplicationServices.AuthenticationService">
</endpoint>
</service>
</services>
</system.serviceModel>
Related
I am trying to understand how log4net works so I've added this to my app.config (I should add that Console Appender and FileAppender work perfectly, I only have trouble with the AdoNetAppender).
How can I debug this, to see if at least the connection to db succeeds?
The problem is the INSERT statement isn't executed.
I should add the
Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;password=juan,
works perfectly when I try to connect to SQL Server manually, so not sure if that's the problem.
Also, the ConnectionType was taken from the official site:
https://logging.apache.org/log4net/log4net-1.2.11/release/sdk/log4net.Appender.AdoNetAppender.ConnectionType.html
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.log4netConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="AdoNetAppender"
type="log4net.Appender.AdoNetAppender">
<bufferSize value="10" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;Password=juan;Pooling=False" />
<commandText value="INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')" />
<commandType value="Text" />
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Later edit (after using the debug method recommended by David):
haacked.com is indeed extremely interesting, great tip! However, it seems that it's describing what I'm instructing log4net to log, but not the result of those actions(?), if I'm reading this well (no failed/or succeeded?)
e.g.
log4net: Setting Property [ConnectionType] to String value
[System.Data.SqlClien t.SqlConnection, System.Data,
Version=1.0.3300.0, Culture=neutral, PublicKeyToke n=b77a5c561934e089]
log4net: Setting Property [ConnectionString] to String value [Data
Source=MyWorkgroup\SQLEXPRESS; Initial
Catalog=MyNewDatabase;
User ID=juan; Password=juan;
Pooling=False] log4net: Setting Property [CommandText] to String value [INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')] log4net:
Setting Property [CommandType] to CommandType value [Text] log4net:
Created Appender [AdoNetAppender] log4net: Adding appender named
[AdoNetAppender] to logger [root]. log4net: Hierarchy Threshold []
Piece of code that helped me obtain this info (in case the site should become unavailable) is:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\temp\log4netdiagn.txt" />
</listeners>
</trace>
</system.diagnostics>
I'm working on a project using Silverlight 4 and WCF. All of the web methods, exept one are working fine. In Silverlight I use a custom xaml writer to write a string and I want to save the string in a database. Using the Insert method on the web service, I can insert data as long as the string parameter is not too large. When trying to insert the string created by the xaml writer, I get an error. I used Fiddler to trace the error and I"m getting and HTTP 400 error. I have read in numerous post that I need to change the config settings on the servce hosting in the web app and in the client config in the Silverlight app. I have made all the changes that I could find on the web. I don't know what else to try and I have ran out of resources. When I paste the xaml string into Notepad and save it, the file is only 425 KB. Here are the changes I've made to each config file. Hopefully someone can pointout anyting I'm missing. Thank you for looking over my issue.
web.config file in web app:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<!-- Enable the serializer to serialize greater number of records -->
<behavior name="CustomServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="CustomBinding">
<readerQuotas maxDepth="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
ServiceReferences.ClientConfig:
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_DBService" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost.:49436/BuilderWebService/DBService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_DBService"
contract="ServiceReference1.DBService" name="BasicHttpBinding_DBService" />
</client>
</system.serviceModel>
In your web.config in the binding tag you shoiuld add attributes: maxBufferPoolSize, maxReceivedMessageSize, maxBufferSize:
<basicHttpBinding>
<binding name="CustomBinding"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647">
<readerQuotas maxDepth="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"
maxStringContentLength="2147483647" />
</binding>
</basicHttpBinding>
In my example, I've provided the maximal values for the sizes, but you can define the sizes you actually need. Hope it will help you.
I want to get a meaningful error message from my WCF service for my Silverlight 4 application. After some investigation, I found that I need to change the reply code from 500 to 200 if I want silverlight enable to read the meaningful error message. Here is the article: http://msdn.microsoft.com/de-de/library/ee844556(VS.95).aspx
I have implemented it as it is written there, the application compiles and I can use the service - but I still get the 500 return code. The main difference I see is that I call the service via HTTPS not HTTP. Maybe this is the reason, why it doesn't work? Any idea, how to get the return code 200?
Here is my Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ServiceConfiguratorDataSource.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="silverlightFaults" type="ServiceConfiguratorDataSource.SilverlightFaultBehavior, ServiceConfiguratorDataSource, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
<services>
<service name="ServiceConfiguratorDataSource.Service" behaviorConfiguration="ServiceConfiguratorDataSourceBehaviour">
<endpoint address="" binding="customBinding" behaviorConfiguration="SLFaultBehavior" bindingConfiguration="ServiceConfiguratorCustomBinding" contract="ServiceConfiguratorDataSource.IService" />
</service>
</services>
<bindings>
<customBinding>
<binding name="ServiceConfiguratorCustomBinding">
<security authenticationMode="UserNameOverTransport"></security>
<binaryMessageEncoding></binaryMessageEncoding>
<httpsTransport/>
</binding>
</customBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceConfiguratorDataSourceBehaviour">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="True"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ServiceConfiguratorDataSource.UserCredentialsValidator,ServiceConfiguratorDataSource" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="SLFaultBehavior">
<silverlightFaults/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
... and here the silverlightFaultBehavior.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel;
namespace ServiceConfiguratorDataSource
{
public class SilverlightFaultBehavior : BehaviorExtensionElement, IEndpointBehavior
{
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
SilverlightFaultMessageInspector inspector = new SilverlightFaultMessageInspector();
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
}
public class SilverlightFaultMessageInspector : IDispatchMessageInspector
{
public void BeforeSendReply(ref Message reply, object correlationState)
{
if (reply.IsFault)
{
HttpResponseMessageProperty property = new HttpResponseMessageProperty();
// Here the response code is changed to 200.
property.StatusCode = System.Net.HttpStatusCode.OK;
reply.Properties[HttpResponseMessageProperty.Name] = property;
}
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
// Do nothing to the incoming message.
return null;
}
}
// The following methods are stubs and not relevant.
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
public override System.Type BehaviorType
{
get { return typeof(SilverlightFaultBehavior); }
}
protected override object CreateBehavior()
{
return new SilverlightFaultBehavior();
}
}
}
Someone knows if this is because of https ... and if so, how to get it to work?
Thanks in advance,
Frank
EDITH says: I just have added some logging: the ApplyDispatchBehavior - method is called, but the BeforeSendReply - method not ... any ideas why?
If I remember correctly, the UserNamePasswordValidator gets called very early in the pipeline, before the dispatcher ever gets called, which is why your custom dispatch behavior isn't affecting anything. (The reason is security: WCF wants to "throw out" unauthorized requests as early as possible, while running as little code as possible for them).
As you yourself suggested in the comments, one solution would be to just validate the credentials later in the pipeline - e.g. in every operation (or maybe even in a message inspector's AfterReceiveRequest?)
I have created a simple WCF-Service which I want to be accessible via https. The WCF-Service uses a UserNamePasswordValidator, customBinding and UserNameOverTransport as authentication mode. I run it in the IIS7.5 where I have created a self-signed server certificate.
I try to connect to that service with an Silverlight 4 application. I create a Service Reference in my Silverlight 4 app, and VS 2010 automatically creates the needed code (so obviously it is able to connect to the service and get the information).
When I call the WCF, I get a SecurityException with no infos about the reason.
I have fiddler running to see what is happening.
GET https://my.server:8099/clientaccesspolicy.xml 404 Not Found (text/html)
GET https://my.server:8099/crossdomain.xml 200 OK (text/xml)
So the GET for the crossdomain.xml seems to be the last call to the server.
The crossdomain.xml looks as follows:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" />
<allow-http-request-headers-from domain="*" headers="*" />
</cross-domain-policy>
The exception happens, when base.EndInvoke(...) is called on the client and the ExceptionMessage is the following:
{System.Security.SecurityException ---> System.Security.SecurityException: Sicherheitsfehler
bei System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
bei System.Net.Browser.BrowserHttpWebRequest.<>c_DisplayClass5.b_4(Object sendState)
bei System.Net.Browser.AsyncHelper.<>c_DisplayClass2.b_0(Object sendState)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
bei System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
bei System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)}
Here is my UserNamePasswordValidator. Note, that included a logger for debugging reasons. Strange thing is, that the logger never writes anything, so it seems, that the Validate function isn't even called.
namespace ServiceConfiguratorDataSource
{
public class UserCredentialsValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (userName != "xyz" || password != "xyz")
{
logging.Logger.instance.StatusRoutine("LogOn Error: " + userName);
throw new FaultException("Credentials are invalid");
}
else
{
logging.Logger.instance.StatusRoutine("LogOn Success: " + userName);
}
}
}
}
Here is the Web.config of my WCF-Service:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="ServiceConfiguratorDataSource.Service" behaviorConfiguration="ServiceConfiguratorDataSourceBehaviour">
<endpoint address="" binding="customBinding" bindingConfiguration="ServiceConfiguratorCustomBinding" contract="ServiceConfiguratorDataSource.IService" />
</service>
</services>
<bindings>
<customBinding>
<binding name="ServiceConfiguratorCustomBinding">
<security authenticationMode="UserNameOverTransport"></security>
<binaryMessageEncoding></binaryMessageEncoding>
<httpsTransport/>
</binding>
</customBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceConfiguratorDataSourceBehaviour">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ServiceConfiguratorDataSource.UserCredentialsValidator,ServiceConfiguratorDataSource" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
and here the ServiceReferences.ClientConfig
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomBinding_IService">
<security authenticationMode="UserNameOverTransport" includeTimestamp="true">
<secureConversationBootstrap />
</security>
<binaryMessageEncoding />
<httpsTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="https://my.server:8099/ServiceConfiguratorDataSource/Service.svc" binding="customBinding" bindingConfiguration="CustomBinding_IService" contract="WCFDataProvider.IService" name="CustomBinding_IService" />
</client>
</system.serviceModel>
</configuration>
I'm out of ideas what might be the cause of the problem.
Thanks in advance,
Frank
Does you clientaccesspolicy.xml allow https?
Here is example.
The working clientaccesspolicy.xml -> Tipp from Samvel Siradeghyan
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="https://*"/>
<domain uri="http://*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
How to get values from App.Config.
Code:
<configuration>
<appSettings>
<add key="ShowRoomCode" value="1000"/>
<add key="FolderPath" value="D:\\Images\\Book\\"/>
</appSettings>
</configuration>
string imageFolderPath = ConfigurationManager.AppSettings["FolderPath"];
But it returns null value. Config file is in the Same project.
If you expand the Properties section of Visual Studio and double click the settings section, you will be able to add custom settings which end up like so in the config file:
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="WpfApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<WpfApplication1.Properties.Settings>
<setting name="FilePath" serializeAs="String">
<value>Thing</value>
</setting>
</WpfApplication1.Properties.Settings>
</userSettings>
</configuration>
Which you can then do this in your code:
string thing = Properties.Settings.Default.FilePath;
Which is nice because it gives you type safety too
The code you wrote should work - make sure you haven't changed 'BuildAction' of the config file.