How do I save user settings of combobox in C#? - csharpcodeprovider

I can't save User Setting of ComboBox like the TextBox or CheckBox? How to do that?

This is a simple example using .NET 5.
I created a form with a ComboBox ("comboBox1") and a Button ("bnAdd") to add a user-entered value to the ComboBox.
I added a setting with a name of "ThepphuongWCombo", type "String", and scope "User".
When the form is closed, the data from the ComboBox is saved, and the saved data is loaded when the app is run.
using System;
using System.Text.Json;
using System.Windows.Forms;
namespace SaveComboBoxToJson
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void bnAdd_Click(object sender, EventArgs e)
{
comboBox1.Items.Add(comboBox1.Text);
}
private void SaveUserData()
{
var json = JsonSerializer.Serialize(comboBox1.Items);
Properties.Settings.Default.ThepphuongWCombo = json;
Properties.Settings.Default.Save();
}
private void Form1_Load(object sender, EventArgs e)
{
// Show the location of the settings file being used in case you want to inspect it.
//var path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
//MessageBox.Show(path);
var cbData = Properties.Settings.Default.ThepphuongWCombo;
if (string.IsNullOrEmpty(cbData))
{
// Add some default values.
comboBox1.Items.Add("CCC");
comboBox1.Items.Add("DDD");
}
else
{
var itms = (object[])JsonSerializer.Deserialize(cbData, typeof(object[]));
comboBox1.Items.AddRange(itms);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
SaveUserData();
}
}
}

Related

How to check whether an item exists in the dynamodb table?

I am making an android app with login via facebook and custom signup. I am using AWS dynamodb to store the user data.
I am able to store the data from facebook and custom signup but unable to scan that data. Actually I want whenever a user come back to login with his/her credentials either custom or facebook, the app should check whether the entered fields present in the table or not. If it is unavailable then app will ask user to signup first.
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
Button login;
TextView signup;
TextView help;
EditText etUsername;
EditText etPassword;
String email;
String pass;
String email1;
String pass1;
private CognitoCachingCredentialsProvider credentialsProvider;
private CallbackManager callbackManager;
private LoginButton loginButton;
private ImageButton btnLoginFb;
private ProgressDialog progressDialog;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
login = (Button) findViewById(R.id.loginbutton);
signup = (TextView) findViewById(R.id.textViewsignup);
help = (TextView) findViewById(R.id.textViewHelp);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
login.setOnClickListener(this);
signup.setOnClickListener(this);
help.setOnClickListener(this);
Context mContext = this.getApplicationContext();
credentialsProvider = new CognitoCachingCredentialsProvider(
mContext, // get the context for the current activity
"us-east-1:*******************************",
Regions.US_EAST_1
);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginbutton:
email = etUsername.getText().toString();
pass = etPassword.getText().toString();
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
if (email != null && pass != null) {
Intent slideactivity = new Intent(MainActivity.this, Welcome.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
return;
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Oops");
// Setting Dialog Message
alertDialog.setMessage("No data found. You have to signup first!!!");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
startActivity(new Intent(MainActivity.this, SignUp.class));
}
});
// Showing Alert Message
alertDialog.show();
}
break;
case R.id.textViewsignup:
Intent slideactivity = new Intent(MainActivity.this, SignUp.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
break;
case R.id.textViewHelp:
Intent slideactivity1 = new Intent(MainActivity.this, LoginHelp.class);
Bundle bndlanimation1 =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity1, bndlanimation1);
break;
}
}
#Override
protected void onResume() {
super.onResume();
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email", "user_friends");
btnLoginFb = (ImageButton) findViewById(R.id.btnLoginFb);
btnLoginFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
loginButton.performClick();
loginButton.setPressed(true);
loginButton.invalidate();
loginButton.registerCallback(callbackManager, mCallBack);
loginButton.setPressed(false);
loginButton.invalidate();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progressDialog.dismiss();
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("response: ", response + "");
try {
user = new User();
user.facebookID = object.getString("id").toString();
pass = user.facebookID;
Log.e(pass, "id");
user.email = object.getString("email").toString();
email = user.email;
Log.e(email, "email");
user.name = object.getString("name").toString();
user.gender = object.getString("gender").toString();
PrefUtils.setCurrentUser(user, MainActivity.this);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "welcome " + user.name, Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
finish();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
new db().execute("");
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class db extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
Item item = new Item();
mapper.load(Item.class, email, pass);
if(item==null)
{
startActivity(new Intent(MainActivity.this,SignUp.class));
}
else{
item.setEmail(email);
item.setPass(pass);
mapper.save(item);
startActivity(new Intent(MainActivity.this,Welcome.class));
}
mapper.load(Item.class, email,pass);
if(item==null) {
startActivity(new Intent(MainActivity.this,SignUp.class));
}
else{
startActivity(new Intent(MainActivity.this,Welcome.class));
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Logcat:-
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMappingException: Null key found for public java.lang.String com.ediode.graphics3d.Item.getEmail()
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.getKey(DynamoDBMapper.java:434)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:387)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:466)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:350)
at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:339)
at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:333)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
            at java.lang.Thread.run(Thread.java:818)
I am stuck on this from 4,5 hours. It would be awesome if anyone can help me this stuff.
Thanks
What does your mapper class look like for item? I'm going to assume you have the email as a hash key with no range key because the login username should be unique. You only need the hash key of the object to load it using the load method. This is assuming that there is no range key.
Try using this.
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
// Use the password as the third parameter if it is a range key.
Item item = mapper.load(Item.class, email1);
if(item == null){
// That email is not in the database
}
else{
// Does exist in database, now compare password.
}

Displaying Multiple Images on a Single Google Glass Live Card

I'm creating a live card app that recieves PNGs from a php script running on my server in response to a request from scanning QR codes. At the moment, I simply replace the image on my Live card with the PNG I recieve from the server, but I would like to recieve and display multiple images from the server with each request.
Is there an approved way to show multiple images on a live card? I was thinking there may be a possiblity of generating a menu full of images that simply closed itself when clicked, but it seems like there might be a better alternative.
This is my code at the moment:
Current Code
import com.google.android.glass.timeline.LiveCard;
import com.google.android.glass.timeline.LiveCard.PublishMode;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.util.Base64;
import android.widget.RemoteViews;
public class iotSplashScreen extends Service {
private static final String LIVE_CARD_TAG = "iotSplashScreen";
private LiveCard mLiveCard;
private RemoteViews mLiveCardView;
public class iotBinder extends Binder {
public void changeImage(String change) {
try {
byte[] bob = Base64.decode(change, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bob, 0, bob.length);
if(bitmap != null) {
mLiveCardView.setImageViewBitmap(R.id.image_view_id, bitmap);
mLiveCard.setViews(mLiveCardView);
}
else
{
System.out.println("Daaang, dat bitmap was null doe");
}
}
catch (IllegalArgumentException e)
{
System.out.println("Base64 had an issues: " + e);
System.out.println(change);
}
catch (NullPointerException e)
{
System.out.println("Null Pointer: " + e);
}
}
}
private final iotBinder mBinder = new iotBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mLiveCard == null) {
mLiveCard = new LiveCard(this, LIVE_CARD_TAG);
mLiveCardView = new RemoteViews(getPackageName(), R.layout.iot_splash_screen);
mLiveCard.setViews(mLiveCardView);
// Display the options menu when the live card is tapped.
Intent menuIntent = new Intent(this, LiveCardMenuActivity.class);
mLiveCard.setAction(PendingIntent.getActivity(this, 0, menuIntent, 0));
mLiveCard.publish(PublishMode.REVEAL);
} else {
mLiveCard.navigate();
}
return START_STICKY;
}
#Override
public void onDestroy() {
if (mLiveCard != null && mLiveCard.isPublished()) {
mLiveCard.unpublish();
mLiveCard = null;
}
super.onDestroy();
}
}
Simply add more ImageViews, either in your layout file (iot_splash_screen) or programmatically.
With the resource IDs of your ImageViews, you can call setImageViewResource on each one.
Make sure that you are setting these images before calling setViews on your Live Card.

Change Activity into Fragment

I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
// List View Feed
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();

Silverlight: Parent ViewModel Property value to Child ViewModel property

I posted this question on the Silverlight forums, but haven't been able to get an answer to solve my issue, so I hope the guru's at SO can help!
Basically I have an entity property in my parent viewmodel. When this entity changes I need the ID of the entity in my child viewmodel. I have created a child control with a dependency property and created a binding in the constructor. I am trying to implement all this using MVVM and MEF.
My ParentViewModel:
[ExportPlugin(ViewModelTypes.ParentViewModel, PluginType.ViewModel)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ParentViewModel: ViewModelBase
{
private Person _currentPerson;
public Person CurrentPerson
{
get { return _currentPerson; }
private set
{
if (!ReferenceEquals(_currentPerson, value))
{
_currentPerson= value;
RaisePropertyChanged("CurrentPerson");
}
}
}
}
My ParentUserControl:
<UserControl x:Class="MyApp.ParentUserControl" x:Name="ParentControl">
<local:ChildUserControl PersonID="{Binding ElementName=ParentControl, Mode=TwoWay, Path=DataContext.CurrentPerson.ID}" />
</UserControl>
My ChildUserControl codebehind:
public partial class ChildUserControl : UserControl
{
#region Private Properties
private PluginCatalogService _catalogService = PluginCatalogService.Instance;
#endregion
#region Dependency Properties
public static readonly DependencyProperty PersonIDProperty =
DependencyProperty.Register("PersonID", typeof(int), typeof(ChildUserControl), new PropertyMetadata(OnPersonIDChanged));
#endregion
#region Public Properties
public int PersonID
{
get { return (int)GetValue(PersonIDProperty); }
set { SetValue(PersonIDProperty, value); }
}
#endregion
#region Constructor
public ChildUserControl()
{
InitializeComponent();
if (!ViewModelBase.IsInDesignModeStatic)
this.DataContext = _catalogService.FindPlugin(ViewModelTypes.ChildViewModel, PluginType.ViewModel);
this.SetBinding(PersonIDProperty, new Binding("PersonID") { Mode = BindingMode.TwoWay, Source = DataContext, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
}
#endregion
private static void OnPersonIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
...
}
My ChildViewModel:
[ExportPlugin(ViewModelTypes.ChildViewModel, PluginType.ViewModel)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ChildViewModel: ViewModelBase
{
private int _personID;
public int PersonID
{
get { return _personID; }
set
{
if (!ReferenceEquals(_personID, value))
{
_personID= value;
RaisePropertyChanged("PersonID");
}
}
}
}
I created the OnPersonIDChanged event to see if when the CurrentPerson entity changed, the change was being picked up in the ChildControl, which it is. It just isn't being picked up in the ChildControl ViewModel.
Any help is much appreciated.
Preferably, if you are using PRISM you can use the EventAggregator...
see http://msdn.microsoft.com/en-us/library/ff921122(v=pandp.40).aspx and https://compositewpf.codeplex.com/
Another option would be to hook (hack) onto the PropertyChanged
ViewModel1.PropertyChanged += (s, e) =>
{
if (e.PropertyName == "XXX")
{
ViewModel2.PropertyX = vm1.PropertY;
}
};

gwt CellList edit cell

CellList<Device> cellList = new CellList<Device>(new ItemCell());
where:
static class ItemCell extends AbstractCell<Device> {
#Override
public void render(Context context, Device device, SafeHtmlBuilder builder) {
if(device == null) {
return;
}
builder.appendHtmlConstant("<div>device.getId()</div>");
builder.appendHtmlConstant("<div>device.getName()</div>");
}
}
And now, I want to make an 'Edit' button, when I'll press on it - I want to see editable selected item. How can I do it? Please answer, who knows.
Use EditTextCell or ActionCell
addColumn(new EditTextCell(), "Name", new GetValue() {
#Override
public String getValue(IData contact) {
return contact.getName();
}
}, new FieldUpdater() {
#Override
public void update(int index, IData object, String value) {
try {
pandingChanges.add(new FirstNameChange(object, value));
} catch (Exception e) {
}
}
});
check this out or >THIS>
I followed the simple old way of doing this.
I used a cell list and a form attached to it. Every time you click on a row, row's data is loaded to the form. You can delete or edit the selected row via this form now.