Hi,
Can someone please save me from my cross-domain access ____? I am trying to connect to some WCF services from a Silverlight 4 client using the net.tcp protocol but keep getting the error:
Could not connect to net.tcp://localhost:4505/SponsorshipWcfService. The connection attempt lasted for a time span of 00:00:00.7750775. TCP error code 10013: An attempt was made to access a socket in a way forbidden by its access permissions.. This could
be due to attempting to access a service in a cross-domain way while the service is not configured for cross-domain access. You may need to contact the owner of the service to expose a sockets cross-domain policy over HTTP and host the service in the allowed
sockets port range 4502-4534.
This is all on my development pc which has a Window 7 64-bit operating system and Visual Studio 2010 (using .Net Framework 3.5). Unfortunately, I am not able to use IIS 7 because the server that this application will live on is a Windows 2003 server,
so I am trying to host my WCF services in a Windows Service. I've been trying to crack this for days and have read every article I can find and tried to replicate several examples. I downloaded Tomasz Janczuk example but got the same error when
I tried to run it.
I have a WCF Library project which was built using Brice Wilson's template and then have a Windows Service project that references this project. I then reference the various services in my silverlight application.
My app.config:
<system.serviceModel>
<bindings>
<customBinding>
<binding name="silverlightBinaryBinding">
<binaryMessageEncoding maxSessionSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
</binaryMessageEncoding>
<tcpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647"/>
</binding>
</customBinding>
</bindings>
<services>
<service behaviorConfiguration="SelfHostedWcfServiceLibrary.CategoriesServiceBehavior"
name="SelfHostedWcfServiceLibrary.CategoriesService">
<endpoint address="" binding="customBinding" bindingConfiguration="silverlightBinaryBinding"
contract="SelfHostedWcfServiceLibrary.ICategoriesService" />
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
<endpoint address="" binding="webHttpBinding" contract="SelfHostedWcfServiceLibrary.IPolicyRetriever" behaviorConfiguration="webHttpEnablingBehavior" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:4505/CategoriesService/" />
<add baseAddress="http://localhost:80/CategoriesService/" />
</baseAddresses>
</host>
</service>
<service behaviorConfiguration="SelfHostedWcfServiceLibrary.SponsorshipWcfServiceBehavior"
name="SelfHostedWcfServiceLibrary.SponsorshipDataService">
<endpoint address="" binding="customBinding" bindingConfiguration="silverlightBinaryBinding"
contract="SelfHostedWcfServiceLibrary.ISponsorshipDataService" />
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
<endpoint address="" binding="webHttpBinding" contract="SelfHostedWcfServiceLibrary.IPolicyRetriever" behaviorConfiguration="webHttpEnablingBehavior" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:4505/SponsorshipWcfService/" />
<add baseAddress="http://localhost:80/SponsorshipWcfService/" />
</baseAddresses>
</host>
</service>
<service behaviorConfiguration="SelfHostedWcfServiceLibrary.SponsorshipPushServiceBehavior"
name="SelfHostedWcfServiceLibrary.WCFPushService">
<endpoint address="" binding="customBinding" bindingConfiguration="silverlightBinaryBinding"
contract="SelfHostedWcfServiceLibrary.IPushService" />
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
<endpoint address="" binding="webHttpBinding" contract="SelfHostedWcfServiceLibrary.IPolicyRetriever" behaviorConfiguration="webHttpEnablingBehavior" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:4505/SponsorshipPushService/" />
<add baseAddress="http://localhost:80/SponsorshipPushService/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SelfHostedWcfServiceLibrary.CategoriesServiceBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceThrottling maxConcurrentCalls="100" maxConcurrentSessions="100"
maxConcurrentInstances="100" />
</behavior>
<behavior name="SelfHostedWcfServiceLibrary.SponsorshipWcfServiceBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceThrottling maxConcurrentCalls="100" maxConcurrentSessions="100"
maxConcurrentInstances="100" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpEnablingBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
PolicyRetriever interface:
[ServiceContract]
public partial interface IPolicyRetriever
{
[OperationContract, WebGet(UriTemplate = "/clientaccesspolicy.xml")]
Stream GetClientAccessPolicy();
[OperationContract, WebGet(UriTemplate = "/crossdomain.xml")]
Stream GetCrossDomain();
}
One of my WCF Service Interfaces:
[ServiceContract]
public interface ICategoriesService
{
[OperationContract]
usp_GetCategoryResult GetCategory(int categoryId, out CustomException ServiceError);
[OperationContract]
bool DeleteCategory(int categoryId, bool IsLogicalDelete, out CustomException ServiceError);
[OperationContract]
InsertResult InsertCategory(usp_GetCategoryResult category, string clientIpAddress, int ChangedByUserId, out CustomException ServiceError);
[OperationContract]
UpdateResult UpdateCategory(usp_GetCategoryResult category, string clientIpAddress, bool ignoreConcurrencyCheck, int ChangedByUserId, out CustomException ServiceError);
}
An example of the implementation of my service with policy retrieval implementation (other services are implemented similarly)
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.NotAllowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]
public class CategoriesService : ICategoriesService, IPolicyRetriever
{
public usp_GetCategoryResult GetCategory(int categoryId, out CustomException ServiceError)
{
usp_GetCategoryResult result = new usp_GetCategoryResult();
try
{
using (SponsorshipLinqDataDataContext dc = new SponsorshipLinqDataDataContext())
{
dc.CommandTimeout = Properties.Settings.Default.DataContextCommandTimeout;
result = dc.usp_GetCategory(categoryId).FirstOrDefault<usp_GetCategoryResult>();
ServiceError = null;
}
}
catch (Exception ex)
{
ServiceError = new CustomException(ex);
SponsorshipHelper.logger.Error(ex.Message);
}
return result;
}
public bool DeleteCategory(int categoryId, bool IsLogicalDelete, out CustomException ServiceError)
{
bool blnSuccessfullyDeleted = false;
int intNoOfRecordsAffected = 0;
try
{
using (SponsorshipLinqDataDataContext dc = new SponsorshipLinqDataDataContext())
{
dc.CommandTimeout = Properties.Settings.Default.DataContextCommandTimeout;
if (categoryId > 0)
{
intNoOfRecordsAffected = dc.usp_DeleteCategory(categoryId, IsLogicalDelete);
blnSuccessfullyDeleted = intNoOfRecordsAffected > 0;
}
ServiceError = null;
}
}
catch (Exception ex)
{
ServiceError = new CustomException(ex);
SponsorshipHelper.logger.Error(ex.Message);
}
return blnSuccessfullyDeleted;
}
public InsertResult InsertCategory(usp_GetCategoryResult category, string clientIpAddress, int ChangedByUserId, out CustomException ServiceError)
{
InsertResult ir = new InsertResult();
int? intId = 0;
PushClient pc = null;
if (category != null)
{
try
{
using (SponsorshipLinqDataDataContext dc = new SponsorshipLinqDataDataContext())
{
dc.CommandTimeout = Properties.Settings.Default.DataContextCommandTimeout;
ServiceError = null;
pc = SponsorshipHelper.PushClients.FirstOrDefault<PushClient>(s => s.PushClientInformation.ipaddress == clientIpAddress);
dc.usp_InsertCategory(category.CategoryName, category.SortOrder, ChangedByUserId, category.HasOTP, category.HasPageBackground, ref intId);
if (intId.Value == 0)
{
ir.Comment = "Unable to add category. Category already exists.";
ir.FailureReason = InsertResult.FailureReasons.AlreadyExists;
}
else
{
ir.Successful = true;
ir.Comment = "Category successfully added!";
ir.Id = intId.Value;
if (pc != null)
{
//Send message to all relevant clients that the calendar data has changed.
SponsorshipHelper.SendMessage(SendMessageType.CalendarDataChanged, "", pc, true);
}
}
}
}
catch (Exception ex)
{
ir.FailureReason = InsertResult.FailureReasons.Exception;
ir.Comment = "Unable to add category!";
ServiceError = new CustomException(ex);
SponsorshipHelper.logger.Error(ex.Message);
}
}
else
{
ServiceError = null;
SponsorshipHelper.logger.Error("Unable to insert category due to invalid parameters.");
}
return ir;
}
public UpdateResult UpdateCategory(usp_GetCategoryResult category, string clientIpAddress, bool ignoreConcurrencyCheck, int ChangedByUserId, out CustomException ServiceError)
{
UpdateResult ur = new UpdateResult();
bool? blnSuccessful = false;
int? intRowCountChangedSinceEditing = 0;
bool blnConcurrencyCheckOk = true;
PushClient pc = null;
if (category != null)
{
try
{
using (SponsorshipLinqDataDataContext dc = new SponsorshipLinqDataDataContext())
{
dc.CommandTimeout = Properties.Settings.Default.DataContextCommandTimeout;
ServiceError = null;
pc = SponsorshipHelper.PushClients.FirstOrDefault<PushClient>(s => s.PushClientInformation.ipaddress == clientIpAddress);
if (!ignoreConcurrencyCheck)
{
dc.usp_CheckCategoryUpdated(category.CategoryId, category.LastUpdated, ref intRowCountChangedSinceEditing);
blnConcurrencyCheckOk = intRowCountChangedSinceEditing == 1;
}
if (blnConcurrencyCheckOk)
{
dc.usp_UpdateCategory(category.CategoryId, category.CategoryName, category.SortOrder, ChangedByUserId, category.HasOTP, category.HasPageBackground, ref blnSuccessful);
if (blnSuccessful.Value)
{
ur.Successful = true;
ur.Comment = "Category successfully updated!";
if (pc != null)
{
//Send message to all relevant clients that the calendar data has changed.
SponsorshipHelper.SendMessage(SendMessageType.CalendarDataChanged, "", pc, true);
}
}
else
{
ur.Comment = "Unable to update category. Category already exists.";
ur.FailureReason = UpdateResult.FailureReasons.AlreadyExists;
}
}
else
{
ur.Comment = "Unable to update category. Category changed by another user.";
ur.FailureReason = UpdateResult.FailureReasons.ChangedByAnotherUser;
}
}
}
catch (Exception ex)
{
ur.Comment = "Unable to update category!";
ur.FailureReason = UpdateResult.FailureReasons.Exception;
ServiceError = new CustomException(ex);
SponsorshipHelper.logger.Error(ex.Message);
}
}
else
{
ServiceError = null;
ur.FailureReason = UpdateResult.FailureReasons.InvalidParameters;
ur.Comment = "Unable to update category due to invalid parameters.";
SponsorshipHelper.logger.Error("Unable to update category due to invalid parameters.");
}
return ur;
}
#region IPolicyRetriever Members
public Stream GetClientAccessPolicy()
{
// TODO: Modify the string below to set the desired cross-domain policy
string result = @"<?xml version=""1.0"" encoding=""utf-8""?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers=""*"">
<domain uri=""*""/>
</allow-from>
<grant-to>
<resource path=""/"" include-subpaths=""true""/>
<socket-resource port=""4502-4534"" protocol=""tcp"" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";
WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
return new MemoryStream(Encoding.UTF8.GetBytes(result));
}
public Stream GetCrossDomain()
{
string result = @"<?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=""*"" />
</cross-domain-policy>";
WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
return new MemoryStream(Encoding.UTF8.GetBytes(result));
}
#endregion
}
Hopefully, I have given enough information. If not, please let me know.
Please help me with this, it is driving me mad.
Thanks.