www.pudn.com > Tustena_CRM_OS_3.0.2_Stable.zip > G.cs, change:2005-12-16,size:36283b


/// TUSTENA PUBLIC LICENSE v1.0 
///  
/// Portions Copyright (c) 2003-2005 Digita S.r.l. All Rights Reserved. 
/// 
/// Tustena CRM is a trademark of: 
/// Digita S.r.l. 
/// Viale Enrico Fermi 14/z 
/// 31011 Asolo (Italy) 
/// Tel. +39-0423-951251 
/// Mail. info@digita.it 
/// 
/// This file contains Original Code and/or Modifications of Original Code 
/// as defined in and that are subject to the Tustena Public Source License 
/// Version 1.0 (the 'License'). You may not use this file except in 
/// compliance with the License. Please obtain a copy of the License at 
/// http://www.tustena.com/TPL/ and read it before using this 
// file. 
/// 
/// The Original Code and all software distributed under the License are 
/// distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER 
/// EXPRESS OR IMPLIED, AND DIGITA S.R.L. HEREBY DISCLAIMS ALL SUCH WARRANTIES, 
/// INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, 
/// FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. 
/// Please see the License for the specific language governing rights and 
/// limitations under the License. 
/// 
/// YOU MAY NOT REMOVE OR ALTER THIS COPYRIGHT NOTICE! 
///  
 
#define   VIEWSTATETOSQLSERVER 
using System; 
using System.Collections; 
using System.Data; 
using System.Globalization; 
using System.IO; 
using System.Resources; 
using System.Text; 
using System.Web; 
using System.Web.Caching; 
using System.Web.UI; 
using Digita.Tustena.Base; 
using Digita.Tustena.Database; 
 
namespace Digita.Tustena 
{ 
	public class G : Page, ITransaction 
	{ 
		public static DateTimeFormatInfo InvariantCultureForDB; //new CultureInfo("en-US").DateTimeFormat; 
		public static ResourceManager rm; 
		public UserConfig UC; 
		public string mode = "0"; 
 
 
		public G() 
		{ 
		} 
 
		protected override void OnInit(EventArgs e) 
		{ 
			Trace.Warn("G Costruttore"); 
			DatabaseConnection.needTransaction = true; 
			InvariantCultureForDB = CultureInfo.InvariantCulture.DateTimeFormat; 
			rm = (ResourceManager) HttpContext.Current.Application["RM"]; 
			UC = new UserConfig(); 
			base.OnInit(e); 
		} 
 
		protected override void OnUnload(EventArgs e) 
		{ 
			DatabaseConnection.CommitTransaction(); 
			base.OnUnload(e); 
		} 
 
		protected override void OnError(EventArgs e) 
		{ 
			DatabaseConnection.RollBackTransaction(); 
			base.OnError(e); 
		} 
 
		public UserConfig CurrentUC 
		{ 
			get { return (UserConfig) HttpContext.Current.Session["UserConfig"]; } 
		} 
 
		public static string GetGroupDescription(int groupId) 
		{ 
			return DatabaseConnection.SqlScalar("select description from groups where id=" + groupId); 
		} 
 
 
		public static string ParseJSString(string s) 
		{ 
			s = s.Replace("'", "\\\'"); 
			s = s.Replace("\"", """); 
			s = s.Replace("\n", " "); 
			s = s.Replace("\r", ""); 
			return s; 
		} 
 
		public string Capitalize(string s) 
		{ 
			return StaticFunctions.Capitalize(s); 
		} 
 
		public static string FixCarriage(string text) 
		{ 
			return StaticFunctions.FixCarriage(text); 
		} 
 
		public static string FixCarriage(string text, bool js) 
		{ 
			return StaticFunctions.FixCarriage(text, js); 
		} 
 
 
		private LosFormatter _formatter = null; 
 
 
		protected override void SavePageStateToPersistenceMedium(object viewState) 
		{ 
			string str = "VIEWSTATE#" + Session.SessionID.ToString() + "#" + DateTime.Now.Ticks.ToString(); 
			RegisterHiddenField("__VIEWSTATE_KEY", str); 
			RegisterHiddenField("__VIEWSTATE", ""); 
 
			if (_formatter == null) 
			{ 
				_formatter = new LosFormatter(); 
			} 
 
#if VIEWSTATETOSQLSERVER 
			StringWriter _writer = new StringWriter(); 
			_formatter.Serialize(_writer, viewState); 
 
			DbSqlParameterCollection Msc = new DbSqlParameterCollection(); 
 
 
			DbSqlParameter ViewPage = new DbSqlParameter("@Page", SqlDbType.VarChar, 50); 
			if (Session["ViewStatePage"] != null) 
			{ 
				ViewPage.Value = Session["ViewStatePage"].ToString(); 
				Session["ViewStatePage"] = null; 
			} 
			else 
			{ 
				ViewPage.Value = Request.Path.ToString(); 
			} 
			Msc.Add(ViewPage); 
 
			DbSqlParameter UserId = new DbSqlParameter("@UserId", SqlDbType.Int, 4); 
			UserId.Value = UC.UserId; 
			Msc.Add(UserId); 
 
			DbSqlParameter SessionId = new DbSqlParameter("@SessionId", SqlDbType.VarChar, 55); 
			SessionId.Value = str; 
			Msc.Add(SessionId); 
			DbSqlParameter ViewStateObj = new DbSqlParameter("@ViewState", SqlDbType.Text); 
			ViewStateObj.Value = _writer.ToString(); 
			Msc.Add(ViewStateObj); 
 
			try 
			{ 
				try 
				{ 
					DatabaseConnection.DoStored("ViewStateMgr", Msc); 
				} 
				catch (Exception e) 
				{ 
					G.SendError("[Tustena] DataBase Error", e.Message); 
					Response.Clear(); 
					Response.Write(String.Format(G.rm.GetString("DbConnetionError"), e.Message)); 
					Response.End(); 
				} 
			} 
			catch 
			{ 
				DatabaseConnection.DoCommand("delete from ViewStateManager WHERE SessionID='" + Session.SessionID.ToString() + "'"); 
			} 
			finally 
			{ 
			} 
#else 
			Cache.Add(str, viewState, null, DateTime.Now.AddMinutes(Session.Timeout), TimeSpan.Zero, CacheItemPriority.Default, null); 
#endif 
		} 
 
		protected override object LoadPageStateFromPersistenceMedium() 
		{ 
 
			if (_formatter == null) 
			{ 
				_formatter = new LosFormatter(); 
			} 
 
			string str = Request.Form["__VIEWSTATE_KEY"]; 
			if (!str.StartsWith("VIEWSTATE#")) 
			{ 
				throw new Exception("Invalid viewstate key:" + str); 
			} 
#if VIEWSTATETOSQLSERVER 
			DbSqlParameterCollection Msc = new DbSqlParameterCollection(); 
 
			DbSqlParameter SessionId = new DbSqlParameter("@SessionId", SqlDbType.VarChar, 55); 
			SessionId.Value = str; //Session.SessionID.ToString(); 
			Msc.Add(SessionId); 
 
			string viewState = String.Empty; 
			try 
			{ 
				viewState = (string) DatabaseConnection.DoStoredScalar("LoadViewStateMgr", Msc, false); 
			} 
			catch (Exception ex) 
			{ 
				SendError("LoadPageStateFromPersistenceMedium", ex.ToString() + "

"); // + error); } finally { } if (viewState == null) { Response.Redirect(Request.UrlReferrer.ToString()); Response.End(); } return _formatter.Deserialize(viewState); #else if (!str.StartsWith("VIEWSTATE#")) { throw new Exception("Invalid viewstate key:" + str); } return Cache[str]; #endif } public bool Login() { if (Request.Params["logoff"] == "true") { UC = HttpContext.Current.Session["UserConfig"] as UserConfig; if (UC != null) { DatabaseConnection.DoCommand("UPDATE Account set State=0 WHERE uid=" + UC.UserId); } Session.Abandon(); return false; } else { if (Session["UserConfig"] != null) { UC = HttpContext.Current.Session["UserConfig"] as UserConfig; IsAlreadyIn(); return true; } else return false; } } public static DataSet FixDateTimeZone(DataSet dt, SimpleTimeZone LTZ) { foreach (DataColumn cc in dt.Tables[0].Columns) { if (cc.DataType.FullName.Equals("System.DateTime")) { foreach (DataRow dr in dt.Tables[0].Rows) { if (dr[cc.ColumnName] != DBNull.Value) dr[cc.ColumnName] = LTZ.ToLocalTime((DateTime) dr[cc.ColumnName]); } } } return dt; } public static string CheckGroup(string table, string dependency) { string[] arryD = dependency.Split('|'); StringBuilder sbGroup = new StringBuilder(); foreach (string ut in arryD) { if (StaticFunctions.IsBlank(table)) { if (ut.Length > 0) sbGroup.AppendFormat("Groups like '%|{0}|%' or ", ut); } else { if (ut.Length > 0) sbGroup.AppendFormat("{0}.Groups like '%|{1}|%' or ", table, ut); } } if (sbGroup.Length > 0) sbGroup.Remove(sbGroup.Length - 3, 3); if (StaticFunctions.IsBlank(table)) return "Groups like '%|0|%' or (" + sbGroup.ToString() + ")"; else return table + ".Groups like '%|0|%' or (" + sbGroup.ToString() + ")"; } public bool isGoBack { get { return (Session["goback1"] is Stack && ((Stack) Session["goback1"]).Count > 0); } } public void SetGoBack(string sheet, string[] parameters) { Stack backSheet = new Stack(); if (isGoBack) backSheet = (Stack) Session["goback1"]; GoBack ba = new GoBack(); ba.sheet = sheet; foreach (string s in parameters) ba.parameter += "|" + s; ba.parameter += "|"; backSheet.Push(ba); Session["goback1"] = backSheet; } public void BtnBack_Click(object sender, EventArgs e) { if (isGoBack) { GoBackClick(); } else { Page.RegisterClientScriptBlock("back", ""); } } public void GoBackClick() { GoBackClick(false); } public void GoBackClick(bool remove) { if (Session["goback1"] == null) return; Stack ba = new Stack(); ba = (Stack) Session["goback1"]; if (ba.Count == 0) return; GoBack gb = new GoBack(); if (remove) gb = (GoBack) ba.Pop(); //(GoBack) ba[ba.Count - 1]; else gb = (GoBack) ba.Peek(); Response.Redirect(gb.sheet); } public void DeleteGoBack(bool nockeck) { if (nockeck) Session.Remove("goback1"); else DeleteGoBack(); } public void DeleteGoBack() { if (!Page.IsPostBack && Request.QueryString["dgb"] != null) Session.Remove("goback1"); } public void AddKeepAlive() { int int_MilliSecondsTimeOut = (this.Session.Timeout*60000) - 10000; this.Page.RegisterClientScriptBlock("Reconnect", ""); } private string InitScript { get { return ""; } } private void InitMessages() { string[] ids = null; if (MessagesHandler.CheckForNewMessage(UC.UserId, out ids)) Page.RegisterClientScriptBlock("message", ""); } protected override void Render(HtmlTextWriter output) { string template; StreamReader objReader; Trace.Warn("Start Render"); if (HttpContext.Current.Items.Contains("render")) return; if (Request.QueryString["render"] != null) { switch (Request.QueryString["render"].ToString()) { case "wiz": objReader = new StreamReader(Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "template" + Path.DirectorySeparatorChar + "twiz.htm"); template = objReader.ReadToEnd(); objReader.Close(); TextWriter tempWriter = new StringWriter(); using (tempWriter) { base.Render(new HtmlTextWriter(tempWriter)); if (Context.Items.Contains("warning")) { template = template.Replace("", Context.Items["warning"].ToString() + tempWriter.ToString()); Context.Items.Remove("warning"); } else template = template.Replace("", tempWriter.ToString()); output.Write(template); } break; case "print": break; default: output.Write(InitScript); base.Render(output); break; } } else { InitMessages(); string helptemplate = HelpMenu(); bool redrawMenu = ((string) Session["CurrentActiveMenu"] != (string) Request.QueryString["m"]); if (Request.QueryString["m"] != null) { Session["CurrentActiveMenu"] = Request.QueryString["m"]; } string cacheId = "template." + UC.UserId; if (Cache[cacheId] is string) { template = Cache[cacheId] as string; } else { objReader = new StreamReader(Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "template" + Path.DirectorySeparatorChar + "tmain.htm"); template = objReader.ReadToEnd(); objReader.Close(); if (Session["UserConfig"] != null) { template = template.Replace("", InitScript); template = template.Replace("", ""+ UC.UserRealName + " "); Cache.Add(cacheId, template, new CacheDependency(Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "template" + Path.DirectorySeparatorChar + "tmain.htm"), Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(60), CacheItemPriority.Low, null); } } TextWriter tempWriter = new StringWriter(); using (tempWriter) { base.Render(new HtmlTextWriter(tempWriter)); template = template.Replace("", CustomMenu(redrawMenu, true)); //CreateMenuNoStretches(redrawMenu)); string query = QuerySecurity(); string menuTitle = String.Empty; if (query.Length > 0) { if (Session["CurrentActiveMenu"] != null) menuTitle = CustomSubMenu((StaticFunctions.IsNumber(Session["CurrentActiveMenu"].ToString()) ? Session["CurrentActiveMenu"].ToString() : "25"), query); } template = template.Replace("", menuTitle); if (helptemplate.Length > 0) { StringBuilder manageHelp = new StringBuilder(); manageHelp.Append(""); manageHelp.AppendFormat("{0}", helptemplate); manageHelp.AppendFormat("{0}", tempWriter.ToString()); helptemplate = manageHelp.ToString(); } else { helptemplate = tempWriter.ToString(); } if (Context.Items.Contains("warning")) { template = template.Replace("", "

Error WARNING: " + Context.Items["warning"].ToString() + "

" + helptemplate); Context.Items.Remove("warning"); } else template = template.Replace("", helptemplate); output.Write(template); } } output.Write("
Powered by Tustena CRM
© 2003-2005 Digita S.r.l. All Rights Reserved.
Visit www.tustena.com for more information.
"); } private string HelpMenu() { string template = String.Empty; if (Request.QueryString["m"] != null && Request.QueryString["si"] == null) { int menuId = int.Parse(Request.QueryString["m"]); if (DatabaseConnection.SqlScalar(String.Format("select count(id) from MenuMap where UserID={0} and MenuID={1} and FirstTime=1", UC.UserId, menuId)) == "0") { DataTable dtHelp = DatabaseConnection.CreateDataset("select * from HelpMenu where MenuID=" + menuId).Tables[0]; if (dtHelp.Rows.Count > 0) { if (File.Exists(Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "help" + Path.DirectorySeparatorChar + UC.Culture.Substring(0, 2) + Path.DirectorySeparatorChar + dtHelp.Rows[0]["HelpFile"].ToString())) { StreamReader objReader = new StreamReader(Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "help" + Path.DirectorySeparatorChar + UC.Culture.Substring(0, 2) + Path.DirectorySeparatorChar + dtHelp.Rows[0]["HelpFile"].ToString()); template = objReader.ReadToEnd(); objReader.Close(); StringBuilder footer = new StringBuilder(); string subMenu = CreateMenuHelp(menuId.ToString(), QuerySecurity()); footer.AppendFormat("
{1}
{4}
{0}
", template, subMenu, Request.QueryString["m"], UC.UserId, rm.GetString("DefaultMenu")); template = footer.ToString(); } else { StreamReader objReader = new StreamReader(Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "help" + Path.DirectorySeparatorChar + "en" + Path.DirectorySeparatorChar + dtHelp.Rows[0]["HelpFile"].ToString()); template = objReader.ReadToEnd(); objReader.Close(); StringBuilder footer = new StringBuilder(); string subMenu = CreateMenuHelp(menuId.ToString(), QuerySecurity()); footer.AppendFormat("
{1}
{4}
{0}
", template, subMenu, Request.QueryString["m"], UC.UserId, rm.GetString("DefaultMenu")); template = footer.ToString(); } } } else { string newHome = DatabaseConnection.SqlScalar(String.Format("select NewHomePage from MenuMap where UserID={0} and MenuID={1} and FirstTime=1", UC.UserId, menuId)); if (newHome.Length > 0) Response.Redirect(newHome); } } return template; } private string CreateMenuHelp(string parent, string query) { StringBuilder menu = new StringBuilder(); menu.Append(""); DataSet dsParent; dsParent = DatabaseConnection.CreateDataset(String.Format("select id,Voice,link,rmvalue from TustenaMenu_View where id={0}", parent)); DataRow drParent = dsParent.Tables[0].Rows[0]; menu.AppendFormat("
{0}
", rm.GetString("Menutxt" + dsParent.Tables[0].Rows[0]["rmvalue"].ToString()).ToUpper()); menu.AppendFormat("{1}
", dsParent.Tables[0].Rows[0]["id"], rm.GetString("Menutxt" + dsParent.Tables[0].Rows[0]["rmvalue"].ToString()).ToUpper() + " HELP"); DataSet secondaryMenuVoices; if (mode == "0" && !UC.DebugMode) { secondaryMenuVoices = DatabaseConnection.CreateDataset(String.Format("select * from TustenaMenu_View where ParentMenu={0}{1} and Mode=0 order by SortOrder", parent, query)); } else { secondaryMenuVoices = DatabaseConnection.CreateDataset(String.Format("select * from TustenaMenu_View where ParentMenu={0}{1} order by SortOrder", parent, query)); } if (secondaryMenuVoices.Tables[0].Rows.Count > 0) { foreach (DataRow DRVocip in secondaryMenuVoices.Tables[0].Rows) { menu.AppendFormat("{1}
", DRVocip["id"], rm.GetString("Menutxt" + DRVocip["rmvalue"].ToString())); } } menu.Append("
"); secondaryMenuVoices.Clear(); drParent.Delete(); dsParent.Clear(); return menu.ToString(); //.Substring(0,menu.ToString().Length-7); } public string QuerySecurity() { string query = String.Empty; if (Session["UserConfig"] != null && UC.GroupDependency != null) { string dependency = UC.GroupDependency; if (dependency == "|0|") { query = String.Empty; } else { string[] dep = dependency.Split('|'); foreach (string group in dep) { if (group.Length > 0) query += " accessgroup like '%|" + group + "|%' or "; } query = " and (" + query.Substring(0, query.Length - 4) + ")"; } return query; } else { return ""; } } private string CustomMenu(bool redraw, bool maintemplate) { redraw=true; string M = Request.QueryString["m"]; string cacheName = String.Format("MENU.{0}.{1}", UC.UserId, UC.CultureSpecific); if (Cache[cacheName] is string && !redraw) return Cache[cacheName] as string; Cache.Remove(cacheName); StringBuilder menuTitle = new StringBuilder(); menuTitle.AppendFormat("{0}
    ",this.GoogleSearch); string query = QuerySecurity(); string newUrl = String.Empty; string highlight = String.Empty; bool firstLoop = true; DataSet titles; if (UC.UserId != 0) { if (mode == "0" && !UC.DebugMode) { titles = DatabaseConnection.CreateDataset(String.Format("select id,link,folder,rmvalue from TustenaMenu_View where MenuTitle=1{0} and Mode={1} order by SortOrder", query, mode)); } else { titles = DatabaseConnection.CreateDataset(String.Format("select id,link,folder,rmvalue from TustenaMenu_View where MenuTitle=1{0} order by SortOrder", query)); } if (titles.Tables[0].Rows.Count > 0) { foreach (DataRow row in titles.Tables[0].Rows) { if (Request.QueryString.HasKeys()) { newUrl = Request.QueryString.ToString(); if (row["link"].ToString().Length > 0) { if (row["Folder"].ToString().Length > 0) newUrl = "/" + row["Folder"].ToString() + "/" + row["link"].ToString(); else newUrl = "/" + row["link"].ToString(); } else { newUrl = Request.ServerVariables["SCRIPT_NAME"].ToString() + "?" + newUrl.Replace("m=" + M, "m=" + row["id"].ToString()); } highlight = (row["id"].ToString() == M ? "id=MenuSelected" : ""); if (firstLoop) { highlight += " class=\"FirstItem\""; firstLoop = false; } menuTitle.AppendFormat("
  • {1}
  • ", newUrl, rm.GetString("Menutxt" + row["rmvalue"].ToString()).ToUpper(), highlight); } else Response.Redirect("/login.aspx", true); } menuTitle.Append("
"); Cache.Add(cacheName, menuTitle.ToString(), null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10), CacheItemPriority.Low, null); return menuTitle.ToString(); } } return (maintemplate ? "" : "
    "); } private string CustomSubMenu(string parent, string query) { StringBuilder menu = new StringBuilder(); menu.Append("
      "); menu.AppendFormat(" \"{1}\"  ", UC.Culture.Substring(0, 2), rm.GetString("Manual"), UC.CultureSpecific); //language); string highlight = String.Empty; bool firstLoop = true; DataSet subMenuVoices; if (mode == "0" && !UC.DebugMode) { subMenuVoices = DatabaseConnection.CreateDataset(String.Format("select * from TustenaMenu_View where ParentMenu={0}{1} and Mode=0 order by SortOrder", parent, query)); } else { subMenuVoices = DatabaseConnection.CreateDataset(String.Format("select * from TustenaMenu_View where ParentMenu={0}{1} order by SortOrder", parent, query)); } if (subMenuVoices.Tables[0].Rows.Count > 0) { foreach (DataRow DRVocip in subMenuVoices.Tables[0].Rows) { highlight = String.Empty; if (firstLoop) { highlight = " class=\"FirstItem\""; firstLoop = false; } string subMenuSelected = string.Empty; if ((Request.Params["si"] != null && DRVocip["id"].ToString() == Request.Params["si"]) || (Request.Params["si"] == null && highlight.Length > 0)) subMenuSelected = "id=\"SubMenuSelected\""; if (DRVocip["link"].ToString().EndsWith(";")) menu.AppendFormat("{1}", DRVocip["link"], rm.GetString("Menutxt" + DRVocip["rmvalue"].ToString()), highlight, subMenuSelected); else if (DRVocip["Folder"].ToString().Length > 0) { menu.AppendFormat("{2}", DRVocip["folder"] + "/" + DRVocip["link"], DRVocip["id"], rm.GetString("Menutxt" + DRVocip["rmvalue"].ToString()), highlight, subMenuSelected); } else { menu.AppendFormat("{2}", DRVocip["link"], DRVocip["id"], rm.GetString("Menutxt" + DRVocip["rmvalue"].ToString()), highlight, subMenuSelected); } } } menu.Append("
    "); return menu.ToString(); } public void UpdateAccess(int company) { DatabaseConnection.DoCommand("UPDATE Tustena_Data SET LastAccess = getdate()"); } public void SetFocus(Control ctrl) { string s = String.Format("", ctrl.ID); RegisterStartupScript("focus", s); } public static void Message(int id, string subject, string body, string htmlBody) { UserConfig UC = (UserConfig) HttpContext.Current.Session["UserConfig"]; using (DigiDapter dg = new DigiDapter()) { dg.Add("Subject", subject.Replace("'", "''")); dg.Add("Body", body.Replace("'", "''")); dg.Add("FromAccount", UC.UserId); dg.Add("ToAccount", id); } if (Convert.ToBoolean(DatabaseConnection.SqlScalar("select FlagNotifyAppointment from account where uid=" + id))) { SendMailNotification(id, subject, htmlBody); } } public static void SendMailNotification(int id, string subject, string body) { DataTable cmd = DatabaseConnection.CreateDataset("Select Notifyemail, UserAccount from Account where uid=" + id).Tables[0]; string to; if (cmd.Rows.Count > 1) { to = (cmd.Rows[0][0].ToString().Length > 0) ? cmd.Rows[0][0].ToString() : cmd.Rows[0][1].ToString(); if (to.Length > 0) { MessagesHandler.SendMail(to, null, "[Tustena] " + subject, body); } } } public static void SendError(string subject, string body) { if(ConfigSettings.TustenaErrorMail.Length>0) MessagesHandler.SendMail(ConfigSettings.TustenaErrorMail, ConfigSettings.TustenaErrorMail, "[Tustena] " + subject, body); } public static string GroupDependency(int gr) { string sqlString = String.Format("select id,dependency from Groups where id={0} or dependency like '%|{0}|%'", gr.ToString()); DataSet dsGroup = DatabaseConnection.CreateDataset(sqlString); StringBuilder sbDependency = new StringBuilder("|"); if (dsGroup.Tables[0].Rows.Count > 0) { foreach (DataRow drdip in dsGroup.Tables[0].Rows) { sbDependency.AppendFormat("{0}|", drdip["id"].ToString()); } } return sbDependency.ToString(); } public string CleanGroups(string arid) { ArrayList al = new ArrayList(); string[] parts = arid.Split('|'); al.InsertRange(0, parts); int y = 0; do { int x; for (x = y + 1; x < al.Count; x++) { if (al[x].Equals(al[y]) || al[x].ToString().Length == 0) { al.RemoveAt(x); break; } } if (x == al.Count) y++; } while (y < al.Count); string[] checkArr = new string[al.Count]; al.CopyTo(checkArr, 0); return "|" + String.Join("|", checkArr, 1, y - 1) + "|"; } public string GroupsSecure() { return GroupsSecure("Groups"); } public string GroupsSecure(string column) { string cacheName = UC.UserId + column; if (HttpContext.Current.Cache[cacheName] is string) return HttpContext.Current.Cache[cacheName].ToString(); string[] arryD = UC.GroupDependency.Split('|'); StringBuilder qGroup = new StringBuilder(); qGroup.AppendFormat(" ({0} like '%|0|%') ", column); foreach (string ut in arryD) if (ut.Length > 0) qGroup.AppendFormat(" or {1} like '%|{0}|%'", ut, column); HttpContext.Current.Cache.Add(cacheName, qGroup.ToString(), null, DateTime.Now.AddMinutes(Session.Timeout), TimeSpan.Zero, CacheItemPriority.Low, null); return qGroup.ToString(); } public void HackLock(string error) { SendError("Tustena HackAttempt", error); Context.Items["warning"] = "Hack Attempt blocked!"; Response.Redirect("/"); } private string GoogleSearch { get { string gs = ""; gs += "go"; return gs; } } public string PrintValues(Array myArr, char mySeparator) { IEnumerator myEnumerator = myArr.GetEnumerator(); int i = 0; string str = String.Empty; while (myEnumerator.MoveNext()) { if (i > 0) { i++; } else { str += mySeparator; } str += String.Format("{0}{1}", mySeparator, myEnumerator.Current); } return str; } public string MakeVoipString(string ph) { DataRow drvoip; drvoip = DatabaseConnection.CreateDataset("select LinkForVoIP,InternationalPrefix from Tustena_Data").Tables[0].Rows[0]; if (drvoip[0].ToString().Length > 0) { return String.Format("\"{0}\"", rm.GetString("VoIP"), drvoip[0].ToString(), ph); } return String.Empty; } public string PrintValues(IEnumerable myCollection) { IEnumerator myEnumerator = myCollection.GetEnumerator(); string str = String.Empty; while (myEnumerator.MoveNext()) str += myEnumerator.Current; return str; } public string FillHelp(string file) { return FillHelp(file, UC); } public string FillHelp(string file, UserConfig myUC) { StreamReader objReader = null; if (File.Exists(Context.Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "help" + Path.DirectorySeparatorChar + (myUC.Culture.Substring(0, 2)) + Path.DirectorySeparatorChar + file + ".htm")) { objReader = new StreamReader(Context.Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "help" + Path.DirectorySeparatorChar + (myUC.Culture.Substring(0, 2)) + Path.DirectorySeparatorChar + file + ".htm"); string hl = objReader.ReadToEnd(); objReader.Close(); return hl.Replace("{0}", "/help/" + (myUC.Culture.Substring(0, 2)) + "/"); } else if (File.Exists(Context.Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "help" + Path.DirectorySeparatorChar + "en" + Path.DirectorySeparatorChar + file + ".htm")) { objReader = new StreamReader(Context.Request.PhysicalApplicationPath + Path.DirectorySeparatorChar + "help" + Path.DirectorySeparatorChar + "en" + Path.DirectorySeparatorChar + file + ".htm"); string hl = objReader.ReadToEnd(); objReader.Close(); return hl.Replace("{0}", "/help/" + (myUC.Culture.Substring(0, 2)) + "/"); } else G.SendError("Tustena Path", "HelpFile not available: " + file + ".htm"); return String.Empty; } private void IsAlreadyIn() { string cachedSession = Cache[UC.UserId.ToString()] as string; if (cachedSession != null) { if (Session.SessionID != cachedSession) { Context.Items["warning"] = "Reentered!"; Session.Abandon(); Server.Transfer("/login.aspx"); } } else Cache.Add(UC.UserId.ToString(), Session.SessionID, null, DateTime.MaxValue, new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0), CacheItemPriority.NotRemovable, null); } } [Serializable] public class GoBack { public string sheet; public string parameter; } [Serializable] public class SQLSecure { public string Name; public string Value; public SqlDbType Type; public int Size; } [Serializable] public class CompanyReport { public int idfield; public Hashtable Params; public byte Type; public bool Finalize; public int itemPage; public bool morerecord = true; } [Serializable] public class PurchaseProduct { public long id; public string ShortDescription; public string LongDescription; public string UM; public double Qta; public decimal UnitPrice; public decimal Vat; public decimal ListPrice; public decimal FinalPrice; public int ObId; public int Contacts; public int Leads; public int Reduction; } public enum CRMTables :byte { Base_Companies = 1, Base_Contacts, CRM_Leads, CRM_WorkActivity } public enum AType :byte { Company = 1, Contacts, Lead } public enum ActivityMoveLog :byte { MoveOwner = 0, MoveDate = 1, MoveCompany = 2, MoveContact = 3, MoveLead = 4, MoveDone = 5, MailSent = 6 } public enum MailEvents :byte { Report = 0, BirthDate = 1, OnLead = 2 } public enum ActivityTypeN :int { PhoneCall = 1, Letter = 2, Fax = 3, Memo = 4, Email = 5, Visit = 6, Generic = 7, CaseSolution = 8, Quote = 9 } }