/// 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("", "