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

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

Related

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

Use asgXmpp to connect to my openfire server failure

I create a C# website to test whether the connection is working.here is my code,please help:
protected void Unnamed1_Click(object sender, EventArgs e)
{
XmppClientConnection xmpp;
xmpp = (XmppClientConnection)Application["xmpp"];
if (xmpp == null)
{
xmpp = new XmppClientConnection();
Application["xmpp"] = xmpp;
}
xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin);
Jid jid = new Jid("ttt#192.168.1.131");
xmpp.AutoPresence = true;
xmpp.AutoResolveConnectServer = true;
xmpp.Port = 5222;
xmpp.UseSSL = false;
xmpp.Server = jid.Server;
xmpp.Username = "test#jh";
xmpp.Password = "123456";
xmpp.ClientVersion = "1.0";
xmpp.SendMyPresence();
xmpp.Open();
}
void xmpp_OnLogin(object sender)
{
Console.WriteLine();
}
I've try lots of times,but still not working.
you should change xmpp.AutoResolveConnectServer = false. I hope, can help you.

return result from async operation in mvvm

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}"
.........
........./>

java mail keeping Transport object connected

How do i keep the java mail transport object alive or connected.
I have written this in my code in a simple class file inside a web application : -
#Resource(name = "myMailServer")
private Session mailSession;
Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
System.out.println("" + transport.isConnected());
if(!transport.isConnected()) {
transport.connect(username, password);
}
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
the full code here
Now everytime i run this code it takes some time to connect with the mail server
and the line
System.out.println("" + transport.isConnected());
prints a false
How do i retain the object transport as it does gets null and into the block
if(transport == null) {
or the transport object remains connected...
Thanks
Pradyut
the code should be....
with a static initialization of transport object
without any problems but can be good with a function
static Transport getTransport() method
#Resource(name = "myMailServer")
private Session mailSession;
static Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
}
if(!transport.isConnected()) {
transport.connect(username, password);
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
Thanks
Regards
Pradyut