return result from async operation in mvvm - silverlight-4.0

I have a viewModel named CarsList with main property
public ObservableCollection<Car> Cars
{
get
{
if (_cars.Count == 0)
{
IsBusy = true;
_ws.GetCarsCompleted += new EventHandler<GetCarsCompletedEventArgs>(GetCarsCompleted);
_ws.GetCarsAsync(_app.HandlerId);
}
return _cars;
}
set
{
if (_cars != value)
{
if (_cars != null)
{
Unsubscribe(_cars);
}
_cars = value;
if (_cars != null)
{
Subscribe(_cars);
}
RaisePropertyChanged("Cars");
}
}
}
private void GetCarsCompleted(object sender, GetCarsCompletedEventArgs e)
{
//_cars = e.Result;
IsBusy = false;
}
When view gets _cars and the list is empty I must wait to get collection of cars from wcf service, and there is a problem because it is async operation.
Or maybe if list is empty I should return null, and fire async operation, and in asynccompleted set _cars to result from the wcf service?

I can only guess that you are trying to set up a view binding and property change notification. If I am right I would change you code as follows:
public void GetCars(Int32 handlerId)
{
_ws.GetCarsCompleted += new EventHandler<GetCarsCompletedEventArgs>GetCarsCompleted);
IsBusy = true;
_ws.GetCarsAsync(handlerId);
}
public ObservableCollection<Car> Cars
{
get
{
return _cars;
}
set
{
if (_cars != value)
{
_cars = value;
RaisePropertyChanged("Cars");
}
}
private void GetCarsCompleted(object sender, GetCarsCompletedEventArgs e)
{
_ws.GetCarsCompleted -= new EventHandler<GetCarsCompletedEventArgs>GetCarsCompleted);
IsBusy = false;
if (e.Error != null)
{
//Error handler
}
else
{
Cars = e.Result;
}
}
And then the view binding (in the case of a DataGrid) would look something like this..
<DataGrid IsReadOnly="True"
ItemsSource="{Binding Cars}"
.........
........./>

Related

error CS0103: The name 'ModelHelper' does not exist in the current context

I am trying to implement Object detection on HoloLens2 using Microsoft Custom Vision.
I have been following the tutorial (https://learn.microsoft.com/en-us/archive/blogs/appconsult/23535)
but faced with this error..
error CS0103: The name 'ModelHelper' does not exist in the current context
the codes are as below.
what is this ModelHelper for?
and is there anything that i have to add to use it?
using System;
using System.Linq;
using System.Threading.Tasks;
#if UNITY_WSA && !UNITY_EDITOR
using Windows.Media.Capture;
using Windows.Media.Capture.Frames;
using Windows.Media.MediaProperties;
public class ScanEngine
{
public TimeSpan PredictionFrequency = TimeSpan.FromMilliseconds(400);
private MediaCapture CameraCapture;
private MediaFrameReader CameraFrameReader;
private Int64 FramesCaptured;
IUnityScanScene UnityApp;
public ScanEngine()
{
}
public async Task Inititalize(IUnityScanScene unityApp)
{
UnityApp = unityApp;
await InitializeCameraCapture();
await InitializeCameraFrameReader();
}
private async Task InitializeCameraCapture()
{
CameraCapture = new MediaCapture();
MediaCaptureInitializationSettings settings = new
MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Video;
await CameraCapture.InitializeAsync(settings);
}
private async Task InitializeCameraFrameReader()
{
var frameSourceGroups = await MediaFrameSourceGroup.FindAllAsync();
MediaFrameSourceGroup selectedGroup = null;
MediaFrameSourceInfo colorSourceInfo = null;
foreach (var sourceGroup in frameSourceGroups)
{
foreach (var sourceInfo in sourceGroup.SourceInfos)
{
if (sourceInfo.MediaStreamType == MediaStreamType.VideoPreview
&& sourceInfo.SourceKind == MediaFrameSourceKind.Color)
{
colorSourceInfo = sourceInfo;
break;
}
}
if (colorSourceInfo != null)
{
selectedGroup = sourceGroup;
break;
}
}
var colorFrameSource = CameraCapture.FrameSources[colorSourceInfo.Id];
var preferredFormat = colorFrameSource.SupportedFormats.Where(format =>
{
return format.Subtype == MediaEncodingSubtypes.Argb32;
}).FirstOrDefault();
CameraFrameReader = await CameraCapture.CreateFrameReaderAsync(colorFrameSource);
await CameraFrameReader.StartAsync();
}
public void StartPullCameraFrames()
{
Task.Run(async () =>
{
for (; ; ) // Forever = While the app runs
{
FramesCaptured++;
await Task.Delay(PredictionFrequency);
using (var frameReference = CameraFrameReader.TryAcquireLatestFrame())
using (var videoFrame = frameReference?.VideoMediaFrame?.GetVideoFrame())
{
if (videoFrame == null)
{
continue; //ignoring frame
}
if (videoFrame.Direct3DSurface == null)
{
videoFrame.Dispose();
continue; //ignoring frame
}
try
{
await
ModelHelper.EvaluateVideoFrameAsync(videoFrame).ConfigureAwait(false);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
}
}
}
});
}
}
#endif

Webform to SQL database - how to pass user.identity.name?

I have a webform built that works well, writes back to my SQL database, but now I need to track the user id of the person who made the change. I am a SQL developer, so am a little out of my knowledge range here.
My .aspx file has
<InsertParameters>
.....
<asp:Parameter Name="StaffId" Type="String" DefaultValue= "Anonymous"/>
and my .aspx.cs file looks like this:
public partial class _BLAHBLAHBLAH_Topic1 : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["UserPermission"] = null;
string username = User.Identity.Name;
if (username.StartsWith("ABC\\"))
username = username.Remove(0, 4);
bool[] userPermssion = GetUserPermissions(username);
if(!userPermssion[0])
{
ASPxGridView1.Visible = false;
WarningLabel.Visible = true;
}
}
}
private bool[] GetUserPermissions(string username)
{
bool canView = false;
bool canUpdate = false;
bool canDelete = false;
bool canInsert = false;
try
{
PermissionDataSet.UserPermissionsDataTable userDataTable = new PermissionDataSet.UserPermissionsDataTable();
PermissionDataSetTableAdapters.UserPermissionsTableAdapter adapter = new PermissionDataSetTableAdapters.UserPermissionsTableAdapter();
adapter.Fill(userDataTable, username);
if (userDataTable != null)
{
if (userDataTable.Rows.Count == 1)
{
canView = Convert.ToBoolean(userDataTable.Rows[0]["ViewFlag"]);
canUpdate = Convert.ToBoolean(userDataTable.Rows[0]["UpdateFlag"]);
canDelete = Convert.ToBoolean(userDataTable.Rows[0]["DeleteFlag"]);
canInsert = Convert.ToBoolean(userDataTable.Rows[0]["InsertFlag"]);
}
}
}
catch(Exception ex)
{
//unable to retrieve permissions - all values are defaulted to false
}
bool[] userPermission = new bool[] { canView, canUpdate, canDelete, canInsert };
Session["UserPermission"] = userPermission;
return userPermission;
}
protected void ASPxGridView1_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
{
if (Session["UserPermission"] != null)
{
bool[] permission = (bool[])Session["UserPermission"];
switch (e.ButtonType)
{
case ColumnCommandButtonType.Edit:
e.Visible = permission[1];
break;
case ColumnCommandButtonType.Delete:
e.Visible = permission[2];
break;
case ColumnCommandButtonType.New:
e.Visible = permission[3];
break;
}
}
else
{
switch (e.ButtonType)
{
case ColumnCommandButtonType.Edit:
e.Visible = false;
break;
case ColumnCommandButtonType.Delete:
e.Visible = false;
break;
case ColumnCommandButtonType.New:
e.Visible = false;
break;
}
}
}
}
I figure that I need to put a
protected void Page_Init(object sender, EventArgs e)
{
DataSource.SelectParameters["StaffId"].DefaultValue = User.Identity.Name;
}
code snippet in there somewhere, but I am really not sure where or how, so any advice would be really appreciated.
Thank you
completed this using the advice from #done_merson on How to use User.Identity.Name as a parameter for SqlDataSource in ASP.NET?
works a charm! Thank you #done_merson

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;
}

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; }
}