app.config Xamarin pcl - binding

I need to add some tag in a app.config file for implement a dll (xmlsoccer).
I have to add something like
<system.serviceModel>
<bindings>
<basicHttpBinding>
in a configuration node, but I don't know where it is.
I tried to create an app.config file and set DotNetConfig.xsd as scheme, but during compile, I have this errors:
WARNING: failed to load endpoint configuration for *
SyStem.InvalidOperationException: A Binding must be configured for this channel factory
can anyone help me?
I tried to write this:
` public class MainActivity : FormsApplicationActivity
{
public static readonly EndpointAddress EndPoint = new EndpointAddress("http://www.xmlsoccer.com/FootballDataDemo.asmx");
App application;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
// LoadApplication(new App(binding, EndPoint));
CreateBasicHttp();
LoadApplication(application);
}
private void CreateBasicHttp()
{
var binding = new BasicHttpBinding()
{
Name = "basicHttpBinding",
MaxReceivedMessageSize = 1000000,
};
binding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
{
MaxArrayLength = 2147483646,
MaxStringContentLength = 5242880,
};
var timeout = new TimeSpan(0, 1, 0);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
application = new App(binding, new EndpointAddress("http://www.xmlsoccer.com/FootballDataDemo.asmx"));
}`
in my MainActivity.cs, but obviously it isn't enough.

Still looking for answer?
Take a look here:
https://forums.xamarin.com/discussion/19303/how-to-consume-wcf-service-in-xamarin-forms-pcl
Steps:
1.- Opening a command prompt in Windows and using the SLSvcUtil.exe tool
from the Silverlight SDK to generate a proxy from a WSDL file. slsvcutil http://www.yourserver.com/WebServices/YourServiceSoapClient.asmx?WSDL /out:YourService.cs That utility is located at C:\Program Files (x86)\Microsoft SDKs\Silverlight\v5.0\Tools\ on my computer.
2.- Adding the resulting YourService.cs file to my project.
3.- Adding the following code to access the service:
// Create the WCF client (created using SLSvcUtil.exe on Windows)
YourServiceSoapClient client = new YourServiceSoapClient(
new BasicHttpBinding(),
new EndpointAddress("hhttp://www.yourserver.com/WebServices/YourServiceSoapClient.asmx"));
// Call the proxy - this should use the async versions
client.ServiceFunctionCompleted += OnGotResult;
client.ServiceFunctionAsync(parameter);
And the OnGotResult function:
void OnGotResult(object sender, ServiceFunctionCompletedEventArgs e)
{
Device.BeginInvokeOnMainThread(async () => {
string error = null;
if (e.Error != null)
error = e.Error.Message;
else if (e.Cancelled)
error = "Cancelled";
if (!string.IsNullOrEmpty(error))
{
await DisplayAlert("Error", error, "OK", "Cancel");
}
else
{
resultsLabel.Text = e.Result;
}
});
}

Related

Vaadin 14 app not loading cache.js files causing blank page

When I try to load my application in Vaadin 14 I see a blank screen like this...
It appears that the servlet container is in fact running but it cannot host some static resources...
When I look in the network tab in the Chrome inspector I see it cannot find a few files such as
http://localhost:8080/VAADIN/static/client/client-122CE29AC0B9685B4DC485343E774096.cache.js
I am unsure why this would be. Any ideas?
UPDATE:
It appears I have to manually ensure all of my .jar files get added as resources in jetty so the static content can be served. I tried doing this like so and it works fine on my laptop but not on the server...
public class App {
public static void main(String[] args) throws Exception {
final var server = new Server(8080);
// Specifies the order in which the configurations are scanned.
Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
// Creation of a temporal directory.
File tempDir = new File(System.getProperty("java.io.tmpdir"), "JettyTest");
if (tempDir.exists()) {
if (!tempDir.isDirectory()) {
throw new RuntimeException("Not a directory: " + tempDir);
}
} else if (!tempDir.mkdirs()) {
throw new RuntimeException("Could not make: " + tempDir);
}
WebAppContext context = new WebAppContext();
context.setInitParameter("productionMode", "false");
// Context path of the application.
context.setContextPath("");
// Exploded war or not.
context.setExtractWAR(false);
context.setTempDirectory(tempDir);
// It pulls the respective config from the VaadinServlet.
context.addServlet(GuiceVaadinServlet.class, "/*").setInitOrder(1);
context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*");
context.setParentLoaderPriority(true);
server.setHandler(context);
// This add jars to the jetty classpath in a certain syntax and the pattern makes sure to load all of them.
final var classpathEntries = ClassPathHelper.getAllClassPathEntries();
final var ideMode = classpathEntries.size() > 1;
final var resourceList = new ArrayList<Resource>();
final var jarFiles = new ArrayList<File>();
if (ideMode) {
System.out.println("Starting in IDE Mode");
for (String entry : ClassPathHelper.getAllClassPathEntries()) {
if (entry.endsWith(".jar")) {
final var file = new File(entry);
jarFiles.add(file);
}
}
} else {
final var baseInstallDir = System.getProperty("user.dir");
System.out.println("Starting in Server WebJar Mode");
final var libsDirectory = new File(baseInstallDir, "lib");
System.out.println("Scanning for jars in " + libsDirectory.getPath());
for (File file : Objects.requireNonNull(libsDirectory.listFiles())) {
if (file.getPath().endsWith(".jar")) {
jarFiles.add(file);
}
}
final var sferionJar = new File(baseInstallDir, "sferion.jar");
jarFiles.add(sferionJar);
System.out.println("Found " + jarFiles.size() + " jar files");
}
for (File jarFile : jarFiles) {
resourceList.add(Resource.newResource("jar:" + jarFile.toURI().toURL() + "!/"));
}
if (ideMode) {
// It adds the web application resources. Styles, client-side components, ...
//TODO: make this property dynamic somehow?
resourceList.add(Resource.newResource("/usr/local/code/sferion/planglobal/src/main/webapp"));
}
// The base resource is where jetty serves its static content from.
context.setBaseResource(new ResourceCollection(resourceList.toArray(new Resource[0])));
server.start();
server.join();
}
}

How to get all PDF files from internal as well as external storage in Flutter?

I want to show All pdf files present in internal as well as external storage, So on tapping that particular file, i want to open that file in full screen dialog.
So in order to do that you need to:
Grant access to external storage in a directory where there are your PDF file. Let's call that folder <external storage>/pdf.
List all file of that directory a display them to the user.
Open the selected file with an application that can visualize PDF.
In order to do all that thinks I suggest you to use those flutter packages:
path_provider
simple_permission
With path_provider you can get the external storage directory of an Android device.
Directory extDir = await getExternalStorageDirectory();
String pdfPath = extDir + "/pdf/";
In order to access external storage you need to set this permission request in the ApplicationManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You could also only use READ_EXTERNAL_STORAGE but then the simple_permission plugin won't work.
With the simple_permission plugin then you go and ask user to be granted external storage access:
bool externalStoragePermissionOkay = false;
_checkPermissions() async {
if (Platform.isAndroid) {
SimplePermissions
.checkPermission(Permission.WriteExternalStorage)
.then((checkOkay) {
if (!checkOkay) {
SimplePermissions
.requestPermission(Permission.WriteExternalStorage)
.then((okDone) {
if (okDone) {
debugPrint("${okDone}");
setState(() {
externalStoragePermissionOkay = okDone;
debugPrint('Refresh UI');
});
}
});
} else {
setState(() {
externalStoragePermissionOkay = checkOkay;
});
}
});
}
}
Once we have been granted external storage access we an list our PDF directory:
List<FileSystemEntity> _files;
_files = dir.listSync(recursive: true, followLinks: false);
And show them in a ListView:
return new ListView.builder(
padding: const EdgeInsets.all(16.0),
itemCount: _files.length,
itemBuilder: (context, i) {
return _buildRow(_files.elementAt(i).path);
});
Than you have to open them with a viewer when the user tap on them.
To do that there isn't an easy way, because with Android we need to build a ContentUri and give access to this URI to the exteranl application viewer.
So we do that in Android and we use flutter platform channels to call the Android native code.
Dart:
static const platform =
const MethodChannel('it.versionestabile.flutterapp000001/pdfViewer');
var args = {'url': fileName};
platform.invokeMethod('viewPdf', args);
Native Java Code:
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "it.versionestabile.flutterapp000001/pdfViewer";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("viewPdf")) {
if (call.hasArgument("url")) {
String url = call.argument("url");
File file = new File(url);
//*
Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider",
file);
//*/
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(photoURI,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(target);
result.success(null);
}
} else {
result.notImplemented();
}
}
});
}
}
And after all we can have our PDF list and viewable on Android.
You have a lot to study. I hope this could be an useful playground for you.
This is for External Storage, but you can get Also the Internal and Temporary directory and act similarly as here.
If you wanna do the same thing on iOS you need to create the same Native Code pdfViewer also on iOS project. Refer alway to flutter platform channels in order to do it. And remember that the external storage doesn't exists on iOS devices. So you could use only the application sandbox document folder or the temporary one.
GitHub repo.
Happy coding.
i use this code for list files and directories
Future<List<FileSystemEntity>> dirContents(Directory dir) {
var files = <FileSystemEntity>[];
var completer = Completer<List<FileSystemEntity>>();
var lister = dir.list(recursive: false);
lister.listen((file) async {
FileStat f = file.statSync();
if (f.type == FileSystemEntityType.directory) {
await dirContents(Directory(file.uri.toFilePath()));
} else if (f.type == FileSystemEntityType.file && file.path.endsWith('.pdf')) {
_files.add(file);
}
}, onDone: () {
completer.complete(files);
setState(() {
//
});
});
return completer.future;
}
Directory dir = Directory('/storage/emulated/0');
var files = await dirContents(dir);
print(files);
Here is my code to list files from the download folder
List<dynamic> filesList = [];
Future listDir() async {
Directory dir = Directory(
'/storage/emulated/0/Download');
await for (FileSystemEntity entity
in dir.list(recursive: true, followLinks: false)) {
FileSystemEntityType type = await FileSystemEntity.type(entity.path);
if (type == FileSystemEntityType.file &&
entity.path.endsWith('.pdf')) {
filesList.add(entity.path);
}
}
return filesList;}

Getting NameResolutionFailure error

Unable to fetch data in Xamarin.Forms project. I have tried with the following code and is getting NameResolutionFailure error.
private const string BaseUrl = "http://intilaqemployees.azurewebsites.net/api/employeesapi";
public async Task<List<Employee>> GetEmployeesAsync()
{
var httpClient = new HttpClient();
try
{
var jsonResponse = await httpClient.GetStringAsync(BaseUrl).ConfigureAwait(false);
//The following line never gets executed
var employeesList = JsonConvert.DeserializeObject<List<Employee>>(jsonResponse);
return employeesList;
}
catch (AggregateException exception) { }
catch (Exception ex)
{
}
return null;
}
This is what I have tried so far
Have enable INTERNET in android manifest
Translating the host name to ip
Tried to set host directly by setting client.DefaultRequestHeaders.Host = "intilaqemployees.azurewebsites.net";
Putting the wifi off in emulator
Please note: Android emulator does not have any internet connectivity.
My problem solved by this code:
var client = new HttpClient {
BaseAddress = new Uri("http://1.2.3.4"),
DefaultRequestHeaders = { Host = "example.com" }
};

Error 401 authenticating with Project Online and CSOM

I get error 401 (or 403) when trying to connect to Project Online with CSOM in a console app. (This is not on-premise. It is Microsoft Project Online 2013.) Here is the code.
ProjectContext projContext = new ProjectContext(pwaPath);
projContext.Credentials = new NetworkCredential("myUserID", "mypwd", "xxx.onmicrosoft.com");
projContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(projContext_ExecutingWebRequest);
projContext.Load(projContext.Projects);
projContext.ExecuteQuery();
**// Error 401 Unauthorized**
static void projContext_ExecutingWebRequest(object sender, WebRequestEventArgs e)
{
e.WebRequestExecutor.WebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
And another try, without ExecutingWebRequest:
ProjectContext projContext = new ProjectContext(pwaPath);
projContext.Credentials = new NetworkCredential("myUserID", "mypwd", "xxx.onmicrosoft.com");
projContext.Load(projContext.Projects);
projContext.ExecuteQuery();
**// Error 403 Forbidden**
Q1: Are there any problems with the code?
Q2: Is there a setting in Project Online that I'm missing?
You can use:
new SharePointOnlineCredentials(username, secpassword);
instead of
new NetworkCredential("admin#myserver.onmicrosoft.com", "password");
First: Install required Client SDK
SharePoint Client SDK :
http://www.microsoft.com/en-au/download/details.aspx?id=35585
Project 2013 SDK:
http://www.microsoft.com/en-au/download/details.aspx?id=30435
Second: add the reference to your project
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
Microsoft.ProjectServer.Client.dll
You can find the dlls in %programfiles%\Common Files\microsoft shared\Web Server Extensions\15\ISAPI
and %programfiles(x86)%\Microsoft SDKs\Project 2013\REDIST
Here is sample code:
using System;
using System.Security;
using Microsoft.ProjectServer.Client;
using Microsoft.SharePoint.Client;
public class Program
{
private const string pwaPath = "https://[yoursitehere].sharepoint.com/sites/pwa";
private const string username ="[username]";
private const string password = "[password]";
static void Main(string[] args)
{
SecureString secpassword = new SecureString();
foreach (char c in password.ToCharArray()) secpassword.AppendChar(c);
ProjectContext pc = new ProjectContext(pwaPath);
pc.Credentials = new SharePointOnlineCredentials(username, secpassword);
//now you can query
pc.Load(pc.Projects);
pc.ExecuteQuery();
foreach(var p in pc.Projects)
{
Console.WriteLine(p.Name);
}
//Or Create a new project
ProjectCreationInformation newProj = new ProjectCreationInformation() {
Id = Guid.NewGuid(),
Name = "[your project name]",
Start = DateTime.Today.Date
};
PublishedProject newPublishedProj = pc.Projects.Add(newProj);
QueueJob qJob = pc.Projects.Update();
JobState jobState = pc.WaitForQueue(qJob,/*timeout for wait*/ 10);
}
}
I already answered this question in other question
How to authenticate to Project Online PSI services?

Creating a process in ASP.NET MVC controller

I have a requirement to run an application through my MVC controller. To get the installation path I used following link (I used answer provided by Fredrik Mörk). It worked and I could able to run the exe through a process. The problem occurred when I deployed this solution on IIS where it did not create the process as it was creating in local dev environment. Can anybody tell me how to create a windows process through a solution which is hosted on IIS ?
private string GetPathForExe(string fileName)
{
private const string keyBase = #"SOFTWARE\Wow6432Node\MyApplication";
RegistryKey localMachine = Registry.LocalMachine;
RegistryKey fileKey = localMachine.OpenSubKey(string.Format(#"{0}\{1}", keyBase, fileName));
object result = null;
if (fileKey != null)
{
result = fileKey.GetValue("InstallPath");
}
fileKey.Close();
return (string)result;
}
public void StartMyApplication()
{
Process[] pname = Process.GetProcessesByName("MyApplication");
if (pname.Length == 0)
{
string appDirectory = GetPathForExe("MyApplication");
Directory.SetCurrentDirectory(appDirectory);
ProcessStartInfo procStartInfo = new ProcessStartInfo("MyApplication.exe");
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
}
}

Resources