Loading a document in XSLT using BASIC authentication in ASP.net - asp.net

For development purposes we have a site setup with BASIC authentication in IIS7. One aspect of the site is that it does a lot transformations using XSLT. However this is causing authentication problems when loading documents in XSLT like this:
<xsl:with-param
name="value"
select="document('/mod_cms/xml/fixed/phaedrus_object_menu_display.xml')
/menuDisplay/option[value=$pagingValue]/name"/>
I get the error:
The remote server returned an error:
(401) Unauthorized.
Looking on the web for solutions, I have come across suggestions to use Credentials, eg:
Dim sw As New StringWriter()
Dim xslArg As New XsltArgumentList()
Dim xslt As New XslCompiledTransform()
Dim settings As New XsltSettings
settings.EnableDocumentFunction = True
Dim resolver As New XmlUrlResolver
Dim xml As New XmlDocument
xml.LoadXml(sXml)
Dim myCache As New System.Net.CredentialCache()
myCache.Add(New Uri("http://URL.net/"), "Basic", New System.Net.NetworkCredential("???", "???"))
myCache.Add(New Uri("http://URL.net/mod_cms/xml/fixed/"), "Basic", New System.Net.NetworkCredential("???", "???"))
resolver.Credentials = myCache '
xslt.Load(sXsl, settings, resolver)
xslt.Transform(xml, xslArg, sw)
But this doesn't seem to work.
Has someone else had this problem.
Thanks in advance for any help.

Try using an XmlUrlResolver object.

Related

How to execute an SSRS .rss script file in IIS/ASP.NET

I need to execute a .rss SSRS script file within an ASP.NET application running in IIS 7.x. How can I do that?
Do I have to configure the IIS AppPool that is running my web application to have elevated privileges such that I can start up the rs.exe console application passing the .rss script to it the way I would otherwise execute an .rss script file outside of IIS?
Or is there another way? Does Visual Studio/.NET provide any mechanism for bootstrapping an .rss script file without needing the rs.exe console application? Is my only option to make the rs.exe console application available to my web application running in IIS?
So, I figured it out. If you're wondering how to create a History Snapshot of a report on your SSRS Reports Server using the ReportServices2010 proxy, here's one example and one way you can accomplish it (many thanks to kyzen for sharing his insight in directing me to the SOAP API):
Dim basicHttpBinding As New BasicHttpBinding()
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm
basicHttpBinding.SendTimeout = New TimeSpan(0, 10, 0)
Dim endPoint As New EndpointAddress("http://server/reportserver/ReportService2010.asmx")
Dim instance As New ReportingService2010SoapClient(basicHttpBinding, endPoint)
Dim itemPath As String = "/Path/to/report"
Dim warnings() As Warning
Dim historyId As String = Nothing
Dim values As ParameterValue() = Nothing
Dim credentials As DataSourceCredentials() = Nothing
Dim t As New TrustedUserHeader()
instance.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation
instance.ClientCredentials.Windows.ClientCredential = New Net.NetworkCredential("userid", "password", "domain")
instance.Open()
oServerInfoHeader = instance.CreateItemHistorySnapshot(t, itemPath, historyId, warnings)
and in C#:
BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
basicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly
basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm
basicHttpBinding.SendTimeout = New TimeSpan(0, 10, 0)
EndpointAddress endPoint = new EndpointAddress("http://server/reportserver/ReportService2010.asmx");
ReportingService2010SoapClient instance = new ReportingService2010SoapClient(basicHttpBinding, endPoint);
string itemPath = "/Path/to/report"
Warning warnings[];
string historyId;
ParameterValue values[];
DataSourceCredentials credentials[];
TrustedUserHeader t = new TrustedUserHeader();
instance.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
instance.ClientCredentials.Windows.ClientCredential = New Net.NetworkCredential("userid", "password", "domain");
instance.Open();
oServerInfoHeader = instance.CreateItemHistorySnapshot(t, itemPath, historyId, warnings);

How to pass data to a WebApi Controller from a console application?

Using this code I am not able to post data to an api (asp.net MVC latest version).
What could be the problem?
Should I set specific headers?
Using client As New Net.WebClient
Dim reqparm As New Specialized.NameValueCollection
reqparm.Add("DeviceId", "devicetest")
reqparm.Add("Message", "messagetest")
Dim responsebytes = client.UploadValues("http://xxx.xxx.com/api/notification", "POST", reqparm)
Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

Can't share isolated storage file between applications in different app pools

I've got various web apps (containing WCF services) in IIS under the default website. As long as they are all running in the same app pool they can access a shared isolated storage file no problem.
However, once I move them to different app pools I get "System.IO.IsolatedStorage.IsolatedStorageException: Unable to create mutex" when one tries to access a file created by another. They are all running under NetworkService user. I tried GetUserStoreForAssembly and GetMachineStoreForAssembly all with the same result. Any ideas why they couldn't use a shared file?
I made sure to close the stream and even dispose it in case one was holding onto it, but I am running a simple test where one service writes it, then another tries to read from it later, and it always fails.
Also, I am accessing the isolated store from a signed assembly.
Does anybody have any ideas?
Here is the code:
Private Sub LoadData()
Dim filename = FullFilePath(_fileName)
Dim isoStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly()
' Tried GetMachineStoreForAssembly, same failure
isoStorage.CreateDirectory(ROOT_DIRECTORY)
If (isoStorage.GetFileNames(filename).Length = 0) Then
Return
End If
Dim stream As Stream = New IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, isoStorage)
If stream IsNot Nothing Then
Try
Dim formatter As IFormatter = New BinaryFormatter()
Dim appData As Hashtable = DirectCast(formatter.Deserialize(stream), Hashtable)
Dim enumerator As IDictionaryEnumerator = appData.GetEnumerator()
While enumerator.MoveNext()
Me(enumerator.Key) = enumerator.Value
End While
Finally
stream.Close()
stream.Dispose()
stream = Nothing
End Try
End If
End Sub
Public Sub Save()
Dim filename = FullFilePath(_fileName)
' Open the stream from the IsolatedStorage.
Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly()
' Tried GetMachineStoreForAssembly, same failure
Dim stream As Stream = New IsolatedStorageFileStream(filename, FileMode.Create, isoFile)
If stream IsNot Nothing Then
Try
Dim formatter As IFormatter = New BinaryFormatter()
formatter.Serialize(stream, DirectCast(Me, Hashtable))
Finally
stream.Close()
stream.Dispose()
stream = Nothing
End Try
End If
End Sub
Looks like it was a trust issue.
After adding the assembly accessing the isolated storage file to the gac it magically worked as everything in the gac has full trust set automatically.
This works for me, but it might not always be an option to do this for other solutions. Check out the .NET Framework caspol utility if this is the case.
Hope this helps somebody! It was a huge pitafor me.

Post XML to a web service

I have a web service, which accepts XML input. What I am trying to do is setup an aspx page which posts xml to the service. Here is my code so far, but I am getting an error 400 (bad request) when I try to submit...
Imports System.Net
Imports System.IO
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Submit.Click
Dim strDataToPost As String
Dim myWebRequest As WebRequest
Dim myRequestStream As Stream
Dim myStreamWriter As StreamWriter
Dim myWebResponse As WebResponse
Dim myResponseStream As Stream
Dim myStreamReader As StreamReader
' Create a new WebRequest which targets the web service method
myWebRequest = WebRequest.Create("http://foo/p09SoapHttpPort")
' Data to send
strDataToPost = DataToSend.Text & Server.UrlEncode(Now())
' Set the method and content type
With myWebRequest
.Method = "POST"
.ContentType = "text/xml"
.Timeout = -1
.ContentLength = strDataToPost.Length()
End With
' write our data to the Stream using the StreamWriter.
myRequestStream = myWebRequest.GetRequestStream()
myStreamWriter = New StreamWriter(myRequestStream)
myStreamWriter.Write(strDataToPost)
myStreamWriter.Flush()
myStreamWriter.Close()
myRequestStream.Close()
' Get the response from the remote server.
myWebResponse = myWebRequest.GetResponse()
' Get the server's response status
myResponseStream = myWebResponse.GetResponseStream()
myStreamReader = New StreamReader(myResponseStream)
ResponseLabel.Text = myStreamReader.ReadToEnd()
myStreamReader.Close()
myResponseStream.Close()
' Close the WebResponse
myWebResponse.Close()
End Sub
End Class
If anyone knows of any good web resources on how to upload .xml files to a web service method that would also be a great help and would answer this question as I can re-work it that way.
Thanks.
P.S in the last edit, I modified the code to have .contentlength (thanks for the assistance). Unfortunately after this I am still getting 'Bad Request'. If anyone can confirm / disconfirm my code should be working, I will start investigating the service itself.
The data you're trying to post might look a little funny if you're concatenating a time string to it:
strDataToPost = DataToSend.Text & Server.UrlEncode(Now())
If DataToSend is proper XML, then you're adding the Url Encoding of Now() which makes me think it will no longer be valid XML.
Check to make sure your StreamWriter is not inserting additional characters (CR, LF). If it does, then the length you're sending does not correspond to the actual data, but that probably wouldn't have caused a problem before you started sending the content length.
Is your web service configuration to accept XML directly? I'm wondering if you might have to encapsulate the XML in multipart/form-data in order for your web service to accept it.
I'm not a web service expert, but I compared your code to some working code I have, and the only relevant difference is that you are not setting the ContentLength of your request.
myWebRequest.ContentLength = strDataToPost.Length()

Adding a database to an ASP.NET Web Service

Okay this question could either be very broad or very specific because I am not sure if I am going about this in a fundamentally wrong way or if I am close to correct.
First an overview: What I am trying to do it create a server application for all of the clients in my organization to connect to. I think the best way to do this is to use a web service. Please correct me if I am wrong!
Anyway, if I use a web service I need the web service(server) to connect to the database. In MS Visual studio when you add a web service project the data menu disappears and you can't add a data source to the project. There may be a workaround for this by hand coding this, but I am not sure how to do it. This is my first time working with a web service and ASP.NET so I am a real noob in this area.
Any help would be greatly appreciated!!!
Add your database connection string to the <connectionStrings/> section of the web service web.config file. Check this web site for a list of the most common database connection strings: Connectionstrings.com
You would use standard ADO.Net commands and SQL statements, rather than using the dataset designer. Example (IN VB)
<WebMethod()> _
Public Function DoesOpenCallExist(ByVal CustID As String, ByVal CallType As String, ByVal SubCallType As String) As Boolean
Dim returnvalue As Boolean = False
' first, entry validation
' snip - code deleted
Dim conn As New System.Data.SqlClient.SqlConnection
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("HEATConnectionString").ConnectionString
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_GetCallCount"
cmd.Parameters.AddWithValue("#CustID", CustID)
' Etc...
Try
conn.Open()
returnvalue = cmd.ExecuteScalar() > 0
Catch ex As Exception
Throw New Exception(ex.ToString())
Finally
conn.Close()
End Try
Return returnvalue
End Function
*This should be done
web.config file*
here the datsource is the servername,initial catlog is the databasename and the userid ur sql userid and the password is as same.
And then in the class we want to get connect with the database......
****class.cs****
public class connect
{
public static SqlConnection con()
{
String con= ConfigurationManager.AppSettings["connections"].ToString();
SqlConnection cn = new SqlConnection(con);
cn.Open();
return cn;
}
}
here the connection is the keyname......
ok i think its sufficient............

Resources