Use asgXmpp to connect to my openfire server failure - authentication

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.

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

youtube live broadcast lifeCycleStatus stuck on 'liveStarting'

I'm trying to figure out what i'm doing wrong when broadcast to live. I have my apk on my android phone stream to youtube. I have no problem streaming for the first time. But if I stop it for about 2 - 3 minutes, and stream again, the lifeCycleStatus of the boardcast keep stay at "liveStarting" and my video is not visible to audience. If I stop long enough, restart stream, the status will go 'live' in about 10 seconds. I have enableMonitorStream disable, and also try LiveBroadcasts.Transition, but it return error redundantTransition. But the lifeCycleStatus wouldn't turn to 'live'. I also try create a new live broadcast and live stream and change the status to 'live' manually, but both get stuck on 'liveStarting'.
public class YoutubeService {
private WeakReference<Context> context;
private static final String PREF_ACCOUNT_NAME = "youtube_account_name";
private static final String[] SCOPES = {YouTubeScopes.YOUTUBE};
private GoogleAccountCredential mCredential;
private YouTube mService;
public YoutubeService(Context context) {
this.context = new WeakReference<Context>(context);
// create account credential
mCredential = GoogleAccountCredential.usingOAuth2(
context, Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
mCredential.setSelectedAccountName("xxxx#gmail.com");
// create youtube builder
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new YouTube.Builder(
transport, jsonFactory, mCredential)
.setApplicationName("My App Name")
.build();
}
// AsyncTask<Void, Void, Map<String, String>>
private void getRtmpUrl() {
try {
// get livebroadcast list
YouTube.LiveBroadcasts.List liveBroadcastRequest = mService.liveBroadcasts().list("id,snippet,contentDetails,status");
liveBroadcastRequest.setBroadcastType("persistent");
liveBroadcastRequest.setMine(true);
LiveBroadcastListResponse liveBroadcastListResponse = liveBroadcastRequest.execute();
List<LiveBroadcast> liveBroadcastList = liveBroadcastListResponse.getItems();
if (liveBroadcastList != null && liveBroadcastList.size() > 0) {
LiveBroadcast liveBroadcast = liveBroadcastList.get(0);
String streamId = liveBroadcast.getContentDetails().getBoundStreamId();
// get livestream list
YouTube.LiveStreams.List livestreamRequest = mService.liveStreams().list("id,cdn");
livestreamRequest.setId(streamId);
LiveStreamListResponse liveStreamListResponse = livestreamRequest.execute();
List<LiveStream> liveStreamList = liveStreamListResponse.getItems();
if (liveStreamList != null && liveStreamList.size() > 0) {
LiveStream liveStream = liveStreamList.get(0);
String serverUrl = liveStream.getCdn().getIngestionInfo().getIngestionAddress();
String streamName = liveStream.getCdn().getIngestionInfo().getStreamName();
String rtmpUrl = serverUrl + "/" + streamName;
// use this rtmpUrl for streaming
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// call 30 seconds after press start streaming
private void checkStatus() {
try {
// get livebroadcast list
YouTube.LiveBroadcasts.List liveBroadcastRequest = mService.liveBroadcasts().list("id,snippet,contentDetails,status");
liveBroadcastRequest.setBroadcastType("persistent");
liveBroadcastRequest.setMine(true);
LiveBroadcastListResponse liveBroadcastListResponse = liveBroadcastRequest.execute();
List<LiveBroadcast> liveBroadcastList = liveBroadcastListResponse.getItems();
if (liveBroadcastList != null && liveBroadcastList.size() > 0) {
LiveBroadcast liveBroadcast = liveBroadcastList.get(0);
// get lifeCycleStatus
String lifeCycleStatus = liveBroadcast.getStatus().getLifeCycleStatus();
String recordingStatus = liveBroadcast.getStatus().getRecordingStatus();
if (lifeCycleStatus != null && lifeCycleStatus.equalsIgnoreCase("live") && recordingStatus != null && recordingStatus.equalsIgnoreCase("recording")) {
String videoId = liveBroadcast.getId();
// the url to watch is www.youtube.com/watch?v=videoId
// video is visible to audience
} else {
// the status is stuck at 'liveStarting', video is not visible to audience
// "status":{"lifeCycleStatus":"liveStarting","privacyStatus":"public","recordingStatus":"recording"}
// check the status of livestream
String boundStreamId = liveBroadcast.getContentDetails().getBoundStreamId();
YouTube.LiveStreams.List livestreamRequest = mService.liveStreams().list("id,cdn,status");
livestreamRequest.setId(boundStreamId);
LiveStreamListResponse liveStreamListResponse = livestreamRequest.execute();
List<LiveStream> liveStreamList = liveStreamListResponse.getItems();
if (liveStreamList != null && liveStreamList.size() > 0) {
LiveStream liveStream = liveStreamList.get(0);
String streamStatus = liveStream.getStatus().getStreamStatus();
if (streamStatus.equalsIgnoreCase("active")) {
// Log.e(TAG,"need to transite to live, liveBroadcastId = " + liveBroadcast.getId());
YouTube.LiveBroadcasts.Transition liveBroadcastTransitionRequest =
mService.liveBroadcasts().transition("live", liveBroadcast.getId(), "id,status");
LiveBroadcast liveBroadcastTransitionResponse = liveBroadcastTransitionRequest.execute();
// get error here
// error 403 Forbidden
// {
// "code" : 403,
// "errors" : [ {
// "domain" : "youtube.liveBroadcast",
// "message" : "Redundant transition",
// "reason" : "redundantTransition"
// } ],
// "message" : "Redundant transition"
// }
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// also try to create livebroadcast and live stream instead of the default one
private void createLiveBroadcast() {
try {
// step 1 create live broadcast
LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
broadcastSnippet.setTitle("Test live broadcast title");
Date currentTime = Calendar.getInstance().getTime();
broadcastSnippet.setScheduledStartTime(new DateTime(currentTime));
LiveBroadcastStatus status = new LiveBroadcastStatus();
status.setPrivacyStatus("public");
// disable MonitorStreamInfo to change transition from ready to live
// refrence https://stackoverflow.com/questions/35003786/cannot-make-transition-of-my-youtube-broadcast-to-live-using-youtube-api
LiveBroadcastContentDetails contentDetails = new LiveBroadcastContentDetails();
MonitorStreamInfo monitorStream = new MonitorStreamInfo();
monitorStream.setEnableMonitorStream(false);
contentDetails.setMonitorStream(monitorStream);
LiveBroadcast broadcast = new LiveBroadcast();
broadcast.setKind("youtube#liveBroadcast");
broadcast.setSnippet(broadcastSnippet);
broadcast.setStatus(status);
broadcast.setContentDetails(contentDetails);
YouTube.LiveBroadcasts.Insert liveBroadcastInsert =
mService.liveBroadcasts().insert("snippet,contentDetails,status", broadcast);
LiveBroadcast returnedBroadcast = liveBroadcastInsert.execute();
// step 2 create live stream
String streamTitle = "Test Live Stream title";
LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
streamSnippet.setTitle(streamTitle);
CdnSettings cdnSettings = new CdnSettings();
cdnSettings.setFormat("720p");
cdnSettings.setIngestionType("rtmp");
LiveStream stream = new LiveStream();
stream.setKind("youtube#liveStream");
stream.setSnippet(streamSnippet);
stream.setCdn(cdnSettings);
YouTube.LiveStreams.Insert liveStreamInsert =
mService.liveStreams().insert("snippet,cdn", stream);
LiveStream returnedStream = liveStreamInsert.execute();
if (returnedStream != null) {
YouTube.LiveBroadcasts.Bind liveBroadcastBind =
mService.liveBroadcasts().bind(returnedBroadcast.getId(), "id,snippet,contentDetails,status");
liveBroadcastBind.setStreamId(returnedStream.getId());
returnedBroadcast = liveBroadcastBind.execute();
String serverUrl = returnedStream.getCdn().getIngestionInfo().getIngestionAddress();
String streamName = returnedStream.getCdn().getIngestionInfo().getStreamName();
String rtmpUrl = serverUrl + "/" + streamName;
// use this rtmpUrl for streaming
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

signalr with sqldepdency firing multiple times for each browser instance

I am having a asp.net mvc app with vs2013 and .net framwork 4.5.1 which should notify users when a certain field gets updated and for a certain recordID.
Everything works fine when I have a single instance of the browser open, but when i open another tab or browser either on the same machine or on the different machine it fires the sqldepdencychange event multiple times.
Below is my hub code
public class MessagesHub : Hub
{
private static string conString = ConfigurationManager.ConnectionStrings["FleetLink_DB"].ToString();
private static string hostName = "";
public static void SendMessages(string hName)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
hostName = hName;
context.Clients.Group(hostName).updateMessages(hName);
}
public Task leaveGroup(string hName)
{
return Groups.Remove(Context.ConnectionId, hName);
}
public Task joinGroup(string hName)
{
return Groups.Add(Context.ConnectionId, hName);
}
}
Below is my signalr script file
$(function () {
var dialog, form
// Declare a proxy to reference the hub.
var notifications = $.connection.messagesHub;
//debugger;
//Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function (hName) {
alert("testing");
getoneMessages(hName)
};
$.connection.hub.logging = true;
$.connection.hub.start().done(function () {
var hostName = getUrlVars()["System_Name"];
notifications.server.joinGroup(hostName);
}).fail(function (e) {
alert(e);
});
});
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function getoneMessages(hName) {
var tbl = $('#selectable');
//alert('mesgID=' + mesgID)
//var tbl = $('#selectable');
$.ajax({
url: '/controller/view',
cache: false,
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
//alert(result);
tbl.empty().append(result);
}).error(function (exception) {
//alert('failed= ' + exception);
});
}
window.onbeforeunload = function (e) {
var hostName = getUrlVars()["System_Name"];
notifications.server.joinGroup(hostName);
$.connection.hub.stop();
};
Below is my partialview code along with the definition for RegisterForNotification and depdendency_onchange event
public PartialViewResult SignalRTesterPartialView()
{
/...COde not included for brevity..../
RegisterForNotifications(ID);
}
public void RegisterForNotifications(int mID)
{
var efConnectionString = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
var builder = new EntityConnectionStringBuilder(efConnectionString);
var regularConnectionString = builder.ProviderConnectionString;
string commandText = null;
commandText = "select ID,Status,Name from tblABC where ID=" + strID;
using (SqlConnection connection = new SqlConnection(regularConnectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
// NOTE: You have to execute the command, or the notification will never fire.
var reader = command.ExecuteReader();
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change && e.Info== SqlNotificationInfo.Update)
{
MessagesHub.SendMessages(hName);
}
RegisterForNotifications(1012);
}
Not sure why it is firing the sendmessages multiple times with each additional browser instance that I open. Any pointers would be helpful!
remove EventHandler when you done with it
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change && e.Info== SqlNotificationInfo.Update)
{
MessagesHub.SendMessages(hName);
}
//remove event handler
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= new OnChangeEventHandler(dependency_OnChange);
RegisterForNotifications(1012);
}

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

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