Insert with Domain Service Object in server side project - asp.net

I got a basic Silverlight Ria Services solution with 2 projects (Silverlight Client and Asp.net Host) with a Domain Service Class in the Host project.
I can create a new Domain Service object in another class inside the host project, and use the methods generated by Visual Studio.
The query methods of this Domain object works fine retrieving data, but insert methods don't apply to the database, probably cause I didn't submit te operation, as the method "SubmitChanges" does in client project.
Question is: how can I apply insert, delete and update operations with this object in server-side since I'm not coding in Domain Service class, but only using an object of this type?
I've found the method DomainService.Submit, but it requires a ChangeSet that don't know how to provide.
EDIT:
//Client Project (Silverlight):
MyDomain domain = new MyDomain();
domain.Products.Add(new Product());
domain.SubmitChanges(); //sucessfull DB insertion
//Host Project, any new asp.net WebPage:
MyDomain domain = new MyDomain();
domain.InsertProduct(new Product()); //nothing happens in DB
domain.SubmitChanges(); //don't exist
domain.Submit(ChangeSet); //don't know how to provide a ChangeSet

It's done a little bit differently on the server vs. the client. On the server, from your domain service class, you can use Me.ObjectContext to add and save your entities, e.g.
Me.ObjectContext.Products.AddObject(new Product)
Me.ObjectContext.SaveChanges()

Related

Call web service and passing a cookie in an ASP.Net Web Application

We have to call a web service hosted by our client. We were able to add a web reference to our ASP.Net web application and use the web service. The client just sent us a text file and said we need to pass this as a cookie to get access to the web service. I ask for their help and they sent me this.
SoapHttpClientProtocol clientProxy = new T();
clientProxy.CookieContainer.Add(uri, cookie);
Is there a way to do this using a web reference? Or do I hav eto make a soap call?
The web reference you have generated should be derived from System.Web.Services.Protocols.SoapHttpClientProtocol (for details see this link). The ancestors of this class also provide a property named CookieContainer so that you can use the following code:
webRefInstance.CookieContainer.Add(uri, cookie);

How to Get WCF RIA service URL

I have created a WFC RIA Service based on ASP.Net Website and adding the nuget packages for RIA service. I have also created a Service named "FactoryService" by extending DomainService class.
I have tested the service by creating a GridView with DomainDataSource pointing to the service. The service is working.
Now I want to access the service from other clients as I have enabled SOAP endpoint. But I cannot find the service's url to the svc file. I need this url to add service reference to my other projects. How do I find the service url?
I have tried the following urls and all returns 404. (namespace "WebApplication3", DomainService class "FactoryService").
- http://localhost:15066/WebApplication3-FactoryService.svc
- http://localhost:15066/services/WebApplication3-FactoryService.svc
- http://localhost:15066/ClientBin/WebApplication3-FactoryService.svc
- http://localhost:15066/FactoryService.svc
- http://localhost:15066/services/FactoryService.svc
- http://localhost:15066/ClientBin/FactoryService.svc
I have found the problem. In the DomainService class, I missed to annotate it with [EnableClientAccess()].
A domain service class must be marked with the
EnableClientAccessAttribute attribute to make the service available to
the client project. The EnableClientAccessAttribute attribute is
automatically applied to a domain service when you select the Enable
client access check box in the Add New Domain Service Class dialog
box.
As I'm using VS2013, the wizard is not available and missed to annotate it with the attribute.
Normally it has the following form
Base-Address + ClientBin + FullName of DomainService (Namespace+TypeName separated by -)
So in your case it should look like
http://localhost:15066/ClientBin/WebApplication3-FactoryService.svc
When you access this link in a Browser you will be provided a page that looks similar to this
Service
You have created a service.
To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:
svcutil.exe http://localhost:15066/ClientBin/WebApplication3-FactoryService.svc?wsdl
You can also access the service description as a single file:
http://localhost:15066/ClientBin/WebApplication3-FactoryService.svc?singleWsdl
This will generate a configuration file and a code file that contains the client class. Add the two files to your client application and use the generated client class to call the Service. For example:
C#
class Test
{
static void Main()
{
HelloClient client = new HelloClient();
// Use the 'client' variable to call operations on the service.
// Always close the client.
client.Close();
}
}
Visual Basic
Class Test
Shared Sub Main()
Dim client As HelloClient = New HelloClient()
' Use the 'client' variable to call operations on the service.
' Always close the client.
client.Close()
End Sub
End Class

ASP.Net custom authentication with existing server

We have an existing user licensing server that is running via PHP. It allows for creation of users, checking if the provided username and password is valid, and updating a user.
We are creating a new ASP.Net website and want it to use this existing user PHP scripts/database to restrict access to portions of the ASP.Net website. Also there are web services that use the same login and password via basic authentication that we need to access as well from the ASP.Net server.
I am looking for a way for .Net to use the remote PHP scripts to validate login. And I need a way for the users login id and password to be available so I can use them to communicate with those existing web services from the ASP.Net server on their behalf.
Does anyone know how to go about getting this sort of thing done. Or any good tutorials or blogs?
Thanks!
It's possible to run PHP and ASP.NET on the same server, and even in the same web application. You can also create .NET code that runs before and/or after each PHP request (with an HttpModule).
PHP under IIS just has a separate HttpHandler that invokes the cgi-bin process.
If you want to call a PHP page from an ASP.NET page, one approach is to use Server.Execute() -- although web services would certainly be cleaner from an architectural perspective.
Beyond that, for the actual authentication/authorization part of your question, the approach depends on the specifics of your implementation. You can certainly do things like share cookies between PHP and .aspx.
unfortunatly they are different languages and php scripts cannot be used in an asp.net site. You would have to recreate your classes(scripts) but what you can do is use your existing database if its in mysql or any other. That's the best you would be able to do as far as I know.
If those PHP web services respect some industry standard such as SOAP for example, you can simply consume them by generating strongly typed client proxies. If not, well, then you still have the good old WebClient which allows you to send HTTP requests and read responses. It's as simple as:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "username", "john" },
{ "pwd", "secret" },
};
var result = client.UploadValues("http://foo.com/login.php", values);
// TODO: do something with the result returned by the PHP script
}
Have you tried using stored procedures instead of PHP scripts? That way you don't have to write multiple instances of the same code and it can be used in .NET and PHP.

Can we expose public properties of a webservice on the client side?

I understand that webservices are stateless. I want to know if there is any way we can expose the public properties (getters and setters) of a webservice on the client side (client side being a vb consumer not javascript)?
Web services are method-based, so they're not designed to access properties.
But there's no reason you couldn't make GetX/SetX methods which are exposed like regular service methods - just make sure you include the [WebMethod] attribute.
As others have suggested, you will need to use get/set methods instead of properties.
As for accessing the web service from JavaScript, just specify the method name in the URL and do an XmlHttpRequest.
The only thing you can "expose" from a web service are the [WebMethod].
You might access your web service with code like the following:
Dim svc as New WebReference.MyWebService()
Dim result As Integer = svc.GetSomeInteger()
svc.SetSomeInteger(result)
Dim result2 As Integer = svc.GetSomeInteger()
You may think that you have created an instance of the web service class. You have not. You have only created an instance of the proxy class in your VB.NET code. In the above code, each call to the web service goes through the same client proxy instance, but will go to a different instance of the server-side web service class.
Even if the web service had properties, or just fields, since you would have a different instance of the web service for each call, you would have a different version of "SomeInteger" each time.

File permissions with FileSystemObject - CScript.exe says one thing, Classic ASP says another

I have a classic ASP page - written in JScript - that's using Scripting.FileSystemObject to save files to a network share - and it's not working. ("Permission denied")
The ASP page is running under IIS using Windows authentication, with impersonation enabled.
If I run the following block of code locally via CScript.exe:
var objNet = new ActiveXObject("WScript.Network");
WScript.Echo(objNet.ComputerName);
WScript.Echo(objNet.UserName);
WScript.Echo(objNet.UserDomain);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var path = "\\\\myserver\\my_share\\some_path";
if (fso.FolderExists(path)) {
WScript.Echo("Yes");
} else {
WScript.Echo("No");
}
I get the (expected) output:
MY_COMPUTER
dylan.beattie
MYDOMAIN
Yes
If I run the same code as part of a .ASP page, substituting Response.Write for WScript.Echo I get this output:
MY_COMPUTER
dylan.beattie
MYDOMAIN
No
Now - my understanding is that the WScript.Network object will retrieve the current security credentials of the thread that's actually running the code. If this is correct - then why is the same user, on the same domain, getting different results from CScript.exe vs ASP? If my ASP code is running as dylan.beattie, then why can't I see the network share? And if it's not running as dylan.beattie, why does WScript.Network think it is?
Your problem is clear. In the current implementation you have only impersonation of users and no delegation. I don't want to repeat information already written by Stephen Martin. I only want to add at least three solutions. The classical way of delegation which Stephen Martin suggests is only one way. You can read some more ways here: http://msdn.microsoft.com/en-us/library/ff647404.aspx#paght000023_delegation. I see three practical ways of you solving your problem:
Convert the impersonation token of the user to a token with delegation level of impersonation or to a new primary token. You can do this with respect of DuplicateToken or DuplicateTokenEx.
Use S4U2Self (see http://msdn.microsoft.com/en-us/magazine/cc188757.aspx and http://msdn.microsoft.com/en-us/library/ms998355.aspx) to receive a new token from the old one with respect of one simple .NET statement WindowsIdentity wi = new WindowsIdentity(identity);
You can access another server with respect of one fixed account. It can be a computer account on an account of the application pool of the IIS. It can be another fixed defined account which one will only use for access to the file system.
It is important to know which version of Windows Server you have on the server where IIS is running and which Domain Function Level you have in Active Directory for your Domain (you see this in "Active Directory Domain and Trusts" tool if you select your domain and choose "Raise Domain Functional Level"). It is also interesting to know under which account the application pool of the IIS runs.
The first and the third way will always work. The third way can be bad for your environment and for the current permission in the file system. The second one is very elegant. It allows control of which servers (file server) are accessed from IIS. This way has some restrictions and it needs some work to be done in Active Directory.
Because you use classic ASP, a small scriptable software component must be created to support your implementation.
Which way do you prefer?
UPDATED based on the question from comment: Because you use classic ASP you can not use a Win32 API directly, but you can write a small COM component in VB6 or in .NET which use APIs which you need. As an example you can use code from http://support.microsoft.com/kb/248187/en. But you should do some other things inside. So I explain now which Win32 API can help you to do everything what you need with tokens and impersonation.
First of all a small explanation about impersonation. Everything works very easy. There are always one primary token under which the process runs. To any thread another token (thread token) can be assigned. To do this one needs to have a token of a user hUserToken and call API ImpersonateLoggedOnUser(hUserToken);.
To go back to the original process token (for the current thread only) you can call RevertToSelf() function. The token of user will be received and already impersonated for you by IIS, because you so configured your Web Site. To go back to the original process token you should implement calling of the function RevertToSelf() in your custom COM component. Probably, if you need to do nothing more in the ASP page, it will be enough, but I recommend you be more careful and save current users token in a variable before operation with files. Then you make all operations with file system and at the end reassign users token back to the current thread. You can assign an impersonation token to a thread with respect of SetThreadToken(NULL,hUserToken);. To give (save) current thread token (user token in your case) you can use OpenThreadToken API. It must work.
UPDATED 2: Probably the usage of RevertToSelf() function at the end of one ASP page would be already OK for you. The corresponding C# code can be so:
Create a new Project in C# of the type "Class Library" with the name LoginAdmin. Paste the following code inside
using System;
using System.Runtime.InteropServices;
namespace LoginAdmin {
[InterfaceTypeAttribute (ComInterfaceType.InterfaceIsDual)]
public interface IUserImpersonate {
[DispId(1)]
bool RevertToSelf ();
}
internal static class NativeMethods {
[DllImport ("advapi32.dll", SetLastError = true)]
internal static extern bool RevertToSelf ();
}
[ClassInterface (ClassInterfaceType.AutoDual)]
public class UserImpersonate : IUserImpersonate {
public UserImpersonate () { }
public bool RevertToSelf () {
return NativeMethods.RevertToSelf();
}
}
}
Check in project properties in "Build" part "Register for COM interop". In "Signing" part of the project check Sign the assembly and in "Choose a strong name key file" choose <New...>, then type any filename and password (or check off "protect my key..."). At the end you should modify a line from AssemblyInfo.cs in Properties part of the project:
[assembly: ComVisible (true)]
After compiling this project you get two files, LoginAdmin.dll and LoginAdmin.tlb. The DLL is already registered on the current computer. To register if on the other computer use RegAsm.exe.
To test this COM DLL on a ASP page you can do following
<%# Language="javascript" %>
<html><body>
<% var objNet = Server.CreateObject("WScript.Network");
Response.Write("Current user: ");Response.Write(objNet.UserName);Response.Write("<br/>");
Response.Write("Current user's domain: ");Response.Write(objNet.UserDomain);Response.Write("<br/>");
var objLoginAdmin = Server.CreateObject("LoginAdmin.UserImpersonate");
var isOK = objLoginAdmin.RevertToSelf();
if (isOK)
Response.Write("RevertToSelf return true<br/>");
else
Response.Write("RevertToSelf return false<br/>");
Response.Write("One more time after RevertToSelf()<br/>");
Response.Write("Current user: ");Response.Write(objNet.UserName);Response.Write("<br/>");
Response.Write("Current user's domain: ");Response.Write(objNet.UserDomain);Response.Write("<br/>");
var fso = Server.CreateObject("Scripting.FileSystemObject");
var path = "\\\\mk01\\C\\Oleg";
if (fso.FolderExists(path)) {
Response.Write("Yes");
} else {
Response.Write("No");
}%>
</body></html>
If the account used to run the IIS application pool has access to the corresponding network share, the output will be look like following
Current user: Oleg
Current user's domain: WORKGROUP
RevertToSelf return true
One more time after RevertToSelf()
Current user: DefaultAppPool
Current user's domain: WORKGROUP
Yes
Under impersonation you can only access securable resources on the local computer you cannot access anything over the network.
On Windows when you are running as an impersonated user you are running under what is called a Network token. This token has the user's credentials for local computer access but has no credentials for remote access. So when you access the network share you are actually accessing it as the Anonymous user.
When you are running a process on your desktop (like CScript.exe) then you are running under an Interactive User token. This token has full credentials for both local and remote access, so you are able to access the network share.
In order to access remote resources while impersonating a Windows user you must use Delegation rather then Impersonation. This will involve some changes to your Active directory to allow delegation for the computer and/or the users in your domain. This can be a security risk so it should be reviewed carefully.

Resources