IdownloadHandler is not working in WPF Cefsharp browser - wpf

public class MyDownloadHandler : IDownloadHandler
{
public event EventHandler<DownloadItem> OnBeforeDownloadFired;
public event EventHandler<DownloadItem> OnDownloadUpdatedFired;
public void OnBeforeDownload(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
{
SharedData.Log.Info(Constants.CONST_TEXT_LOG_DEBUG_DATA + Constants.CONST_TEXT_LOG_DEBUG_DATA_DELIMITER + "CEF OnBeforeDownload : started");
OnBeforeDownloadFired?.Invoke(this, downloadItem);
if (!callback.IsDisposed)
{
using (callback)
{
callback.Continue(downloadItem.SuggestedFileName, showDialog: true);
}
}
SharedData.Log.Info(Constants.CONST_TEXT_LOG_DEBUG_DATA + Constants.CONST_TEXT_LOG_DEBUG_DATA_DELIMITER + "CEF OnBeforeDownload : ended");
}
public void OnDownloadUpdated(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
{
SharedData.Log.Info(Constants.CONST_TEXT_LOG_DEBUG_DATA + Constants.CONST_TEXT_LOG_DEBUG_DATA_DELIMITER + "CEF OnDownloadUpdated : started");
OnDownloadUpdatedFired?.Invoke(this, downloadItem);
}
Downloading progress bar is shown but download doesn't happen, OnBeforeDownload event is not working:
public DxLogin(string url)
{
Cef.Initialize(cefSettings);
dxloginpage = new ChromiumWebBrowser();
dxloginpage.DownloadHandler = new MyDownloadHandler();
InitializeComponent();
dxloginpage.Address = url;
}

Related

window.external is null for new windows

Problem; window.external is null for child windows
I have a WinForms application that contains a CEFSharp Chromium browser control on the main form. The complete code is provided here; note this is not my application but a much simpler example that shows the problem.
public partial class Form1 : Form
{
private WebInteropAPI _objForScripting;
public Form1()
{
InitializeComponent();
Load += OnFormLoaded;
_objForScripting = new WebInteropAPI();
}
private void OnFormLoaded(object sender, EventArgs e)
{
SetupBrowser();
_browser.Load("http://localhost:80");
}
private void SetupBrowser()
{
_browser.JavascriptObjectRepository.ResolveObject += ResolveObject;
_browser.FrameLoadStart += FrameLoadStart;
}
private void FrameLoadStart(object sender, FrameLoadStartEventArgs e)
{
_browser.ExecuteScriptAsync("CefSharp.DeleteBoundObject(\"external\"); CefSharp.RemoveObjectFromCache(\"external\"); CefSharp.BindObjectAsync(\"external\");");
}
private void ResolveObject(object sender, JavascriptBindingEventArgs e)
{
var repo = e.ObjectRepository;
if (e.ObjectName == "external" && repo != null && _objForScripting != null)
{
BindingOptions options = BindingOptions.DefaultBinder;
options.CamelCaseJavascriptNames = false;
try
{
repo.Register("external", _objForScripting, true, options);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
}
}
Here is the WebInteropAPI class for completeness
public class WebInteropAPI
{
public string Push(string name, string payload)
{
Debug.WriteLine("#### Push() name:" + name + " payload:" + payload + " ####");
return payload;
}
public void PushData(string payload)
{
Debug.WriteLine("#### PushData() payload:" + payload + " ####");
}
}
On form load I register my interop and navigate the browser to a local HTML page on my machine; it looks as follows
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
</head>
<body>
<p>
<button onclick="myFunction()">Invoke Push Data on Host</button>
Launch child iFrame
</p>
<script type="text/javascript">
$('.open-popup').click(function(e) {
e.preventDefault();
window.open(this.href, '_blank', 'width=1000,height=750');
});
</script>
<script>
function myFunction() {
window.external.Push("This is the name property","This is the payload data property");
}
</script>
</body>
</html>
Running the application results in the rather fetching UI
Clicking the button does indeed invoke the method on my WebInteropAPI
However; clicking the link to open a new child window and then clicking the button results in an error
Any help is greatly appreciated.
UPDATE; I've found something that works but I'm unsure if it's good or bad from a standards point of view.
My updated Forms view now looks like;
public partial class Form1 : Form
{
private FrameHelper _frameHelper;
private JSObjectHelper _jsObjectHelper;
public Form1()
{
InitializeComponent();
Load += OnFormLoaded;
}
private void OnFormLoaded(object sender, EventArgs e)
{
SetupBrowser();
_browser.Load("http://localhost:80");
}
private void SetupBrowser()
{
_jsObjectHelper = new JSObjectHelper(new WebInteropAPI());
_frameHelper = new FrameHelper();
_browser.JavascriptObjectRepository.ResolveObject += (s, a) =>
{
_jsObjectHelper.ResolveObject(a);
};
_browser.FrameLoadStart += (s, a) =>
{
_frameHelper.FrameLoadStart(_browser);
};
_browser.LifeSpanHandler = new LifeSpanHandler(_frameHelper, _jsObjectHelper);
}
}
The magic now happens in the LifeSpanHandler
public class LifeSpanHandler : ILifeSpanHandler
{
private readonly FrameHelper _frameHelper;
private readonly JSObjectHelper _jsObjectHelper;
private ChromiumWebBrowser _browser;
public LifeSpanHandler(FrameHelper frameHelper, JSObjectHelper jsObjectHelper)
{
_frameHelper = frameHelper;
_jsObjectHelper = jsObjectHelper;
}
public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
return false;
}
public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser){}
public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser){}
public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
{
_browser = new ChromiumWebBrowser(string.Empty);
_browser.Bounds = ((ChromiumWebBrowser)chromiumWebBrowser).Bounds;
_browser.BrowserSettings = ((ChromiumWebBrowser)chromiumWebBrowser).BrowserSettings;
_browser.FrameLoadStart += (s, a) => { _frameHelper.FrameLoadStart(_browser); };
_browser.JavascriptObjectRepository.ResolveObject += (s, a) => { _jsObjectHelper.ResolveObject(a); };
newBrowser = _browser;
return false;
}
}
And for completeness; here's the frame helper and the JsObjectHelper
public class FrameHelper
{
public void FrameLoadStart(IWebBrowser browser)
{
browser.ExecuteScriptAsync("CefSharp.DeleteBoundObject(\"external\"); CefSharp.RemoveObjectFromCache(\"external\"); CefSharp.BindObjectAsync(\"external\");");
}
}
public class JSObjectHelper
{
private readonly WebInteropAPI _objForScripting;
public JSObjectHelper(WebInteropAPI objForScripting)
{
_objForScripting = objForScripting;
}
public WebInteropAPI ObjForScripting { get; }
public void ResolveObject(JavascriptBindingEventArgs e)
{
var repo = e.ObjectRepository;
if (e.ObjectName == "external" && repo != null && _objForScripting != null)
{
BindingOptions options = BindingOptions.DefaultBinder;
options.CamelCaseJavascriptNames = false;
try
{
repo.Register("external", _objForScripting, true, options);
}
catch
{
}
}
}
}

Dockfill not working in mstsc activeX control

I am trying to create a rdp in WPF. I used the AxMSTSCLib library to create a rdp client in my wpf application. I planned to create a usercontrol that hosts the rdp.I achieved it with the following code.
But i get the grey area of the windows host visible. I need to fill the rdp client for the size of the windows host.
public partial class RDPUserControl : UserControl
{
internal RDPActiveXControl _rdp;
internal string Servername { get; set; }
internal string Username { get; set; }
internal string Password { get; set; }
internal TabItem TabItem { get; set; }
public RDPUserControl()
{
InitializeComponent();
}
private void InitData()
{
_rdp = new RDPActiveXControl();
((System.ComponentModel.ISupportInitialize)(_rdp)).BeginInit();
_rdp.Name = "rdp";
_rdp.Enabled = true;
wfHost.Child = _rdp;
((System.ComponentModel.ISupportInitialize)(_rdp)).EndInit();
}
internal void Connect()
{
_rdp.Server = Servername;
_rdp.UserName = Username;
_rdp.AdvancedSettings7.ClearTextPassword = Password;
_rdp.ColorDepth = 24;
_rdp.AdvancedSettings7.SmartSizing = true;
_rdp.AdvancedSettings7.AuthenticationLevel = 2;
_rdp.AdvancedSettings7.EnableCredSspSupport = true;
_rdp.Width = Convert.ToInt32(this.ActualWidth);
_rdp.Height = Convert.ToInt32(this.ActualHeight);
_rdp.DesktopWidth = Convert.ToInt32(this.ActualWidth);
_rdp.DesktopHeight = Convert.ToInt32(this.ActualHeight);
_rdp.OnDisconnected += _rdp_OnDisconnected;
try
{
_rdp.Connect();
}
catch(Exception e)
{
MessageBox.Show("Connection Failed: "+e.Message);
}
}
private void _rdp_OnDisconnected(object sender, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEvent e)
{
MainWindow window = Application.Current.MainWindow as MainWindow;
Page page = window._mainFrame.Content as Page;
ConnectionsPage connectionPage = page as ConnectionsPage;
connectionPage.CloseTab(TabItem);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
InitData();
Connect();
}
public class RDPActiveXControl : AxMSTSCLib.AxMsRdpClient6NotSafeForScripting
{
public RDPActiveXControl() : base() { }
protected override void WndProc(ref System.Windows.Forms.Message m)
{
// Fix for the missing focus issue on the rdp client component
if (m.Msg == 0x0021) // WM_MOUSEACTIVATE
{
if (!this.ContainsFocus)
{
this.Focus();
}
}
base.WndProc(ref m);
}
}
How to make the RDP ActiveXControl for Full size of the windowsFormHost
I tried with
_rdp.Dock = System.Windows.Forms.DockStyle.Fill;
But it makes the app to disappear.Anyone know what is wrong with this?. Any working example will be helpful.

Getting the next turn/direction in Mapbox

I'm trying to get the direction of the upcoming turn while travelling, i.e. I want to trigger an event in my app according to the direction of the upcoming turn.
I've tried using event listeners, taking help of the documentation and the provided examples but as I'm pretty new to android studio and mapbox, I've not been successful (my app either crashed or the function would never get triggered). I've also tried searching for getting the voice commands into text form or log form but have failed.
While my current code does display directions and gives voiced instructions, I can't figure out how to access either of them. I'd like to know if there's a simple way of achieving what I'm after without using any event listeners.
private MapView mapView;
private MapboxMap mapboxMap;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private MapboxNavigation navigation;
private Button button;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
// Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
//Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconSymbolLayer(style);
mapboxMap.addOnMapClickListener(MainActivity.this);
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
});
}
private void addDestinationIconSymbolLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
Log.d(TAG, "addDestinationIconSymbolLayer: " + geoJsonSource);
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}
#SuppressWarnings( {"MissingPermission"})
#Override
public boolean onMapClick(#NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
Log.d(TAG, "Does this even work");
Log.d(TAG, "onMapClick: " + source.toString());
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
return true;
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadedMapStyle);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
// Add the mapView's own lifecycle methods to the activity's lifecycle methods
#Override
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
// Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
It sounds like you might want to look at using an event listener for a custom milestone. Here's a link to the docs:
https://docs.mapbox.com/android/navigation/overview/milestones/#milestone-event-listener

How to upload file from fragment webview in android?

I have used tabhost of two fragments. One fragment is for list and other is for webview. From that fragment I have to upload file from gallery. Following is my fragment for webview.
public class AppleFragment extends Fragment{
private static final String TAG = "SocialActivityFragment";
//protected static final int FILECHOOSER_RESULTCODE = 0;
WebView browser;
static String cookieString;
ProgressBar Pbar;
HashMap<String, String> headerMap = new HashMap<String, String>();
private ValueCallback<Uri> mUploadMessage;
final static int FILECHOOSER_RESULTCODE=1;
#Override
public void onActivityResult(int requestCode, int resultCode,Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/** Creating array adapter to set data in listview */
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), R.layout.social_activities_layout, apple_versions);
LayoutInflater layoutInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.social_layout, null);
Pbar = (ProgressBar) layout.findViewById(R.id.pB1);
String strResponse = util.makeWebCall("http://google.com");
DefaultHttpClient mClient = util.getClient();
Cookie sessionInfo;
List<Cookie> cookies = mClient.getCookieStore().getCookies();
if (! cookies.isEmpty()){
CookieSyncManager.createInstance(getActivity().getApplicationContext());
CookieManager cookieManager = CookieManager.getInstance();
for(Cookie cookie : cookies){
sessionInfo = cookie;
cookieString = sessionInfo.getName() + "=" + Sessions.getPhpSessid(getActivity().getApplicationContext()) + "; domain=" + sessionInfo.getDomain();
cookieManager.setCookie("http://youornot.com/social/", cookieString);
CookieSyncManager.getInstance().sync();
//Toast.makeText(getApplicationContext(), cookieString, Toast.LENGTH_LONG).show();
}
}
AlertDialogManager alert=new AlertDialogManager();
ConnectionDetector cd=new ConnectionDetector(getActivity().getApplicationContext());
if(!cd.isConnectedToInternet())
{
alert.showAlertDialog(getActivity(), "Error..!", "You have not Connected to Internet", true);
}
browser=(WebView)layout.findViewById(R.id.webBrowser);
// WebView browser = new WebView(SocialActivity.this);
WebSettings settings = browser.getSettings();
browser.setScrollBarStyle(browser.OVER_SCROLL_IF_CONTENT_SCROLLS);
WebViewClient wvClient = new WebViewClient();
browser.setWebViewClient(wvClient);
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
browser.setWebChromeClient(new WebChromeClient() {
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
#SuppressWarnings("unused")
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult( Intent.createChooser( i, "File Chooser" ),FILECHOOSER_RESULTCODE );
}
public void onProgressChanged(WebView view, int progress)
{
if(progress < 100 && Pbar.getVisibility() == ProgressBar.GONE){
Pbar.setVisibility(ProgressBar.VISIBLE);
//txtview.setVisibility(View.VISIBLE);
}
Pbar.setProgress(progress);
if(progress == 100) {
Pbar.setVisibility(ProgressBar.GONE);
// txtview.setVisibility(View.GONE);
}
}
});
headerMap.put("Cookie", cookieString);
browser.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
//The key is this line.
v.requestFocusFromTouch();
break;
}
return false;
}
});
browser.loadUrl("http://google.com", headerMap);
return layout;//super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.web_menu, menu);
}
#SuppressLint("NewApi")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.refresh:
browser.reload();
// browser.loadUrl("http://google.com", headerMap);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Whenever I am uploading file then webview is not responding at all.When i will close the application then also webview not responding. So how I can upload file in webview that is in the tabhost fragment.
Thanks in advance.
public class AppleFragment extends Fragment{
WebView webView;
//make HTML upload button work in Webview
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != getActivity().RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_web, container, false);
// Web View
webView = (WebView) view.findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebChromeClient(new WebChromeClient(){
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
getActivity().startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(Intent.createChooser(i, "File Browser"),FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
getActivity().startActivityForResult( Intent.createChooser( i, "File Chooser" ), FILECHOOSER_RESULTCODE );
}
});
webView.loadUrl(yourUrl);
return view;
}
}
public class FragmentWeb extends Fragment {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == this.mUploadMessage) {
return;
}
Uri result=null;
try{
if (resultCode != getActivity().RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = intent == null ? mCapturedImageURI : intent.getData();
}
}
catch(Exception e)
{
Toast.makeText(getActivity().getApplicationContext(), "activity :"+e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
.
.
.
.
.
}
and YOU ALSO NEED TO PUT THE BELOW CODE AT MainActivity
public class MainActivity extends Activity {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
.
.
.
.
}

How to setup FiddlerCore code to capture REST calls from WPF application

I have a WPF application. I am making REST calls from that.
I would like to alter the response XML/JSON of the rest service.
I am using FiddlerCore to intercept the call.
I need to listen to ALL the ports in my local machine.
List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>();
FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;
oFCSF = (oFCSF & ~FiddlerCoreStartupFlags.DecryptSSL);
//Fiddler.FiddlerApplication.Startup(8080, true, true);
FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
{
};
FiddlerApplication.BeforeResponse += delegate(Fiddler.Session oS)
{
}
};
Fiddler.FiddlerApplication.Startup(0, true, false);
This issue is resolved - Look at the below link
https://gist.githubusercontent.com/timiles/4079321/raw/268f71249f381649a06f4b48ebfb54cbaa8ee282/MockWebProxyHelper.cs
using System;
using System.Net;
// http://www.fiddler2.com/fiddler/Core/
using Fiddler;
public static class MockWebProxyHelper
{
public enum HttpMethods
{
GET, POST, PUT, Unknown
}
public class Response
{
public Response(string header = "HTTP/1.1 200 OK", string body = "", string contentType = "application/json")
{
Header = header;
Body = body;
ContentType = contentType;
}
public string Header { get; private set; }
public string Body { get; private set; }
public string ContentType { get; private set; }
}
public static Func<HttpMethods, string, Response> GetMockResponse = delegate { return new Response(); };
public static Func<HttpMethods, string, bool> InterceptRequest = delegate { return true; };
public static void SetUp(bool registerAsSystemProxy = false)
{
const int port = 18833;
FiddlerApplication.Startup(port, FiddlerCoreStartupFlags.DecryptSSL
| (registerAsSystemProxy ? FiddlerCoreStartupFlags.RegisterAsSystemProxy : FiddlerCoreStartupFlags.None));
WebRequest.DefaultWebProxy = new WebProxy("localhost", port);
FiddlerApplication.BeforeRequest += BeforeRequest;
}
private static void BeforeRequest(Session session)
{
var httpMethod = GetHttpMethod(session);
var url = session.url;
if (InterceptRequest(httpMethod, url))
{
session.utilCreateResponseAndBypassServer();
var response = GetMockResponse(httpMethod, url);
session.oResponse.headers = Parser.ParseResponse(response.Header);
session.oResponse.headers.Add("Content-Type", response.ContentType);
session.utilSetResponseBody(response.Body);
}
}
private static HttpMethods GetHttpMethod(Session session)
{
return session.HTTPMethodIs("GET") ? HttpMethods.GET
: session.HTTPMethodIs("POST") ? HttpMethods.POST
: session.HTTPMethodIs("PUT") ? HttpMethods.PUT : HttpMethods.Unknown;
}
public static void TearDown()
{
FiddlerApplication.BeforeRequest -= BeforeRequest;
FiddlerApplication.oProxy.Detach();
FiddlerApplication.Shutdown();
}
}

Resources