public static void GetPrimaryContactAddressStep( ICustevent custevent, out System.String result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()) { string sql = "select top 1 a.address1 from sysdba.opportunity_contact oc left join sysdba.contact c on oc.contactid=c.contactid left join sysdba.address a on a.entityid=c.contactid where oc.isprimary='T' and a.isprimary='T' and opportunityid='"+custevent.Id.ToString()+"'"; string add1 = session.CreateSQLQuery(sql).UniqueResult<string>(); sql = "select top 1 a.address2 from sysdba.opportunity_contact oc left join sysdba.contact c on oc.contactid=c.contactid left join sysdba.address a on a.entityid=c.contactid where oc.isprimary='T' and a.isprimary='T' and opportunityid='"+custevent.Id.ToString()+"'"; string add2 = session.CreateSQLQuery(sql).UniqueResult<string>(); sql = "select top 1 a.city from sysdba.opportunity_contact oc left join sysdba.contact c on oc.contactid=c.contactid left join sysdba.address a on a.entityid=c.contactid where oc.isprimary='T' and a.isprimary='T' and opportunityid='"+custevent.Id.ToString()+"'"; string city = session.CreateSQLQuery(sql).UniqueResult<string>(); sql = "select top 1 a.state from sysdba.opportunity_contact oc left join sysdba.contact c on oc.contactid=c.contactid left join sysdba.address a on a.entityid=c.contactid where oc.isprimary='T' and a.isprimary='T' and opportunityid='"+custevent.Id.ToString()+"'"; string state = session.CreateSQLQuery(sql).UniqueResult<string>(); sql = "select top 1 a.postalcode from sysdba.opportunity_contact oc left join sysdba.contact c on oc.contactid=c.contactid left join sysdba.address a on a.entityid=c.contactid where oc.isprimary='T' and a.isprimary='T' and opportunityid='"+custevent.Id.ToString()+"'"; string pcode = session.CreateSQLQuery(sql).UniqueResult<string>(); sql = "select top 1 a.country from sysdba.opportunity_contact oc left join sysdba.contact c on oc.contactid=c.contactid left join sysdba.address a on a.entityid=c.contactid where oc.isprimary='T' and a.isprimary='T' and opportunityid='"+custevent.Id.ToString()+"'"; string country = session.CreateSQLQuery(sql).UniqueResult<string>(); string fswon = string.Concat(add1," ",add2," ",city,", ",state," ",pcode," ",country); result=fswon; } }
private void RolloverOpportunities(IUser user) { // Get Current Date DateTime today = DateTime.Now.Date; // Get Fiscal Year Settings int period = Platform.GetQAndFPeriod(); DateTime firstDayofPeriod = (DateTime)Platform.FirstDayofPeriod(DateTime.Now); DateTime beginPreviousPeriod = (DateTime)Platform.FirstDayofPeriod(today.AddMonths(-1 * period)).Value.Date; DateTime endPreviousPeriod = Date.EndOfDay((DateTime)Platform.LastDayofPeriod(beginPreviousPeriod)); using (var session = new SessionScopeWrapper(true)) { Phase = String.Format(Resources.Job_OpportunityRollover_Phase_ProcessingOpportunities, user.UserInfo.NameLF); // Get the Opportunities that need to be rolled over from the previous period IList <IOpportunity> opportunities = session.QueryOver <IOpportunity>() .Where(x => x.AccountManager == user && x.Status == "Open" && x.AddToForecast == true && x.EstimatedClose >= beginPreviousPeriod && x.EstimatedClose <= endPreviousPeriod) .List <IOpportunity>(); foreach (IOpportunity opportunity in opportunities) { opportunity.EstimatedClose = firstDayofPeriod; opportunity.Save(); } } }
public static AuthenticationData RetrieveAuthenticationData(String providerName) { using (var sess = new SessionScopeWrapper()) { var prov = sess.CreateQuery("from OAuthProvider where ProviderName=?") .SetString(0, providerName) .List <IOAuthProvider>().FirstOrDefault(); if (prov == null) { throw new Exception(String.Format("Unable to locate {0} provider in the configured OAuth providers", providerName)); } var userToken = sess.CreateQuery("from UserOAuthToken where OAuthProvider.Id=? and User.Id=?") .SetString(0, prov.Id.ToString()) .SetString(1, ApplicationContext.Current.Services.Get <IUserService>().UserId) .List <IUserOAuthToken>() .FirstOrDefault(); if (userToken == null || userToken.AccessToken == null) { throw new Exception(String.Format("Unable to locate authorization token for current user under {0} provider", providerName)); } if (userToken.ExpirationDate != null && userToken.ExpirationDate < DateTime.Now) { // TODO: refresh, if possible?? (Not applicable to either Twitter or Linked in, though) throw new Exception(String.Format("Authentication token for {0} provider has expired", providerName)); } return(new AuthenticationData { ConsumerKey = prov.ClientId, ConsumerSecret = prov.Secret, Token = userToken.AccessToken, TokenSecret = userToken.AccessTokenSecret, RefreshToken = userToken.RefreshToken }); } }
protected override void OnExecute() { Phase = Resources.Job_Phase_Detail_Initializing; // Set progress bar to 0 Progress = 0; int count = 0; // Retrieve all Users in the Role defined for Quota & Forecast Users using (var session = new SessionScopeWrapper(true)) { Phase = Resources.Job_OpportunityRollover_Phase_Retrieving_Users; IRole role = session.QueryOver <IRole>() .Where(x => x.RoleName == Resources.Job_OpportunityRollover_RoleName) .SingleOrDefault <IRole>(); foreach (IUserRole userRole in role.Users) { RolloverOpportunities(userRole.User); GenerateForecast(userRole.User); Progress = (100M * ++count / role.Users.Count); if (Interrupted) { return; } } } Progress = 100; Phase = Resources.Job_Phase_Detail_Completed; PhaseDetail = String.Format(Resources.Job_OpportunityRollover_Results, count); }
protected override void OnExecute() { Progress = 0; using (var session = new SessionScopeWrapper()) { Phase = "Gathering up Items to deliver"; IList <IDeliveryItem> deliveryItems = session.QueryOver <IDeliveryItem>() .Where(di => di.Status == DeliveryItemStatuses.ToBeProcessed) .List <IDeliveryItem>(); if (deliveryItems != null) { decimal counter = 0; Phase = "Delivering Items"; foreach (IDeliveryItem di in deliveryItems) { ProcessDeliveryItem(di); Progress = 100M * ++counter / deliveryItems.Count; if (Interrupted) { return; } } } } Progress = 100; Phase = Resources.Job_Phase_Detail_Completed; }
// событие OnFormBound используется для регистрации клиентского сценария на странице protected override void OnFormBound() { // проверка выполнения каких либо действий на странице if (!IsCurrentTabVisible) { return; } base.OnFormBound(); //var newcontact = Sage.Platform.EntityFactory.GetById<IContact>("C6UJ9A000CW6"); //btnAdd.OnClientClick = string.Format("Sage.Utility.loadDetailsDialog({{ entityType: 'Sage.Entity.Interfaces.IAssociation, Sage.Entity.Interfaces', entityId: '{0}', smartPart: 'FbAddEditAccountAssociation',dialogParameters: {{ Key:'EntityType', Value:'{2}' }}, dialogTitle: '{1}', isCentered: true, dialogHeight: 260, dialogWidth: 800 }});return false;", id, (string)(CurrentEntity.GetType().Name == "Account" ? GetLocalResourceObject("FbAddEditAccountAssociation.Header") : GetLocalResourceObject("FbAddEditContactAssociation.Header")), CurrentEntity.GetType().Name); using (var session = new SessionScopeWrapper()) // новая сессия { // определение и настройка источника данных для объектов на странице ascs grdFbAccountMyProduct.DataSource = session.CreateSQLQuery( "SELECT FB_ACCOUNTMYPRODUCT.FB_ACCOUNTMYPRODUCTID as Id, FB_ACCOUNTMYPRODUCT.AMOUNT, FB_MYPRODUCT.PRODUCTNAME, FB_ACCOUNTMYPRODUCT.INTERESTRATE FROM FB_ACCOUNTMYPRODUCT INNER JOIN FB_MYPRODUCT ON FB_ACCOUNTMYPRODUCT.MYPRODUCTID = FB_MYPRODUCT.fb_MYPRODUCTID WHERE ACCOUNTID = :accountId") .SetString("accountId", Convert.ToString(CurrentEntity.Id)) .ListAs(new { Id = default(string), AMOUNT = default(decimal), PRODUCTNAME = default(string), INTERESTRATE = default(decimal), }); // привязка данных к источнику данных grdFbAccountMyProduct.DataBind(); } }
public static AuthenticationData RetrieveAuthenticationData(String providerName) { using (var sess = new SessionScopeWrapper()) { var prov = sess.CreateQuery("from OAuthProvider where ProviderName=?") .SetString(0, providerName) .List<IOAuthProvider>().FirstOrDefault(); if (prov == null) { throw new Exception(String.Format("Unable to locate {0} provider in the configured OAuth providers", providerName)); } var userToken = sess.CreateQuery("from UserOAuthToken where OAuthProvider.Id=? and User.Id=?") .SetString(0, prov.Id.ToString()) .SetString(1, ApplicationContext.Current.Services.Get<IUserService>().UserId) .List<IUserOAuthToken>() .FirstOrDefault(); if (userToken == null || userToken.AccessToken == null) { throw new Exception(String.Format("Unable to locate authorization token for current user under {0} provider", providerName)); } if (userToken.ExpirationDate != null && userToken.ExpirationDate < DateTime.Now) { // TODO: refresh, if possible?? (Not applicable to either Twitter or Linked in, though) throw new Exception(String.Format("Authentication token for {0} provider has expired", providerName)); } return new AuthenticationData { ConsumerKey = prov.ClientId, ConsumerSecret = prov.Secret, Token = userToken.AccessToken, TokenSecret = userToken.AccessTokenSecret, RefreshToken = userToken.RefreshToken }; } }
protected override void OnExecute() { if (String.IsNullOrEmpty(BulletinName)) { throw new InvalidOperationException(Resources.Job_BulletinName_NotSpecified); } using (var session = new SessionScopeWrapper()) { IBulletin bulletin = session.QueryOver <IBulletin>() .Where(x => x.BulletinName == BulletinName) .SingleOrDefault <IBulletin>(); if (bulletin == null) { throw new InvalidOperationException(Resources.Job_BulletinName_NotFound); } switch (bulletin.BulletinName) { case "Weekly Forecast Summary": WeeklyForecastSummary(bulletin); break; } } }
private void MoveContactData(SessionScopeWrapper session, string source, string target) { var cmd = session.Connection.CreateCommand(); try { if (cmd.Connection.State == ConnectionState.Closed) { cmd.Connection.Open(); } ExecuteCmd(cmd, string.Format("UPDATE ACTIVITY SET CONTACTID = '{0}' WHERE CONTACTID = '{1}'", target, source)); ExecuteCmd(cmd, string.Format("UPDATE HISTORY SET CONTACTID = '{0}' WHERE CONTACTID = '{1}'", target, source)); ExecuteCmd(cmd, string.Format("UPDATE ATTACHMENT SET CONTACTID = '{0}' WHERE CONTACTID = '{1}'", target, source)); if (cbDelete.Checked) { ExecuteCmd(cmd, string.Format("DELETE FROM CONTACT WHERE CONTACTID = '{0}'", source)); } } catch (Exception error) { logger.Error(error); } }
public static void OnAfterUpdateStep(IAddress address) { using (var session = new SessionScopeWrapper(false)) { //обновить контакты CommonProcedures.UpdateAccountContacts(address.EntityId, session); } }
public static void ReloadSalesOrderStep(IAddEditSalesOrder form, EventArgs args) { using (NHibernate.ISession session = new SessionScopeWrapper(false)) { // forces NHibernate to reload the object session.Refresh(form.CurrentEntity); } }
public static void GetFirstServiceWonStep(ICustfinancial custfinancial, out System.DateTime result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()) { string sql = "select min(actualclose) from opportunity_product where opportunityid='" + custfinancial.Id.ToString() + "'"; DateTime fswon = session.CreateSQLQuery(sql).UniqueResult<DateTime>(); result = fswon; } }
public static void GetMemberPhoneStep( IMeetingTeam meetingteam, out System.String result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()) { string sql = "select phone from userinfo where userid='"+ meetingteam.UserID.ToString()+"'"; result=session.CreateSQLQuery(sql).UniqueResult<string>(); } }
public static void GetActualOrderRevStep( IOrderSummaryDetail ordersummarydetail, out System.Decimal result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()) { string sql = "select revenue from order_summary_detail where ordertype='Actual' and order_summary_detailid='" + ordersummarydetail.Id.ToString() + "'"; decimal fswon = session.CreateSQLQuery(sql).UniqueResult<decimal>(); result = fswon; } }
public static void GetTotalAnticRepBudgetStep( ICustfinancial custfinancial, out System.Decimal result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()) { string sql = "select sum(revenue) from order_summary_detail where ordertype='Anticipated' and opportunityid='" + custfinancial.Id.ToString() + "'"; decimal fswon = session.CreateSQLQuery(sql).UniqueResult<decimal>(); result = fswon; } }
public static void GetBusDevRepStep( ICustfinancial custfinancial, out System.String result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()){ string sql = "select username from userinfo where userid=(select meetingmanager from accountconferon where accountid='"+custfinancial.Accountid+"')"; string fswon = session.CreateSQLQuery(sql).UniqueResult<string>(); result=fswon; } }
public static void GetWonServiceRevStep(ICustfinancial custfinancial, out System.Decimal result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()) { string sql = "select sum(extendedprice) from opportunity_product where status='Execution' and opportunityid='" + custfinancial.Id.ToString() + "'"; decimal fswon = session.CreateSQLQuery(sql).UniqueResult<decimal>(); result = fswon; } }
public static void GetProductName( IOrderSummaryDetail ordersummarydetail, out System.String result) { using (ISession session = new SessionScopeWrapper()) { string sql = "select description from product where productid='"+ordersummarydetail.Productid.ToString()+"'"; string prodname = session.CreateSQLQuery(sql).UniqueResult<string>(); result=prodname; } }
/// <summary> /// Attempt to extract properties from the lookup metadata. /// The result of this operation is cached. /// </summary> /// <param name="lookupName"></param> /// <param name="entityTypeName"></param> /// <returns></returns> internal static LookupPropertyCollection GetLookupProperties(String lookupName, String entityTypeName) { LookupPropertyCollection result = null; if (HttpContext.Current != null && ((result = HttpContext.Current.Cache["LookupProperties$" + entityTypeName + "$" + lookupName] as LookupPropertyCollection) != null)) { return(result); } result = new LookupPropertyCollection(); using (var sess = new SessionScopeWrapper()) { Type entityType = Type.GetType(entityTypeName); if (entityType == null) { throw new ArgumentException("Unable to locate type " + entityTypeName); } if (entityType.IsInterface) { throw new ArgumentException("Must use the concrete class as EntityTypeName (e.g., Sage.SalesLogix.Entities.Contact)"); } String entityName = ((SessionFactoryImpl)sess.SessionFactory).TryGetGuessEntityName(entityType); if (entityName == null) { throw new ArgumentException("Unable to locate persister for entity type " + entityType.FullName); } AbstractEntityPersister persister = (AbstractEntityPersister)((SessionFactoryImpl)sess.SessionFactory).GetEntityPersister(entityName); foreach (LookupLayoutField lookupField in GetLookupFields(sess, persister.TableName, lookupName)) { String[] tableField = lookupField.Path.Split(new char[] { ':' }); if (persister == null || persister.TableName != tableField[0]) { throw new ArgumentException("Invalid lookup data - table name does not match persister table (" + persister.TableName + " vs " + tableField[0] + ") - check EntityName setting"); } String propName = DecomposePath((SessionFactoryImpl)sess.SessionFactory, persister, tableField[1], lookupField.Format); if (propName != null) { result.Add(new LookupProperty(propName, lookupField.Caption)); // TODO: we should set the property format here } } } if (LOG.IsDebugEnabled) { foreach (LookupProperty prop in result) { LOG.Debug("Using property '" + prop.PropertyName + "' with header '" + prop.PropertyHeader + "'"); } } if (HttpContext.Current != null) { HttpContext.Current.Cache["LookupProperties$" + entityTypeName + "$" + lookupName] = result; } return(result); }
/// <summary> /// Gets the opp contact. /// </summary> /// <param name="opportunityContactId">The opportunity contact id.</param> /// <returns></returns> private static IOpportunityContact GetOppContact(string opportunityContactId) { IOpportunityContact oppcon = null; using (ISession session = new SessionScopeWrapper()) { oppcon = EntityFactory.GetById <IOpportunityContact>(opportunityContactId); } return(oppcon); }
/// <summary> /// True if specified user is in specified team (or department). /// Note that this will return true whether the user is a direct member of the team, /// or manager of someone who is. /// </summary> /// <param name="userId"></param> /// <param name="teamName"></param> /// <returns></returns> public static bool IsUserInTeam(String userId, String teamName) { using (var sess = new SessionScopeWrapper()) { return 0 < sess.CreateQuery("select count(*) from OwnerRights sr where sr.User.Id=? and sr.Owner.OwnerDescription=?") .SetString(0, userId) .SetString(1, teamName) .UniqueResult<long>(); } }
public IEnumerable<IRecord> Read() { using (var sess = new SessionScopeWrapper()) { var qry = sess.CreateQuery(_query); IList lst = qry.List(); foreach (object o in lst) yield return new HqlRecordWrapper(o); } }
public void TestFormatUserName() { String entityName = "Sage.SalesLogix.Entities.Contact"; using (var sess = new SessionScopeWrapper()) { SessionFactoryImpl sf = (SessionFactoryImpl)sess.SessionFactory; AbstractEntityPersister persister = (AbstractEntityPersister)(sf.GetEntityPersister(entityName)); Assert.AreEqual("AccountManager.UserInfo.UserName", SimpleLookup.DecomposePath(sf, persister, "ACCOUNTMANAGERID", "6")); } }
/// <summary> /// Gets the user. /// </summary> /// <param name="userId">The user id.</param> /// <returns></returns> private static IUser GetUser(string userId) { IUser user = null; using (ISession session = new SessionScopeWrapper()) { user = EntityFactory.GetById <IUser>(userId); } return(user); }
/// <summary> /// Gets the contact. /// </summary> /// <param name="contactId">The contact id.</param> /// <returns></returns> private static IContact GetContact(string contactId) { IContact contact = null; using (ISession session = new SessionScopeWrapper()) { contact = EntityFactory.GetById <IContact>(contactId); } return(contact); }
public void TestFormatOwner() { String entityName = "Sage.SalesLogix.Entities.Contact"; using (var sess = new SessionScopeWrapper()) { SessionFactoryImpl sf = (SessionFactoryImpl)sess.SessionFactory; AbstractEntityPersister persister = (AbstractEntityPersister)(sf.GetEntityPersister(entityName)); Assert.AreEqual("Owner.OwnerDescription", SimpleLookup.DecomposePath(sf, persister, "SECCODEID", "8")); } }
public static void GetServiceNameStep( ISalesOrderItem salesorderitem, out System.String result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()) { string sql = "select description from product where productid='"+salesorderitem.Product.Id+"'"; string prodname = session.CreateSQLQuery(sql).UniqueResult<string>(); result=prodname; } }
public static void GetPrimaryContactPhoneStep2( ICustevent custevent, out System.String result) { // TODO: Complete business rule implementation using (ISession session = new SessionScopeWrapper()) { string sql = "select top 1 c.workphone from sysdba.opportunity_contact oc left join sysdba.contact c on oc.contactid=c.contactid where oc.isprimary='T' and opportunityid='"+custevent.Id.ToString()+"'"; string fswon = session.CreateSQLQuery(sql).UniqueResult<string>(); result=fswon; } }
public IList<OrmKeyColumn> LoadKeyColumns(string tableName) { Guard.ArgumentNotNullOrEmptyString(tableName, "tableName"); using (ISession session = new SessionScopeWrapper()) { return session.CreateCriteria(typeof (OrmKeyColumn)) .Add(Expression.Eq("TableName", tableName)) .List<OrmKeyColumn>(); } }
public static void OnAfterDelete(IAccNewsletter accnewsletter) { using (var session = new SessionScopeWrapper()) { // обновить контакты if (accnewsletter.AccContactInfo != null) { CommonProcedures.UpdateAccountContacts(accnewsletter.AccContactInfo.AccountId, session); } } }
protected void cmdOK_Click(object sender, EventArgs e) { try { // if there is no target account selected, return and notify user if (lueTargetAccount.LookupResultValue == null) { lblTargetAccountErr.Visible = true; return; } // check to make sure the contact is not being copied to same account if (Contact.Account.Equals(lueTargetAccount.LookupResultValue)) { lblTargetAccountErr.Visible = true; return; } // get the source account var theAcct = (IAccount)lueTargetAccount.LookupResultValue; // create a dictionary fo key value pairs for all the selected copy options var options = new Dictionary <string, bool> { { "AssociateWithSource", chkAssociateWithSource.Checked }, { "UseTargetAddressPhn", chkUseTargetAddressPhn.Checked }, { "CopyNotes", chkCopyNotes.Checked }, { "CopyActivities", chkCopyActivities.Checked }, { "CopyHistory", chkCopyHistory.Checked } }; // session wrapper to pass in ISession session = new SessionScopeWrapper(); // call the CopyToNewContact method var copiedContact = Contact.CopyNewContact(theAcct, options, session); if (copiedContact.Id != null) { Response.Redirect(string.Format("Contact.aspx?entityId={0}", (copiedContact.Id)), false); } } catch (Exception ex) { string sSlxErrorId = null; var sMsg = ErrorHelper.GetClientErrorHtmlMessage(ex, ref sSlxErrorId); if (!string.IsNullOrEmpty(sSlxErrorId)) { log.Error(ErrorHelper.AppendSlxErrorId("The call to SmartParts_Contact_CopyNewContact.cmdOK_Click failed", sSlxErrorId), ex); } DialogService.ShowHtmlMessage(sMsg, ErrorHelper.IsDevelopmentContext() ? 600 : -1, ErrorHelper.IsDevelopmentContext() ? 800 : -1); } DialogService.CloseEventHappened(sender, e); }
/// <summary> /// True if specified user is in specified team (or department). /// Note that this will return true whether the user is a direct member of the team, /// or manager of someone who is. /// </summary> /// <param name="userId"></param> /// <param name="teamName"></param> /// <returns></returns> public static bool IsUserInTeam(String userId, String teamName) { using (var sess = new SessionScopeWrapper()) { return(0 < sess.CreateQuery("select count(*) from OwnerRights sr where sr.User.Id=? and sr.Owner.OwnerDescription=?") .SetString(0, userId) .SetString(1, teamName) .SetCacheable(true) .UniqueResult <long>()); } }
protected override void OnExecute() { IList <INotificationEvent> notificationEvents = null; // Get the list of Notification Events to process using (var session = new SessionScopeWrapper()) { notificationEvents = session.QueryOver <INotificationEvent>() .Where(x => x.NextTimeToCheck <= DateTime.Now && x.Enabled == true) .List <INotificationEvent>(); } if (notificationEvents != null) { foreach (INotificationEvent ne in notificationEvents) { string query = ParseQueryForLiterals(ne); DateTime now = DateTime.UtcNow; bool bResult = false; // Execute the query using (var session = new SessionScopeWrapper()) { Type entityType = typeof(Sage.SalesLogix.Entities.Account).Assembly.GetType(String.Format("Sage.SalesLogix.Entities.{0}", ne.EntityName)); IList <dynamic> payload = session.CreateQuery(query).List <dynamic>(); if (payload.Count > 0) { if (ne.Digest == true) { bResult = ProcessDigestEvent(ne, payload); } else { bResult = ProcessSingleEvent(ne, payload); } } else { // Noting to process, but move the next time to check anyway. bResult = true; } } if (bResult) { // Update Notification Event ne.LastChecked = now; ne.NextTimeToCheck = GetNextTimeToCheck(ne, now); ne.Save(); } } } }
private IPickListView GetPickListView() { IPickListView plv = BindingSource.Current as IPickListView; using (ISession session = new SessionScopeWrapper(true)) { return(session.QueryOver <IPickListView>() .Where(x => x.Id == plv.Id) .SingleOrDefault()); } }
public IEnumerable<IRecord> Read(WorkItem workItem) { String query = String.Format("from {0} where {1}", _entity, workItem.EvaluateLiterals(_where, this)); using (var sess = new SessionScopeWrapper()) { var qry = sess.CreateQuery(query); IList lst = qry.List(); foreach (object o in lst) yield return new EntityRecordWrapper(o); } }
private void WeeklyForecastSummary(IBulletin bulletin) { DateTime today = DateTime.UtcNow; ForecastSummary fs = new ForecastSummary(); Progress = 0; decimal counter = 0; using (var session = new SessionScopeWrapper()) { IList <IForecast> forecasts = session.QueryOver <IForecast>() .Where(x => today >= x.BeginDate && today <= x.EndDate && x.Active == true) .List <IForecast>(); foreach (IForecast f in forecasts) { ForecastInfo fi = new ForecastInfo(); fi.ForecastName = f.Description; fi.AssignedTo = f.AssignedTo.UserInfo.NameLF; fi.Amount = Convert.ToDecimal(f.Amount); fi.Pipeline = (decimal)f.PeriodPipelineAmt("Avg"); fi.ClosedWon = (decimal)f.PeriodClosedWonAmt(); fi.Quota = GetQuotaAmtforUser(f.AssignedTo, today); fs.forecasts.Add(fi); Progress = (100M * ++counter / forecasts.Count) / 2; } } counter = 0; if (fs.forecasts.Count > 0) { string msgBody = BuildMessageBody(fs); string subject = "Weekly Forecast Summary"; IDeliveryItem di = Sage.Platform.EntityFactory.Create <IDeliveryItem>(); di.Body = msgBody; di.Subject = subject; di.DeliverySystem = bulletin.DeliverySystem; di.Status = "To Be Processed"; foreach (IBulletinSubscriber subscriber in bulletin.Subscribers) { IDeliveryItemTarget target = EntityFactory.Create <IDeliveryItemTarget>(); target.DeliveryItem = di; target.Address = subscriber.Subscriber.UserInfo.Email; target.Type = "TO"; di.DeliveryItemTargets.Add(target); di.Save(); Progress = 50M + (50M * ++counter / bulletin.Subscribers.Count); } } }
/// <summary> /// Gets the opp contact count. /// </summary> /// <param name="opportunityId">The opportunity id.</param> /// <returns></returns> private static int GetOppContactCount(string opportunityId) { int count = 0; IOpportunity opp; using (ISession session = new SessionScopeWrapper()) { opp = EntityFactory.GetById <IOpportunity>(opportunityId); count = opp.Contacts.Count; } return(count); }
/// <summary> /// Gets the opp account manager. /// </summary> /// <param name="opportunityId">The opportunity id.</param> /// <returns></returns> private static IUser GetOppAccountManager(string opportunityId) { IUser user = null; IOpportunity opp = null; using (ISession session = new SessionScopeWrapper()) { opp = EntityFactory.GetById <IOpportunity>(opportunityId); user = opp.AccountManager; } return(user); }
public static void ValidateCommissionStep(IOpportunity opportunity, out Boolean result) { // TODO: Complete business rule implementation result = false; using (ISession session = new SessionScopeWrapper()) { string strSQL = "select count(*) from salesorder where salescommission>0 and salescommission2>0 and accountid='"+opportunity.Account.Id.ToString()+"' and opportunityid='"+opportunity.Id.ToString()+"'"; int salesorder = session.CreateSQLQuery(strSQL).UniqueResult<int>(); if (salesorder > 0) { result = true; } } }
public void TestDecomposePath() { String entityName = "Sage.SalesLogix.Entities.Contact"; using (var sess = new SessionScopeWrapper()) { SessionFactoryImpl sf = (SessionFactoryImpl)sess.SessionFactory; AbstractEntityPersister persister = (AbstractEntityPersister)(sf.GetEntityPersister(entityName)); Assert.AreEqual("LastName", SimpleLookup.DecomposePath(sf, persister, "LASTNAME", "0")); Assert.AreEqual("Address.PostalCode", SimpleLookup.DecomposePath(sf, persister, "ADDRESSID=ADDRESSID.ADDRESS!POSTALCODE", "0")); Assert.AreEqual("AccountManager.UserInfo.UserName", SimpleLookup.DecomposePath(sf, persister, "ACCOUNTMANAGERID>USERID.USERINFO!USERNAME", "0")); } }
public static void ValidateSalesOrderStep( IOpportunityProduct opportunityproduct, out Boolean result) { // TODO: Complete business rule implementation result = false; using (ISession session = new SessionScopeWrapper()) { string strSQL = "select count(*) from salesorderdetail where productid ='"+opportunityproduct.Product.Id.ToString()+"' and salesorderid in (select salesorderid from salesorder where Actual = 'F' and Opportunityid='"+opportunityproduct.Opportunity.Id.ToString()+"')"; int salesorder = session.CreateSQLQuery(strSQL).UniqueResult<int>(); if (salesorder > 0) { result = true; } } }
public static void GetInitialSalesRepStep( IOpportunity opportunity, out System.String result) { // TODO: Complete business rule implementation string fswon = string.Empty; try{ using (ISession session = new SessionScopeWrapper()) { string sql = "select username from userinfo where userid='"+opportunity.Account.AccountConferon.InitialSalesRep.ToString()+"'"; fswon = session.CreateSQLQuery(sql).UniqueResult<string>(); } }catch(Exception){} result=fswon; }
private IPickListView GetPickListView() { IPickListView plv = this.BindingSource.Current as IPickListView; using (ISession session = new SessionScopeWrapper(true)) { IQuery query = session.CreateQuery("select p1 from PickListView p1 where p1.Id = :PickListId"); query .SetAnsiString("PickListId", plv.Id.ToString()) .SetCacheable(false); return(query.UniqueResult <IPickListView>()); } }
public static void OnAfterInsertStep(IAccNewsletter accnewsletter) { accnewsletter.UnsetAllMain(); //accnewsletter.CheckAccContactInfo(); using (var session = new SessionScopeWrapper()) { // обновить контакты if (accnewsletter.AccContactInfo != null) { CommonProcedures.UpdateAccountContacts(accnewsletter.AccContactInfo.AccountId, session); } } }
/// <summary> /// Handles the SelectedIndexChanged event of the cboQualifications control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void cboQualifications_SelectedIndexChanged(object sender, EventArgs e) { ListItem item = cboQualifications.SelectedItem; if (item != null) { using (NHibernate.ISession session = new SessionScopeWrapper()) { ILead lead = GetCurrentLead(); if (lead != null) { IQualificationCategory currentCategory = lead.QualificationCategory; if (currentCategory != null) { IList <IQualification> qualifications = GetQualifications(currentCategory); if (qualifications != null) { IList <ILeadQualification> lead_qualifications = GetLeadQualifications(currentCategory, qualifications, lead); if (lead_qualifications != null) { if (lead_qualifications.Count > 0) { string confirmation = htxtConfirmation.Value; if (!string.IsNullOrEmpty(confirmation)) { const string cFalse = "false"; if (confirmation.ToLower() == cFalse) { cboQualifications.SelectedValue = currentCategory.Id.ToString(); return; } } foreach (ILeadQualification lead_qual in lead_qualifications) { lead_qual.Delete(); } lead_qualifications.Clear(); } } } } IQualificationCategory category = EntityFactory.GetById <IQualificationCategory>(item.Value); if (category != null) { lead.QualificationCategory = category; session.Update(lead); } } } } }
private IList <IPickListItemView> GetItems(IPickListView pickList) { using (ISession session = new SessionScopeWrapper(true)) { if (string.IsNullOrEmpty(_sortExpression)) { _sortExpression = "OrderSeq"; } var query = session.QueryOver <IPickListItemView>() .Where(x => x.UserId == "ADMIN" && x.PickListId == (string)pickList.Id); query.UnderlyingCriteria.AddOrder(new Order(_sortExpression, _sortDirection)); return(query.List()); } }
/// <summary> /// Gets the opp contacts. /// </summary> /// <param name="opportunityId">The opportunity id.</param> /// <returns></returns> private static IList <IContact> GetOppContacts(string opportunityId) { List <IContact> contacts = new List <IContact>(); IOpportunity opp = null; using (ISession session = new SessionScopeWrapper()) { opp = EntityFactory.GetById <IOpportunity>(opportunityId); foreach (IOpportunityContact oppCon in opp.Contacts) { contacts.Add(oppCon.Contact); } } return(contacts); }
public string GetPeriodIdForCurrentDate() { var periodId = string.Empty; var currentdate = DateTime.UtcNow.Date; using (ISession session = new SessionScopeWrapper()) { var presentDatePeriod = session .Query <IPeriod>().ToList().Find(x => x.EffectiveFrom.Value.Date <= currentdate && x.ExpiresAfter.Value.Date >= currentdate); if (presentDatePeriod != null) { periodId = presentDatePeriod.Id.ToString(); } } return(periodId); }
public static void GetInitialSalesRepStep( ICustfinancial custfinancial, out System.String result) { string fswon = string.Empty; try{ using (ISession session = new SessionScopeWrapper()) { if (!string.IsNullOrEmpty(custfinancial.Account.AccountConferon.InitialSalesRep.ToString()) || custfinancial.Account.AccountConferon.InitialSalesRep.ToString()!=null) { string sql = "select username from userinfo where userid='"+custfinancial.Account.AccountConferon.InitialSalesRep.ToString()+"'"; fswon = session.CreateSQLQuery(sql).UniqueResult<string>(); } } } catch(Exception){ } result=fswon; }
private IList <IPickListItemView> GetItems(IPickListView pickList) { using (ISession session = new SessionScopeWrapper(true)) { if (string.IsNullOrEmpty(_sortExpression)) { _sortExpression = "OrderSeq"; } var query = session.QueryOver <IPickListItemView>() .Where(x => x.UserId == "ADMIN" && x.PickListId == (string)pickList.Id); if (!cboViewedLanguage.SelectedValue.Equals(AllItems)) { query.WhereRestrictionOn(x => x.LanguageCode).IsInsensitiveLike(cboViewedLanguage.Text); } query.UnderlyingCriteria.AddOrder(new Order(_sortExpression, _sortDirection)); return(query.List()); } }
public static void GetSalesOrdReceiptsStep( ISalesOrder salesorder, out System.Decimal result) { // TODO: Complete business rule implementation try{ using (ISession session = new SessionScopeWrapper()) { decimal fswon=0; if (salesorder!=null){ if (!string.IsNullOrEmpty(salesorder.Id.ToString())){ string sql = "select sum(amount) from receipts where salesorderid= (select top 1 salesorderid from salesorder where actual = 'T' and anticipatedid='" + salesorder.Id.ToString() + "')"; fswon = session.CreateSQLQuery(sql).UniqueResult<decimal>(); } } if (!string.IsNullOrEmpty(fswon.ToString())){ result = fswon; } else { result = 0; } } } catch(Exception){result=0;} }
public static void GetCSAnticNoStep( ISalesOrder salesorder, out System.String result) { try{ using (ISession session = new SessionScopeWrapper()){ string fswon = string.Empty; if (salesorder!=null){ if (!string.IsNullOrEmpty(salesorder.Id.ToString())){ string sql = "select documentid from salesorder where actual = 'F' and salesorderid='"+salesorder.Id.ToString()+"'"; fswon = session.CreateSQLQuery(sql).UniqueResult<string>(); } } if (!string.IsNullOrEmpty(fswon)){ result=fswon; } else { result="-"; } } } catch(Exception){ result="-";} }
public static void GetSalesOrdActRevStep(ISalesOrder salesorder, out System.Double result) { // TODO: Complete business rule implementation try{ using (ISession session = new SessionScopeWrapper()) { double fswon=0; if (salesorder!=null){ if (!string.IsNullOrEmpty(salesorder.Id.ToString())){ string sql = "select top 1 ordertotal from salesorder where Actual='T' and anticipatedid='" + salesorder.Id.ToString() + "'"; fswon = session.CreateSQLQuery(sql).UniqueResult<double>(); } } if (!string.IsNullOrEmpty(fswon.ToString())){ result = fswon; } else { result = 0; } } } catch(Exception) { result=0;} }
/// <summary> /// Handles the Click event of the GetPasswordHint control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void GetPasswordHint_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(slxLogin.UserName)) { HintText.Text = GetLocalResourceObject("PasswordHintUserNameRequired").ToString(); } else { IList<IContact> contacts = null; using (ISession session = new SessionScopeWrapper()) { contacts = session.CreateQuery("from Contact c where c.WebUserName = :value") .SetAnsiString("value", slxLogin.UserName) .List<IContact>(); } if ((contacts != null) && (contacts.Count > 0)) { HintText.Text = (contacts[0].WebPasswordHint); } } HintTextDiv.Style.Add(HtmlTextWriterStyle.Display, "inline"); }
public static void GetSalesOrdAnticDateStep( ISalesOrder salesorder, out System.DateTime result) { // TODO: Complete business rule implementation] try{ using (ISession session = new SessionScopeWrapper()) { DateTime fswon = System.DateTime.MinValue; if (salesorder!=null){ if (!string.IsNullOrEmpty(salesorder.Id.ToString())){ string sql = "select orderdate from salesorder where actual = 'F' and salesorderid='" + salesorder.Id.ToString() + "'"; fswon = session.CreateSQLQuery(sql).UniqueResult<DateTime>(); } } if (!string.IsNullOrEmpty(fswon.ToString())){ result = fswon; } else { result=System.DateTime.MinValue; } } } catch(Exception){ result=System.DateTime.MinValue;} }
public static void CreateSalesOrderStep( IOpportunityProduct opportunityproduct) { // TODO: Complete business rule implementation ISession session = new SessionScopeWrapper(); string strSQL = "select max(documentid)+1 from salesorder where len(documentid)>5"; int docid = session.CreateSQLQuery(strSQL).UniqueResult<int>(); //-------- Sage.Entity.Interfaces.ISalesOrder saleso =Sage.Platform.EntityFactory.Create<Sage.Entity.Interfaces.ISalesOrder>(); Sage.Entity.Interfaces.ISalesorderdetail sodetail = Sage.Platform.EntityFactory.Create<Sage.Entity.Interfaces.ISalesorderdetail>(); try { saleso.Account = opportunityproduct.Opportunity.Account; saleso.Opportunity = opportunityproduct.Opportunity; if (opportunityproduct.ExtendedPrice!=null){ saleso.OrderTotal = (double) opportunityproduct.ExtendedPrice; } else { saleso.OrderTotal = 0; } if (opportunityproduct.ExtendedPrice!=null){ saleso.Totalcommissionable = (double) opportunityproduct.ExtendedPrice; } else { saleso.Totalcommissionable = 0; } saleso.OrderType = "Regular Order" ; saleso.DocumentId = docid.ToString(); saleso.Status = "Open Order"; saleso.UserId = opportunityproduct.Opportunity.AccountManager.Id.ToString(); if (opportunityproduct.Opportunity.OpportunityCIUDF.Accountmanagerid2!=null){ saleso.UserID2 = opportunityproduct.Opportunity.OpportunityCIUDF.Accountmanagerid2.ToString(); } saleso.Owner = opportunityproduct.Opportunity.Owner; if (opportunityproduct.Product.Family.ToString().Trim()=="FAMCLI"){ saleso.BillToName = opportunityproduct.Opportunity.Account.AccountName; saleso.Billtoaccount = opportunityproduct.Opportunity.Account.Id.ToString(); strSQL = "select contactid from contact where accountid='"+opportunityproduct.Opportunity.Account.Id.ToString()+"' and isprimary='T'"; saleso.Billtocontact = session.CreateSQLQuery(strSQL).UniqueResult<string>(); } saleso.Actual=false; } catch { throw new Sage.Platform.Application.ValidationException("Sales Order Information Incomplete. Please Check that this Opportunity have a Primary Contact Related."); } try { sodetail.SalesOrder = saleso; sodetail.ProductId = opportunityproduct.Product.Id.ToString(); if (opportunityproduct.OpportunityProductCI.Other_fees!=null || opportunityproduct.OpportunityProductCI.Other_fees>0) { // //sodetail.Num2 = (short)opportunityproduct.OpportunityProductCI.Num2; /*sodetail.Num3 = opportunityproduct.OpportunityProductCI.Num3; sodetail.Num4 = opportunityproduct.OpportunityProductCI.Num4; sodetail.Fees1 = opportunityproduct.OpportunityProductCI.Fees1; sodetail.Fees1Desc = opportunityproduct.OpportunityProductCI.Fees1Desc; sodetail.Fees2 = opportunityproduct.OpportunityProductCI.Fees2; sodetail.Fees2Desc = opportunityproduct.OpportunityProductCI.Fees2Desc; sodetail.Fees3 = opportunityproduct.OpportunityProductCI.Fees3; sodetail.Fees3Desc = opportunityproduct.OpportunityProductCI.Fees3Desc; sodetail.Fees4 = opportunityproduct.OpportunityProductCI.Fees4; sodetail.Fees4Desc = opportunityproduct.OpportunityProductCI.Fees4Desc; sodetail.Rate = opportunityproduct.OpportunityProductCI.Rate; sodetail.Rate2 = opportunityproduct.OpportunityProductCI.Rate2; sodetail.Rate3 = opportunityproduct.OpportunityProductCI.Rate3; sodetail.Rate4 = opportunityproduct.OpportunityProductCI.Rate4; */ if (opportunityproduct.CalculatedPrice!=null){ sodetail.Calcprice = (double)opportunityproduct.CalculatedPrice; } if (opportunityproduct.ExtendedPrice!=null){ sodetail.Extendedprice = (double)opportunityproduct.ExtendedPrice; } if (opportunityproduct.Price!=null){ sodetail.Price = (double)opportunityproduct.Price; } if (opportunityproduct.OpportunityProductCI.Commission!=null){ sodetail.Commission = opportunityproduct.OpportunityProductCI.Commission; } if (opportunityproduct.OpportunityProductCI.Discount!=null){ sodetail.Discount = opportunityproduct.OpportunityProductCI.Discount; } if (opportunityproduct.OpportunityProductCI.Onsite_fees!=null){ sodetail.Onsite_fees = (decimal) opportunityproduct.OpportunityProductCI.Onsite_fees; } else { sodetail.Onsite_fees = 0; } if (opportunityproduct.OpportunityProductCI.Other_fees!=null){ sodetail.Other_fees = (decimal) opportunityproduct.OpportunityProductCI.Other_fees; } else { sodetail.Other_fees = 0; } if (opportunityproduct.OpportunityProductCI.Num!=null){ sodetail.Num = opportunityproduct.OpportunityProductCI.Num; } } saleso.OrderDate = DateTime.Now; saleso.Salesorderdetails.Add(sodetail); saleso.Save(); } //End Try catch { throw new Sage.Platform.Application.ValidationException("Creation Process not completed. Please Check that this Opportunity have a Primary Contact Related."); } }
private void ExportPickListData(IList<string> selections, string format) { if (selections == null) { using (ISession session = new SessionScopeWrapper()) { selections = session.QueryOver<PickList>() .Where(x => x.PickListId == "PICKLISTLIST") .OrderBy(x => x.Text).Asc .Select(x => x.ItemId) .Cacheable() .List<string>(); } } DataTable dt = new DataTable("PickLists"); DataColumn dc = dt.Columns.Add(); dc.ColumnName = "PickListName"; dc.DataType = typeof(string); dc.AllowDBNull = true; dc = dt.Columns.Add(); dc.ColumnName = "Text"; dc.DataType = typeof(string); dc.AllowDBNull = true; dc = dt.Columns.Add(); dc.ColumnName = "Code"; dc.DataType = typeof(string); dc.AllowDBNull = true; dc = dt.Columns.Add(); dc.ColumnName = "Order"; dc.DataType = typeof(int); dc.AllowDBNull = true; dc = dt.Columns.Add(); dc.ColumnName = "IsDefault"; dc.DataType = typeof(bool); dc.AllowDBNull = true; dc = dt.Columns.Add(); dc.ColumnName = "PickListId"; dc.DataType = typeof(string); dc.AllowDBNull = true; dc = dt.Columns.Add(); dc.ColumnName = "ItemId"; dc.DataType = typeof(string); dc.AllowDBNull = true; IDictionary<string, Layout> layout = new Dictionary<string, Layout>(); Layout item = new Layout(); item = new Layout(); item.ColumnName = "PickListName"; item.ColumnCaption = "PickListName"; item.Visible = true; item.FormatType = string.Empty; item.FormatString = string.Empty; item.Width = 64; layout.Add(item.ColumnName, item); item = new Layout(); item.ColumnName = "Text"; item.ColumnCaption = "Text"; item.Visible = true; item.FormatType = string.Empty; item.FormatString = string.Empty; item.Width = 64; layout.Add(item.ColumnName, item); item = new Layout(); item.ColumnName = "Code"; item.ColumnCaption = "Code"; item.Visible = true; item.FormatType = string.Empty; item.FormatString = string.Empty; item.Width = 64; layout.Add(item.ColumnName, item); item = new Layout(); item.ColumnName = "Order"; item.ColumnCaption = "Order"; item.Visible = true; item.FormatType = string.Empty; item.FormatString = string.Empty; item.Width = 64; layout.Add(item.ColumnName, item); item = new Layout(); item.ColumnName = "IsDefault"; item.ColumnCaption = "IsDefault"; item.Visible = true; item.FormatType = string.Empty; item.FormatString = string.Empty; item.Width = 64; layout.Add(item.ColumnName, item); item = new Layout(); item.ColumnName = "PickListId"; item.ColumnCaption = "PickListId"; item.Visible = true; item.FormatType = string.Empty; item.FormatString = string.Empty; item.Width = 64; layout.Add(item.ColumnName, item); item = new Layout(); item.ColumnName = "ItemId"; item.ColumnCaption = "ItemId"; item.Visible = true; item.FormatType = string.Empty; item.FormatString = string.Empty; item.Width = 64; layout.Add(item.ColumnName, item); foreach (string pickListId in selections) { PickList pl = PickList.GetPickListById(pickListId); if (pl != null) { PickList defaultItem = PickList.GetDefaultItem(pickListId); IList<PickList> Items = PickList.GetPickListItems(pickListId, false); if ((items != null) || (Items.Count > 0)) { foreach (PickList pitem in Items) { DataRow row = dt.NewRow(); row["PickListId"] = pickListId; row["ItemId"] = pitem.ItemId; row["PickListName"] = pl.Text; row["Text"] = pitem.Text; row["Code"] = pitem.Shorttext; row["Order"] = pitem.Id; if ((defaultItem != null) && (defaultItem.ItemId == pitem.ItemId)) { row["IsDefault"] = true; } else { row["IsDefault"] = false; } dt.Rows.Add(row); } } else { DataRow row = dt.NewRow(); row["PickListId"] = pickListId; row["ItemId"] = "NOITEMS"; row["PickListName"] = pl.Text; row["Text"] = ""; row["Code"] = ""; row["Order"] = -1; row["IsDefault"] = false; dt.Rows.Add(row); } } } switch (format) { case "csv": ToCSV(dt, layout); break; case "tab": ToTab(dt, layout); break; } }