Cannot use EWS.dll with ExchangeWebServices namespace - dll

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

Related

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

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

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

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

can not run multiple jobs with quartz

Hi i m trying to run two jobs using batch framework.
My problem is SimpleJobLauncher is running only one job which is last in the jobs list.
Here what i am doing:
I have two jobs in my database along with the steps for the jobs.
I read the job data from database and process it as following
public class BatchJobScheduler {
private static Log sLog = LogFactory.getLog(BatchJobScheduler.class);
private ApplicationContext ac;
private DataSourceTransactionManager mTransactionManager;
private SimpleJobLauncher mJobLauncher;
private JobRepository mJobRepository;
private SimpleStepFactoryBean stepFactory;
private MapJobRegistry mapJobRegistry;
private JobDetailBean jobDetail;
private CronTriggerBean cronTrigger;
private SimpleJob job;
private SchedulerFactoryBean schedulerFactory;
private static String mDriverClass;
private static String mConnectionUrl;
private static String mUser;
private static String mPassword;
public static JobMetaDataFeeder metadataFeeder;
static {
try {
loadProperties();
metadataFeeder = new JobMetaDataFeeder();
metadataFeeder.configureDataSource(mDriverClass, mConnectionUrl,
mUser, mPassword);
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (SQLException e) {
} catch (ClassNotFoundException e) {
}
}
private static void loadProperties() throws FileNotFoundException,
IOException {
Properties properties = new Properties();
InputStream is;
if (BatchJobScheduler.class.getClassLoader() != null) {
is = BatchJobScheduler.class.getClassLoader().getResourceAsStream(
"batch.properties");
} else {
is = System.class.getClassLoader().getResourceAsStream(
"batch.properties");
}
properties.load(is);
mDriverClass = properties.getProperty("batch.jdbc.driver");
mConnectionUrl = properties.getProperty("batch.jdbc.url");
mUser = properties.getProperty("batch.jdbc.user");
mPassword = properties.getProperty("batch.jdbc.password");
}
public void start(WebApplicationContext wac) throws Exception {
try {
ac = new FileSystemXmlApplicationContext("batch-spring.xml");
mTransactionManager = (DataSourceTransactionManager) ac
.getBean("mTransactionManager");
mJobLauncher = (SimpleJobLauncher) ac.getBean("mJobLauncher");
mJobRepository = (JobRepository) ac.getBean("mRepositoryFactory");
mJobLauncher.afterPropertiesSet();
List<JobMetadata> jobsMetaData = getJobsData(mDriverClass,
mConnectionUrl, mUser, mPassword, null);
createAndRunScheduler(jobsMetaData);
} catch (Exception e) {
e.printStackTrace();
sLog.error("Exception while starting job", e);
}
}
#SuppressWarnings("unchecked")
public List<CronTriggerBean> getJobTriggers(List<JobMetadata> jobsMetaData)
throws Exception {
List<CronTriggerBean> triggers = new ArrayList<CronTriggerBean>();
for (JobMetadata jobMetadata : jobsMetaData) {
job = (SimpleJob) ac.getBean("job");
job.setName(jobMetadata.getJobName());
ArrayList<Step> steps = new ArrayList<Step>();
for (StepMetadata stepMetadata : jobMetadata.getSteps()) {
// System.err.println(ac.getBean("stepFactory").getClass());
stepFactory = new SimpleStepFactoryBean<String, Object>();
stepFactory.setTransactionManager(mTransactionManager);
stepFactory.setJobRepository(mJobRepository);
stepFactory.setCommitInterval(stepMetadata.getCommitInterval());
stepFactory.setStartLimit(stepMetadata.getStartLimit());
T5CItemReader itemReader = (T5CItemReader) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepReaderClass()));
itemReader
.setItems(getItemList(jobMetadata.getJobParameters()));
stepFactory.setItemReader(itemReader);
stepFactory.setItemProcessor((ItemProcessor) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepProcessorClass())));
stepFactory.setItemWriter((ItemWriter) BeanUtils
.instantiateClass(Class.forName(stepMetadata
.getStepWriterClass())));
stepFactory.setBeanName(stepMetadata.getStepName());
steps.add((Step) stepFactory.getObject());
}
job.setSteps(steps);
ReferenceJobFactory jobFactory = new ReferenceJobFactory(job);
mapJobRegistry = (MapJobRegistry) ac.getBean("jobRegistry");
mapJobRegistry.register(jobFactory);
jobDetail = (JobDetailBean) ac.getBean("jobDetail");
jobDetail.setJobClass(Class.forName(jobMetadata.getMJoblauncher()));
jobDetail.setGroup(jobMetadata.getJobGroupName());
jobDetail.setName(jobMetadata.getJobName());
Map<String, Object> jobDataMap = new HashMap<String, Object>();
jobDataMap.put("jobName", jobMetadata.getJobName());
jobDataMap.put("jobLocator", mapJobRegistry);
jobDataMap.put("jobLauncher", mJobLauncher);
jobDataMap.put("timestamp", new Date());
// jobDataMap.put("jobParams", jobMetadata.getJobParameters());
jobDetail.setJobDataAsMap(jobDataMap);
jobDetail.afterPropertiesSet();
cronTrigger = (CronTriggerBean) ac.getBean("cronTrigger");
cronTrigger.setJobDetail(jobDetail);
cronTrigger.setJobName(jobMetadata.getJobName());
cronTrigger.setJobGroup(jobMetadata.getJobGroupName());
cronTrigger.setCronExpression(jobMetadata.getCronExpression());
triggers.add(cronTrigger);
}
return triggers;
}
private void createAndRunScheduler(List<JobMetadata> jobsMetaData)
throws Exception {
// System.err.println(ac.getBean("schedulerFactory").getClass());
schedulerFactory = new SchedulerFactoryBean();
List<CronTriggerBean> triggerList = getJobTriggers(jobsMetaData);
Trigger[] triggers = new Trigger[triggerList.size()];
int triggerCount = 0;
for (CronTriggerBean trigger : triggerList) {
triggers[triggerCount] = trigger;
triggerCount++;
}
schedulerFactory.setTriggers(triggers);
schedulerFactory.afterPropertiesSet();
}
private List<JobMetadata> getJobsData(String driverClass,
String connectionURL, String user, String password, String query)
throws SQLException, ClassNotFoundException {
metadataFeeder.createJobMetadata(query);
return metadataFeeder.getJobsMetadata();
}
private List<String> getItemList(String jobParameterString) {
List<String> itemList = new ArrayList<String>();
String[] parameters = jobParameterString.split(";");
for (String string : parameters) {
String[] mapKeyValue = string.split("=");
if (mapKeyValue.length == 2) {
itemList.add(mapKeyValue[0] + ":" + mapKeyValue[1]);
} else {
// exception for invalid job parameters
System.out.println("exception for invalid job parameters");
}
}
return itemList;
}
private Map<String, Object> getParameterMap(String jobParameterString) {
Map<String, Object> parameterMap = new HashMap<String, Object>();
String[] parameters = jobParameterString.split(";");
for (String string : parameters) {
String[] mapKeyValue = string.split("=");
if (mapKeyValue.length == 2) {
parameterMap.put(mapKeyValue[0], mapKeyValue[1]);
} else {
// exception for invalid job parameters
System.out.println("exception for invalid job parameters");
}
}
return parameterMap;
}
}
public class MailJobLauncher extends QuartzJobBean {
/**
* Special key in job data map for the name of a job to run.
*/
static final String JOB_NAME = "jobName";
private static Log sLog = LogFactory.getLog(MailJobLauncher.class);
private JobLocator mJobLocator;
private JobLauncher mJobLauncher;
/**
* Public setter for the {#link JobLocator}.
*
* #param jobLocator
* the {#link JobLocator} to set
*/
public void setJobLocator(JobLocator jobLocator) {
this.mJobLocator = jobLocator;
}
/**
* Public setter for the {#link JobLauncher}.
*
* #param jobLauncher
* the {#link JobLauncher} to set
*/
public void setJobLauncher(JobLauncher jobLauncher) {
this.mJobLauncher = jobLauncher;
}
#Override
#SuppressWarnings("unchecked")
protected void executeInternal(JobExecutionContext context) {
Map<String, Object> jobDataMap = context.getMergedJobDataMap();
executeRecursive(jobDataMap);
}
private void executeRecursive(Map<String, Object> jobDataMap) {
String jobName = (String) jobDataMap.get(JOB_NAME);
JobParameters jobParameters = getJobParametersFromJobMap(jobDataMap);
sLog.info("Quartz trigger firing with Spring Batch jobName=" + jobName
+ jobDataMap + jobParameters);
try {
mJobLauncher.run(mJobLocator.getJob(jobName), jobParameters);
} catch (JobInstanceAlreadyCompleteException e) {
jobDataMap.remove("timestamp");
jobDataMap.put("timestamp", new Date());
executeRecursive(jobDataMap);
} catch (NoSuchJobException e) {
sLog.error("Could not find job.", e);
} catch (JobExecutionException e) {
sLog.error("Could not execute job.", e);
}
}
/*
* Copy parameters that are of the correct type over to {#link
* JobParameters}, ignoring jobName.
* #return a {#link JobParameters} instance
*/
private JobParameters getJobParametersFromJobMap(
Map<String, Object> jobDataMap) {
JobParametersBuilder builder = new JobParametersBuilder();
for (Entry<String, Object> entry : jobDataMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String && !key.equals(JOB_NAME)) {
builder.addString(key, (String) value);
} else if (value instanceof Float || value instanceof Double) {
builder.addDouble(key, ((Number) value).doubleValue());
} else if (value instanceof Integer || value instanceof Long) {
builder.addLong(key, ((Number) value).longValue());
} else if (value instanceof Date) {
builder.addDate(key, (Date) value);
} else {
sLog
.debug("JobDataMap contains values which are not job parameters (ignoring).");
}
}
return builder.toJobParameters();
}
}
I couldnt figure it out why launcher is ignoring all other jobs please help me.
Regards
Make sure these properties are set:
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=3
org.quartz.threadPool.threadPriority=5
This will allow a few jobs to run at the same time. Adjust the settings as needed.