I want to comunicate with Console XML RPC server from my silvelight application. Is it possibile?
Steps:
1. Start the Console XML RPC server
Code for Console XML RPC server is this:
using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using CookComputing.XmlRpc;
public class StateNameServer : MarshalByRefObject, IStateName
{
public string GetStateName(int stateNumber)
{
return "whatever";
}
}
class _
{
static void Main(string[] args)
{
IDictionary props = new Hashtable();
props["name"] = "MyHttpChannel";
props["port"] = 5678;
HttpChannel channel = new HttpChannel(props,null,new XmlRpcServerFormatterSinkProvider());
ChannelServices.RegisterChannel(channel,false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(StateNameServer),"statename.rem",WellKnownObjectMode.Singleton);
Console.WriteLine("Press <ENTER> to shutdown");
Console.ReadLine();
}
}
Run Silverlight application
I used the code from http://code.google.com/p/xmlrpc-silverlight/
I created new Silverlight application to which I have attached the code from that link. When I start web site (in localhost with port 1139) which executes my SL app happens SecurityException.
void ResponseResponse(IAsyncResult result)
{
XmlRpcHelperRequestState state = result.AsyncState as XmlRpcHelperRequestState;
try
{
state.Response = (HttpWebResponse)state.Request.EndGetResponse(result);
...
}
catch (Exception e)
{
// comes here with SecurityException
}
finally
{
...
}
}
I am using VS2008 Professional,XP Professional, .net 3.5, Silverlight3. I will gladly provide any additional information (or code) which is needed.
I suspect that this is a case of a missing clientaccesspolicy.xml file.
Since your silverlight app will have been launched from another authority it will attempt to access this file the http://localhost:5678/. Since you little test doesn't support that file Silverlight blocks this cross "domain" activity.
Related
I'm implementing NUnit Integration Tests of our controller REST endpoints in a .NET Web API 2 project. We use an Entity Framework code-first from database approach to create our controllers and models.
I've got the myProjectIntegrationTests project set up, with NUnit installed and a reference to myProject.
From my research, the next step is to create a TestSetup script which, on each test, creates an Integration Tests Database in a LocalDb. This allows us to integration test our API calls without affecting the master dev database.
This TestSetup script should do several things each time a test runs:
- check if a connection is currently open in Integration Test Db - if so, close it.
- check if an existing Integration Test db exists - if so, tear it down.
- run a migration from my master dev database to my Integration Test Db to load it with real data.
- create a new instance of Integration Test Db
- integration tests run...
- close Integration Test Db connections
- teardown Integration Test Db
Creating this TestSetup class is what's giving me trouble. I've found tutorials on how to do this for .NET MVC, .NET Core and also Entity Framework - but none of these seem to be utilizing just .Net Web API, so some of the libraries and code being referenced isn't working for me. Can someone provide an example script or tutorial link that might work in .NET Web API 2?
Here's an example of someone doing this for EntityFramework, using I believe .Net Core. This is part of a great PluralSight tutorial on integration testing in Entity Framework by Michael Perry, found here:
using Globalmantics.DAL;
using Globalmantics.DAL.Migrations;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.E ntity;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Globalmantics.IntegrationTests
{
[SetUpFixture]
public class TestSetup
{
[OneTimeSetUp]
public void SetUpDatabase()
{
DestroyDatabase();
CreateDatabase();
}
[OneTimeTearDown]
public void TearDownDatabase()
{
DestroyDatabase();
}
private static void CreateDatabase()
{
ExecuteSqlCommand(Master, $#"
CREATE DATABASE [Globalmantics]
ON (NAME = 'Globalmantics',
FILENAME = '{Filename}')");
var migration = new MigrateDatabaseToLatestVersion<
GlobalmanticsContext, GlobalmanticsConfiguration>();
migration.InitializeDatabase(new GlobalmanticsContext());
}
private static void DestroyDatabase()
{
var fileNames = ExecuteSqlQuery(Master, #"
SELECT [physical_name] FROM [sys].[master_files]
WHERE [database_id] = DB_ID('Globalmantics')",
row => (string)row["physical_name"]);
if (fileNames.Any())
{
ExecuteSqlCommand(Master, #"
ALTER DATABASE [Globalmantics] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
EXEC sp_detach_db 'Globalmantics'");
fileNames.ForEach(File.Delete);
}
}
private static void ExecuteSqlCommand(
SqlConnectionStringBuilder connectionStringBuilder,
string commandText)
{
using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
}
private static List<T> ExecuteSqlQuery<T>(
SqlConnectionStringBuilder connectionStringBuilder,
string queryText,
Func<SqlDataReader, T> read)
{
var result = new List<T>();
using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = queryText;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(read(reader));
}
}
}
}
return result;
}
private static SqlConnectionStringBuilder Master =>
new SqlConnectionStringBuilder
{
DataSource = #"(LocalDB)\MSSQLLocalDB",
InitialCatalog = "master",
IntegratedSecurity = true
};
private static string Filename => Path.Combine(
Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location),
"Globalmantics.mdf");
}
}
And here's an older example of someone doing this for .Net MVC:
using System;
using System.Data.Entity;
using NUnit.Framework;
namespace BankingSite.IntegrationTests
{
[SetUpFixture]
public class TestFixtureLifecycle
{
public TestFixtureLifecycle()
{
EnsureDataDirectoryConnectionStringPlaceholderIsSet();
EnsureNoExistingDatabaseFiles();
}
private static void EnsureDataDirectoryConnectionStringPlaceholderIsSet()
{
// When not running inside MVC application the |DataDirectory| placeholder
// is null in a connection string, e.g AttachDBFilename=|DataDirectory|\TestBankingSiteDb.mdf
AppDomain.CurrentDomain.SetData("DataDirectory", NUnit.Framework.TestContext.CurrentContext.TestDirectory);
}
private void EnsureNoExistingDatabaseFiles()
{
const string connectionString = "name=DefaultConnection";
if (Database.Exists(connectionString))
{
Database.Delete(connectionString);
}
}
}
}
Probably not the answer you are looking for but I have had success recently using the sql server docker image with docker compose.
You can fire up a database instance and delete the data volumes when the the image shuts down. Using the —rm switch on the docker run command will do that automatically for you.
If you are using dot net core you can setup another container to run your entity framework migrations and tests.
If you are using dotnet framework you maybe be able to run windows docker images however they tend to be a bit slower to startup.
This approach would work best if you launched everything from a powershell script. Launching the infrastructure from the code as you are looking to do could be tricky and perhaps more complex than it needs to be.
Going line-by-line through the type of sql commands you'll need for these operations is just going to be painful. You would benefit much better to just develop a stored procedure that does the tear-down/build-up steps. You appear to already have a start in that as I see you writing code around the statements. Then your integration test code would just need to call this procedure and wait for the setup to complete. Remember, You don't have to do everything in code.
I'm having trouble following the second step here.
I really don't understand how this sample does anything other than return a simple toast message. How does it utilize the API to display that message?
class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
#Override
protected String doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
I'm afraid my this sample is too complex for my limited knowledge. How exactly do I "talk" to the Google Endpoints Module when running an app? Specifically, What is EndpointsAsyncTask();?
Are there any resources listing all the methods available to me? Is there a simpler example of an app communicating with a Google Cloud Endpoint?
The service methods available to you are defined by the backend source in section 1.
In the example you posted, this line: myApiService.sayHi(name).execute()
is an actual invocation call to the backend that you defined by annotating #ApiMethod("sayHi") on the method in the MyEndpoint.java class of your backend module.
The reason your Android app defines an EndpointsAsyncTask is because slow operations such as calls that hit the network need to happen off of the UI thread to avoid locking the UI. The demo simply puts the returned value into a Toast but you could modify onPostExecute() to do whatever you'd like with the result.
For more info on Google Endpoints check out:
https://cloud.google.com/appengine/docs/java/endpoints/
And for info about using an Android AsyncTask look here:
http://developer.android.com/reference/android/os/AsyncTask.html
Having a silverlight application, intended to implement backup restore mechanism for the end user.
I have to get list of files in a specific directory resided in WebSite project via ria services.
By using which object I will be able to list files in specific directory of WebSite project.
Thanks for your attention.
You can use the Directory class to enumerate files on the server. Adding a method to your domain service to return the list of file names to the Silverlight client should be fairly trivial after that.
http://msdn.microsoft.com/en-us/library/system.io.directory(v=vs.100).aspx
The answer is some kind of hack. I was inspired by the method that I have used to send client IP address to the service.
In default.aspx add this param to your silverlight object :
<param name="initParams" value="clientIP=<%=Request.UserHostAddress%>,serverPath=<%=Server.MapPath(".")%>" />
And in silverlight application :
public string ClientIP=string.Empty;
public string ServerPath = string.Empty;
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new MainPage();
try
{
ClientIP = e.InitParams["clientIP"].ToString();
ServerPath = e.InitParams["serverPath"].ToString();
}
catch
{
}
}
Consider that I sent client ip to the xap file for logging issues. You can omit it if you care.
and in Silverlight application call service method in this way :
ser.GetFileList(((App)(App.Current)).ServerPath, FilesListReceived, null);
And the service side :
public List<string> GetFileList(string baseDirectory)
{
var result = new List<BRFile>();
var files =Directory.EnumerateFiles( baseDirectory + "\\DBBackup" );
....
}
Good Luck.
Seems to be a simple thing using a WebClient object to retrieve content of a text file in a Silverlight web application.
It works in our intranet setup on a local server, but when deployed on a hosted "hostgator" server, WebClient gets a security exception. Following suggestions from numerous web blogs, I tried crossdomain access policy and crossdomain.xml with no result - no wonder, all in on the same domain.
private void LoadCSVFile(string csvFile)
{
try
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(csvFile, UriKind.Absolute));
}
catch (Exception ex)
{
string errorMessage = String.Format("Ex accessing csv: {0}\n{1}", csvFile,
}
}
//the csvFile is an absolute path: http://myserver.com/myapplication:port/sourcefiles/file.csv
//The sourcefiles is a virtual directory in the same website containing csv files
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Result))
{
mainFileData = new List<string>();
string line;
}
}
catch (Exception ex)
{
string errorMessage = ex.InnerException;
}else
{
"here is the place for the exception!!!!!!! so, e.Error is not null"
}
}
The text of the exception reads: System.SecurityException: Security error at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) etc.
Spend 2 days gooogling with no result.
Please help.
V
A couple of things to check:
(1) The format for the URL that you list (http://myserver.com/myapplication:port/sourcefiles/file.csv) looks odd. Shouldn't it be http://myserver.com:port/myapplication/sourcefiles/file.csv? Or is that just a typo?
(2) What's the port number that you're accessing? The Silverlight WebClient will only access ports 80 and 443.
(3) Can you get to the file using a direct URL? Sometimes web servers need to be told about a specific file type before they'll allow it to be served up.
I am new to .NET and C#. I created a Web service, and I am able to view it from a Web page. When I try to call it from a Windows Application, I get the Exception 401 : unauthorized. Code compiles OK, but throws exception when running. This is the code from the Windows App. :
namespace BookStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Create a new instance of a service
localhost.Service1 datasvc = new localhost.Service1();
// Create instance of dataset, using WebService method GetTitleAuthors.
DataSet myData = datasvc.GetTitleAuthors();
// Set DataGrid's datasource to the myData DataSet.
dataGridView1.DataSource = myData;
//Expand all rows.
//dataGridView1.Expand(-1);
//Expand DataTable
//dataGridView1.NavigateTo(0, "Authors");
}
}
}
PS : I am using Windows Authentication in the website that hosts the web service.
I believe there is a property on the generated proxy to the effect of UseDefaultCredentials try setting that to true.
datasvc.UseDefaultCredentials = true;
Although it's been a while I think this will force the service to pass windows credentials.
I don't know what type your Service1 object inherits so I can't say what properties or methods you have associated with it, but whenever I know you can make calls to you web service with using
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
And then either using
req.UseDefaultCredentials = true;
or
req.Credentials = new NetworkCredential(userName, password);