How can I Enable/Disable a tab in AppShell via binding ? It does not work for me, I am doing something wrong - tabs

Please send me in the right direction here - I'm really confused.
See, I have this App.Shell:
<?xml version="1.0" encoding="UTF-8" ?>
<Shell
x:Class="ExpensesMobile.AppShell"
x:DataType="Login_VM:Login_VM"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:Approvals="clr-namespace:ExpensesMobile.View.Approvals"
xmlns:Settings="clr-namespace:ExpensesMobile.View.AppSettings"
xmlns:Login_VM="clr-namespace:ExpensesMobile.ViewModel.Login"
xmlns:Login="clr-namespace:ExpensesMobile.View.Login"
xmlns:Globals="clr-namespace:ExpensesMobile"
xmlns:ExpenseReports="clr-namespace:ExpensesMobile.View.ExpenseReports"
xmlns:res="clr-namespace:ExpensesMobile.Resources.Strings"
Title="{x:Static res:AppRes.ExpenseReports}"
Shell.FlyoutBehavior="Disabled">
<Shell.Items>
<ShellContent x:Name="Login" ContentTemplate="{DataTemplate Login:Login}" Route="Login" Shell.FlyoutBehavior="Disabled" Shell.NavBarIsVisible="False" ></ShellContent>
</Shell.Items>
<TabBar Route="Login">
<ShellContent ContentTemplate="{DataTemplate Login:Login}" Shell.FlyoutBehavior="Disabled" Shell.NavBarIsVisible="False" ></ShellContent>
</TabBar>
<TabBar x:Name="MyTabBar" Shell.NavBarHasShadow="true" Route="Home">
<Tab
x:Name="tabExpenseReports"
Title="{x:Static res:AppRes.ExpenseReports}"
Icon="ExpenseReports"
Shell.BackgroundColor="#001933"
Shell.ForegroundColor="#AB1300">
<ShellContent
x:Name="Pending"
ContentTemplate="{DataTemplate ExpenseReports:Pending}"
Route="Pending"
Title="{x:Static res:AppRes.Pending}"
Icon="pending.svg"
Shell.NavBarIsVisible="False">
</ShellContent>
<ShellContent
x:Name="Finalized"
ContentTemplate="{DataTemplate ExpenseReports:Finalized}"
Route="Finalized"
Title="{x:Static res:AppRes.Finalized}"
Icon="finalized.svg"
Shell.NavBarIsVisible="False">
</ShellContent>
</Tab>
<Tab
x:Name="tabApprovals"
Title="{x:Static res:AppRes.Approvals}"
Icon="approvals"
IsEnabled="{Binding TabApprovalsIsEnabled}"
Shell.BackgroundColor="#AB1300"
Shell.ForegroundColor="#001933">
<ShellContent
x:Name="Approvals"
ContentTemplate="{DataTemplate Approvals:Approvals}"
Shell.NavBarIsVisible="False"
Route="Approvals"
Title="{x:Static res:AppRes.Approvals}"
Icon="approvals.svg">
</ShellContent>
<ShellContent
x:Name="Approved"
ContentTemplate="{DataTemplate ExpenseReports:Approved}"
Shell.NavBarIsVisible="False"
Route="Approved"
Title="{x:Static res:AppRes.Approved}"
Icon="approved.svg">
</ShellContent>
</Tab>
<Tab
Title="{x:Static res:AppRes.Settings}"
Icon="settings" Shell.BackgroundColor="#193300"
x:Name="tabSettings">
<ShellContent
ContentTemplate="{DataTemplate Settings:Settings}"
Route="Settings" />
</Tab>
</TabBar>
</Shell>
In the Login page I decide whether the logged-in user is an admin or not. If he isn't, then he shouldn't have access to the tab "Approvals".
I have tried in several ways to make the tab disabled in this case. This is what I have right now:
In the class "Globals" I have this (I have them in the Globals class because I will need to refer to these values across the application):
using ExpensesMobile.Model;
namespace ExpensesMobile
{
public static class Globals
{
public static ExpensesMobileDB ExpensesMobileDB;
public static LoginStatus loginStatus;
public enum LoginStatus
{
loginRefused,
loginAcceptedAdmin,
loginAcceptedRegularUser
}
}
}
In Login_VM I have this code:
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ExpensesMobile.Resources.Strings;
using ExpensesMobile.Services;
using ExpensesMobile.Utils;
using ExpensesMobile.View.ExpenseReports;
using System.Diagnostics;
using static ExpensesMobile.Globals;
namespace ExpensesMobile.ViewModel.Login
{
[QueryProperty(nameof(Login), "Login")]
public partial class Login_VM : Base_VM
{
public readonly LoginService loginService;
private readonly IConnectivity connectivity;
[ObservableProperty]
private string password;
[ObservableProperty]
private bool tabApprovalsIsEnabled = false;
[ObservableProperty]
private string username;
public Login_VM(LoginService loginService, IConnectivity connectivity)
{
this.loginService = loginService;
this.connectivity = connectivity;
//TEMP CODE - DEBUG
username = ".....";
password = ".....";
}
private static async Task ShowToast(LoginStatus loginStatus)
{
string text;
if (loginStatus == LoginStatus.loginAcceptedAdmin)
text = AppRes.LoginConfirmationManager;
else
text = AppRes.LoginConfirmationUser;
await Utils.Utils.ShowToast(text);
}
[RelayCommand]
private async Task LoginAsync()
{
if (IsBusy)
{
return;
}
try
{
if (connectivity.NetworkAccess != NetworkAccess.Internet)
{
await Shell.Current.DisplayAlert(AppRes.MsgConnectivity1, AppRes.MsgConnectivity2, "OK"); //No connectivity, Please check your internet connection and then try again;
return;
}
IsBusy = true;
LoginStatus loginStatus = LoginService.Login(username, password);
if (loginStatus == LoginStatus.loginAcceptedAdmin)
{
TabApprovalsIsEnabled = true;
await ShowToast(loginStatus);
await Shell.Current.GoToAsync($"//{nameof(Pending)}");
}
else if (LoginService.Login(username, password) == LoginStatus.loginAcceptedRegularUser)
{
TabApprovalsIsEnabled = false;
await ShowToast(loginStatus);
await Shell.Current.GoToAsync($"//{nameof(Pending)}");
}
else if (LoginService.Login(username, password) == LoginStatus.loginRefused)
{
await Shell.Current.DisplayAlert(AppRes.Login, AppRes.LoginWrongUsernameOrPass, "OK"); //Wrong username and/or password !
}
Globals.loginStatus = loginStatus;
}
catch (Exception ex)
{
Debug.WriteLine($"Unable to login: {ex.Message}");
ErrorHandling.HandleError(ex);
}
finally
{
IsBusy = false;
}
}
}
}
If I login as a regular user, the line 'tabApprovalsIsEnabled = false;' executes.
I have added this line because I wanted App.Shell to bind to Login_VM and not to Globals directly (that is a regular class, and has no knowledge of ObservableProperties).
However, although the tab Approvals has the xaml 'IsEnabled="{Binding TabApprovalsIsEnabled}"', this is not taken into consideration and my tab remains enabled.
Obviously I am missing something, and probably I am ignorant enough of the sequence of operations in MAUI - probably the code above executes and sets the property "tabApprovalsIsEnabled" to false AFTER the binding in AppShell has been done, I don't know....
How could I solve this problem, please ?
Thank you very much,
Alex.

You should reset the value of property TabApprovalsIsEnabled not tabApprovalsIsEnabled .
Please refer to the following code:
[RelayCommand]
private async Task LoginAsync()
{
// other code
try
{
// other code
LoginStatus loginStatus = LoginService.Login(username, password);
if (loginStatus == LoginStatus.loginAcceptedAdmin)
{
// replace `tabApprovalsIsEnabled` with `TabApprovalsIsEnabled`
//tabApprovalsIsEnabled = true;
TabApprovalsIsEnabled = true;
//........
}
else if (LoginService.Login(username, password) == LoginStatus.loginAcceptedRegularUser)
{
// replace `tabApprovalsIsEnabled` with `TabApprovalsIsEnabled`
// tabApprovalsIsEnabled = false;
TabApprovalsIsEnabled = true;
}
else if (LoginService.Login(username, password) == LoginStatus.loginRefused)
{
//Wrong username and/or password !
await Shell.Current.DisplayAlert(AppRes.Login, AppRes.LoginWrongUsernameOrPass, "OK");
}
Globals.loginStatus = loginStatus;
}
catch (Exception ex)
{
Debug.WriteLine($"Unable to login: {ex.Message}");
ErrorHandling.HandleError(ex);
}
finally
{
IsBusy = false;
}
}
Note:
We need set BindingContext for AppShell.xaml.cs. Then if we change the value of property TabApprovalsIsEnabled of the current ViewModel, the UI could refresh automatically.
public partial class AppShell : Shell
{
Login_VM _VM;
public AppShell()
{
InitializeComponent();
Routing.RegisterRoute("DetailPage", typeof(DetailPage));
_VM = new Login_VM();
this.BindingContext = _VM;
}
[Obsolete]
protected override void OnAppearing()
{
base.OnAppearing();
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
_VM.TabApprovalsIsEnabled = false;
return false;
});
}
}

Related

Xamarin forms: HTML data conversion on android and windows platforms

I am using a custom webview to convert my HTML data on the ios app. I am looking for the same custom renderer on android and windows.
MyWebView.cs
public class MyWebView : WebView
{
public static readonly BindableProperty UrlProperty = BindableProperty.Create(
propertyName: "Url",
returnType: typeof(string),
declaringType: typeof(MyWebView),
defaultValue: default(string));
public string Url
{
get { return (string)GetValue(UrlProperty); }
set { SetValue(UrlProperty, value); }
}
}
MyWebViewRenderer.cs on ios
[assembly: ExportRenderer(typeof(MyWebView), typeof(MyWebViewRenderer))]
namespace MyApp.iOS.Renderer
{
public class MyWebViewRenderer : ViewRenderer<MyWebView, WKWebView>
{
WKWebView _wkWebView;
protected override void OnElementChanged(ElementChangedEventArgs<MyWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var config = new WKWebViewConfiguration();
_wkWebView = new WKWebView(Frame, config);
_wkWebView.NavigationDelegate = new MyNavigationDelegate();
SetNativeControl(_wkWebView);
}
}
public class MyNavigationDelegate : WKNavigationDelegate
{
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
string fontSize = "";
if (Device.Idiom == TargetIdiom.Phone)
{
fontSize = "250%";
}
else if (Device.Idiom == TargetIdiom.Tablet)
{
fontSize = "375%";
}
string stringsss = String.Format(#"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '{0}'", fontSize);
WKJavascriptEvaluationResult handler = (NSObject result, NSError err) =>
{
if (err != null)
{
System.Console.WriteLine(err);
}
if (result != null)
{
System.Console.WriteLine(result);
}
};
webView.EvaluateJavaScript(stringsss, handler);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == "Url")
{
Control.LoadHtmlString(Element.Url, null);
}
}
}
}
XAML and XAML.cs
<local:MyWebView
x:Name="web_view"
web_view.Url = "htmldata";
Output screenshot on ios device:
Sample HTML data added here. I need the same output on android and windows platforms, so requesting custom render codes for android and windows platforms.
If you want to present a string of HTML defined dynamically in code, you'll need to create an instance of HtmlWebViewSource:
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = #"copy the html string here";
web_view.Source = htmlSource;

UWP app crashes while performing an async method

I have created two methods in my BaseViewModel (MVVMLight App) to perform any async code with some logic:
public async Task PerformOperation(Func<Task> action)
{
IsBusy = true;
try
{
await action?.Invoke();
}
catch(Exception ex)
{
// logging is here
}
finally
{
IsBusy = false;
}
}
public async Task PerformOperation(params Operation[] actions)
{
IsBusy = true;
MultipleOperatrions = true;
OperationStatuses = new ObservableCollection<OperationStatus>();
try
{
foreach(var action in actions)
{
var status = new OperationStatus() { StatusText = action.StatusText };
OperationStatuses.Add(status);
try
{
await action?.AsyncAction();
status.Success = true;
}
catch
{
status.Success = false;
}
finally
{
status.IsFinished = true;
}
}
}
catch (Exception ex)
{
// logging is here
}
finally
{
await Task.Delay(1000);
IsBusy = false;
MultipleOperatrions = false;
OperationStatuses = new ObservableCollection<OperationStatus>();
}
}
My models:
public class Operation
{
public Func<Task> AsyncAction { get; private set; }
public string StatusText { get; private set; }
public Operation(Func<Task> action, string statusText)
{
AsyncAction = action;
StatusText = statusText;
}
}
My code of calling the methods in the view model:
...
private IAsyncCommand _buildCommand;
public IAsyncCommand BuildCommand => _buildCommand ?? (_buildCommand = new AsyncCommand(Build));
#endregion
#region Methods
public async Task Build()
{
// IT WORKS
// this method is used for performing only a single operation
// await PerformOperation(async () => { await Task.Delay(3000); });
// IT CRASHES THE APP
// for many tasks
await PerformOperation(new Operation(async () => { await Task.Delay(3000); }, "Preparing..."));
}
...
So, if I call PerformOperation to call just only a single method - it works fine. But it doesn't for the method of performing of several operations - the application just crashes without any exception or messages. I subscribed in App.cs to UnhandledException event to catch it but the app just crashes.

primefaces org.primefaces.component.diagram override

I have a problem with org.primefaces.component.diagram, i want to add an action when click on any overlay or connector, i make this using jquery, but the problem is that there is no identifier for the connection, after search i was able to get the ids of the 2 end points of the connection but if there is many connection between the same points then i cannot distinguish between them, i tried to override the diagram and add "connectionId" attribute on the connection but i got an exception in the front end :
Uncaught ReferenceError: connectionId590236 is not defined at eval (eval at (jquery.js.xhtml?ln=primefaces&v=5.2:14), :1:1488)
screenshot
The closet solution would be is to use setId on Element in the DefaultDiagramModel creation.
An example would be as the following:
Element elementA = new Element("A", "20em", "6em");
elementA.setId("element-a");
Element elementB = new Element("B", "10em", "18em");
elementB.setId("element-b");
Element elementC = new Element("C", "40em", "18em");
elementC.setId("element-c");
...
Since PrimeFaces doesn't provide the control you are searching for, and the original component comes from jsPlumb, you may rely on that to achieve what you are looking for.
First make sure that the <p:diagram> has a widgetVar value, es. diagramWV
An example would be the following:
$(document).ready(function () {
//timeout makes sure the component is initialized
setTimeout(function () {
for (var key in PF('diagramWV').canvas.getAllConnections()) {
if (PF('diagramWV').canvas.getAllConnections().hasOwnProperty(key)) {
//Elemenets Events
// on source just once
$(PF('diagramWV').canvas.getAllConnections()[key].source).off('click').on('click', function () {
console.log($(this).attr('id'))
});
// on target just once
$(PF('diagramWV').canvas.getAllConnections()[key].target).off('click').on('click', function () {
console.log($(this).attr('id'))
});
//Connection Event
PF('diagramWV').canvas.getAllConnections()[key].bind("click", function (conn) {
console.log("source " + conn.sourceId);
console.log("target " + conn.targetId);
});
}
}
}, 500);
});
Note: The canvas property of the widgetVar is the current instance of jsPlumbInstance
Here's an online demo, and a small working example on github.
finally i found an acceptable solution :
-> add an label overlay on the connection and set the identifier on it.
org.primefaces.model.diagram.Connection conn = new org.primefaces.model.diagram.Connection(
EndPointA, EndPointB);
LabelOverlay labelOverlay = new LabelOverlay(connection.getId(), "labelOverlayClass", 0.3);
conn.getOverlays().add(labelOverlay);
-> then add JS function to handle on dbclick action on the connection and get the id from its related overlay using the classes "._jsPlumb_overlay" and "._jsPlumb_hover"
<p:remoteCommand name="connectionClicked"
actionListener="#{yourBean.onConnectionDoubleClick}" />
<script type="text/javascript">
var connectionId;
$('._jsPlumb_connector').on('dblclick', function(e) {
$('._jsPlumb_overlay._jsPlumb_hover').each(function() {
connectionId = $(this).text();
});
connectionClicked([ { name : 'connectionId', value : connectionId } ]);
});
});
</script>
-> finally in the bean you extract the id and do whatever you want
public void onConnectionDoubleClick() {
Map<String, String> params = FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap();
String connectionId = params.get("connectionId");
if(StringUtils.isBlank(connectionId))
return;
.........
I was able to add a click event to Overlay by extending the primefaces Overlay class. If you make a change to the toJS() class (taking heavy inspiration from the Primefaces LabelOverLay) then you can write your own overlay with the jsplumb overlay constructor. Here's my implementation of a ClickableLabelOverlay.
public class ClickableLabelOverlay implements Overlay {
private String label;
private String styleClass;
private double location = 0.5;
private String onClick;
public ClickableLabelOverlay() {
}
public ClickableLabelOverlay(String label) {
this.label = label;
}
public ClickableLabelOverlay(String label, String styleClass, double location, String onClick) {
this(label);
this.styleClass = styleClass;
this.location = location;
this.onClick = onClick;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getStyleClass() {
return styleClass;
}
public void setStyleClass(String styleClass) {
this.styleClass = styleClass;
}
public double getLocation() {
return location;
}
public void setLocation(double location) {
this.location = location;
}
public String getOnClick() {
return onClick;
}
public void setOnClick(String onClick) {
this.onClick = onClick;
}
public String getType() {
return "Label";
}
public String toJS(StringBuilder sb) {
sb.append("['Label',{label:'").append(label).append("'");
if(styleClass != null) sb.append(",cssClass:'").append(styleClass).append("'");
if(location != 0.5) sb.append(",location:").append(location);
if(onClick != null) sb.append(",events:{click:function(labelOverlay, originalEvent){").append(onClick).append("}}");
sb.append("}]");
return sb.toString();
}
}
Put any javascript you want to execute inside of the onClick variable and it'll run when you click on the overlay. For convenience I added it to the set of default overlays for my diagram.
diagram.getDefaultConnectionOverlays().add(new ClickableLabelOverlay(...)

I am getting error in LoginAsync method during wp8 App development for sky drive

I am developing a windows phone 8 application to access sky drive. I am getting following error when I call LoginAsync() method-
An exception of type 'Microsoft.Live.LiveAuthException' occurred in mscorlib.ni.dll but was not handled in user code
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Live;
namespace SkyDriveApp
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
LiveConnectClient client;
public MainPage()
{
InitializeComponent();
}
public async void Auth()
{
string clientId = "My_client_id";
LiveAuthClient auth = new LiveAuthClient(clientId);
// var result = await auth.InitializeAsync(new[] { "wl.basic", "wl.signin", "wl.skydrive_update" });
var result = await auth.LoginAsync(new[] { "wl.basic", "wl.signin", "wl.skydrive_update" });
if (result.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(result.Session);
tbMessage.Text = "Connected!";
}
}
private void btnLogin_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
Auth();
}
}
}
I see that you are using provided login buton, try this:
In xaml:
<live:SignInButton Name="skyBtn" ClientId="your client ID" Scopes="wl.signin wl.skydrive wl.skydrive_update" Branding="Skydrive" TextType="Login"/>
In code behind:
private void skyBtn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(session);
tbMessage.Text = "Connected!";
}
else tbMessage.Text = "Not Connected!";
if (e.Error != null)
{
tbMessage.Text = "Not Connected!";
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Error.Message);
});
}
}

Http Post with Blackberry 6.0 issue

I am trying to post some data to our webservice(written in c#) and get the response. The response is in JSON format.
I am using the Blackberry Code Sample which is BlockingSenderDestination Sample. When I request a page it returns with no problem. But when I send my data to our webservice it does not return anything.
The code part that I added is :
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
What am i doing wrong? And what is the alternatives or more efficients way to do Post with Blackberry.
Regards.
Here is my whole code:
class BlockingSenderSample extends MainScreen implements FieldChangeListener {
ButtonField _btnBlock = new ButtonField(Field.FIELD_HCENTER);
private static UiApplication _app = UiApplication.getUiApplication();
private String _result;
public BlockingSenderSample()
{
_btnBlock.setChangeListener(this);
_btnBlock.setLabel("Fetch page");
add(_btnBlock);
}
public void fieldChanged(Field button, int unused)
{
if(button == _btnBlock)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://192.168.1.250/mobileServiceOrjinal.aspx"; //our webservice address
//String uriStr = "http://www.blackberry.com";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("name", URI.create(uriStr));//name for context is name. is it true?
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("ender"),
URI.create(uriStr)
);
}
//Dialog.inform( "1" );
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
if(response != null)
{
BSDResponse(response);
}
}
catch(Exception e)
{
//Dialog.inform( "ex" );
// process the error
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
}
private void BSDResponse(Message msg)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result = new String(data);
}
}
_app.invokeLater(new Runnable() {
public void run() {
_app.pushScreen(new HTTPOutputScreen(_result));
}
});
}
}
..
class HTTPOutputScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public HTTPOutputScreen(String message)
{
_rtfOutput.setText("Retrieving data. Please wait...");
add(_rtfOutput);
showContents(message);
}
// After the data has been retrieved, display it
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
HttpMessage does not extend ByteMessage so when you do:
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
it throws a ClassCastException. Here's a rough outline of what I would do instead. Note that this is just example code, I'm ignoring exceptions and such.
//Note: the URL will need to be appended with appropriate connection settings
HttpConnection httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
OutputStream out = httpConn.openOutputStream();
out.write(<YOUR DATA HERE>);
out.flush();
out.close();
InputStream in = httpConn.openInputStream();
//Read in the input stream if you want to get the response from the server
if(httpConn.getResponseCode() != HttpConnection.OK)
{
//Do error handling here.
}