Add new Item and Edit Item in silverlight DataForm not correctly updating SharePoint List - silverlight-4.0

I am trying to make a simple Silverlight application that will be hosted on a SharePoint site.
I am reading the information from the list "testlist" and I am trying to use a dataform control to edit, add and delete data from the list. I am able to delete just fine. When I try to add it adds a new entry with the data from the item previously viewed and I am unable to edit current Items whatsoever. Here is my code:
namespace SP2010
{
public partial class MainPage : UserControl
{
ClientContext context;
List customerList;
ListItemCollection allCustomers;
public MainPage()
{
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
InitializeComponent();
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = this;
context = new ClientContext(ApplicationContext.Current.Url);
customerList = context.Web.Lists.GetByTitle("testlist");
context.Load(customerList);
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =#"<View><Query></Query><RowLimit>1000</RowLimit></View>";
allCustomers = customerList.GetItems(camlQuery);
context.Load(allCustomers);
context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler(OnRequestSucceeded), new ClientRequestFailedEventHandler(OnRequestFailed));
}
private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
{
Dispatcher.BeginInvoke(DisplayListData);
}
private void OnRequestFailed(Object sender, ClientRequestFailedEventArgs args)
{
MessageBox.Show(args.ErrorDetails + " " + args.Message);
}
public ObservableCollection<SPCustomers> Printers
{
get
{
if (printers == null)
{
printers = new ObservableCollection<SPCustomers>();
foreach (ListItem item in allCustomers)
{
printers.Add(new SPCustomers
{
IPAddress = item["Title"].ToString(),
Make = item["make"].ToString(),
Model = item["model"].ToString(),
xCord = item["x"].ToString(),
yCord = item["y"].ToString(),
id = Convert.ToInt32(item["ID"].ToString())
});
}
}
return (printers);
}
}
private ObservableCollection<SPCustomers> printers;
private void DisplayListData()
{
dataForm1.DataContext = Printers;
}
private void dataForm1_EditEnded(object sender, DataFormEditEndedEventArgs e)
{
if (e.EditAction == DataFormEditAction.Commit)
{
if (dataForm1.IsItemChanged)
{
customerList = context.Web.Lists.GetByTitle("testlist");
SPCustomers printer = dataForm1.CurrentItem as SPCustomers;
ListItem items = customerList.GetItemById(printer.id);
items["Title"] = printer.IPAddress;
items["make"] = printer.Make;
items["model"] = printer.Model;
items["x"] = printer.xCord;
items["y"] = printer.yCord;
items.Update();
context.ExecuteQueryAsync(OnRequestSucceeded, OnRequestFailed);
}
}
}
private void dataForm1_AddingNewItem(object sender, DataFormAddingNewItemEventArgs e)
{
customerList = context.Web.Lists.GetByTitle("testlist");
SPCustomers printe = dataForm1.CurrentItem as SPCustomers;
ListItemCreationInformation itemcreationinfo = new ListItemCreationInformation();
ListItem items = customerList.AddItem(itemcreationinfo);
items["Title"] = printe.IPAddress;
items["make"] = printe.Make;
items["model"] = printe.Model;
items["x"] = printe.xCord;
items["y"] = printe.yCord;
items.Update();
context.ExecuteQueryAsync(OnRequestSucceeded, OnRequestFailed);
}
private void dataForm1_DeletingItem(object sender, System.ComponentModel.CancelEventArgs e)
{
SPCustomers printer = dataForm1.CurrentItem as SPCustomers;
ListItem oListItem = customerList.GetItemById(printer.id);
oListItem.DeleteObject();
context.ExecuteQueryAsync(OnRequestSucceeded, OnRequestFailed);
}
}
}
and my dataform:
<df:DataForm ItemsSource="{Binding}" Height="276" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataForm1" VerticalAlignment="Top" Width="376" EditEnded="dataForm1_EditEnded" AddingNewItem="dataForm1_AddingNewItem" DeletingItem="dataForm1_DeletingItem" CommandButtonsVisibility="All" />
Thanks for the help.
update: changed to this will answer in like 7 hours when it lets me

never mind I figured it out I changed my editended to this and deleted my addingNewitem method entirely. Now I just have to hide the ID field and it will be working perfectly
private void dataForm1_EditEnded(object sender, DataFormEditEndedEventArgs e)
{
if (e.EditAction == DataFormEditAction.Commit)
{
customerList = context.Web.Lists.GetByTitle("testlist");
SPCustomers printer = dataForm1.CurrentItem as SPCustomers;
ListItem items;
if (printer.id != 0)
{
items = customerList.GetItemById(printer.id);
}
else
{
ListItemCreationInformation itemcreationinfo = new ListItemCreationInformation();
items = customerList.AddItem(itemcreationinfo);
}
items["Title"] = printer.IPAddress;
items["make"] = printer.Make;
items["model"] = printer.Model;
items["x"] = printer.xCord;
items["y"] = printer.yCord;
items.Update();
context.ExecuteQueryAsync(OnRequestSucceeded, OnRequestFailed);
}
}

Related

Implement Infinite scroll with ViewModel And Retrofit in recyclerview

Before adding viewmodel & livedata , i successfully implemented infinity scroll with retrofit. But after adding viewmodel & livedata with Retrofit, My can't update recyclerview with new data call or viewmodel observer not update the list.
I simply want to infinite scrolling as my code does before. I add a global variable to reuse next page token. Am i missing anything or any sample to implement infinite recyclerview with viewmodel & retrofit will be awesome.
public static String NEXT_PAGE_URL = null;
I coded like that.
My Activity -> PlaceListActivity
placeRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
LogMe.d(tag, "onScrollStateChanged:: " + "called");
// check scrolling started or not
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LogMe.d(tag, "onScrolled:: " + "called");
super.onScrolled(recyclerView, dx, dy);
currentItem = layoutManager.getChildCount();
totalItems = layoutManager.getItemCount();
scrolledOutItems = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
LogMe.d(tag, "currentItem:: " + currentItem);
LogMe.d(tag, "totalItems:: " + totalItems);
LogMe.d(tag, "scrolledOutItems:: " + scrolledOutItems);
if (isScrolling && (currentItem + scrolledOutItems == totalItems)) {
LogMe.d(tag, "view:: " + "finished");
isScrolling = false;
if (ApplicationData.NEXT_PAGE_URL != null) {
LogMe.d(tag, "place adding:: " + " onScrolled called");
ll_loading_more.setVisibility(View.VISIBLE);
// todo: call web api here
callDataFromLocationAPi(type, ApplicationData.NEXT_PAGE_URL, currentLatLng);
} else {
LogMe.d(tag, "next_page_url:: " + " is null");
}
}
}
});
private void callDataFromLocationAPi(String type, String next_page_url, LatLng latLng) {
if (Connectivity.isConnected(activity)) {
showProgressDialog();
model.getNearestPlaces(type, next_page_url, latLng).
observe(activity, new Observer<List<PlaceDetails>>() {
#Override
public void onChanged(#Nullable List<PlaceDetails> placeDetails) {
ll_loading_more.setVisibility(View.GONE);
LogMe.i(tag, "callDataFromLocationAPi: onChanged called !");
hideProgressDialog();
if (placeDetails != null) {
placeDetailsList = placeDetails;
placeListAdapter.setPlaceList(placeDetails);
}
}
});
} else {
showAlertForInternet(activity);
}
}
In PlaceViewModel
public class PlaceViewModel extends AndroidViewModel {
//this is the data that we will fetch asynchronously
private MutableLiveData<List<PlaceDetails>> placeList;
private PlaceRepository placeRepository;
private String tag = getClass().getName();
public PlaceViewModel(Application application) {
super(application);
placeRepository = new PlaceRepository(application);
}
//we will call this method to get the data
public MutableLiveData<List<PlaceDetails>> getNearestPlaces(String type,
String next_page_token,
LatLng latLng) {
//if the list is null
if (placeList == null) {
placeList = new MutableLiveData<>();
//we will load it asynchronously from server in this method
//loadPlaces(type, next_page_token, latLng);
placeList = placeRepository.getNearestPlacesFromAPI(type, next_page_token, latLng);
}
//finally we will return the list
return placeList;
}
}
In my PlaceRepository.java looks
public class PlaceRepository {
private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
// Since we didn't alter the table, there's nothing else to do here.
}
};
private PlaceDatabase placeDatabase;
private CurrentLocation currentLocation = null;
private String tag = getClass().getName();
//this is the data that we will fetch asynchronously
private MutableLiveData<List<PlaceDetails>> placeList;
public PlaceRepository(Context context) {
placeDatabase = PlaceDatabase.getDatabase(context);
//addMigrations(MIGRATION_1_2)
placeList =
new MutableLiveData<>();
}
public MutableLiveData<List<PlaceDetails>> getNearestPlacesFromAPI(String type, final String next_page_token, LatLng latLng) {
List<PlaceDetails> placeDetailsList = new ArrayList<>();
try {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<Example> call = apiService.getNearbyPlaces(type,
latLng.latitude + "," +
latLng.longitude, ApplicationData.PROXIMITY_RADIUS,
ApplicationData.PLACE_API_KEY, next_page_token);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
try {
Example example = response.body();
ApplicationData.NEXT_PAGE_URL = example.getNextPageToken();
// next_page_url = example.getNextPageToken();
LogMe.i(tag, "next_page_url:" + ApplicationData.NEXT_PAGE_URL);
if (example.getStatus().equals("OK")) {
LogMe.i("getNearbyPlaces::", " --- " + response.toString() +
response.message() + response.body().toString());
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < example.getResults().size(); i++) {
Double lat = example.getResults().get(i).getGeometry().getLocation().getLat();
Double lng = example.getResults().get(i).getGeometry().getLocation().getLng();
String placeName = example.getResults().get(i).getName();
String vicinity = example.getResults().get(i).getVicinity();
String icon = example.getResults().get(i).getIcon();
String place_id = example.getResults().get(i).getPlaceId();
PlaceDetails placeDetails = new PlaceDetails();
if (example.getResults().get(i).getRating() != null) {
Double rating = example.getResults().get(i).getRating();
placeDetails.setRating(rating);
}
//List<Photo> photoReference = example.getResults().
// get(i).getPhotos();
placeDetails.setName(placeName);
placeDetails.setAddress(vicinity);
placeDetails.setLatitude(lat);
placeDetails.setLongitude(lng);
placeDetails.setIcon(icon);
placeDetails.setPlace_id(place_id);
//placeDetails.setPlace_type(place_type_title);
double value = ApplicationData.
DISTANCE_OF_TWO_LOCATION_IN_KM(latLng.latitude, latLng.longitude, lat, lng);
//new DecimalFormat("##.##").format(value);
placeDetails.setDistance(new DecimalFormat("##.##").format(value));
String ph = "";
if (example.getResults().
get(i).getPhotos() != null) {
try {
List<Photo> photos = example.getResults().
get(i).getPhotos();
//JSONArray array = new JSONArray(example.getResults().
//get(i).getPhotos());
//JSONObject jsonObj = new JSONObject(array.toString());
//ph = jsonObj.getString("photo_reference");
ph = photos.get(0).getPhotoReference();
//LogMe.i(tag, "\n" + ph);
} catch (Exception e) {
e.printStackTrace();
//placeDetails.setPicture_reference(ph);
//PLACE_DETAILS_LIST.add(placeDetails);
//LogMe.i(tag, "#### Exception Occureed ####");
ph = "";
//continue;
}
}
placeDetails.setPicture_reference(ph);
placeDetailsList.add(placeDetails);
placeList.postValue(placeDetailsList);
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Log.e("onFailure", t.toString());
}
});
} catch (RuntimeException e) {
//hideProgressDialog();
Log.d("onResponse", "RuntimeException is an error");
e.printStackTrace();
} catch (Exception e) {
Log.d("onResponse", "Exception is an error");
}
return placeList;
}
}
I precise code due to question simplicity.
Though you already use android-jetpack, take a look at Paging library. It's specially designed for building infinite lists using RecyclerView.
Based on your source code, I'd say that you need PageKeyedDataSource, here is some example which includes info about how to implement PageKeyedDataSource -
7 steps to implement Paging library in Android
If talking about cons of this approach:
You don't need anymore to observe list scrolling (library doing it for you), you just need to specify your page size in the next way:
PagedList.Config myPagingConfig = new PagedList.Config.Builder()
.setPageSize(50)
.build();
From documentation:
Page size: The number of items in each page.
Your code will be more clear, you'll get rid of your RecyclerView.OnScrollListener
ViewModel code will be shorter, it's will provide only PagedList:
#NonNull
LiveData<PagedList<ReviewSection>> getReviewsLiveData() {
return reviewsLiveData;
}

How to use MetaTrader4.Manager.Wrapper to listening the event of TradeAdded/TradeClosed/TradeDeleted

I wand to listening the event of TradeAdded/TradeClosed/TradeDeleted ,that's my code:
public partial class Demo : Form
{
public static ConnectionParameters conParam = new ConnectionParameters();
public static ClrWrapper mt;
private void Hedera_Load(object sender, EventArgs e)
{
Login();
}
public void Login()
{
conParam = new ConnectionParameters
{
Login = serverConfig.ManageAccount,
Password = serverConfig.ManagePassword,
Server = serverConfig.ManageServer
};
mt = new ClrWrapper(conParam);
List<UserRecord> users = mt.UsersRequest().ToList();
mt.TradeClosed +=new TradeRecordUpdated(this.MyTradeClosed);
mt.TradeDeleted += new TradeRecordUpdated(this.MyTradeDeleted);
mt.TradeAdded += new TradeRecordUpdated(this.MyTradeAdded);
}
public void MyTradeAdded(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeAdded");
}
public void MyTradeClosed(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeClosed");
}
public void MyTradeDeleted(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeDeleted");
}
}
When i trade on the MetaTrader4 client ,I want to get the notify in my C# program.
“UsersRequest” is ok now,but the event does not run.
Where is wrong in my code ?
Can you write an example for me?
Those events are fired only in extended pumping mode. so you have to switch:
public void Login()
{
conParam = new ConnectionParameters
{
Login = serverConfig.ManageAccount,
Password = serverConfig.ManagePassword,
Server = serverConfig.ManageServer
};
mt = new ClrWrapper(conParam);
List<UserRecord> users = mt.UsersRequest().ToList();
mt.TradeClosed +=new TradeRecordUpdated(this.MyTradeClosed);
mt.TradeDeleted += new TradeRecordUpdated(this.MyTradeDeleted);
mt.TradeAdded += new TradeRecordUpdated(this.MyTradeAdded);
metatrader.PumpingSwitchEx();
}
However, after switching into pumping mode, you won't be able to use non pumping methods

GridView: Get Index on Drop Event

How do I get the index or position where a GridViewItem is being dropped inside the OnDrop event of the GridView? As I have read around that it is possible with GridView.ItemContainerGenerator.ContainerFromItem(item) but for me ItemContainerGenerator is null.
This is my current code:
void gridMain_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
var item = e.Items.First();
var source = sender;
e.Data.Properties.Add("item", item);
e.Data.Properties.Add("source", sender);
}
void gridMain_Drop(object sender, DragEventArgs e)
{
var item = e.Data.Properties.Where(p => p.Key == "item").Single();
object source;
e.Data.Properties.TryGetValue("source", out source);
var s = ((GridView)source).ItemContainerGenerator.ContainerFromItem(item);
}
Any hint or suggestion will be really helpful.
Use GetPosition method of DragEventArgs to find the position where item was dropped and then calculate the actual index, see code snippet below for the handler. Similar question was asked here using this MSDN example as an answer (Scenario 3).
private void GridView_Drop(object sender, DragEventArgs e)
{
GridView view = sender as GridView;
// Get your data
var item = e.Data.Properties.Where(p => p.Key == "item").Single();
//Find the position where item will be dropped in the gridview
Point pos = e.GetPosition(view.ItemsPanelRoot);
//Get the size of one of the list items
GridViewItem gvi = (GridViewItem)view.ContainerFromIndex(0);
double itemHeight = gvi.ActualHeight + gvi.Margin.Top + gvi.Margin.Bottom;
//Determine the index of the item from the item position (assumed all items are the same size)
int index = Math.Min(view.Items.Count - 1, (int)(pos.Y / itemHeight));
// Call your viewmodel with the index and your data.
}
EDIT: Please, consider this as just a prototype. I tried it and it has worked properly, but you may revise it according to your scenario (tweak delay timeout, differentiate more TaskCompletionSource at once, etc.).
The idea is to start a task after Remove action to check whether the item was only removed, or reordered.
private async void observableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
object removedItem = e.OldItems[0];
var reorderTask = NoticeReorderAsync(removedItem);
try
{
var task = await Task.WhenAny(reorderTask, Task.Delay(100));
if (reorderTask == task)
{
// removedItem was in fact reordered
Debug.WriteLine("reordered");
}
else
{
TryCancelReorder();
// removedItem was really removed
Debug.WriteLine("removedItem");
}
}
catch (TaskCanceledException ex)
{
Debug.WriteLine("removedItem (from exception)");
}
finally
{
tcs = null;
}
}
else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
object addedItem = e.NewItems[0];
bool added = NoticeAdd(addedItem);
if (added)
{
// addedItem was just added, not reordered
Debug.WriteLine("added");
}
}
}
TaskCompletionSource<object> tcs;
private void TryCancelReorder()
{
if (tcs != null)
{
tcs.TrySetCanceled();
tcs = null;
}
}
private Task NoticeReorderAsync(object removed)
{
TryCancelReorder();
tcs = new TaskCompletionSource<object>(removed);
return tcs.Task;
}
private bool NoticeAdd(object added)
{
if (tcs != null)
{
try
{
if (object.Equals(tcs.Task.AsyncState, added))
{
tcs.TrySetResult(added);
return false;
}
else
{
tcs.TrySetCanceled();
return true;
}
}
finally
{
tcs = null;
}
}
return true;
}

Cannot use EWS.dll with ExchangeWebServices namespace

This link outlines what I am trying to do
http://msdn.microsoft.com/en-us/library/aa494212(v=exchg.140).aspx
HOW do I get the right DLL for this? This is really hard for some reason....
I am trying to use the class
GetUserAvailabilityResponseType
the only DLLs I can get that have anything to do with exchange are
Microsoft.Exchange.WebServices.dll
For a while I thought this was EWS.dll, however it does not contain the namespace 'ExchangeWebServices'. Which I need to access the class, it only contains the Microsoft.Exchange.WebServices.Data namespace which does not have my required classes.
can some please tell me how I can get the right namespace?
Thanks.
You have the right DLL, but the link you refer to is a type defined for the older EWS Proxy classes, which don't have a DLL per se, but are defined via the wsdl command. Everything being equal, you don't want to use these old classes, but rather the new EWS Managed API, which is provided by the DLL in question. The equivalent functionality (availability) is provided there, and a placed to start looking into how to use it is here:
public partial class ServiceDialog : IDisposable
{
ExchangeService _service = null;
public ExchangeService CurrentService
{
get
{
return _service;
}
set
{
_service = value;
}
}
EwsEditorAppSettings _CurrentAppSettings = null;
public EwsEditorAppSettings CurrentAppSettings
{
get
{
return _CurrentAppSettings;
}
set
{
_CurrentAppSettings = value;
}
}
public void Dispose()
{
}
private List<ConnectingIdType> connectingIdCombo = new List<ConnectingIdType>();
private List<ExchangeVersion> exchangeVersionCombo = new List<ExchangeVersion>();
public ServiceDialog()
{
//InitializeComponent();
//EwsEditorAppSettings oAppSettings = null;
//ExchangeService service = null;
//DialogResult result = ServiceDialog.ShowDialog(ref service, ref oAppSettings);
}
/// <summary>
/// A passed ExchangeService can be displayed for editing or a new
/// service will be returned after created using this dialog.
/// </summary>
/// <param name="service">ExchangeService to be returned or displayed</param>
/// <returns>DialogResult indicating the user action which closed the dialog</returns>
public void ShowDialog(ref ExchangeService service, ref EwsEditorAppSettings oAppSettings)
{
ServiceDialog dialog = new ServiceDialog();
if (service != null)
{
dialog.CurrentService = service;
}
if (oAppSettings != null)
{
dialog.CurrentAppSettings = oAppSettings;
}
service = dialog.CurrentService;
oAppSettings = dialog.CurrentAppSettings;
//return res;
}
//private void BtnOK_Click(object sender, EventArgs e)
public void OnstartLogon( string strusername,string strpassword,string strdomain)
{
// Validation for credential input...
string UserName = "";
string Password = "";
string ServerName= "";
string DomainName= "";
string strMakeUrl = "https://" + strdomain + "/EWS/exchange.asmx";
Uri ExchangeUrl = new Uri(strMakeUrl);
UserName = strusername;
Password = strpassword;
DomainName = strdomain;
//if (rdoCredentialsUserSpecified.Checked && (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0))
//{
// ErrorDialog.ShowInfo(DisplayStrings.MSG_SPECIFY_CREDS);
// return;
//}
//// Validation for Autodiscover input...
//if (this.rdoAutodiscoverEmail.Checked && String.IsNullOrEmpty(this.AutodiscoverEmailText.Text))
//{
// ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
// return;
//}
//// Validation for URL input...
//if (this.rdoServiceUrl.Checked && String.IsNullOrEmpty(this.ExchangeServiceURLText.Text))
//{
// ErrorDialog.ShowInfo(DisplayStrings.MSG_SERVICE_REQ);
// return;
//}
//// Validation for Impersonation input...
//if (this.ImpersonationCheck.Checked && (String.IsNullOrEmpty(this.ImpersonatedIdTextBox.Text) || !this.connectingIdCombo.SelectedItem.HasValue))
//{
// ErrorDialog.ShowInfo(DisplayStrings.MSG_IMPERSON_REQ);
// return;
//}
try
{
//Cursor = System.Windows.Forms.Cursors.WaitCursor;
EwsProxyFactory.RequestedExchangeVersion = ExchangeVersion.Exchange2013;// exchangeVersionCombo.SelectedItem;
EwsProxyFactory.OverrideTimezone = GlobalSettings.OverrideTimezone;
EwsProxyFactory.SelectedTimeZoneId = GlobalSettings.SelectedTimeZoneId;
EwsProxyFactory.AllowAutodiscoverRedirect = GlobalSettings.AllowAutodiscoverRedirect;
EwsProxyFactory.UseDefaultCredentials = false;// this.rdoCredentialsDefaultWindows.Checked;
//if (this.rdoCredentialsDefaultWindows.Checked)
//{
// EwsProxyFactory.AuthenticationMethod = RequestedAuthType.DefaultAuth;
//}
EwsProxyFactory.CredentialsUserSpecified = true;// this.rdoCredentialsUserSpecified.Checked;
//if (this.rdoCredentialsUserSpecified.Checked)
if(true)
{
EwsProxyFactory.AuthenticationMethod = RequestedAuthType.SpecifiedCredentialsAuth;
}
if (false/*this.rdoCredentialsOAuth.Checked*/)
{
EwsProxyFactory.AuthenticationMethod = RequestedAuthType.oAuth;
}
// MailboxBeingAccessed
switch (EwsProxyFactory.AuthenticationMethod)
{
case RequestedAuthType.DefaultAuth:
//AutodiscoverEmailText.Text = UserPrincipal.Current.EmailAddress;
break;
case RequestedAuthType.SpecifiedCredentialsAuth:
//if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
// EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
//else
// EwsProxyFactory.MailboxBeingAccessed = this.txtUserName.Text.Trim();
//break;
EwsProxyFactory.MailboxBeingAccessed = UserName;
break;
case RequestedAuthType.oAuth:
//EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim(); // override later in ewsproxyfactory
EwsProxyFactory.MailboxBeingAccessed = UserName; // override later in ewsproxyfactory
break;
}
//if (this.AutodiscoverEmailText.Text.Trim().Length != 0)
// EwsProxyFactory.MailboxBeingAccessed = this.AutodiscoverEmailText.Text.Trim();
//if (this.ImpersonationCheck.Checked) // Override
// EwsProxyFactory.MailboxBeingAccessed = ImpersonatedIdTextBox.Text.Trim();
EwsProxyFactory.UserImpersonationSelected = false;// this.ImpersonationCheck.Checked;
//EwsProxyFactory.UserToImpersonate = this.ImpersonatedIdTextBox.Text // set below
EwsProxyFactory.ImpersonationType = "SmtpAddress";//this.connectingIdCombo.SelectedItem.Value.ToString();
EwsProxyFactory.ImpersonatedId = "";//this.ImpersonatedIdTextBox.Text.Trim();
EwsProxyFactory.UseoAuth = false;//this.rdoCredentialsOAuth.Checked;
EwsProxyFactory.oAuthRedirectUrl = "https://microsoft.com/EwsEditor";//this.txtOAuthRedirectUri.Text.Trim();
EwsProxyFactory.oAuthClientId = "0e4bf2e2-aa7d-46e8-aa12-263adeb3a62b";//this.txtOAuthAppId.Text.Trim();
EwsProxyFactory.oAuthServerName = ServerName;//this.txtOAuthServerName.Text.Trim();
EwsProxyFactory.oAuthAuthority = "https://login.windows.net/common";//this.txtOAuthAuthority.Text.Trim();
EwsProxyFactory.EnableScpLookup = GlobalSettings.EnableScpLookups;
EwsProxyFactory.PreAuthenticate = GlobalSettings.PreAuthenticate;
EwsProxyFactory.OverrideTimeout = GlobalSettings.OverrideTimeout;
EwsProxyFactory.Timeout = GlobalSettings.Timeout;
EwsProxyFactory.UserAgent = GlobalSettings.UserAgent;
EwsProxyFactory.UserName = UserName;//this.txtUserName.Text.Trim();
// EwsProxyFactory.Password = this.txtPassword.Text.Trim(); // Don't keep.
EwsProxyFactory.Domain = DomainName;//this.txtDomain.Text.Trim();
EwsProxyFactory.SetDefaultProxy = GlobalSettings.SetDefaultProxy;
EwsProxyFactory.BypassProxyForLocalAddress = GlobalSettings.BypassProxyForLocalAddress;
EwsProxyFactory.SpecifyProxySettings = GlobalSettings.SpecifyProxySettings;
EwsProxyFactory.ProxyServerName = GlobalSettings.ProxyServerName;
EwsProxyFactory.ProxyServerPort = GlobalSettings.ProxyServerPort;
EwsProxyFactory.OverrideProxyCredentials = GlobalSettings.OverrideProxyCredentials;
EwsProxyFactory.ProxyServerUser = GlobalSettings.ProxyServerUser;
EwsProxyFactory.ProxyServerPassword = GlobalSettings.ProxyServerPassword;
EwsProxyFactory.ProxyServerDomain = GlobalSettings.ProxyServerDomain;
//EwsProxyFactory.EwsUrl = this.rdoAutodiscoverEmail.Checked ?
// null : new Uri(ExchangeServiceURLText.Text.Trim());
EwsProxyFactory.EwsUrl = ExchangeUrl;
//EwsProxyFactory.UserToImpersonate = this.ImpersonationCheck.Checked ?
// new ImpersonatedUserId(this.connectingIdCombo.SelectedItem.Value, this.ImpersonatedIdTextBox.Text.Trim()) : null;
EwsProxyFactory.UserToImpersonate = null;
EwsProxyFactory.SetXAnchorMailbox = false;//this.chkSetXAnchorMailbox.Checked;
EwsProxyFactory.XAnchorMailbox = null;//this.txtXAnchorMailbox.Text.Trim();
EwsProxyFactory.SetXPublicFolderMailbox = null;//;this.chkSetXPublicFolderMailbox.Checked;
EwsProxyFactory.XPublicFolderMailbox = "";//this.txtXPublicFolderMailbox.Text.Trim();
EwsProxyFactory.EnableAdditionalHeader1 = GlobalSettings.EnableAdditionalHeader1;
EwsProxyFactory.AdditionalHeader1 = GlobalSettings.AdditionalHeader1;
EwsProxyFactory.AdditionalHeaderValue1 = GlobalSettings.AdditionalHeaderValue1;
EwsProxyFactory.EnableAdditionalHeader2 = GlobalSettings.EnableAdditionalHeader2;
EwsProxyFactory.AdditionalHeader2 = GlobalSettings.AdditionalHeader2;
EwsProxyFactory.AdditionalHeaderValue2 = GlobalSettings.AdditionalHeaderValue2;
EwsProxyFactory.EnableAdditionalHeader3 = GlobalSettings.EnableAdditionalHeader3;
EwsProxyFactory.AdditionalHeader3 = GlobalSettings.AdditionalHeader3;
EwsProxyFactory.AdditionalHeaderValue3 = GlobalSettings.AdditionalHeaderValue3;
EwsProxyFactory.AddTimeZoneContext = GlobalSettings.AddTimeZoneContext;
EwsProxyFactory.SelectedTimeZoneContextId = GlobalSettings.SelectedTimeZoneContextId;
//EwsProxyFactory.ServiceEmailAddress = this.AutodiscoverEmailText.Text.Trim();
EwsProxyFactory.UseAutoDiscover = false;//this.rdoAutodiscoverEmail.Checked;
//EwsProxyFactory.ServiceCredential = rdoCredentialsUserSpecified.Checked ?
// new NetworkCredential(
// this.txtUserName.Text.Trim(),
// this.txtPassword.Text.Trim(), // This will fail on passwords ending with whitespace
// this.txtDomain.Text.Trim()) :
// null;
// ----- Set Credentials ----
EwsProxyFactory.ServiceCredential = null;
EwsProxyFactory.ServiceNetworkCredential = null;
if (false/*rdoCredentialsDefaultWindows.Checked*/)
{
EwsProxyFactory.ServiceCredential = (NetworkCredential)CredentialCache.DefaultCredentials;
EwsProxyFactory.ServiceNetworkCredential = (NetworkCredential)CredentialCache.DefaultCredentials;
}
if (true/*rdoCredentialsUserSpecified.Checked*/)
{
NetworkCredential oNetworkCredential = new NetworkCredential(
UserName/*this.txtUserName.Text.Trim()*/,
Password,/*this.txtPassword.Text.Trim()*/ // This will fail on passwords ending with whitespace
DomainName);/*this.txtDomain.Text.Trim())*/
EwsProxyFactory.ServiceCredential = oNetworkCredential;
EwsProxyFactory.ServiceNetworkCredential = oNetworkCredential;
}
if (false/*this.rdoCredentialsOAuth.Checked*/)
{
AuthenticationHelper oAH = new AuthenticationHelper();
EwsProxyFactory.ServiceCredential = oAH.Do_OAuth(ref EwsProxyFactory.MailboxBeingAccessed, ref EwsProxyFactory.AccountAccessingMailbox,
EwsProxyFactory.oAuthAuthority, EwsProxyFactory.oAuthClientId, EwsProxyFactory.oAuthRedirectUrl, EwsProxyFactory.oAuthServerName);
//EwsProxyFactory.AccountAccessingMailbox
//EwsProxyFactory.MailboxBeingAccessed = EwsProxyFactory.AccountAccessingMailbox;
}
// ---- Autodiscover ----
if (false/*this.rdoAutodiscoverEmail.Checked*/)
{
EwsProxyFactory.DoAutodiscover();
}
// ---- New service & app settings ----
CurrentService = EwsProxyFactory.CreateExchangeService();
// ---- Save settings ----
EwsEditorAppSettings oAppSettings = new EwsEditorAppSettings();
EwsProxyFactory.SetAppSettingsFromProxyFactory(ref oAppSettings);
CurrentAppSettings = oAppSettings;
//CurrentAppSettings.MailboxBeingAccessed = EwsProxyFactory.AccountAccessingMailbox;
// CurrentAppSettings
// EwsProxyFactory.AccountAccessingMailbox
// ---- Do a basic test to be sure that the mailbox can be reached with an EWS call ----
CurrentService.TestExchangeService();
CurrentService.OnSerializeCustomSoapHeaders += m_Service_OnSerializeCustomSoapHeaders;
//DialogResult = DialogResult.OK;
}
finally
{
//Cursor = System.Windows.Forms.Cursors.Default;
}
}
private Uri Uri(string p)
{
throw new NotImplementedException();
}
///// <summary>
///// This is used for adding soap headers not exposed in the EWS Managed API
///// </summary>
///// <param name="oRequest"></param>
public void m_Service_OnSerializeCustomSoapHeaders(XmlWriter writer)
{
// Add TimeZoneDefinition...
// http://blogs.msdn.com/b/emeamsgdev/archive/2014/04/23/ews-missing-soap-headers-when-using-the-ews-managed-api.aspx
if (EwsProxyFactory.AddTimeZoneContext == true)
{
writer.WriteRaw(Environment.NewLine + " <t:TimeZoneContext><t:TimeZoneDefinition Id=\"" + GlobalSettings.SelectedTimeZoneContextId + "\"/></t:TimeZoneContext>" + Environment.NewLine);
}
}
private void ChkCredentials_CheckedChanged(object sender, EventArgs e)
{
}
private void ChkImpersonation_CheckedChanged(object sender, EventArgs e)
{
// ImpersonatedIdTextBox.Text = string.Empty;
//this.connectingIdCombo.Enabled = ImpersonationCheck.Checked;
//ImpersonatedIdTextBox.Enabled = ImpersonationCheck.Checked;
//lblImpId.Enabled = ImpersonationCheck.Checked;
//lblImpIdType.Enabled = ImpersonationCheck.Checked;
}
/// <summary>
/// Display the GetMailboxNameDialog to get the SMTP address and
/// perform Autodiscover operation to get the EWS service URL.
/// </summary>
/// <param name="sender">The parameter is not used.</param>
/// <param name="e">The parameter is not used.</param>
private void BtnAutodiscover_Click(object sender, EventArgs e)
{
//Mailbox mbx = null;
//// If the result isn't OK do nothing.
//if (GetMailboxNameDialog.ShowDialog(ref mbx) != DialogResult.OK)
//{
// return;
//}
//try
//{
// this.Cursor = Cursors.WaitCursor;
// ExchangeService tempService = new ExchangeService(ExchangeVersion.Exchange2010);
// tempService.TraceEnabled = true;
// tempService.TraceEnablePrettyPrinting = true;
// tempService.TraceListener = new EWSEditor.Logging.EwsTraceListener();
// if (GlobalSettings.AllowAutodiscoverRedirect)
// {
// tempService.AutodiscoverUrl(
// mbx.Address,
// delegate(string url) { return true; });
// }
// else
// {
// tempService.AutodiscoverUrl(mbx.Address);
// }
// AutodiscoverEmailText.Text = mbx.Address;
// ExchangeServiceURLText.Text = tempService.Url.ToString();
//}
//finally
//{
// this.Cursor = Cursors.Default;
//}
}
private void ServiceDialog_Load(object sender, EventArgs e)
{
//this.exchangeVersionCombo.TransformComboBox(this.TempExchangeVersionCombo);
//this.exchangeVersionCombo.HasEmptyItem = true;
//this.exchangeVersionCombo.Text = "Exchange2013";
//this.connectingIdCombo.TransformComboBox(this.TempConnectingIdCombo);
//this.connectingIdCombo.SelectedItem = ConnectingIdType.SmtpAddress;
//// If CurrentService is already set then we are editing an
//// existing ExchangeService and need to load it first.
//if (this.CurrentService != null)
//{
// if (this.CurrentService.Url != null)
// {
// this.rdoAutodiscoverEmail.Checked = false;
// this.ExchangeServiceURLText.Text = this.CurrentService.Url.ToString();
// }
// this.exchangeVersionCombo.SelectedItem = this.CurrentService.RequestedServerVersion;
// if (this.CurrentService.Credentials != null)
// {
// this.rdoCredentialsUserSpecified.Checked = true;
// NetworkCredential cred = this.CurrentService.GetNetworkCredential();
// this.txtUserName.Text = cred.UserName;
// this.txtPassword.Text = cred.Password;
// this.txtDomain.Text = cred.Domain;
// }
// if (this.CurrentService.ImpersonatedUserId != null)
// {
// this.ImpersonationCheck.Checked = true;
// this.connectingIdCombo.SelectedItem = this.CurrentService.ImpersonatedUserId.IdType;
// this.ImpersonatedIdTextBox.Text = this.CurrentService.ImpersonatedUserId.Id;
// }
//}
//SetAutoDiscoverSelection();
//SetAuthEnablement();
}
private void chkUseSpecifiedTimezone_CheckedChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
private void btnOptions_Click(object sender, EventArgs e)
{
// OptionsDialog.ShowDialog();
}
private void cmboTimeZoneIds_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void rdoAutodiscoverEmail_CheckedChanged(object sender, EventArgs e)
{
SetAutoDiscoverSelection();
}
private void SetAutoDiscoverSelection()
{
if (true/*this.rdoAutodiscoverEmail.Checked == true*/)
{
//this.AutodiscoverEmailText.Text = string.Empty;
//this.AutodiscoverEmailText.Enabled = true;
//this.lblAutodiscoverEmailDesc.Enabled = true;
//this.AutodiscoverEmailText.Focus();
//this.ExchangeServiceURLText.Enabled = false;
//this.lblExchangeServiceURLTextDesc.Enabled = false;
//this.btnDefault365Settings.Enabled = false;
}
if (false/*this.rdoServiceUrl.Checked == true*/)
{
//this.ExchangeServiceURLText.Text = string.Empty;
//this.ExchangeServiceURLText.Enabled = true;
//this.lblExchangeServiceURLTextDesc.Enabled = true;
//this.ExchangeServiceURLText.Focus();
//this.btnDefault365Settings.Enabled = true;
//this.AutodiscoverEmailText.Enabled = false;
//this.lblAutodiscoverEmailDesc.Enabled = false;
}
}
private void rdoServiceUrl_CheckedChanged(object sender, EventArgs e)
{
SetAutoDiscoverSelection();
}
private void lblImpId_Click(object sender, EventArgs e)
{
}
//private void panel1_Paint(object sender, PaintEventArgs e)
//{
//}
private void txtDefaultSmtp_Click(object sender, EventArgs e)
{
// AutodiscoverEmailText.Text = UserPrincipal.Current.EmailAddress;
}
//private void panel2_Paint(object sender, PaintEventArgs e)
//{
//}
private void btnDefault365Settings_Click(object sender, EventArgs e)
{
//ExchangeServiceURLText.Text = "https://outlook.office365.com/EWS/Exchange.asmx";
}
private void btnDefaultSmtp_Click(object sender, EventArgs e)
{
// AutodiscoverEmailText.Text = UserPrincipal.Current.EmailAddress;
}
private void TempConnectingIdCombo_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void chkSetXAnchorMailbox_CheckedChanged(object sender, EventArgs e)
{
//txtXAnchorMailbox.Enabled = chkSetXAnchorMailbox.Checked;
//// Default ImpersonatedIdTextBox ImpersonationCheck
//if (chkSetXAnchorMailbox.Checked == true && txtXAnchorMailbox.Text.Trim().Length == 0)
//{
// if (ImpersonationCheck.Checked == true)
// {
// if (ImpersonatedIdTextBox.Text.Contains("#"))
// txtXAnchorMailbox.Text = ImpersonatedIdTextBox.Text;
// }
// else
// {
// if (rdoAutodiscoverEmail.Checked == true && AutodiscoverEmailText.Text.Contains("#"))
// {
// txtXAnchorMailbox.Text = AutodiscoverEmailText.Text;
// }
// else
// {
// if (txtUserName.Text.Contains("#"))
// txtXAnchorMailbox.Text = txtUserName.Text;
// }
// }
//}
}
private void rdoCredentialsUserSpecified_CheckedChanged(object sender, EventArgs e)
{
SetAuthEnablement();
}
private void SetAuthEnablement()
{
bool bUserSpecified = false;/*this.rdoCredentialsUserSpecified.Checked*/;
bool bUseOAuth = false;//this.rdoCredentialsOAuth.Checked;
//txtUserName.Text = string.Empty;
//txtPassword.Text = string.Empty;
//txtDomain.Text = string.Empty;
//txtUserName.Enabled = bUserSpecified;
//txtPassword.Enabled = bUserSpecified;
//txtDomain.Enabled = bUserSpecified;
//lblUserName.Enabled = bUserSpecified;
//lblPassword.Enabled = bUserSpecified;
//lblDomain.Enabled = bUserSpecified;
//if (this.rdoCredentialsUserSpecified.Checked == true)
//{
// if (rdoAutodiscoverEmail.Checked == true)
// {
// if (txtUserName.Text.Trim().Length == 0)
// {
// if (AutodiscoverEmailText.Text.Trim().Length != 0)
// {
// txtUserName.Text = AutodiscoverEmailText.Text.Trim();
// }
// }
// }
//}
//this.lblOAuthAppId.Enabled = bUseOAuth;
//this.lblOAuthAuthority.Enabled = bUseOAuth;
//this.lblOAuthRedirectUri.Enabled = bUseOAuth;
//this.lblOAuthServerName.Enabled = bUseOAuth;
//this.txtOAuthAppId.Enabled = bUseOAuth;
//this.txtOAuthAuthority.Enabled = bUseOAuth;
//this.txtOAuthRedirectUri.Enabled = bUseOAuth;
//this.txtOAuthServerName.Enabled = bUseOAuth;
}
private void txtOAuthRedirectUri_TextChanged(object sender, EventArgs e)
{
}
private void rdoCredentialsOAuth_CheckedChanged(object sender, EventArgs e)
{
SetAuthEnablement();
}
private void rdoCredentialsDefaultWindows_CheckedChanged(object sender, EventArgs e)
{
SetAuthEnablement();
}
//private void panel3_Paint(object sender, PaintEventArgs e)
//{
//}
private void ImpersonatedIdTextBox_TextChanged(object sender, EventArgs e)
{
}
private void btnDefaultUserNameSmtp_Click(object sender, EventArgs e)
{
// this.txtUserName.Text = UserPrincipal.Current.EmailAddress;
}
private void chkSetXPublicFolderMailbox_CheckedChanged(object sender, EventArgs e)
{
//txtXPublicFolderMailbox.Enabled = chkSetXPublicFolderMailbox.Checked;
}
public Uri https { get; set; }
}

Sharing video and photo in metro apps through share charm

i am trying to take a picture and video from within the app and trying to share it through share charm but i am having a problem doing that. After i take the pic ,the share charm says it has trouble sharing the image. This is my code .Can anybody please let me know what i am doing wrong.
namespace Temp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Page1 : Page
{
private StorageFile _photo; // Photo file to share
private StorageFile _video; // Video file to share
private async void OnCapturePhoto(object sender, TappedRoutedEventArgs e)
{
var camera = new CameraCaptureUI();
var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
_photo = file;
DataTransferManager.ShowShareUI();
}
}
private async void OnCaptureVideo(object sender, TappedRoutedEventArgs e)
{
var camera = new CameraCaptureUI();
camera.VideoSettings.Format = CameraCaptureUIVideoFormat.Wmv;
var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Video);
if (file != null)
{
_video = file;
DataTransferManager.ShowShareUI();
}
}
void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var request = args.Request;
if (_photo != null)
{
request.Data.Properties.Description = "Component photo";
var reference = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(_photo);
request.Data.Properties.Thumbnail = reference;
request.Data.SetBitmap(reference);
_photo = null;
}
else if (_video != null)
{
request.Data.Properties.Description = "Component video";
List<StorageFile> items = new List<StorageFile>();
items.Add(_video);
request.Data.SetStorageItems(items);
_video = null;
}
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;
}
}
In order for your app to share, you must set the Title of the DataPackagePropertySet and at least one of the "SetXXX" methods. If you do not, you'll see the following message when trying to share "There was a problem with the data from ."
So add request.Data.Properties.Title = "Title_of_photo_or_video"; in OnDataRequested event.