Home » .Net FrameworkRSS

TCP error code 10013: An attempt was made to access a socket in a way forbidden by its access permis

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.

 

 

11 Answers Found

 
 

Answer 2

Hi Christopher,

Thanks for replying.  My policy is available at http://localhost:80/CategoriesService/clientaccesspolicy.xml" for my service at "net.tcp://localhost:4505/CategoriesService/" and at http://localhost:80/ActivitiesService/clientaccesspolicy.xml" for my service at "net.tcp://localhost:4505/ActivitiesService/" etc.  Is this correct or should all my services be looking at http://localhost:80/clientaccesspolicy.xml? If this is the case how can I achieve this because I am unable to set the http (the one for the clientaccesspolicy.xml file) base addresses for my various services to the same address.  I have one Windows Service hosting all my WCF Services for this project.

Please help.

 

Answer 3

Policy needs to be at http://localhost:80/clientaccesspolicy.xml. Silverlight will look there only. And to be more specific, it will actually look at http://IPAddressOfTheMachine:80/clientaccesspolicy.xml

You can fine grain the access  to your service in the policy file, or define multiple policies. So combine your policies in one.

<?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="/ActivitiesService" include-subpaths="true"/>
        <socket-resource port="4505" protocol="tcp" />
      </grant-to>
    </policy>
    <policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/CategoriesService" include-subpaths="true"/>
        <socket-resource port="4505" protocol="tcp" />
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

 

Answer 4

How do I get the clientaccesspolicy.xml file to appear at  "http://localhost:80/clientaccesspolicy.xml"?  I am able to get it to appear at "http://localhost:80/MyServiceName/clientaccesspolicy.xml" by defining it as a host base address for each service, but if I put <"add baseAddress="http://localhost:80/" />" in the host base address for each service I would get an error  as they are the same.  How can I get around this?  Please help.
 
 

Answer 6

From the examples, I thought I had to implement the IPolicyRetriever for each service.  I now stopped implementing it on all my WCF services.  I then created a new WCF Service that implements this interface and supplies the clientaccesspolicyfile.xml at http://localhost:80/clientaccesspolicy.xml.  I can see it at this address now in IE.  I took "<endpoint address="" binding="webHttpBinding" contract="SelfHostedWcfServiceLibrary.IPolicyRetriever" behaviorConfiguration="webHttpEnablingBehavior" />" out of the app.config for all my services and also took out the "<add baseAddress="http://localhost:80/SponsorshipPushService/" />" base addresses for these services.  I defined my new policy service as below:

         <service behaviorConfiguration="MumWcfServices.PolicyRetrieverServiceBehavior" name="MumWcfServices.PolicyRetriever">
            <endpoint address="" binding="webHttpBinding" contract="MumWcfServices.IPolicyRetriever" behaviorConfiguration="webHttpEnablingBehavior"/>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            <host>
               <baseAddresses>
                  <add baseAddress="http://mel-dl-nsa2:80/"/>
               </baseAddresses>
            </host>
         </service>

I think I am now pretty close to the right solution but now I cannot run my Silverlight app from VS2010 or IE.  IE says "No Service End Point found" and VS2010 says "The web server could not find the requested resource"  I tested my WCF services with the WCF Tester and they all work and can return data.

What am I doing wrong?

 

Answer 7

What do you use as an EndpointAddress for your Silverlight client? localhost? IpAddress? MachineName? Full Domain Machine Name?

Try each of these, that might be the solution.

 

Answer 8

Hi Christopher,

I'm a bit confused can you please clear up the following for me:  Do I need to implement IPolicyRetriever against all of my services (they are all hosted together in the same Windows service) or do I need to create a seperate wcf service with webHttpBinding that implements this service and provide the clientaccesspolicy.xml at at http://localhost:80/clientaccesspolicy.xml?  If the former then I have the problem with trying to define the same base address for each service's webHttpBinding endpoint.  If the later, then why couldn't I just copy the clientaccesspolicy.xml to the wwwroot directory?

I tried the following: I got rid of the implementations of IPolicyRetriever on all the services and deleted their webHttpBinding endpoints and relevant base addresses and then copied the clientaccesspolicy.xml to the wwwroot directory (this enabled access to it via http://localhost:80/clientaccesspolicy.xml in the browser).  This stopped the "TCP error  code 10013: An attempt  was made  to access  a socket  in a way forbidden  by its access permissions" error message but now it is giving me "The message with Action 'http://tempuri.org/ISponsorshipDataService/GetCategories' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None)."

I just want to connect to some wcf services self-hosted on a windows service via net.tcp; surely it shouldn't be this hard.

Thanks for your help thus far, I really appreciate it.  Please help me to resolve this.

 

Answer 9

You need one policy to rule all your service. So the one policy file at the root of your wwwroot directory works, and so should have the solution with webHttpBinding (though it didn't, which I can't explain right now why myself).

As for your newest exception, where is it from? service or client?

It seems a lot of things have changed on your service, so I would consider updating the service reference, maybe even recreating it completely. Also, can you share how you initialize your client proxy? Do you use config only, or do you use code? What is the endpoint address used by the client? What is the endpoint address used to create the service? These two should match in Silverlight scenarios to work.

 

Answer 10

I am getting this message on the Silverlight client.  I have deleted and recreated the service references but still get this error.  I am creating the client proxy in code  below:

 TcpTransportBindingElement tcpElement = new TcpTransportBindingElement();
 tcpElement.MaxBufferSize = int.MaxValue;
 tcpElement.MaxReceivedMessageSize = int.MaxValue;

 BinaryMessageEncodingBindingElement binaryMsgEncodingElement = new BinaryMessageEncodingBindingElement();

 CustomBinding binding = new CustomBinding(binaryMsgEncodingElement, tcpElement);
 binding.ReceiveTimeout = TimeSpan.FromMinutes(ClientTimeoutInMinutes);
   
 System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress(new Uri(wcfPushServiceUrl));

public static SponsorshipWcfServiceReference.SponsorshipDataServiceClient SponsorshipWcfClient = new SponsorshipPushServiceReference.PushServiceClient(binding, address);
 

Answer 11

Hi Christopher,

I copied the above code  to the server to create the host so they would be the same but this didn't help.

I solved it in the end by instantiating the client using the empty constructor (SponsorshipWcfServiceReference.SponsorshipDataServiceClient SponsorshipWcfClient = new SponsorshipPushServiceReference.PushServiceClient();) so that the values in the ServiceReferences.ClientConfig file would be used.  This worked!

Thanks so much for your help and patience.

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter