System.Security.HostProtectionException when calling webservice from with a function - sql

I'm getting the following error when calling a webservice from a function.
I have referenced all the required assemblies in sql server with "unsafe" permission set and have registered the project assembly with "external access" and the serializer assembly with "safe" permission sets. I have also looked into the code and I don't see anything like message popup etc...that would be irrelevant in sql server's context. I have created another console app that uses the same service and it can access the service just fine from the same server. What else could be causing this issue? Any help is appreciated.
Error: System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host. at System.ServiceModel.Description.TypeLoader.LoadContractDescriptionHelper(Type contractType, Type serviceType, Object serviceImplementation) at System.ServiceModel.ChannelFactory1.CreateDescription() at System.ServiceModel.ChannelFactory.InitializeEndpoint(Binding binding, EndpointAddress address) at System.ServiceModel.ChannelFactory1..ctor(Binding binding, EndpointAddress remoteAddress) at System.ServiceModel.ClientBase`1..ctor(Binding binding, EndpointAddress remoteAddress) at MWMInterfaceBeanServiceClient.MWMInterfaceBeanServiceClient..ctor(Binding binding, EndpointAddress remoteAddress) at MWMInterfaceBeanServiceClient.MWMServiceClient.GetClient() at MWMInterfaceBeanServiceClient.MWMServiceClient.UpdateMobileCrew(Boolean active, Boolean available, Boolean availForOp, String contract, String code, String name, Int32 number, String crewCenter, String crewGroup, String crewId, Int32 crewSize, String crewSupervisor, String crewType, Boolean mdtCrew, SqlXml members, String district, String division, String serviceArea, String mobileNum, String pagerNum, Boolean tempFlag, SqlXml vehicles) The protected resources (only available with full trust) were: All The demanded resources were: Synchronization, ExternalThreading

so, I marked the assemblies as UNSAFE and that made this error go away but gave me another error that said it wasn't able to serialize one of the proxies generated by svcutil to make the request. I already had the serializer assembly generated using sgen in a post build task and registered as UNSAFE and it seems that didn't work. Maybe this only works for simple methods with native types? Therefore, I resorted to a different method mentioned in the following link.
http://www.vishalseth.com/post/2009/12/22/Call-a-webservice-from-TSQL-(Stored-Procedure)-using-MSXML.aspx

Related

I'm trying to set up a new SharePoint production server and getting an error creating an Open XML 2.5 document

I have a SharePoint application written in Visual Basic that works fine and creates Word Documents using Open XML 2.5 on my development machine. We recently set up a new Production server and I published the .wsp file and deployed it on the new server. The application all works fine except the code that generates reports in Word format. It fails on the following line of code.
Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
This is what the code looks like in the function that is failing.
''' \<summary\>
'''
''' \</summary\>
''' \<param name="MemStream"\>\</param\>
''' \<returns\>\</returns\>
Public Function WPDCreateFromStream(MemStream As MemoryStream) As WordprocessingDocument
Try
Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
Dim MainPart As MainDocumentPart = wpd.AddMainDocumentPart()
MainPart.Document = New Document()
Dim DocBody As New Body()
Return wpd
Catch ex As Exception
WriteErrorToEventLog("OpenXML", "WPDCreateFromStream", "", ex)
Return Nothing
End Try
End Function
Here is the exception detail I get when trying to make the WordProcessingDocument.Create call above.
ERROR: Source: OpenXML Routine: WPDCreateFromStream User:
Message: The type initializer for 'MS.Utility.EventTrace' threw an exception.
StackTrace: at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)
Source: WindowsBase
Data: System.Collections.ListDictionaryInternal
InnerException: System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
The Zone of the assembly that failed was:
MyComputer
ToString: System.TypeInitializationException: The type initializer for 'MS.Utility.EventTrace' threw an exception. ---> System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
--- End of inner exception stack trace ---
at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)
TargetSite: Void EasyTraceEvent(Keyword, Event)
I know this is not an issue with the code as the same code works in development. I assume it has to do with permissions, or getting the DocumentFormat.OpenXML.dll installed / registered correctly on the new server, but I've had no luck searching for a solution.
I tried installing OpenXML and the Productivity tool on the server. The productivity tool works and can open a word document, but the Application has the same issue.
If anyone has run into this and can point me to a solution, I would appreciate it.
The MemoryStream is created and passed in to be used by this function. The WordProcessingDocument is returned to the calling function. I could explicitly call ByVal, but in this case it would not change anything.
I am creating a new document, that is why it is coded using WordProcessingDocument.Create
Remember, this code all functions perfectly on the development SharePoint server. It has been used heavily for about a year. I'm just trying to get this to work on a new production server we recently stood up. I have to believe this is related to some permission issue, or a component that is not installed or registered correctly. For Open XML, I believe there is just the one DLL (DocumentFormat.OpenXML.DLL) and it does not register. It is on the server from installing the .wsp package. I also tried installing Open XML 2.5 on the server along with the productivity tool and they all work fine.
The more I think about it, it just feels like a permission issue.

Broken Reference.vb generated after update to VS2012

In my WCF service I have the following OperationContract:
<OperationContract()>
Function getResults(ByVal Settings As Dictionary(Of String, String)) As IO.Stream
...and MessageContract:
<MessageContract()>
Public Class FI
Implements IDisposable
<MessageHeader(MustUnderstand:=True)_
Public id as Integer
<MessageHeader(MustUnderstand:=True)_
Public token as String
<MessageHeader(MustUnderstand:=True)_
Public length as Long
<MessageHeader(MustUnderstand:=True)_
Public del as Char
<MessageHeader(Order:=1)_
Public stream as System.IO.Stream`
Public Sub Dispose() Implements IDisposable.Dispose
FI.Close()
FI=Nothing
End Sub
End Class
On the client side after configuring the service in VS and updating I get multiple errors:
1) For getResults: Instead of the Dictionary an ArrayOfKeyValueOfstringstringKeyValueOfstringstring is expected. I already declared the operation contract as <OperationContract(), ServiceKnownType(GetType(Dictionary(Of String, String)))> without success. My client settings are CollectionType = Generic.List and DictionaryCollectionType = Generic.Dictionary. I also tried deleting and adding the service again.
2) For FI: The method signature that uses the MessageContract FI expects the parameter del to be of type Integer. Here I have no idea what to do.
I have to add, that everything was working fine until recently, the only change I can remember is updating Visual Studio from 2010 to 2012.
I just found out that the underlying problem was an update to .NET 4.5. That's what I did on the machine running VS2010 where the generation used to work. Downgrading to .NET 4.0 did the trick. The generation from within VS is working again.
In conclusion: not a problem of the VS version but of the .NET version of the machine where VS is executed. I guess that the svcutil (or whatever resource the "Update Service Reference" function in VS uses) contained in .NET 4.5 is responsible for the bug.

Can I reference a DataContract and its proxy version from same class

I'm dipping my foot into WCF and am trying to make a simple test project that can both consume the service as a service and also directly instantiate it's classes and work with them.
I had an earlier working version where data passed was just primitive types. However, when I attempted to convert to using data contracts, I'm getting conflicts in whether it's referencing the proxy-declared version of the contract or the version from the project itself.
Question: Is it possible to do this and if so, how would I resolve the data contract references?
private void Test()
{
MyService fssDirect = new MyService(); // direct instantiation
MyServiceClient fssService = new MyServiceClient(); // Service proxy
ClientCredentialsContract Client = new ClientCredentialsContract();
ResponseDataContract Result = new ResponseDataContract();
if (CallAsService)
{
Result = fssService.Create(Client, Request);
}
else
{
Result = fssDirect.Create(Client, Request);
}
}
In the above, any reference to the RequestDataContract and ClientCredentialsContract types indicates
Warning: The type 'MyContracts.RequestDataContract' in 'C:...\Test\MyServiceProxy.cs' conflicts with the imported type 'MyContracts.RequestDataContract' in 'C:...\MyService\bin\Debug\Contracts.dll'. Using the type defined in 'C:...\Test\MyServiceProxy.cs'.
(Names changed and paths shortened to protect the innocent)
Thanks,
John
When you create the proxy for your service, try referencing the assembly which contains the data contracts (if using "Add Service Reference", go to the advanced options, select "reuse types in referenced assemblies"; if using svcutil, use the /r argument). This way the tool won't generate the data contracts and you won't have the conflicts.

WCF service with 4 input parms and 3 out parms gets reordered by Add Service Reference in Proxy Class Project

I've looked in SO and elsewhere and seen questions posed about this along with some answers that still make no sense to me in my case.
I'm refactoring my working VStudio 2010 solution which has:
one project with an ASMX webservice
another separate project for the proxy class (no code here except what is generated by Add Web Reference
another separate project for the client (contains a reference to the
ProxyClass.dll
The new VStudio 2010 solution has:
one project of type WCF service library for the contract by itself (IFileService.cs)
one project of type WCF service library for the implementation of the contract (FileService.cs)
another separate project for the proxy class (no code here except what is generated by Add Service Reference
another separate project for the client (contains a reference to the WCFProxyClass.dll)
Here is the contract which ends with 3 out parameters (and the implementation of same is the same order):
[ServiceContract(Name = "IFileService", Namespace = "http://www.cbmiweb.com/TrimWCF/2011/11")]
public interface IFileService
{
[OperationContract]
public string DownloadFile(string trimURL
, string TrimRecordNumber
, string CallerPC
, string RequestorID
, out byte[] docContents
, out string returnFiletype
, out string returnFilename)
{
Here is what Add Service Reference generated in my proxy class project:
public string DownloadFile(
out byte[] docContents
, out string returnFiletype
, out string returnFilename
, string trimURL
, string TrimRecordNumber
, string CallerPC
, string RequestorID)
{
return base.Channel.DownloadFile(out docContents, out returnFiletype, out returnFilename, trimURL, TrimRecordNumber, CallerPC, RequestorID);
}
I have read answers ranging from "you cannot use out parms in WCF" to "you should not use Add Service Reference but instead use svcutil.exe" to "the order of the parameters do not matter...it will still work".
I am confused about what to do here (and what I've done wrong that led to this re-arranged order and WHY that happened).
First of all, you haven't done anything wrong :). Even though the signatures in the methods in the client and the server are different, they're equivalent wrt the messages which will be produced / consumed by them. You can use that proxy class without any problems, and it should work just as well.
Why this happens is another story - in the service description (WSDL), there are two "messages" for each (non-one-way) operation: one with the input parameters, one with the output parameters. The messages contains respectively the input(s) and output(s) of the operation, but there's nothing in the WSDL which shows the order of them. So when a tool such as Add Service Reference or svcutil is generating the client proxy, it will simply "choose" one order (out parameters first), but the request which the proxy will send to the service will be compatible with what the server expects (and also, the response from the server will be correctly understood by the proxy).
If you want to maintain the order of the parameters, you can create the proxy class yourself. For this you can either use the ChannelFactory<T> class, or create your own client class derived from ChannelBase<T>. But you don't really need to do that, as I mentioned before.

Adding field to WCF data contract breaks clients?

I have a WCF service that returns a class that implements IExtensibleDataObject. I need to add a new field to this class. I updated the DataContract interface and made the change to the class. Now when I try to run my client application I get the following error:
Could not load file or assembly
'xxx.yyyy.zzzz, Version=1.3.9.26111,
Culture=neutral,
PublicKeyToken=b09e2f3e9b5894f0' or
one of its dependencies. The located
assembly's manifest definition does
not match the assembly reference.
(Exception from HRESULT: 0x80131040)
The AssemblyVersion of the WFC class has been changed - does that break client?
EDIT:
There are clients in production that use this service. I do not want to make them update their service reference and redeploy their clients for this simple change if possible.
It depends on how you have set up your data contract.
In WCF, using all the defaults, your service will use the DataContractSerializer (DCS) to serialize your object into XML. The DCS will serialize your fields in order - first the public ones, then the private ones. Within each visibility group, it will order the fields/properties alphabetically by name.
Thus, if you introduce a new public property MiddleName and you already had FirstName and LastName, you would be fine: the old XML would have been
<YourObject>
....
<FirstName>.....</FirstName>
<LastName>.....</LastName>
</YourObject>
and your new one would just simply add a new property at the end:
<YourObject>
....
<FirstName>.....</FirstName>
<LastName>.....</LastName>
<MiddleName>....</MiddleName>
</YourObject>
Such an update "add something at the end" should work just fine, the DCS will just simply ignore additional tags in the XML.
However: had you introduced a property called Gender, that would be stuck between <FirstName> and <LastName> and would thus break the order of the data in your XML and thus would break the data contract - no "old" client will be able to call your new service.
In order to take control of this, you can put specific Order= attributes on your data members in your data contract:
[DataContract]
public class SomeAddress
{
[DataMember(Order=0)]
public string FirstName;
[DataMember(Order=1)]
public string LastName;
}
Then you could easily add a new property - just add it to the end of the list!
[DataContract]
public class SomeAddress
{
[DataMember(Order=0)]
public string FirstName;
[DataMember(Order=1)]
public string LastName;
[DataMember(Order=2)]
public string Gender;
}
So by using the Order= attribute on your data contracts, you can take control of your XML layout, and you can make simple extensions of existing data contracts non-breaking updates.
For more background and in-depth know-how, you ought to read Serialization in Windows Communication Foundation on MSDN Magazine's web site - highly recommended.
From your service reference context menu choose... "Update Service Reference"