I have a native sdk in my Xamarin Forms which does nothing. I have a xaml file behind the platform specific .cs file but the contents are not displayed.
Main file
private async void Video()
{
DependencyService.Get<InterfaceFile>().GetNativeMethod();
}
Interface file
public interface InterfaceFile
{
void GetNativeMethod();
}
Native file:
[assembly: Xamarin.Forms.Dependency(typeof(Demo))]
namespace Demo.Droid
{
public partial class Demo : InterfaceFile
{
public string GetNativeMthod()
{
/// code
}
}
}
The above platform specific code has video implementation using third party native sdks. I have xaml code behind this file.
I want to start this video call in this xaml file, which is not happening. How to bind the xaml file to .cs file?
Edit
I have tried removing the xaml code, and added only .cs file with following code(using Vidyo native sdk):
public void GetNativeMethod()
{
_vidyoConnector = new Connector(viewHandle,Connector.ConnectorViewStyle.ConnectorviewstyleDefault, 16, "warning all#VidyoConnector info#VidyoClient", "", 0);
_vidyoConnector.ShowViewAt(viewHandle, 0, 0, viewWidth, viewHeight);
_vidyoConnector.Connect(host, token, displayName, resourceId, this);
}
With above code, app crashes because frame is not defined here.
Native sdk code for Connector method:
public Connector(IntPtr viewId, ConnectorViewStyle viewStyle, uint remoteParticipants, String logFileFilter, String logFileName, ulong userData){
IntPtr nLogFileFilter = MarshalPtrToUtf8.GetInstance().MarshalManagedToNative(logFileFilter ?? string.Empty);
IntPtr nLogFileName = MarshalPtrToUtf8.GetInstance().MarshalManagedToNative(logFileName ?? string.Empty);
objPtr = VidyoConnectorConstructNative(ref viewId, viewStyle, remoteParticipants, nLogFileFilter, nLogFileName, userData);
Marshal.FreeHGlobal(nLogFileName);
Marshal.FreeHGlobal(nLogFileFilter);
VidyoConnectorSetUserDataNative(objPtr, GCHandle.ToIntPtr(GCHandle.Alloc(this, GCHandleType.Weak)));
}
Documentation reference for vidyo: https://developer.vidyo.io/#/documentation
Related
Im currently having an issue loading a local pdf into a webview. I have the code which works without any errors and when I run it on the iPad simulator, it works absolutely perfect. However, the issue comes when I try to run it on a physical iPad device. When I run it and it gets to the point where it needs to show the PDF, the webview loads but there is no PDF shown in the webview.
The PDF is actually generated by the app and I store it inside a directory inside the library folder.
Code to show the PDF in the WebView:
public void LoadPdfToWebView(string pdfPath)
{
//Console.WriteLine("Load request started");
WebView.LoadRequest(new NSUrlRequest(new NSUrl(pdfPath, false)));
View.AddSubview(WebView);
//Console.WriteLine("Load request Finished");
}
Not really sure why this would be the case and hopefully somebody can help.
I've just had to fix this for an app and thought I'd post the solution
This is for WKWebView which is a requirement from Apple as of Dec 2020 though the deadline has been temporarily extended
Xaml PdfWebView ContentPage
<controls:PdfWebView
Source="{Binding PDFSource}"
HeightRequest="1000"
WidthRequest="1000"/>
control
namespace XForms.Controls
{
public class PdfWebView : WebView { }
}
VM, only the relevant part
private string _pdfSource;
public string PDFSource
{
get => _pdfSource;
set
{
if (Device.RuntimePlatform == Device.Android && value.StartsWith("file:") == false)
{
value = $"file:///android_asset/pdfjs/web/viewer.html?file=file:///{WebUtility.UrlEncode(value)}";
}
SetProperty(ref _pdfSource, value);
}
}
iOS renderer for PdfWebView
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using XForms.Controls;
using WebKit;
using Foundation;
[assembly: ExportRenderer(typeof(PdfWebView), typeof(iOSUI.Renderers.PdfWebViewRenderer))]
namespace iOSUI.Renderers
{
public class PdfWebViewRenderer : ViewRenderer<WebView, WKWebView>
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var wkWebViewConfiguration = new WKWebViewConfiguration();
var wkWebView = new WKWebView(Frame, wkWebViewConfiguration)
{
AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
};
SetNativeControl(wkWebView);
}
if (e.NewElement != null)
{
if (string.IsNullOrEmpty(((UrlWebViewSource)e.NewElement.Source)?.Url) == false)
{
var url = ((UrlWebViewSource)e.NewElement.Source).Url;
if(url.StartsWith("http"))
{
Control.LoadRequest(new NSUrlRequest(new NSUrl(url)));
}
else
{
Control.LoadFileUrl(new NSUrl($"file://{url}"), new NSUrl($"file://{url}"));
}
}
}
}
}
}
Android Renderer
using System.Net;
using Android.Content;
using Android.Views;
using Android.Webkit;
using XForms.Controls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(PdfWebView), typeof(AndroidUI.Renderers.PDFViewRenderer))]
namespace AndroidUI.Renderers
{
public class PDFViewRenderer : WebViewRenderer
{
public PDFViewRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.AllowFileAccess = true;
Control.Settings.AllowFileAccessFromFileURLs = true;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.SetWebChromeClient(new WebChromeClient());
}
}
// If you want to enable scrolling in WebView uncomment the following lines.
public override bool DispatchTouchEvent(MotionEvent e)
{
Parent.RequestDisallowInterceptTouchEvent(true);
return base.DispatchTouchEvent(e);
}
}
}
This solution uses pdfjs in Android and WKWebview in iOS to render the PDF
The PDFSource is the full path to the file, I use System.IO .net standard calls to handle this in a cross platform way
All the files are stored in (I have a method called GetFullPath to return the cross platform common path)
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Combined with a filename with Path.Combine
Path.Combine(GetFullPath(), fileName);
That is the PDFSource that gets set in the VM
The Pdfjs library files are just copied into Assets/pdfjs for Android
The magic for iOS is just calling LoadFileUrl instead of LoadRequest and prepending "file://"
I've slightly sanitised our namespaces so some of them wont resolve like XForms.Controls and so on that refer to our internal code
In Xamarin.IOS to show a document type other than HTML in a UIWebView:
Add the document (for example, a PDF) to your Xamarin.iOS project. Set the Build Action to BundleResource. You can set the build action for a file by right-clicking on that file and and choosing Build Action in the menu that opens.
Create a UIWebView and add it to a view:
webView = new UIWebView (View.Bounds);
View.AddSubview(webView);
Load the file using NSUrl and NSUrlRequest classes:
string fileName = "Loading a Web Page.pdf"; // remember case-sensitive
string localDocUrl = Path.Combine (NSBundle.MainBundle.BundlePath, fileName);
webView.LoadRequest(new NSUrlRequest(new NSUrl(localDocUrl, false)));
webView.ScalesPageToFit = true;
You can refer to this officical steps.If have problems or other needs, you can refer to this link
If you can't read the resources in the bundle, you can put the resource cache in the temp directory of the sandbox and try to read it using LoadRequest.
I have library code in c# using Z339xLib.dll file
the code is :
#region Assembly Z339xLib.dll, v4.0.30319
// C:\Documents and Settings\Hytham\Desktop\Software Protocol n Image Capture SDK_New\Software Protocol n Image Capture SDK\Z339x_SDK_Sample\Z339x_SDK_Sample\bin\Debug\Z339xLib.dll
#endregion
using System;
using System.Drawing;
namespace Z339xLib
{
public class Z339xLibSdk
{
public Z339xLibSdk();
public bool GetImageAndSaveFile(string portname, string filename, int type);
public Bitmap GetImageByBitmap(string portname);
public string SearchDevice_VCOM();
}
}
I need to convert this code to delphi programing, i create a code in delphi like this:
unit Z339xLib_Sdk;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,Controls,Dialogs,
StdCtrls, ExtCtrls;
Const Z339xLibSdk = 'Z339xLib.dll';
function GetImageAndSaveFile(hport:WideString;ImageDir:WideString;Imagetype:integer): boolean; stdcall;external Z339xLibSdk;
function GetImageByBitmap(hport:WideString): BITMAP; stdcall;external Z339xLibSdk;
function SearchDevice_VCOM : string; stdcall;external Z339xLibSdk;
implementation
end.
when call the function i get error :
the applicaion failed to intialize properly(0xc000007b)
please any help or there is any problem with my syantex code.
and this is explaining of the function:
Function bool GetImageAndSaveFile(String Port_Name, String File_Name, int Format);
Parameters String Port_Name = Virual Com Port Name(ex. COM1…).
Or you can just use “AUTO” as a serial port name, system will automatic search the device.
String File_Name A string that contains the name of the file to which to save this Image.
int Format Image Format
0: png
1:bmp
2:Jpeg
3:Tiff
Return values True: Success
False: error occurred.
thanks for your help
I am developing an application in C# that interacts with DLL assemblies exchanging values, since the application can read and write in the DLL file.
Each DLL file is a class library project, since they are plugins that extend the functionality of my application; nevertheless, I need that each DLL can store certain parameters that my application can read and modify freely and that when modified, these parameters keep their value permanently.
Each DLL file has an embedded DLL file to store these parameters (obviously I can not load the XML by its path as it is inside a DLL), however, I can not change the values of the nodes in the XML file.
Having said that, I have the following class in the DLL assembly:
public class AssemblyData
{
private Assembly assembly;
private XmlDocument xmldocument;
private Stream stream;
public AssemblyData()
{
this.assembly = Assembly.GetExecutingAssembly();
this.xmldocument = new XmlDocument();
string classNamespace = typeof(AssemblyData).Namespace;
this.stream = this.assembly.GetManifestResourceStream($"{classNamespace}.Settings.xml");
this.xmldocument.Load(this.stream);
}
public string Test
{
get => this.xmldocument.SelectSingleNode("Settings/Test").InnerText;
set
{
this.xmldocument.SelectSingleNode("Settings/Test").InnerText = value;
this.SaveXml();
}
}
public void SaveXml()
{
this.xmldocument.Save(this.stream);
}
}
However, the value of the Test node never changes. What is this about?
I'm working on Xamarin Android project and I want to implement taking photo with MvvmCross.
Here's my code:
public class PhotoService:IPhotoService
{
private const int MaxPixelDimension = 1280;
private const int DefaultJpegQuality = 90;
private Stream imageStream;
public Stream ImageStream
{
get { return imageStream; }
set { imageStream = value; }
}
public void GetPhoto()
{
var task = Mvx.Resolve<IMvxPictureChooserTask>();
task.TakePicture(
MaxPixelDimension,
DefaultJpegQuality,
SavePicture, null);
}
private void SavePicture(Stream stream)
{
ImageStream = stream;
}
}
but in:
task.TakePicture(
MaxPixelDimension,
DefaultJpegQuality,
SavePicture,
null);
I have error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
UPDATE
in call stack I have:
0x0 in Android.Content.Intent..ctor at /Users/builder/data/lanes/3511/501e63ce/source/monodroid/src/Mono.Android/platforms/android-24/src/generated/Android.Content.Intent.cs:1275,6 C#
0x12 in MvvmCross.Plugins.PictureChooser.Droid.MvxPictureChooserTask.TakePicture C#
0x3A in App.Services.PhotoService.PhotoService.GetPhoto at C:\app\App.Services\PhotoService\PhotoService.cs:38,4 C#
0x7 in App.ViewModels.ViewModels.MainViewModel.TakePhoto at C:\app\App.ViewModels\ViewModels\MainViewModel.cs:49,4 C#
Alternative solution you can use Media Plugin that available in nuget
https://www.nuget.org/packages/Xam.Plugin.Media/
You can use dependency service to call the takePictureAsync method from android project. With this library you can specify file name and folder path to store your image. This library can also take video using takeVideoAsync method.
I believe you need to add the MVVMCross.Pugin.PictureChooser package to your Core and platform specific projects.
I am building a game with XNA, and I have a custom file format for my game's levels. I want to load them and parse them myself, without using XNA's content pipeline. I have this much working, and by adding the files to the Content project I can even edit them in Visual Studio (which I also want).
The Problem: I get a warning stating "Project item 'item.lvl' was not built with the XNA Framework Content Pipeline. Set its Build Action property to Compile to build it."
I do not want XNA to Compile it, since I am doing my own parsing. How can I disable the warning?
Set the file's Build Action to None, and then set it to Copy if newer. That will cause the file to be written to the proper output directory without putting it through the Content Pipeline.
The solution could be create a custom content importer as explained here: Creating a Custom Importer and Processor. To create a simple content importer you have to inherit your class from the ContentImporter<T> (abstract class) and override the Import() method.
Here is a simple example from the msdn:
//...
using Microsoft.Xna.Framework.Content.Pipeline;
class PSSourceCode
{
const string techniqueCode = "{ pass p0 { PixelShader = compile ps_2_0 main(); } }";
public PSSourceCode(string sourceCode, string techniqueName)
{
this.sourceCode = sourceCode + "\ntechnique " + techniqueName + techniqueCode;
}
private string sourceCode;
public string SourceCode { get { return sourceCode; } }
}
[ContentImporter(".psh", DefaultProcessor = "PSProcessor", DisplayName = "Pixel Shader Importer")]
class PSImporter : ContentImporter<PSSourceCode>
{
public override PSSourceCode Import(string filename,
ContentImporterContext context)
{
string sourceCode = System.IO.File.ReadAllText(filename);
return new PSSourceCode(sourceCode, System.IO.Path.GetFileNameWithoutExtension(filename));
}
}