org.apache.geode.cache.UnsupportedOperationInTransactionException - gemfire

Getting below exception while updating entry in the cache while establishing Many to Many relation.
org.apache.geode.cache.UnsupportedOperationInTransactionException: Expected size of 1 {[/__PR/_B__User_101]} for target=192.168.1.2(cacheServer2:7756)<v1>:41001 during a distributed transaction but got 2 {[[], [DistTxThinEntryState: ,regionVersion=2 ,tailKey=440 ,memberID=null]]}
at org.apache.geode.internal.cache.DistTXStateProxyImplOnCoordinator.populateEntryEventMap(DistTXStateProxyImplOnCoordinator.java:576)
at org.apache.geode.internal.cache.DistTXStateProxyImplOnCoordinator.doPrecommit(DistTXStateProxyImplOnCoordinator.java:484)
at org.apache.geode.internal.cache.DistTXStateProxyImplOnCoordinator.commit(DistTXStateProxyImplOnCoordinator.java:88)
at org.apache.geode.internal.cache.TXManagerImpl.commit(TXManagerImpl.java:426)
at com.trendcore.cache.peertopeer.service.UserServiceImpl.attachRoleToUser(UserServiceImpl.java:108)
at com.trendcore.cache.peertopeer.CacheApplication.attachRoleToUser(CacheApplication.java:121)
Cache Configuration -> It's Peer to Peer configration with 2 regions.
Properties properties = new Properties();
properties.setProperty("locators", "localhost[13489]");
properties.setProperty("mcast-address", "224.0.0.0");
properties.setProperty("mcast-port", "0");
properties.setProperty(NAME, "cacheServer1");
CacheFactory cacheFactory = new CacheFactory(this.cacheConfiguration);
cache = cacheFactory.create();
User Region
RegionFactory<Long, User> regionFactory = this.cache.createRegionFactory(RegionShortcut.PARTITION);
userRegion = regionFactory.create(USER_REGION);
Role Region
RegionFactory<Long, Role> regionFactory = this.cache.createRegionFactory(RegionShortcut.PARTITION);
roleRegion = regionFactory.create(ROLE_REGION);
User model resides in User region
public class User implements Serializable{
private Long id;
private String username;
private Map<Long,Object> roles;
//Getters , Setters
public void addRole(Long roleId) {
roles.put(roleId,null);
}
}
Role model resides in Role region
public class Role implements Serializable {
private Long id;
private String roleName;
//getters , setters
}
Users and roles are inserted in the respective regions using below code.
public void insertUser(User user) {
CacheTransactionManager cacheTransactionManager = cache.getCacheTransactionManager();
try {
cacheTransactionManager.begin();
userRegion.put(user.getId(), user);
cacheTransactionManager.commit();
} catch (Exception e) {
cacheTransactionManager.rollback();
}
}
public void insertRole(Role role) {
CacheTransactionManager cacheTransactionManager = cache.getCacheTransactionManager();
try {
cacheTransactionManager.begin();
roleRegion.put(role.getId(), role);
cacheTransactionManager.commit();
} catch (Exception e) {
cacheTransactionManager.rollback();
}
}
When any roleIds are put in existing cache user object then above exception is thrown.
public void attachRoleToUser(Long userId, Long roleId) {
Region<Long, User> userRegion = cache.getRegion(USER_REGION);
Region<Long, Role> roleRegion = cache.getRegion("Role");
CacheTransactionManager cacheTransactionManager = cache.getCacheTransactionManager();
try {
cacheTransactionManager.setDistributed(true);
cacheTransactionManager.begin();
Role role = roleRegion.get(roleId);
if (role != null) {
User user = userRegion.get(userId);
user.addRole(role.getId());
userRegion.put(userId,user);
}
cacheTransactionManager.commit();
} catch (Exception e) {
try {
cacheTransactionManager.rollback();
}catch (Exception rbe){
}
throw new RuntimeException(e);
}
}
Any guidance in this case will be appreciated.

1.) Distributed transactions only work for Replicated Regions at this point.
2.) In the second case, only one region is now in the transaction boundary, so co-location is not needed.
3.) I think in your first case, you had two partitioned regions as part of a transaction, this requires the regions to be co-located ( the relevant data has to exist on the node, so it's also possible that one is a replicated region and the other is a partitioned)

Changed, attach user to role method to below and there is no exception.
Region<Long, User> userRegion = cache.getRegion(USER_REGION);
Region<Long, Role> roleRegion = cache.getRegion("Role");
CacheTransactionManager cacheTransactionManager = cache.getCacheTransactionManager();
try {
//This is change fetching role information outside transaction boundry.
Role role = roleRegion.get(roleId);
cacheTransactionManager.setDistributed(true);
cacheTransactionManager.begin();
//This line is causing below exception
//org.apache.geode.cache.UnsupportedOperationInTransactionException: Expected size of 1 {[/__PR/_B__User_101]}
//Role role = roleRegion.get(roleId);
if (role != null) {
User user = userRegion.get(userId);
user.addRole(role.getId());
userRegion.put(userId,user);
}
cacheTransactionManager.commit();
} catch (Exception e) {
try {
if(cacheTransactionManager != null && cacheTransactionManager.exists())
cacheTransactionManager.rollback();
}catch (Exception rbe){
}
throw new RuntimeException(e);
}
And there is no exception.
However need more information on below points.
Transaction was set to distributed.
User and Role both regions were involved in this case transaction failed, with exception UnsupportedOperationInTransactionException
Distributed transactions are not working on multiple regions.

Related

authentication in liferay without login hook

I have a problem, I get the user and password of a view and I check if this data is correct in the data of liferay, when it's correct my method return 1 if the validation is true, but I don't know how to make the successful login in liferay, this is my method:
try {
long companyId = PortalUtil.getDefaultCompanyId();
System.out.println(companyId + " id company");
User user1;
try {
user1 = UserLocalServiceUtil.getUserByEmailAddress(companyId, name);
long cmp = user1.getCompanyId();
Company company = CompanyLocalServiceUtil.getCompany(cmp);
int a = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), user.getId(), pass, null,
null, null);
if (a == 1) {
System.out.println("Log in successful");
}
} catch (PortalException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("algo salio mal");
}
This seems to be a case where you would need an auto-login hook. In Liferay 7, you just need components like in: https://www.e-systems.tech/blog/-/blogs/autologin-in-liferay-7
You can use an indicator within the user session, like a token, and check it in a custom logic:
#Override
protected String[] doLogin(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final long companyId = portal.getCompanyId(request);
final HttpSession session = request.getSession();
// code your logic here..
final String[] credentials = new String[3];
credentials[0] = String.valueOf(user.getUserId());
credentials[1] = user.getPassword();
credentials[2] = Boolean.FALSE.toString();
return credentials;
}
This solution is also valid for LR6, the difference is that you are not using OSGi there, so you have to create a hook through the SDK.

SQL Express 2014 edition call pull Snapshot replication subscribers

I have Sql Stander edition 2014 Which is Distributor and Publisher Also. I created Subscriber on Sql Stander Edition on other Server.Subscriber pull Snapshot Replication is working proper and i can look at the data.
When i Used the 2014 Express edition the pull Subscription is not working because 2014 express edition not support SQL Server Agent.
can any one know any other option is present to call the pull subscription model in the express edition. or we cant do it.
This is Code i have used
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// createSubscriber();
//disableTheServer2Distributor();
}
public bool CreatePublication( string publisherName, string publicationName, string publicationDbName)
{
ReplicationDatabase publicationDb;
TransPublication publication;
// Create a connection to the Publisher using Windows Authentication.
ServerConnection conn;
conn = new ServerConnection(publisherName);
try
{
// Connect to the Publisher.
conn.Connect();
// Enable the AdventureWorks database for transactional publishing.
publicationDb = new ReplicationDatabase(publicationDbName, conn);
// If the database exists and is not already enabled,
// enable it for transactional publishing.
if (publicationDb.LoadProperties())
{
if (!publicationDb.EnabledTransPublishing)
{
publicationDb.EnabledTransPublishing = true;
}
// If the Log Reader Agent does not exist, create it.
if (!publicationDb.LogReaderAgentExists)
{
// Specify the Windows account under which the agent job runs.
// This account will be used for the local connection to the
// Distributor and all agent connections that use Windows Authentication.
publicationDb.LogReaderAgentProcessSecurity.Login = textBox1.Text ;
publicationDb.LogReaderAgentProcessSecurity.Password = textBox2.Text;
// Explicitly set authentication mode for the Publisher connection
// to the default value of Windows Authentication.
publicationDb.LogReaderAgentPublisherSecurity.WindowsAuthentication = true;
// Create the Log Reader Agent job.
publicationDb.CreateLogReaderAgent();
}
}
else
{
throw new ApplicationException(String.Format(
"The {0} database does not exist at {1}.",
publicationDb, publisherName));
}
// Set the required properties for the transactional publication.
publication = new TransPublication();
publication.ConnectionContext = conn;
publication.Name = publicationName;
publication.DatabaseName = publicationDbName;
// Specify a transactional publication (the default).
publication.Type = PublicationType.Snapshot;
// Activate the publication so that we can add subscriptions.
publication.Status = State.Active;
// Enable push and pull subscriptions and independent Distribition Agents.
publication.Attributes |= PublicationAttributes.AllowPull;
//publication.Attributes |= PublicationAttributes.AllowPush;
//publication.Attributes |= PublicationAttributes.IndependentAgent;
// Specify the Windows account under which the Snapshot Agent job runs.
// This account will be used for the local connection to the
// Distributor and all agent connections that use Windows Authentication.
publication.SnapshotGenerationAgentProcessSecurity.Login = textBox1.Text;
publication.SnapshotGenerationAgentProcessSecurity.Password = textBox2.Text;
// Explicitly set the security mode for the Publisher connection
// Windows Authentication (the default).
publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;
ReplicationAgentSchedule schedule;
if (publication.LoadProperties() || publication.SnapshotAvailable)
{
// Set a weekly schedule for the filtered data snapshot.
schedule = new ReplicationAgentSchedule();
schedule.FrequencyType = ScheduleFrequencyType.Continuously;
schedule.FrequencyRecurrenceFactor = 1;
schedule.FrequencyInterval = Convert.ToInt32(0x001);
}
if (!publication.IsExistingObject)
{
// Create the transactional publication.
publication.Create();
// Create a Snapshot Agent job for the publication.
publication.CreateSnapshotAgent();
}
else
{
throw new ApplicationException(String.Format(
"The {0} publication already exists.", publicationName));
}
return true;
}
catch (Exception ex)
{
return false;
// Implement custom application error handling here.
throw new ApplicationException(String.Format(
"The publication {0} could not be created.", publicationName), ex);
}
finally
{
conn.Disconnect();
}
}
/// <summary>
///
/// </summary>
/// <param name="distributionDbName">distribution data base Name</param>
/// <param name="publisherName">Publisher Name </param>
/// <param name="publicationDbName">Publication data base name</param>
/// <param name="distributionDbPassword"> Set the password of the database</param>
/// <param name="WorkingDirectoryPath">Network location from where it can be access </param>
/// <returns></returns>
public bool ConfigurationPublishreAndDistributor(string distributionDbName , string publisherName, string publicationDbName, string distributionDbPassword,string WorkingDirectoryPath)
{
DistributionDatabase distributionDb;
ReplicationServer distributor;
DistributionPublisher publisher;
ReplicationDatabase publicationDb;
// Create a connection to the server using Windows Authentication.
ServerConnection conn = new ServerConnection(publisherName);
try
{
// Connect to the server acting as the Distributor
// and local Publisher.
conn.Connect();
// Define the distribution database at the Distributor,
// but do not create it now.
distributionDb = new DistributionDatabase(distributionDbName, conn);
distributionDb.MaxDistributionRetention = 96;
distributionDb.HistoryRetention = 120;
// Set the Distributor properties and install the Distributor.
// This also creates the specified distribution database.
distributor = new ReplicationServer(conn);
distributor.InstallDistributor(distributionDbPassword, distributionDb);
// Set the Publisher properties and install the Publisher.
publisher = new DistributionPublisher(publisherName, conn);
publisher.DistributionDatabase = distributionDb.Name;
publisher.WorkingDirectory = WorkingDirectoryPath;
publisher.PublisherSecurity.WindowsAuthentication = true;
publisher.Create();
// Enable AdventureWorks2012 as a publication database.
publicationDb = new ReplicationDatabase(publicationDbName, conn);
publicationDb.EnabledTransPublishing = true;
publicationDb.EnabledMergePublishing = true;
return true;
}
catch (Exception ex)
{
// Implement appropriate error handling here.
return false;
throw new ApplicationException("An error occured when installing distribution and publishing.", ex);
}
finally
{
conn.Disconnect();
}
}
private void CreateDistributorServer1_Click(object sender, EventArgs e)
{
if (ConfigurationPublishreAndDistributor("distribution", #"SERVER-002\SQLSERVER2014", "ReplicationDB", "Asdf1234!", #"\\SERVER-001\Replication-001"))
{
if (CreatePublication(#"SERVER-002\SQLSERVER2014", "ReplicationSnapShort", "ReplicationDB"))
{
string publisherName = #"SERVER-002\SQLSERVER2014";
string publicationName = "ReplicationSnapShort";
string publicationDbName = "ReplicationDB";
string articleName = "student";
string schemaOwner = "dbo";
TransArticle article;
// Create a connection to the Publisher.
ServerConnection conn = new ServerConnection(publisherName);
// Create a filtered transactional articles in the following steps:
// 1) Create the article with a horizontal filter clause.
// 2) Add columns to or remove columns from the article.
try
{
// Connect to the Publisher.
conn.Connect();
// Define a horizontally filtered, log-based table article.
article = new TransArticle();
article.ConnectionContext = conn;
article.Name = articleName;
article.DatabaseName = publicationDbName;
article.SourceObjectName = articleName;
article.SourceObjectOwner = schemaOwner;
article.PublicationName = publicationName;
article.Type = ArticleOptions.LogBased;
String[] articlecolumns = new String[2];
articlecolumns[0] = "studentid";
articlecolumns[1] = "name";
article.AddReplicatedColumns(articlecolumns);
//article.FilterClause = "DiscontinuedDate IS NULL";
// Ensure that we create the schema owner at the Subscriber.
article.SchemaOption |= CreationScriptOptions.Schema;
if (!article.IsExistingObject)
{
// Create the article.
article.Create();
}
else
{
throw new ApplicationException(String.Format(
"The article {0} already exists in publication {1}.",
articleName, publicationName));
}
// Create an array of column names to remove from the article.
String[] columns = new String[2];
columns[0] = "studentid";
columns[1] = "name";
// Remove the column from the article.
article.AddReplicatedColumns(columns);
// publication.StartSnapshotGenerationAgentJob();
}
catch (Exception ex)
{
// Implement appropriate error handling here.
throw new ApplicationException("The article could not be created.", ex);
}
finally
{
conn.Disconnect();
startTheAgentNow();
}
}
}
MessageBox.Show("Create the Distributor and Publisher");
}
public bool startTheAgentNow()
{
string publisherName = #"SERVER-002\SQLSERVER2014";
string publicationName = "ReplicationSnapShort";
string publicationDbName = "ReplicationDB";
TransPublication publication;
// Create a connection to the Publisher using Windows Authentication.
ServerConnection conn;
conn = new ServerConnection(publisherName);
try
{
// Connect to the Publisher.
conn.Connect();
// Set the required properties for an existing publication.
publication = new TransPublication();
publication.ConnectionContext = conn;
publication.Name = publicationName;
publication.DatabaseName = publicationDbName;
if (publication.LoadProperties())
{
// Start the Snapshot Agent job for the publication.
publication.StartSnapshotGenerationAgentJob();
}
else
{
throw new ApplicationException(String.Format(
"The {0} publication does not exist.", publicationName));
}
}
catch (Exception ex)
{
// Implement custom application error handling here.
throw new ApplicationException(String.Format(
"A snapshot could not be generated for the {0} publication."
, publicationName), ex);
}
finally
{
conn.Disconnect();
// createSubscriber();
}
return true;
}
public bool createSubscriber()
{
// Define the Publisher, publication, and databases.
string publicationName = "ReplicationSnapShort";
string publisherName = #"SERVER-002\SQLSERVER2014";
string subscriberName = #"SERVER-001\SQLSERVER2014";
string subscriptionDbName = "ReplicationDB1";
string publicationDbName = "ReplicationDB";
//Create connections to the Publisher and Subscriber.
ServerConnection subscriberConn = new ServerConnection(subscriberName);
ServerConnection publisherConn = new ServerConnection(publisherName);
// Create the objects that we need.
TransPublication publication;
TransPullSubscription subscription;
try
{
// Connect to the Publisher and Subscriber.
subscriberConn.Connect();
publisherConn.Connect();
// Ensure that the publication exists and that
// it supports pull subscriptions.
publication = new TransPublication();
publication.Name = publicationName;
publication.DatabaseName = publicationDbName;
publication.ConnectionContext = publisherConn;
if (publication.IsExistingObject)
{
if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
{
publication.Attributes |= PublicationAttributes.AllowPull;
}
// Define the pull subscription.
subscription = new TransPullSubscription();
subscription.ConnectionContext = subscriberConn;
subscription.PublisherName = publisherName;
subscription.PublicationName = publicationName;
subscription.PublicationDBName = publicationDbName;
subscription.DatabaseName = subscriptionDbName;
// Specify the Windows login credentials for the Distribution Agent job.
subscription.SynchronizationAgentProcessSecurity.Login = textBox1.Text;
subscription.SynchronizationAgentProcessSecurity.Password = textBox2.Text;
// Make sure that the agent job for the subscription is created.
subscription.CreateSyncAgentByDefault = true;
// By default, subscriptions to transactional publications are synchronized
// continuously, but in this case we only want to synchronize on demand.
subscription.AgentSchedule.FrequencyType = ScheduleFrequencyType.Continuously;
// Create the pull subscription at the Subscriber.
subscription.Create();
Boolean registered = false;
// Verify that the subscription is not already registered.
foreach (TransSubscription existing
in publication.EnumSubscriptions())
{
if (existing.SubscriberName == subscriberName
&& existing.SubscriptionDBName == subscriptionDbName)
{
registered = true;
}
}
if (!registered)
{
// Register the subscription with the Publisher.
publication.MakePullSubscriptionWellKnown(
subscriberName, subscriptionDbName,
SubscriptionSyncType.Automatic,
TransSubscriberType.ReadOnly);
}
}
else
{
// Do something here if the publication does not exist.
throw new ApplicationException(String.Format(
"The publication '{0}' does not exist on {1}.",
publicationName, publisherName));
}
}
catch (Exception ex)
{
// Implement the appropriate error handling here.
throw new ApplicationException(String.Format(
"The subscription to {0} could not be created.", publicationName), ex);
}
finally
{
subscriberConn.Disconnect();
publisherConn.Disconnect();
}
MessageBox.Show("Subscription is Created");
return true;
}
/// <summary>
/// This is the code of the
/// </summary>
public void disableTheServer2Distributor()
{
string publisherName = #"SERVER-002\SQLSERVER2014";
string publicationDbName = "ReplicationDB";
string distributorName = #"SERVER-002\SQLSERVER2014";
string distributionDbName = "distribution";
// Create connections to the Publisher and Distributor
// using Windows Authentication.
ServerConnection publisherConn = new ServerConnection(publisherName);
ServerConnection distributorConn = new ServerConnection(distributorName);
// Create the objects we need.
ReplicationServer distributor =
new ReplicationServer(distributorConn);
DistributionPublisher publisher;
DistributionDatabase distributionDb =
new DistributionDatabase(distributionDbName, distributorConn);
ReplicationDatabase publicationDb;
publicationDb = new ReplicationDatabase(publicationDbName, publisherConn);
try
{
// Connect to the Publisher and Distributor.
publisherConn.Connect();
distributorConn.Connect();
// Disable all publishing on the AdventureWorks2012 database.
if (publicationDb.LoadProperties())
{
if (publicationDb.EnabledMergePublishing)
{
publicationDb.EnabledMergePublishing = false;
}
else if (publicationDb.EnabledTransPublishing)
{
publicationDb.EnabledTransPublishing = false;
}
}
else
{
throw new ApplicationException(
String.Format("The {0} database does not exist.", publicationDbName));
}
// We cannot uninstall the Publisher if there are still Subscribers.
if (distributor.RegisteredSubscribers.Count == 0)
{
// Uninstall the Publisher, if it exists.
publisher = new DistributionPublisher(publisherName, distributorConn);
if (publisher.LoadProperties())
{
publisher.Remove(false);
}
else
{
// Do something here if the Publisher does not exist.
throw new ApplicationException(String.Format(
"{0} is not a Publisher for {1}.", publisherName, distributorName));
}
// Drop the distribution database.
if (distributionDb.LoadProperties())
{
distributionDb.Remove();
}
else
{
// Do something here if the distribition DB does not exist.
throw new ApplicationException(String.Format(
"The distribution database '{0}' does not exist on {1}.",
distributionDbName, distributorName));
}
// Uninstall the Distributor, if it exists.
if (distributor.LoadProperties())
{
// Passing a value of false means that the Publisher
// and distribution databases must already be uninstalled,
// and that no local databases be enabled for publishing.
distributor.UninstallDistributor(false);
}
else
{
//Do something here if the distributor does not exist.
throw new ApplicationException(String.Format(
"The Distributor '{0}' does not exist.", distributorName));
}
}
else
{
throw new ApplicationException("You must first delete all subscriptions.");
}
}
catch (Exception ex)
{
// Implement appropriate error handling here.
throw new ApplicationException("The Publisher and Distributor could not be uninstalled", ex);
}
finally
{
publisherConn.Disconnect();
distributorConn.Disconnect();
}
}
private void CreateDistributorServer2_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
createSubscriber();
}
private void button13_Click(object sender, EventArgs e)
{
string publisherName = #"SERVER-002\SQLSERVER2014";
string publicationDbName = "ReplicationDB";
String subscriberName = #"SERVER-001\SQLSERVER2014";
String publicationName = "ReplicationSnapShort";
String subscriptionDbName = "ReplicationDB1";
// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);
TransPullSubscription subscription;
try
{
// Connect to the Subscriber.
conn.Connect();
// Define subscription properties.
subscription = new TransPullSubscription();
subscription.ConnectionContext = conn;
subscription.DatabaseName = subscriptionDbName;
subscription.PublisherName = publisherName;
subscription.PublicationDBName = publicationDbName;
subscription.PublicationName = publicationName;
// If the pull subscription and the job exists, mark the subscription
// for reinitialization and start the agent job.
if (subscription.LoadProperties() && subscription.AgentJobId != null)
{
subscription.Reinitialize();
subscription.SynchronizeWithJob();
}
else
{
// Do something here if the subscription does not exist.
throw new ApplicationException(String.Format(
"A subscription to '{0}' does not exists on {1}",
publicationName, subscriberName));
}
}
catch (Exception ex)
{
// Do appropriate error handling here.
//throw new ApplicationException("The subscription could not be reinitialized.", ex);
}
finally
{
conn.Disconnect();
startTheAgentNow();
MessageBox.Show("Agents are started");
}
}
private void button9_Click(object sender, EventArgs e)
{
}
}
Above Code is Working as Expected I getting issue When I change the Subscriber to SQL
I see you are using the TransPullSubscription class and calling the SynchronizeWithJob() method to synchronize the subscription. As you found out, the SQL Server Agent is not available in SQL Server Express so this approach does not work.
However, the RMO TransSynchronizationAgent class exposes a Synchronize method which can be used to synchronize a pull subscription without an agent job. This is covered in How to: Synchronize a Pull Subscription (RMO Programming).
Get an instance of the TransSynchronizationAgent class from the
SynchronizationAgent property, and call the Synchronize method. This
method starts the agent synchronously, and control remains with the
running agent job. During synchronous execution, you can handle the
Status event while the agent is running.
I have a similar example for a Merge pull subscription found here.
Note that if you specified a value of false for CreateSyncAgentByDefault (the default) when you created the pull subscription, you also need to set additional properties before you can call Synchronize().
If you specified a value of false for CreateSyncAgentByDefault (the
default) when you created the pull subscription, you also need to
specify Distributor, DistributorSecurityMode, and optionally
DistributorLogin and DistributorPassword because the agent job related
metadata for the subscription is not available in
MSsubscription_properties.
Thanks
Brandon Williams ,
I make the changes on the code is given below
`
{
TransSynchronizationAgent agent;
// Sync BackgroundWorker
BackgroundWorker syncBackgroundWorker;
public Form1()
{
InitializeComponent();
lblSubscriptionName.Text = "[" + subscriptionDbName + "] - [" + publisherName + "] - [" + publicationDbName + "]";
lblPublicationName.Text = publicationName;
}
private void btnStart_Click(object sender, EventArgs e)
{
// Instantiate a BackgroundWorker, subscribe to its events, and call RunWorkerAsync()
syncBackgroundWorker = new BackgroundWorker();
syncBackgroundWorker.WorkerReportsProgress = true;
syncBackgroundWorker.DoWork += new DoWorkEventHandler(syncBackgroundWorker_DoWork);
syncBackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(syncBackgroundWorker_ProgressChanged);
syncBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(syncBackgroundWorker_RunWorkerCompleted);
// Disable the start button
btnStart.Enabled = false;
// Initialize the progress bar and status textbox
pbStatus.Value = 0;
tbLastStatusMessage.Text = String.Empty;
pictureBoxStatus.Visible = true;
pictureBoxStatus.Enabled = true;
// Kick off a background operation to synchronize
syncBackgroundWorker.RunWorkerAsync();
}
// This event handler initiates the synchronization
private void syncBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Connect to the Subscriber and synchronize
SynchronizeMergePullSubscriptionViaRMO();
}
// Synchronize
public void SynchronizeMergePullSubscriptionViaRMO()
{
// Create a connection to the Subscriber.
ServerConnection conn = new ServerConnection(subscriberName);
// Merge pull subscription
TransPullSubscription subscription;
try
{
// Connect to the Subscriber.
conn.Connect();
// Define the pull subscription.
subscription = new TransPullSubscription();
subscription.ConnectionContext = conn;
subscription.DatabaseName = subscriptionDbName;
subscription.PublisherName = publisherName;
subscription.PublicationDBName = publicationDbName;
subscription.PublicationName = publicationName;
// If the pull subscription exists, then start the synchronization.
if (subscription.LoadProperties())
{
// Get the agent for the subscription.
agent = subscription.SynchronizationAgent;
// Set the required properties that could not be returned
// from the MSsubscription_properties table.
//agent.PublisherSecurityMode = SecurityMode.Integrated;
agent.DistributorSecurityMode = SecurityMode.Integrated;
agent.Distributor = publisherName;
// Enable verbose merge agent output to file.
agent.OutputVerboseLevel = 4;
agent.Output = "C:\\TEMP\\mergeagent.log";
// Handle the Status event
agent.Status += new AgentCore.StatusEventHandler(agent_Status);
// Synchronously start the Merge Agent for the subscription.
agent.Synchronize();
}
else
{
// Do something here if the pull subscription does not exist.
throw new ApplicationException(String.Format(
"A subscription to '{0}' does not exist on {1}",
publicationName, subscriberName));
}
}
catch (Exception ex)
{
// Implement appropriate error handling here.
throw new ApplicationException("The subscription could not be " +
"synchronized. Verify that the subscription has " +
"been defined correctly.", ex);
}
finally
{
conn.Disconnect();
}
}
// This event handler handles the Status event and reports the agent progress.
public void agent_Status(object sender, StatusEventArgs e)
{
syncBackgroundWorker.ReportProgress(Convert.ToInt32(e.PercentCompleted), e.Message.ToString());
}
// This event handler updates the form with agent progress.
private void syncBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Set the progress bar percent completed
pbStatus.Value = e.ProgressPercentage;
// Append the last agent message
tbLastStatusMessage.Text += e.UserState.ToString() + Environment.NewLine;
// Scroll to end
ScrollToEnd();
}
// This event handler deals with the results of the background operation.
private void syncBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
tbLastStatusMessage.Text += "Canceled!" + Environment.NewLine;
ScrollToEnd();
}
else if (e.Error != null)
{
tbLastStatusMessage.Text += "Error: " + e.Error.Message + Environment.NewLine;
ScrollToEnd();
}
else
{
tbLastStatusMessage.Text += "Done!" + Environment.NewLine;
ScrollToEnd();
}
btnStart.Enabled = true;
pictureBoxStatus.Enabled = false;
}
private void ScrollToEnd()
{
// Scroll to end
tbLastStatusMessage.SelectionStart = tbLastStatusMessage.TextLength;
tbLastStatusMessage.ScrollToCaret();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}`

Issue : SQL Azure connection is broken . After reconnecting and accessing entity object , An Error occurred

Connected to website and keeping idle for 30 mins, then trying to access the entities I am getting the following error.
Entity framework An error occurred while executing the command definition. See the inner exception for details . Inner exception {“Invalid object name 'dbo.TableName'.”}
Sample Code
Static Class Azure
{
public static CrmEntities ConnectCustomerEntity()
{
CrmEntities customerEntity = null;
policy.ExecuteAction(() =>
{
try
{
var shardId = GetShardId();
customerEntity = new CrmEntities(ConnectionStringCustomerDB());
string federationCmdText = #"USE FEDERATION Customer_Federation(ShardId =" + shardId + ") WITH RESET, FILTERING=ON";
customerEntity.Connection.Open();
customerEntity.ExecuteStoreCommand(federationCmdText);
}
catch (Exception e)
{
customerEntity.Connection.Close();
SqlConnection.ClearAllPools();
//throw e;
}
});
return customerEntity;
}
public static CrmEntities DBConnect(CrmEntities _db)
{
try{
if (_db == null)
_db = Azure.ConnectCustomerEntity();
if ((_db.Connection.State == ConnectionState.Broken) || (_db.Connection.State == ConnectionState.Closed))
{
SqlConnection.ClearAllPools();
_db = Azure.ConnectCustomerEntity();
}
else
{ //This code is to find out any issues in connection pool database connection
string sqlCmdText = #"select top 1 Id from Project";
_db.ExecuteStoreCommand(sqlCmdText);
}
}
catch (Exception ex)
{
_db.Connection.Close();
SqlConnection.ClearAllPools();
_db = Azure.ConnectCustomerEntity();
}
return _db;
}
}
Mvc Controller. The following code I am gettting that exception, after 30 mins
public class FilterController : Controller
{
public ActionResult GetFilters(string entityName,string typeFilter)
{
_crmEntities=Azure.DBConnect(_db);
var query = _db.FilterFields.Where(filter => filter.TableId == tableId).ToList(); // Here I am getting that exception
}
}
I dont know, Why i m getting that exception. I tried all possibilities. Nothing helped. I really struck with this. If anybody knows please tell your views to come out from this exception
Thanks in Advance.
I think your session times out.
try to increase session timeout:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout.aspx

Possible to access remote EJBs from a custom LoginModule?

I found some nice hints on how to write a custom realm and loginModule. I'm wondering though if it is possible to access a remote EJB within the custom loginModule.
In my case, I have remote EJBs that provide access to user-entities (via JPA) -- can I use them (e.g. via #EJB annotation)?
Ok, I found the answer myself: works fine! I can get a reference to the remote SLSB via an InitialContext.
Here's the code:
public class UserLoginModule extends AppservPasswordLoginModule {
Logger log = Logger.getLogger(this.getClass().getName());
private UserFacadeLocal userFacade;
public UserLoginModule() {
try {
InitialContext ic = new InitialContext();
userFacade = (UserFacadeLocal) ic.lookup("java:global/MyAppServer/UserFacade!com.skalio.myapp.beans.UserFacadeLocal");
log.info("userFacade bean received");
} catch (NamingException ex) {
log.warning("Unable to get userFacade Bean!");
}
}
#Override
protected void authenticateUser() throws LoginException {
log.fine("Attempting to authenticate user '"+ _username +"', '"+ _password +"'");
User user;
// get the realm
UserRealm userRealm = (UserRealm) _currentRealm;
try {
user = userFacade.authenticate(_username, _password.trim());
userFacade.detach(user);
} catch (UnauthorizedException e) {
log.warning("Authentication failed: "+ e.getMessage());
throw new LoginException("UserLogin authentication failed!");
} catch (Exception e) {
throw new LoginException("UserLogin failed: "+ e.getMessage());
}
log.fine("Authentication successful for "+ user);
// get the groups the user is a member of
String[] grpList = userRealm.authorize(user);
if (grpList == null) {
throw new LoginException("User is not member of any groups");
}
// Add the logged in user to the subject's principals.
// This works, but unfortunately, I can't reach the user object
// afterwards again.
Set principals = _subject.getPrincipals();
principals.add(new UserPrincipalImpl(user));
this.commitUserAuthentication(grpList);
}
}
The trick is to separate the interfaces for the beans from the WAR. I bundle all interfaces and common entities in a separate OSGi module and deploy it with asadmin --type osgi. As a result, the custom UserLoginModule can classload them.

service.close() vs. service.abort() - WCF example

In one of the WCF tutorials, I saw the following sample code:
Dim service as ...(a WCF service )
try
..
service.close()
catch ex as Exception()
...
service.abort()
end try
Is this the correct way to ensure that resources (i.e. connections) are released even under error conditions?
See Indisposable: WCF Gotcha #1*, where he comes up with a convenient wrapper method:
public delegate void UseServiceDelegate<T>(T proxy);
public static class Service<T>
{
public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");
public static void Use(UseServiceDelegate<T> codeBlock)
{
var proxy = (IClientChannel)_channelFactory.CreateChannel();
var success = false;
try
{
codeBlock((T)proxy);
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
}
Usage:
Service<IOrderService>.Use(
orderService =>
{
orderService.PlaceOrder(request);
});
* Link removed as it appears to be malicious.
I've had good luck with this model:
Dim service As New MyService()
Dim closed As Boolean = False
Try
service.Open()
If Not service.State = ServiceModel.CommunicationState.Opened Then
''Handle a not-opened state here
End If
service.MyMethod()
service.Close()
closed = true
Catch ex As Exception
''Handle errors here
Finally
If Not closed Then
service.Abort()
End If
End Try
service = Nothing
You've got the general idea correct. I've used the following extension method to keep the lines of repetitive code to a minimum.
public static class ICommunicationObjectExtensions
{
public static void SafelyCloseConnection(this ICommunicationObject objectToClose)
{
bool success = false;
try
{
objectToClose.Close();
success = true;
}
finally
{
if (!success)
{
objectToClose.Abort();
}
}
}
}
Example of code using this extension method:
HelloWorldServiceClient client = new HelloWorldServiceClient();
HelloWorldDataContract dc = new HelloWorldDataContract();
try
{
client.Open();
dc = client.SayHello();
} // Add catch blocks here for anything you want to handle.
finally
{
client.SafelyCloseConnection();
}
Of course this is C#, but I think that should still be of help.
If you use a client side cache, you might consider using Expression Trees (see http://thegrenade.blogspot.com/2009/07/using-expression-trees-for-more-elegant.html):
private static TEntity GetItem<TProxy, TEntity, TIdentity>(Expression<Func<TProxy, TIdentity, TEntity>> expression, TProxy proxy, TIdentity id)
where TEntity : class
where TProxy : ICommunicationObject
{
TEntity item = Cache.GetItem<TEntity, TIdentity>(id);
if (item == null)
{
try
{
var originalDelegate = expression.Compile();
item = originalDelegate.Invoke(proxy, id);
}
finally
{
try{ proxy.Close(); }
finally { proxy.Abort(); }
}
Cache.AddItem<TEntity, TIdentity>(item);
}
return item;
}
Usage:
Product p = GetItem((client, identifier) => client.GetProduct(identifier), new CatalogServiceClient(), 123);