PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label cross-platform. Show all posts
Showing posts with label cross-platform. Show all posts

Sunday, November 6, 2022

[FIXED] How to detect properly Windows, Linux & Mac operating systems

 November 06, 2022     c#, cross-platform, macos, mono     No comments   

Issue

I could not found anything really efficient to detect correctly what platform (Windows / Linux / Mac) my C# progrma was running on, especially on Mac which returns Unix and can't hardly be differenciated with Linux platforms !

So I made something less theoretical, and more practical, based on specificities of Mac.

I'm posting the working code as an answer. Please, comment if it works well for you too / can be improved.

Thanks !

Response :

Here is the working code !

    public enum Platform
    {
        Windows,
        Linux,
        Mac
    }

    public static Platform RunningPlatform()
    {
        switch (Environment.OSVersion.Platform)
        {
            case PlatformID.Unix:
                // Well, there are chances MacOSX is reported as Unix instead of MacOSX.
                // Instead of platform check, we'll do a feature checks (Mac specific root folders)
                if (Directory.Exists("/Applications")
                    & Directory.Exists("/System")
                    & Directory.Exists("/Users")
                    & Directory.Exists("/Volumes"))
                    return Platform.Mac;
                else
                    return Platform.Linux;

            case PlatformID.MacOSX:
                return Platform.Mac;

            default:
                return Platform.Windows;
        }
    }

Solution

Maybe check out the IsRunningOnMac method in the Pinta source:



Answered By - TheNextman
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Which GUI toolkit would you use for a touchscreen interface?

 November 06, 2022     cross-platform, gui-toolkit, touchscreen, windows     No comments   

Issue

The only experience I have so far with a touchscreen interface was one where everything was custom drawn, and I get the feeling it's not the most efficient way of doing it (even the most basic layout change is hell to make). I know plenty of GUI toolkits intended at keyboard & mouse interfaces, but can you advise something suited for touchscreens? Target platform is Windows, but cross-platform would be nice.


Solution

Check out the Windows Presentation Foundation (WPF). It uses XML (XAML) to define the interface and it is therefore quite easy to create an interface which would be easy to use with the touchscreen.

.NET 3.0 required.



Answered By - Ilya Kochetov
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to have text between a top border line in flutter

 November 06, 2022     android, cross-platform, dart, flutter, mobile     No comments   

Issue

How can I do something like this with flutter

Screenshot


Solution

You can use a row with expanded and a text between them

Row(
 children: [
 Expanded(
   child : Container(
     height: 2,
     color: Colors.black
   )
 ),
 Text('some text here'),
 Expanded(
   child : Container(
     height: 2,
     color: Colors.black
   )
 ),
]
)


Answered By - Kaushik Chandru
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I list available operating system signals by name in a cross-platform way in Go?

 November 06, 2022     cross-platform, go, signals, unix     No comments   

Issue

Let's say I'm implementing the kill program in Go. I can accept numeric signals and PIDs from the commandline and send them to syscall.Kill no problem.

However, I don't know how to implement the "string" form of signal dispatch, e.g. kill -INT 12345.

The real use case is a part of a larger program that prompts the user to send kill signals; not a replacement for kill.

Question:

How can I convert valid signal names to signal numbers on any supported platform, at runtime (or at least without writing per-platform code to be run at compile time)?

What I've tried:

  • Keep a static map of signal names to numbers. This doesn't work in a cross-platform way (for example, different signal lists are returned by kill -l on Mac OSX versus a modern Linux versus an older Linux, for example). The only way to make this solution work in general would be to make maps for every OS, which would require me to know the behavior of every OS, and keep up to date as they add new signal support.
  • Shell out to the GNU kill tool and capture the signal lists from it. This is inelegant and kind of a paradox, and also requires a) being able to find kill, b) having the ability/permission to exec subprocesses, and c) being able to predict/parse the output of kill-the-binary.
  • Use the various Signal types' String method. This just returns strings containing the signal number, e.g. os.Signal(4).String() == "signal 4", which is not useful.
  • Call the private function runtime.signame, which does exactly what I want. go://linkname hacks will work, but I'm assuming that this sort of thing is frowned-upon for a reason.

Ideas/Things I Haven't Tried:

  • Use CGo somehow. I'd rather not venture into CGO territory for a project that is otherwise not low-level/needful of native integration at all. If that's the only option, I will, but have no idea where to start.
  • Use templating and code generation to build lists of signals based on external sources at compile time. This is not preferable for the same reasons as CGo.
  • Reflect and parse the members of syscall that start with SIG somehow. I am told that this is not possible because names are compiled away; is it possible that, for something as fundamental as signal names, there's someplace they're not compiled away?

Solution

Commit d455e41 added this feature in March 2019 as sys/unix.SignalNum() and is thus available at least since Go 1.13. More details in GitHub issue #28027.

From the documentation of the golang.org/x/sys/unix package:

func SignalNum(s string) syscall.Signal

SignalNum returns the syscall.Signal for signal named s, or 0 if a signal with such name is not found. The signal name should start with "SIG".

To answer a similar question, "how can I list the names of all available signals (on a given Unix-like platform)", we can use the inverse function sys/unix.SignalName():

    import "golang.org/x/sys/unix"

    // See https://github.com/golang/go/issues/28027#issuecomment-427377759
    // for why looping in range 0,255 is enough.
    for i := syscall.Signal(0); i < syscall.Signal(255); i++ {
        name := unix.SignalName(i)
        // Signal numbers are not guaranteed to be contiguous.
        if name != "" {
            fmt.Println(name)
        }
    }


Answered By - marco.m
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to disable tab switching on tab press?

 November 06, 2022     android, cross-platform, ios, react-native, reactjs     No comments   

Issue

I am using react-native-tab-view for tabs. now i have a very strange use case that i don't want user to traverse to other tabs by clicking on the tab i.e on tab press.

I want to use custom buttons on each tab to traverse back and forth.


Solution

Answering my own question.

For this, there is one prop called onTabPress in TabBar props in react-native-tab-view.

use the following function: preventDefault().

you can do the following to disable tab click.

  • If you want to disable it for particular tab than...
<TabBar onTabPress={({ route, preventDefault }) => {
     // here `route.key` will be your particular tab's route key
     if (route.key === 'home') {
       preventDefault();

      // Do something else
     }   
    }} 
    ... 
    />
  • If you want to disable tab click for all the tabs.

       <TabBar
       {...props}
       onTabPress={({preventDefault}) => {
        preventDefault();
       }}
       />
    

Note: This will work with react navigation as well. Attaching the link: https://reactnavigation.org/docs/navigation-events/



Answered By - Shail Patel
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I get a platform-dependent new line character?

 November 06, 2022     cross-platform, eol, java, newline     No comments   

Issue

How do I get a platform-dependent newline in Java? I can’t use "\n" everywhere.


Solution

In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting methods) you can use %n as in

Calendar c = ...;
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY%n", c); 
//Note `%n` at end of line                                  ^^

String s2 = String.format("Use %%n as a platform independent newline.%n"); 
//         %% becomes %        ^^
//                                        and `%n` becomes newline   ^^

See the Java 1.8 API for Formatter for more details.



Answered By - Alex B
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, November 5, 2022

[FIXED] How do I tell conda/mamba to use windows/linux/osx channels that are different from the system OS?

 November 05, 2022     conda, cross-platform, mamba, python, virtual-environment     No comments   

Issue

I would like to help someone solve their problem with installing a particular mamba environment: New mamba environment force torch CPU and I don't know why

However, they use Windows, and I am on macOS.

How can I tell mamba to use pytorch/win-64 and conda-forge/win-64 channels instead of osx-arm subchannels?

I know I can specify channels using -c but how do I specify the system subdirectory?


Solution

The CONDA_SUBDIR variable works well for this. For example,

CONDA_SUBDIR=win-64 mamba create -dn foo -c pytorch -c conda-forge pytorch


Answered By - merv
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, September 14, 2022

[FIXED] How to delete an Item selected form ListView in Xamarin

 September 14, 2022     button, cross-platform, listview, xamarin.forms, xaml     No comments   

Issue

I'm building a Xamarin CrossPlatform App!

App contains 2 pages : HomePage, DetailGetData

HomePage: This page contains a ListView which is displaying list of data form webapi in cells and whenever I clicked each cell it goes to DetailGetDatapage which shows the detail of that data.

Problem: Now the problem is that I wanted to delete that selected item from DetailGetData page. A DeleteButton is placed and when i press that button that details and selected item should be deleted from the ListView as well. How it is possible ?

ScreenShot DetailGetData :https://i.stack.imgur.com/TXg4G.png

ScreenShot HomePage : https://i.stack.imgur.com/g1Hn1.png

Code:

DetailGetData Xaml:

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.Views.DetailGetData">

    <StackLayout HorizontalOptions="Center" VerticalOptions="Center">

        <Label Text="{Binding employee_name}" x:Name="empname" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_age}" x:Name="age" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_salary}" x:Name="salary" FontSize="Medium" FontAttributes="Bold" />

        <Button x:Name="DeleteItem" Text="Delete" Clicked="DeleteItem_Clicked"  />
    </StackLayout>

</ContentPage>

HomePage Xaml:

    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.HomePage">


    <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <ListView x:Name="Demolist" ItemSelected="OnItemSelected" BackgroundColor="White">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell Height="100">
                        <ViewCell.ContextActions>
                            <MenuItem x:Name="OnMore" Clicked="OnMore_Clicked" CommandParameter="{Binding .}"
                                 Text="More" />
                            <MenuItem x:Name="OnDelete" Clicked="OnDelete_Clicked" CommandParameter="{Binding .}"
                                 Text="Delete" IsDestructive="True" />
                        </ViewCell.ContextActions>
                        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="30,0">

                            <Label Text="{Binding employee_name}" FontAttributes="bold" FontSize="Small" TextColor="Black" x:Name="en"/>
                            <Label Text="{Binding employee_age}" FontSize="Micro" TextColor="Black" FontAttributes="Italic"/>
                            <Label Text="{Binding id}" IsVisible="False" />


                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <ImageButton Source="fedit.png" 
            BackgroundColor="Transparent"
            AbsoluteLayout.LayoutFlags="PositionProportional"  
            AbsoluteLayout.LayoutBounds=".95,.95,55,55" 
            Clicked="ImageButton_Clicked">
        </ImageButton>

    </AbsoluteLayout>
</ContentPage>

HomePage.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;
using Last_MSPL.Views;
using System.Collections;

namespace Last_MSPL
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {
        public IEnumerable ObjOrderList { get; private set; }


        public HomePage()
        {
            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
        }



        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;
                Demolist.ItemsSource = ObjOrderList.GetRange(0, 40);
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }

DetailGetData.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;

namespace Last_MSPL.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);

        }



        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {





            await Navigation.PopModalAsync();
        }
    }
}

Solution

You can realize the function of deleting the item by adding a static datasouce class. And set the Demolist.ItemsSource = DataSource.collection; When click delete button in DetailGetData page, modify the Demolist.ItemsSource by deleting the item. So the code is like this:

DataSource.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace App10
{
    public static class DataSource
    {
        public static ObservableCollection<GetData> collection;

        static DataSource()
        {
        }
        public static void persist(List<GetData> collection)
        {
            //do something here
        }

        public static void initializeData(List<GetData> listdata)
        {
            collection = new ObservableCollection<GetData>(listdata);
        }
    }
}

MainPage.xaml.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
        List<GetData> dataList;
        public MainPage()
        {
            //((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
            //RefreshList();
        }
        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;

                dataList = ObjOrderList.GetRange(0, 40);
                DataSource.initializeData(dataList);
                Demolist.ItemsSource = DataSource.collection;

            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }
}

DetailGetData.xaml.cs

   [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public GetData thisData;

        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);
            thisData = _data;

        }


        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {

            GetData toberemoveditem = (from item in DataSource.collection
                                       where item.id == thisData.id
                             select item)
                            .FirstOrDefault<GetData>();
            DataSource.collection.Remove(toberemoveditem);


            await Navigation.PopModalAsync();
        }
    }


Answered By - AbbyWang - MSFT
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why won't my cross platform test automation framework run in parallel?

 September 14, 2022     appium, cross-platform, parallel-processing, selenium, testng     No comments   

Issue

I am currently rewriting the automated testing framework for my company's mobile testing. We are attempting to use an interface which is implemented by multiple Page Object Models dependent on the Operating System of the mobile device the application is being run on. I can get this framework to run sequentially and even create multiple threads but it will not run in parallel no matter what I do. Of Note, we use Appium and something called the DeviceCart/DeviceConnect which allows me to physically remote into multiple devices, thus this isn't running on a grid. With that said I will link my pertinent code (this is my second version of this same code, I wrote one with and one without using ThreadLocal)

This should instantiate a new driver with a new thread for each Test

public class TLDriverFactory {

    private ThreadLocal < AppiumDriver < MobileElement >> tlDriver = new ThreadLocal <>();

    public synchronized void setTLDriver(OS platform, String server, String udid, String bundleID) {

        switch (platform) {
        case IOS:
            tlDriver = ThreadLocal.withInitial(() -> {
                try {
                    return new IOSDriver < MobileElement > (new URL(server), DesiredCapsManager.getDesiredCapabilities(OS.IOS, udid, bundleID));
                } catch(MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            });
            break;
        case ANDROID:
            tlDriver = ThreadLocal.withInitial(() -> {
                try {
                    return new AndroidDriver < MobileElement > (new URL(server), DesiredCapsManager.getDesiredCapabilities(OS.ANDROID, udid, bundleID));
                } catch(MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            });
            break;
        default:
            break;
        }
    }

    public synchronized ThreadLocal < AppiumDriver < MobileElement >> getTLDriver() {
        return tlDriver;
    }
}

This handles browser capbilities

public class DesiredCapsManager {

    public static DesiredCapabilities getDesiredCapabilities(OS platform, String udid, String bundleID) {
        //Set DesiredCapabilities
        DesiredCapabilities capabilities = new DesiredCapabilities();

        capabilities.setCapability("deviceConnectUserName", "User@Name.com");
        capabilities.setCapability("deviceConnectApiKey", "API-Token-Here");
        capabilities.setCapability("udid", udid);
        capabilities.setCapability("platformName", platform);
        capabilities.setCapability("bundleID", bundleID);
        //IOS only Settings
        if (platform.equals(OS.IOS)) {
            capabilities.setCapability("automationName", "XCUITest");
        }
        else {
            //Android only Settings
            capabilities.setCapability("automationName", "appium");
        }

        return capabilities;
    }
}

This is the Base Test class from which every test inherits

public class BaseTest {

    protected AppiumDriver < MobileElement > driver;
    protected AppiumSupport.TLDriverFactory TLDriverFactory = new AppiumSupport.TLDriverFactory();

    public enum OS {
        ANDROID,
        IOS
    }

    @AfterMethod
    public synchronized void tearDown() throws Exception {
        driver.quit();
        TLDriverFactory.getTLDriver().remove();
    }
}

Here is the test case itself

public class Test_SignIn extends BaseTest {

    protected SignInPage signInPage;

    @Parameters(value = {
        "udid",
        "bundleID",
        "platform",
        "server"
    })
    @BeforeMethod
    public void setup(String udid, String bundleID, OS platform, String server) throws MalformedURLException,
    InterruptedException {
        //Set & Get ThreadLocal Driver
        TLDriverFactory.setTLDriver(platform, server, udid, bundleID);
        driver = TLDriverFactory.getTLDriver().get();
        Thread.sleep(5000);
        switch (platform) {
        case IOS:
            signInPage = new SignInPageIOS(driver);
            break;

        case ANDROID:
            signInPage = new SignInPageAndroid(driver);
            break;

        default:
            break;
        }

        System.out.println("Current Thread ID BeforeTest: " + Thread.currentThread().getName());
    }

    @Test
    public synchronized void Authenticate() throws Exception {
        System.out.println("Current Thread ID Test 1: " + Thread.currentThread().getName());
        signInPage.Login("Username", "Password");

    }
}

Here is the testng.xml file

   < !DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Test" parallel="tests" thread-count="4">
   <test name="SignIn" parallel ="instances" thread-count="2">
          <parameter name="udid" value="DeviceIdGoesHere" />
          <parameter name="bundleID" value="Environment.address.here" />
          <parameter name="platform" value="ANDROID" />
          <parameter name="server" value="http://deviceconnect/appium" />
          <classes>
              <class name="Test.Test_SignIn">
              </class>
          </classes>
   </test>
   <test name="SignIn2" parallel="instances" thread-count="2">
          <parameter name="udid" value="DeviceIdGoesHere" />
          <parameter name="bundleID" value="Environment.address.here" />
          <parameter name="platform" value="IOS" />
          <parameter name="server" value="http://deviceconnect/appium" />
          <classes>
              <class name="Test.Test_SignIn">
              </class>
          </classes>
   </test>
</suite>

What I'm looking for is if anyone can determine what mistake I've made or what the bottleneck is preventing the tests from running in parallel


Solution

Based on what you have shared so far, here's the cleaned-up and fixed code that should support your concurrency requirements.

The Driver factory class which is responsible for creation and clean-up of Appium driver instances for each and every thread, looks like below:

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.ios.IOSDriver;

import java.net.MalformedURLException;
import java.net.URL;

public class TLDriverFactory {

    private static final ThreadLocal<AppiumDriver<MobileElement>> tlDriver = new ThreadLocal<>();

    public static void setTLDriver(BaseTest.OS platform, String server, String udid, String bundleID) throws MalformedURLException {

        System.out.println("Current Thread ID Driver Instantiation: " + Thread.currentThread().getName());

        AppiumDriver<MobileElement> driver;
        switch (platform) {
            case IOS:
                driver = new IOSDriver<>(new URL(server), DesiredCapsManager.getDesiredCapabilities(BaseTest.OS.IOS, udid, bundleID));
                break;

            default:
                driver = new AndroidDriver<>(new URL(server), DesiredCapsManager.getDesiredCapabilities(BaseTest.OS.ANDROID, udid, bundleID));
                break;
        }

        tlDriver.set(driver);
    }

    public static AppiumDriver<MobileElement> getTLDriver() {
        return tlDriver.get();
    }

    public static void cleanupTLDriver() {
        tlDriver.get().quit();
        tlDriver.remove();
    }
}

Here's how the BaseTest which I am guessing is supposed to be the base class for all tests, would look like

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;

public class BaseTest {

    private static final ThreadLocal<SignInPage> signInPage = new ThreadLocal<>();

    public enum OS {
        ANDROID,
        IOS
    }

    @Parameters(value = {"udid", "bundleID", "platform", "server"})
    @BeforeMethod
    public void setup(String udid, String bundleID, OS platform, String server) throws Exception {
        //Set & Get ThreadLocal Driver
        TLDriverFactory.setTLDriver(platform, server, udid, bundleID);

        Thread.sleep(5000);
        SignInPage instance;
        switch (platform) {
            case IOS:
                instance = new SignInPageIOS(TLDriverFactory.getTLDriver());
                break;

            default:
                instance = new SignInPageAndroid(TLDriverFactory.getTLDriver());
                break;
        }

        System.out.println("Current Thread ID BeforeTest: " + Thread.currentThread().getName());
        signInPage.set(instance);
    }

    @AfterMethod
    public void tearDown() {
        System.out.println("Current Thread ID AfterTest: " + Thread.currentThread().getName());
        TLDriverFactory.cleanupTLDriver();
    }

    protected static SignInPage getPageForTest() {
        return signInPage.get();
    }

}

Here's how the constructor of your page classes would look like

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;

public class SignInPageIOS extends SignInPage {
    public SignInPageIOS(AppiumDriver<MobileElement> tlDriver) {
        super(tlDriver);
    }
}

Here's how a typical test case could look like

import org.testng.annotations.Test;

public class Test_SignIn extends BaseTest {
    @Test
    public void authenticate() {
        //Get the instance of "SignInPage" for the current thread and then work with it.
        getPageForTest().Login("Username", "Password");
    }
}


Answered By - Krishnan Mahadevan
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to develop Windows app on Visual Studio for Mac

 September 14, 2022     cross-platform, uwp, visual-studio-mac, xamarin     No comments   

Issue

I recently bought an iMac in order to develop my App on Visual Studio for Mac in a better environment (lots of issues on Windows), but on the Visual Studio for mac, there is no UWP projects.

It is understood that I have to create a new .NET project, but what are exactly the steps to follow in order to achieve that correctly for the app to work on Windows with a peace of mind? Should I have gone with Visual Studio code, which support the .NET core framework completely?

I saw on other answers that I need the .NET SDK tool, and so forth, but further details are needed if you don't mind on the why (not the installation stuffs, only the tech savvy explanations for the app to build correctly at the end!


Solution

You will need to run a Windows installation (eg, via Parallels or Boot Camp) and then run the Windows version of Visual Studio to create UWP apps.

You can do a lot of the business-logic coding inside Visual Studio on MacOS, but you will need Visual Studio and the Windows SDK to use WinRT types (which are required to build a UWP app) and to correctly build / package the app for deployment.



Answered By - Peter Torr - MSFT
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Where is Unity3D Project Wizard project list stored on Linux/Mac?

 September 14, 2022     cross-platform, linux, regedit, unity3d, wizard     No comments   

Issue

In Windows, the project list is stored on the Regedit at this location:

...

But where is this located on Linux or Mac? I want to do a program that need to use this paths.


Solution

for MacOS:

~/Library/Preferences⁩/com.unity3d.UnityEditor5.x.plist


Answered By - siusiulala
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to learn OpenGL 3.x using C?

 September 14, 2022     c, cross-platform, opengl     No comments   

Issue

I know there are many tutorials on OpenGL out there, but all good tutorials I found use some C++ libraries (mostly GLM) that make it hard to follow for people that would like to use C, or/and were specific to Microsoft Windows.

My Questions are:

  1. Does anybody know a good OpenGL 3.x tutorial that uses C and is not Windows specific?
  2. Which programming language does the OpenGL "redbook" use?

Solution

Does anybody know a good OpenGL 3.x tutorial that uses C and is not Windows specific?

If I remember correctly, Nicol Bolas's tutorials use C++ (for GLM). I suggest you replace GLM with my linmath.h where applicable.

Which programming language does the OpenGL "redbook" use?

The older editions (<= OpenGL-2.1) used pure C. The newer ones I actually didn't read.



Answered By - datenwolf
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to change NavBar colour of MasterMainPage in Xamarin

 September 14, 2022     background-color, cross-platform, navbar, xamarin.forms     No comments   

Issue

I'm building a Xamarin cross-platform App!

The problem is I want to change the colour of NavigationBar of MainPage which is MasterPage with a drawer menu in it.

I tried with this code to change the colour but an extra bar appears on NavBar which I don't Want to.

App.xaml.cs:

  MainPage = new NavigationPage(new MainPage())

        {
            BarBackgroundColor = Color.FromHex("#00477f"),
            BarTextColor = Color.White,
        };

ScreenShots: These Screenshots shows what the problem I'm facing!

https://i.stack.imgur.com/fbXie.png

https://i.stack.imgur.com/vuA1A.png


Solution

Here, when you assign App.xaml's MainPage, a NavigationPage, it shows it's own NavigationBar. Under the hood, your MasterDetailPage also shows the NavigationBar. Thus, you are viewing two NavigationBars.

Go to your MainPage.xaml.cs backend page and in the Constructor, write the line:

NavigationPage.SetHasNavigationBar(this, false);

Thus, your MainPage.xaml.cs should look like :

public MainPage()
{
    NavigationPage.SetHasNavigationBar(this, false);
    InitializeComponent();
    ......
}

This will hide the NavigationBar of MasterDetailPage.



Answered By - MilanG
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can i use table view and picker as user input?

 September 14, 2022     c#, cross-platform, view, xamarin.forms     No comments   

Issue

I would like to create a page like this: [1]: https://imgur.com/YreKQi3. But picker comes with underline and i also am not being able to display table separator line.

I tried to use tableview inside a frame but it didnt work. because frame's width is larger than table and seperator becomes invisible.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="KiaiDay.Views.PosLogin.ComoTeSentesPage"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             Title="Como te sentes?">
    <ContentPage.Content>
        <StackLayout Padding="30">
            <StackLayout HorizontalOptions="Center">
                <Label Text="Como te sentes hoje?" FontAttributes="Bold" FontSize="Medium" TextColor="Black"/>
            </StackLayout>
            <Frame CornerRadius="10" BackgroundColor="#ECECEC" BorderColor="LightGray" Padding="10" HeightRequest="200">
                <TableView Intent="Form" HeightRequest="200">
                    <TableRoot>
                        <TableSection>
                        <ViewCell>
                                <StackLayout HeightRequest="40">
                                    <StackLayout Orientation="Horizontal">
                                        <Label Text="Energia" TextColor="White"  VerticalOptions="Center" HorizontalOptions="Center" WidthRequest="500" Opacity="1"/>
                                        <Picker ItemsSource="{Binding Opcoes}" BackgroundColor="White" WidthRequest="50"/>

                                    </StackLayout>
                                </StackLayout>
                            </ViewCell>
                                <ViewCell>
                                <StackLayout HeightRequest="40">
                        <StackLayout Orientation="Horizontal" BackgroundColor="Blue">
                    <Picker ItemsSource="{Binding Opcoes}" BackgroundColor="White" WidthRequest="50"/>

                    <Label Text="Mindset" TextColor="White"  VerticalOptions="Center" HorizontalOptions="StartAndExpand" FontAttributes="Bold"/>
                                    </StackLayout>
                                </StackLayout>
                            </ViewCell>
                            <ViewCell>
                                <StackLayout HeightRequest="40">
                                    <StackLayout Orientation="Horizontal" BackgroundColor="Blue">
                                        <Picker ItemsSource="{Binding Opcoes}" BackgroundColor="White" WidthRequest="50"/>

                                        <Label Text="Estratégia" TextColor="White"  VerticalOptions="Center" HorizontalOptions="StartAndExpand" FontAttributes="Bold"/>
                                    </StackLayout>
                                </StackLayout>
                            </ViewCell>
                            <ViewCell>
                                <StackLayout HeightRequest="40">
                                    <StackLayout Orientation="Horizontal" BackgroundColor="Blue">
                                        <Picker ItemsSource="{Binding Opcoes}" TextColor="White" BackgroundColor="White" WidthRequest="50"/>

                                        <Label Text="Acção" TextColor="White"  VerticalOptions="Center" HorizontalOptions="StartAndExpand" FontAttributes="Bold"/>
                                    </StackLayout>
                                </StackLayout>
                            </ViewCell>
                            <ViewCell>
                                <StackLayout HeightRequest="40">
                                    <StackLayout Orientation="Horizontal" BackgroundColor="Blue">
                                        <Picker ItemsSource="{Binding Opcoes}" BackgroundColor="White" WidthRequest="50"/>

                                        <Label Text="Conexão" TextColor="White" VerticalOptions="Center" HorizontalOptions="StartAndExpand" FontAttributes="Bold"/>
                                    </StackLayout>
                                </StackLayout>
                            </ViewCell>


                        </TableSection>
                    </TableRoot>
                </TableView>
            </Frame>

        </StackLayout>


    </ContentPage.Content>
</ContentPage>
´´´

Solution

I write a simple demo to achieve the requirement of the image in your answer, I use Frame and Grid:

<StackLayout Padding="30">
    <StackLayout HorizontalOptions="Center">
        <Label Text="Como te sentes hoje?" FontAttributes="Bold" FontSize="Medium" TextColor="Black"/>
    </StackLayout>
    <Frame CornerRadius="7" BackgroundColor="Gray" BorderColor="LightGray" Padding="3" HeightRequest="180" HasShadow="False">

        <Grid ColumnSpacing="1" RowSpacing="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Label Text="CVC Code:" BackgroundColor="LightGray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" Grid.Row="0" Grid.Column="0" WidthRequest="100" HeightRequest="60"/>
            <local:BorderlessPicker BackgroundColor="White"   Grid.Row="0" Grid.Column="1" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

                <Picker.ItemsSource>
                    <x:Array Type="{x:Type x:String}">
                        <x:String>1321</x:String>
                        <x:String>3299</x:String>
                    </x:Array>
                </Picker.ItemsSource>
            </local:BorderlessPicker>


        <Label Text="Card No:" BackgroundColor="LightGray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" Grid.Row="1" Grid.Column="0" WidthRequest="100" HeightRequest="60"/>
            <local:BorderlessPicker BackgroundColor="White"   Grid.Row="1" Grid.Column="1" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

                <Picker.ItemsSource>
                    <x:Array Type="{x:Type x:String}">
                        <x:String>1900</x:String>
                        <x:String>1233</x:String>
                    </x:Array>
                </Picker.ItemsSource>
            </local:BorderlessPicker>



            <Label Text="Expiry:" BackgroundColor="LightGray" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" Grid.Row="2" Grid.Column="0" WidthRequest="100" HeightRequest="60"/>
            <local:BorderlessPicker BackgroundColor="White"   Grid.Row="2" Grid.Column="1" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

                <Picker.ItemsSource>
                    <x:Array Type="{x:Type x:String}">
                        <x:String>12/4</x:String>
                        <x:String>11/8</x:String>
                    </x:Array>
                </Picker.ItemsSource>
            </local:BorderlessPicker>


        </Grid>

    </Frame>

</StackLayout>

In code behind, I removed the border of picker by using custom renderer: AndroDevil mentioned in the comment: xamarin-tip-borderless-picker :

public class BorderlessPicker : Picker
    {
    }

Here is the result:

result



Answered By - nevermore
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get a mixed SSIS-J2EE system to communicate via messaging?

 September 14, 2022     cross-platform, msmq, ssis     No comments   

Issue

I'm currently developing an ETL solution which, for various reasons, include SSIS components as well as J2EE services.

I need the various components to communicate asynchronously via messaging queues. However, the obvious constraint is that SSIS only integrates with MSMQ while it obviously makes sense to use JMS on the Java side.

I have considered the MSMQ/MQSeries Bridge (we use WebsphereMQ internally) but I feel this adds another layer of complexity to the solution.

I now wonder whether there is a simpler solution to achieve cross-platform messaging. The purpose of the messaging approach is really to implement transfer of control between components, rather than pass data. Each component, whether it's a SSIS package or a J2EE service, will read/write from the same underlying database so I wonder if I'm better off just implementing a polling mechanism on either side. Suggestions are welcome.

Christophe.


Solution

depending on your needs you could write your own bridge to move messages between MSMQ and WMQ. We have done pretty easily using .NET and the IBM XMS libraries.

http://www-01.ibm.com/support/docview.wss?rs=171&uid=swg24011756&loc=en_US&cs=utf-8&lang=en



Answered By - J. Scarbrough
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to find user's home directory on Windows and Linux in PHP

 September 14, 2022     cross-platform, linux, php, windows     No comments   

Issue

I've understood there are several ways to determine the user's home, depending on the platform (mainly Unix/Linux vs Windows).

Composer uses an environment variable, in composer/Platform package:

public static function getUserDirectory()
{
    if (false !== ($home = getenv('HOME'))) {
        return $home;
    }
    if (self::isWindows() && false !== ($home = getenv('USERPROFILE'))) {
        return $home;
    }
    if (function_exists('posix_getuid') && function_exists('posix_getpwuid')) {
        $info = posix_getpwuid(posix_getuid());
        return $info['dir'];
    }
    throw new \RuntimeException('Could not determine user directory');
}

public static function isWindows()
{
    return defined('PHP_WINDOWS_VERSION_BUILD');
}

Webmozart's path-util package uses other environment variables:

public static function getHomeDirectory()
{
    // For UNIX support
    if (getenv('HOME')) {
        return static::canonicalize(getenv('HOME'));
    }
    // For >= Windows8 support
    if (getenv('HOMEDRIVE') && getenv('HOMEPATH')) {
        return static::canonicalize(getenv('HOMEDRIVE').getenv('HOMEPATH'));
    }
    throw new RuntimeException("Your environment or operation system isn't supported");
}

What is the difference between these two methods? Is one more reliable than the other? Note: I'm using PHP in the CLI, so it's always the actual current user running PHP.

EDIT> I understand that this question seems to ask for an opinion, but it's not the case. I DO NOT KNOW Windows and do not understand why some packages use different ways to determine the user's home directory. I'm asking for explanations about the two mentioned methods: is one of them more reliable than the other and why? I've edited the title and the question to reflect this precision.


Solution

After not working on this for a long time, I finally decided to definitely answer this question.

There are some usefull environment variables defined on Windows: USERPROFILE, APPDATA, LOCALAPPDATA. They are easily accessible via getenv() function:

getenv('USERPROFILE');

USERPROFILE exists on any Windows, according to https://docs.microsoft.com/fr-fr/windows/desktop/shell/knownfolderid

So, on Windows, it seems to be reliable.

If you need to store data for the current user, APPDATA and LOCALAPPDATA are good variables to find that place.

I've written a package to make these tools reusable: https://github.com/Arcesilas/Platform

It's still work in progress and certainly needs to be improved. Any help is welcome to make this tool reliable on any platform.

Thanks to eryksun whose comments helped a lot in solving this question.



Answered By - Arcesilas
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is your favorite cross-platform solution to access multiple different databases (MySQL, Oracle...) in C/C++?

 September 14, 2022     c, c++, cross-platform, database     No comments   

Issue

I am writing a simple C++ application which might be installed on Linux or Windows, and which will connect to a database. I want my application to be compatible at least with Oracle and MySQL (or PostgreSQL).

Which C or C++ library would you recommend to handle the database queries: I am open to any library, whether it's very thin (just execute SQL queries) or very fat (a whole object persistence layer, clustering, etc.).

One library per answer, please. A little description (pros & cons) would be great. Thanks a lot.


Solution

I enjoy using SOCI, it's very C++ like. When it comes to performance with respect to Oracle database, it's comparable with native OCI. It provides backend to some RDBMS:

  • Oracle
  • PostgreSQL
  • MySQL

And some more in the CVS repository.

It's fairly simple to use, the documentation is thorough and rationale is pretty clear. It supports connection pooling, has nice extensible way of converting between datatypes.



Answered By - Anonymous
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use the same C++ code for Android and iOS?

 September 14, 2022     c++, cross-platform, java, java-native-interface, objective-c++     No comments   

Issue

Android with NDK has support to C/C++ code and iOS with Objective-C++ has support too, so how can I write applications with native C/C++ code shared between Android and iOS?


Solution

Update.

This answer is quite popular even four years after I write it, in this four years a lot of things has changed, so I decided to update my answer to fit better our current reality. The answer idea does not change; the implementation has changed a little. My English also has changed, it has improved a lot, so the answer is more understandable to everyone now.

Please take a look at the repo so you can download and run the code I'll show below.

The Answer

Before I show the code, please take a lot on the following diagram.

Arch

Each OS has its UI and peculiarities, so we intend to write specific code to each platform in this regard. In other hands, all logic code, business rules, and things that can be shared we intend to write using C++, so we can compile the same code to each platform.

In the diagram, you can see the C++ layer at the lowest level. All shared code is in this segment. The highest level is regular Obj-C / Java / Kotlin code, no news here, the hard part is the middle layer.

The middle layer to iOS side is simple; you only need to configure your project to build using a variant of Obj-c know as Objective-C++ and it is all, you have access to C++ code.

The thing became harder on the Android side, both languages, Java and Kotlin, on Android, run under a Java Virtual Machine. So the only way to access C++ code is using JNI, please take time to read the basics of JNI. Fortunately, today's Android Studio IDE has vast improvements on JNI side, and a lot of problems are shown to you while you edit your code.

The code by steps

Our sample is a simple app that you send a text to CPP, and it converts that text to something else and returns it. The idea is, iOS will send "Obj-C" and Android will send "Java" from their respective languages, and the CPP code will create a text as a follow "cpp says hello to << text received >>".

Shared CPP code

First of all, we are going to create the shared CPP code, doing it we have a simple header file with the method declaration that receives the desired text:

#include <iostream>

const char *concatenateMyStringWithCppString(const char *myString);

And the CPP implementation:

#include <string.h>
#include "Core.h"

const char *CPP_BASE_STRING = "cpp says hello to %s";

const char *concatenateMyStringWithCppString(const char *myString) {
    char *concatenatedString = new char[strlen(CPP_BASE_STRING) + strlen(myString)];
    sprintf(concatenatedString, CPP_BASE_STRING, myString);
    return concatenatedString;
}

Unix

An interesting bonus is, we can also use the same code for Linux and Mac as well as other Unix systems. This possibility is especially useful because we can test our shared code faster, so we are going to create a Main.cpp as follow to execute it from our machine and see if the shared code is working.

#include <iostream>
#include <string>
#include "../CPP/Core.h"

int main() {
  std::string textFromCppCore = concatenateMyStringWithCppString("Unix");
  std::cout << textFromCppCore << '\n';
  return 0;
}

To build the code, you need to execute:

$ g++ Main.cpp Core.cpp -o main
$ ./main 
cpp says hello to Unix

iOS

It is time to implement on the mobile side. As far as iOS has a simple integration we are starting with it. Our iOS app is a typical Obj-c app with only one difference; the files are .mm and not .m. i.e. It is an Obj-C++ app, not an Obj-C app.

To a better organization, we create the CoreWrapper.mm as follow:

#import "CoreWrapper.h"

@implementation CoreWrapper

+ (NSString*) concatenateMyStringWithCppString:(NSString*)myString {
    const char *utfString = [myString UTF8String];
    const char *textFromCppCore = concatenateMyStringWithCppString(utfString);
    NSString *objcString = [NSString stringWithUTF8String:textFromCppCore];
    return objcString;
}

@end

This class has the responsibility to convert CPP types and calls to Obj-C types and calls. It is not mandatory once you can call CPP code on any file you want on Obj-C, but it helps to keep the organisation, and outside your wrapper files you maintain a complete Obj-C styled code, only the wrappers file become CPP styled.

Once your wrapper is connected to the CPP code, you can use it as a standard Obj-C code, e.g. ViewController"

#import "ViewController.h"
#import "CoreWrapper.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString* textFromCppCore = [CoreWrapper concatenateMyStringWithCppString:@"Obj-C++"];
    [_label setText:textFromCppCore];
}

@end

Take a look of how the app looks:

Xcode iPhone

Android

Now it is time for Android integration. Android uses Gradle as the build system, and to C/C++ code it uses CMake. So the first thing we need to do is to configure the CMake on gradle file:

android {
...
externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}
...
defaultConfig {
    externalNativeBuild {
        cmake {
            cppFlags "-std=c++14"
        }
    }
...
}

And the second step is to add the CMakeLists.txt file:

cmake_minimum_required(VERSION 3.4.1)

include_directories (
    ../../CPP/
)

add_library(
    native-lib
    SHARED
    src/main/cpp/native-lib.cpp
    ../../CPP/Core.h
    ../../CPP/Core.cpp
)

find_library(
    log-lib
    log
)

target_link_libraries(
    native-lib
    ${log-lib}
)

The CMake file is where you need to add the CPP files and header folders you will use on the project, on our example, we are adding the CPP folder and the Core.h/.cpp files. To know more about C/C++ configuration please read it.

Now the core code is part of our app it is time to create the bridge, to make the things more simple and organized we create a specific class named CoreWrapper to be our wrapper between JVM and CPP:

public class CoreWrapper {

    public native String concatenateMyStringWithCppString(String myString);

    static {
        System.loadLibrary("native-lib");
    }

}

Note this class has a native method and loads a native library named native-lib. This library is the one we create, in the end, the CPP code will become a shared object .so File embed in our APK, and the loadLibrary will load it. Finally, when you call the native method, the JVM will delegate the call to the loaded library.

Now the most strange part of Android integration is the JNI; We need a cpp file as follow, in our case "native-lib.cpp":

extern "C" {

JNIEXPORT jstring JNICALL Java_ademar_androidioscppexample_CoreWrapper_concatenateMyStringWithCppString(JNIEnv *env, jobject /* this */, jstring myString) {
    const char *utfString = env->GetStringUTFChars(myString, 0);
    const char *textFromCppCore = concatenateMyStringWithCppString(utfString);
    jstring javaString = env->NewStringUTF(textFromCppCore);
    return javaString;
}

}

The first thing you will notice is the extern "C" this part is necessary to JNI work correctly with our CPP code and method linkages. You will also see some symbols JNI uses to works with JVM as JNIEXPORT and JNICALL. To you understand the meaning of those things, it is necessary to take a time and read it, for this tutorial purposes just consider these things as boilerplate.

One significant thing and usually the root of a lot of problems is the name of the method; it needs to follow the pattern "Java_package_class_method". Currently, Android studio has excellent support for it so it can generate this boilerplate automatically and show to you when it is correct or not named. On our example our method is named "Java_ademar_androidioscppexample_CoreWrapper_concatenateMyStringWithCppString" it is because "ademar.androidioscppexample" is our package, so we replace the "." by "_", CoreWrapper is the class where we are linking the native method and "concatenateMyStringWithCppString" is the method name itself.

As we have the method correctly declared it is time to analyze the arguments, the first parameter is a pointer of JNIEnv it is the way we have access to JNI stuff, it is crucial to we make our conversions as you will see soon. The second is a jobject it is the instance of the object you had used to call this method. You can think it as the java "this", on our example we do not need to use it, but we still need to declare it. After this jobject, we are going to receive the arguments of the method. Because our method has only one argument - a String "myString", we have only a "jstring" with the same name. Also notice that our return type is also a jstring. It is because our Java method returns a String, for more information about Java/JNI types please read it.

The final step is to convert the JNI types to the types we use on CPP side. On our example, we are transforming the jstring to a const char * sending it converted to the CPP, getting the result and converting back to jstring. As all other steps on JNI, it is not hard; it is only boilerplated, all the work is done by the JNIEnv* argument we receive when we call the GetStringUTFChars and NewStringUTF. After it our code is ready to run on Android devices, lets take a look.

AndroidStudio Android



Answered By - ademar111190
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 13, 2022

[FIXED] Which platforms does Xamarin support?

 September 13, 2022     cross-platform, target-platform, xamarin     No comments   

Issue

I tried finding the information both on their website and on the Internet, but it appears that everywhere I look, a different list pops up.

  • Their front page says iOS, Android, Windows and Mac.

  • In their documentation (http://docs.xamarin.com/), only Android iOS, Mac are mentioned at the docs front-page. I'm wondering does this mean Windows has lesser priority compared to others.

  • On the Internet, I've found even more inconclusive information. Also, it's hard to conclude what Windows means, mobile or desktop.

I've never used the product, but would love to try it for the game that I want to create, so I have two questions:

  1. Can you give me a complete list of supported platforms (Android, iOS, Mac, Windows, Windows Phone, HTML5, Flash...)?
  2. Can I target Facebook app with Xamarin?

Thanks in advance.


Solution

To update and extend Jason's answer there is now Xamarin.Forms that let us build cross-platform GUI for Android, iOS and Windows Phone. Looking at Xamarin's FormsGallery sample app I think it is fair to say that it de facto supports Windows Phone as well.

In addition to Xamarin.Forms there's always the possibility to use Xamarin.iOS, Xamarin.Android and Xamarin.Mac for platform customizations.

Xamarin.Mobile is in a preview release and supports Android, iOS and Windows Phone. It is used as an abstracted API of the native services (camera, geolocation etc).

However since you need the local SDK's installed for compilation you need a Mac computer to be able to deply for iOS. In order to compile for Windows Phone you need to use Visual Studio and the Xamarin Plugin, Xamarin Studio is not able to do this.

To conclude Xamarin supports development for

  • Android
  • iOS
  • Windows Phone
  • Mac

However not all of Xamarin's API's are implemented for all platforms.



Answered By - HischT
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get a Kony application's name at runtime

 September 13, 2022     cross-platform, debugging, mobile, temenos-quantum     No comments   

Issue

I'm writing a logger module for a Kony app to print out debugging statements. The Kony SDK already has a kony.print function but I'd like this logger to print out the application's name as a prefix to each statement, to get something like:

FooApp: x is 1
FooApp: a is ["hello", "world"]

The point here is to make it easier for me to filter/find my debug statements in the Xcode or Android Studio logs while debugging.

So I'm aiming to write something like:

var Logger = (function(){

    var prefix = ""; //kony.getAppId()?

    return{
        print: function(message){
            kony.print(`${prefix}: ${message}`);
        }
    };
})();

So the question is whether there is anything like a kony.getAppId() function, a constant or equivalent I can query to get the appropriate value for prefix in order to make the module reusable, rather than hard-code it for every project.


Solution

I've found that there's an appConfig variable built into every Kony app that includes useful information about the application like its name and version. So now I can initialise the prefix variable in my module like this:

var prefix = appConfig.appId || appConfig.appName;

I hope this is useful to others.



Answered By - Mig82
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing