/projects/PigeonCms.Core/BaseClasses/BaseModuleControl.cs

http://pigeoncms.googlecode.com/ · C# · 456 lines · 289 code · 48 blank · 119 comment · 55 complexity · d03680c0f49e019a3f0915c7a25ab0ab MD5 · raw file

  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.HtmlControls;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Reflection;
  13. using System.Text;
  14. /// <summary>
  15. /// Base class for module controls
  16. /// </summary>
  17. ///
  18. namespace PigeonCms
  19. {
  20. /// <summary>
  21. /// Use this attribute to specify that a static method should be exposed as an AJAX PageMethod call
  22. /// through the owning page.
  23. /// </summary>
  24. [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
  25. public sealed class UserControlScriptMethodAttribute : Attribute
  26. {
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="UserControlScriptMethodAttribute"/> class.
  29. /// </summary>
  30. public UserControlScriptMethodAttribute() { }
  31. }
  32. public class BaseModuleControl : System.Web.UI.UserControl
  33. {
  34. private List<ResLabel> labelsList;
  35. private Menu menuTarget = null;
  36. #region properties
  37. /// <summary>
  38. /// int pkey, current record Id (usually used by admin modules to keep current record state)
  39. /// </summary>
  40. protected int CurrentId
  41. {
  42. get
  43. {
  44. int res = 0;
  45. if (ViewState["CurrentId"] != null)
  46. res = (int)ViewState["CurrentId"];
  47. return res;
  48. }
  49. set { ViewState["CurrentId"] = value; }
  50. }
  51. /// <summary>
  52. /// string pkey, current record Id (usually used by admin modules to keep current record state)
  53. /// </summary>
  54. protected string CurrentKey
  55. {
  56. get
  57. {
  58. string res = "";
  59. if (ViewState["CurrentKey"] != null)
  60. res = (string)ViewState["CurrentKey"];
  61. return res;
  62. }
  63. set { ViewState["CurrentKey"] = value; }
  64. }
  65. public PigeonCms.Module BaseModule { get; set; }
  66. private PigeonCms.Menu currMenu = new PigeonCms.Menu();
  67. public PigeonCms.Menu CurrMenu
  68. {
  69. get { return currMenu; }
  70. set { currMenu = value; }
  71. }
  72. public string CurrViewPath
  73. {
  74. get
  75. {
  76. return VirtualPathUtility.ToAbsolute(
  77. Config.ModulesPath + this.BaseModule.ModuleFullName) + "/views/"
  78. + this.BaseModule.CurrViewFolder + "/";
  79. }
  80. }
  81. /// <summary>
  82. /// dictionary list to use in module admin area (combo)
  83. /// </summary>
  84. /// <returns></returns>
  85. public Dictionary<string, string> GetCssFiles(/*string controlFullName, string currView*/)
  86. {
  87. throw new NotImplementedException("Not used, css files depends by the current view");
  88. //Dictionary<string, string> res = new Dictionary<string, string>();
  89. //if (!string.IsNullOrEmpty(this.BaseModule.CurrViewFolder))
  90. //{
  91. // try
  92. // {
  93. // DirectoryInfo dir = new DirectoryInfo(this.CurrViewPath);
  94. // if (dir.Exists)
  95. // {
  96. // FileInfo[] files = dir.GetFiles("*.css");
  97. // foreach (FileInfo file in files)
  98. // {
  99. // res.Add(file.Name, file.Name);
  100. // }
  101. // }
  102. // }
  103. // finally
  104. // {
  105. // }
  106. //}
  107. //return res;
  108. }
  109. public Dictionary<string, string> Params
  110. {
  111. get
  112. {
  113. string[] splitter = { ":=" };
  114. var paramsDict = new Dictionary<string, string>();
  115. if (this.BaseModule != null)
  116. {
  117. List<string> paramsList = Utility.String2List(this.BaseModule.ModuleParams);
  118. foreach (string item in paramsList)
  119. {
  120. string[] arr = item.Split(splitter, StringSplitOptions.None);
  121. string key = arr[0];
  122. string value = "";
  123. if (arr.Length > 1) value = arr[1];
  124. paramsDict.Add(key, value);
  125. }
  126. }
  127. return paramsDict;
  128. }
  129. }
  130. #endregion
  131. #region methods
  132. public BaseModuleControl(){}
  133. //read param from module params
  134. protected string GetStringParam(string paramName, string defaultValue)
  135. {
  136. return GetStringParam(paramName, defaultValue, "");
  137. }
  138. /// <summary>
  139. /// read param in order of priority from:
  140. /// -current Context.Items collection
  141. /// -querystring
  142. /// -from module params
  143. /// </summary>
  144. /// <param name="paramName">param name</param>
  145. /// <param name="defaultValue">default value</param>
  146. /// <param name="requestParamName">context or querystring param name</param>
  147. /// <returns>string param value</returns>
  148. protected string GetStringParam(string paramName, string defaultValue, string requestParamName)
  149. {
  150. //design param
  151. string res = defaultValue;
  152. //backend param
  153. //20111031 works on droidcatalogue
  154. string backendValue = defaultValue;
  155. {
  156. this.Params.TryGetValue(paramName, out backendValue);
  157. if (string.IsNullOrEmpty(backendValue))
  158. backendValue = defaultValue;
  159. }
  160. if (backendValue != defaultValue)
  161. res = backendValue;
  162. else
  163. {
  164. if (!string.IsNullOrEmpty(requestParamName))
  165. {
  166. //context param
  167. if (Context.Items[requestParamName] != null)
  168. {
  169. res = Context.Items[requestParamName].ToString().Replace(".aspx", "");
  170. }
  171. else if (Request[requestParamName] != null) //querystring param
  172. {
  173. res = Request[requestParamName].ToString();
  174. }
  175. }
  176. }
  177. //if (res == defaultValue) //##20100302
  178. //{
  179. // //backend param
  180. // if (!this.Params.TryGetValue(paramName, out res))
  181. // res = defaultValue;
  182. //}
  183. return res;
  184. }
  185. //read param from module params
  186. protected int GetIntParam(string paramName, int defaultValue)
  187. {
  188. return GetIntParam(paramName, defaultValue, "");
  189. }
  190. /// <summary>
  191. /// read param in order of priority from:
  192. /// -from backend module params
  193. /// -current Context.Items collection
  194. /// -querystring
  195. /// </summary>
  196. /// <param name="paramName">param name</param>
  197. /// <param name="defaultValue">default value</param>
  198. /// <param name="requestParamName">context or querystring param name</param>
  199. /// <returns>int param value</returns>
  200. protected int GetIntParam(string paramName, int defaultValue, string requestParamName)
  201. {
  202. //design param
  203. int res = defaultValue;
  204. //backend param
  205. //20111031 works on droidcatalogue
  206. int backendValue = defaultValue;
  207. {
  208. string parValue = "";
  209. if (this.Params.TryGetValue(paramName, out parValue))
  210. {
  211. int.TryParse(parValue, out backendValue);
  212. }
  213. }
  214. if (backendValue != defaultValue)
  215. res = backendValue;
  216. else
  217. {
  218. if (!string.IsNullOrEmpty(requestParamName))
  219. {
  220. //context param
  221. if (Context.Items[requestParamName] != null)
  222. {
  223. int.TryParse(Context.Items[requestParamName].ToString().Replace(".aspx", ""), out res);
  224. }
  225. else if (Request[requestParamName] != null) //querystring param
  226. {
  227. int.TryParse(Request[requestParamName].ToString(), out res);
  228. }
  229. }
  230. }
  231. //if (res == defaultValue)
  232. //{
  233. // //backend param
  234. // string parValue = "";
  235. // if (this.Params.TryGetValue(paramName, out parValue))
  236. // {
  237. // int.TryParse(parValue, out res);
  238. // }
  239. //}
  240. return res;
  241. }
  242. protected bool GetBoolParam(string paramName, bool defaultValue)
  243. {
  244. bool res = defaultValue;
  245. string parValue = "";
  246. if (this.Params.TryGetValue(paramName, out parValue))
  247. {
  248. if (parValue == "0")
  249. res = false;
  250. if (parValue == "1")
  251. res = true;
  252. }
  253. return res;
  254. }
  255. protected string GetLabel(string resourceId, string defaultValue, Control targetControl, bool getTitle)
  256. {
  257. string title = "";
  258. if (getTitle)
  259. {
  260. title = GetLabel(resourceId + "Description");
  261. }
  262. string res = GetLabel(resourceId, defaultValue, targetControl, title);
  263. return res;
  264. }
  265. protected string GetLabel(string resourceId, string defaultValue, Control targetControl, string title)
  266. {
  267. bool visible = true;
  268. if (!string.IsNullOrEmpty(title))
  269. title = "title='" + title + "'";
  270. string clientID = "";
  271. if (targetControl != null)
  272. {
  273. clientID = targetControl.ClientID;
  274. visible = targetControl.Visible;
  275. }
  276. string res = GetLabel(resourceId, defaultValue);
  277. res = "<label for='" + clientID + "' " + title + ">" + res + "</label>";
  278. if (!visible) res = "";
  279. return res;
  280. }
  281. protected string GetLabel(string resourceId, string defaultValue, Control targetControl)
  282. {
  283. return GetLabel(resourceId, defaultValue, targetControl, "");
  284. }
  285. protected string GetLabel(string resourceId)
  286. {
  287. return GetLabel(resourceId, "");
  288. }
  289. private bool? isMobileDevice = null;
  290. protected bool? IsMobileDevice
  291. {
  292. get
  293. {
  294. if (isMobileDevice == null)
  295. isMobileDevice = Utility.Mobile.IsMobileDevice(Context);
  296. return isMobileDevice;
  297. }
  298. }
  299. /// <summary>
  300. /// retrieve localized label value
  301. /// </summary>
  302. /// <param name="resourceId">the label key</param>
  303. /// <returns>the localized label value</returns>
  304. protected string GetLabel(string resourceId, string defaultValue)
  305. {
  306. string res = "";
  307. if (labelsList == null)
  308. {
  309. //preload all labels of current moduletype
  310. labelsList = LabelsProvider.GetLabelsByResourceSet(BaseModule.ModuleFullName);
  311. }
  312. res = LabelsProvider.GetLocalizedLabelFromList(labelsList, resourceId);
  313. if (string.IsNullOrEmpty(res))
  314. {
  315. res = defaultValue;
  316. }
  317. if (HttpContext.Current.Request.QueryString["tp"] == "1")
  318. {
  319. res = "[" + resourceId + "]" + res;
  320. }
  321. return res;
  322. }
  323. /// <summary>
  324. /// create link between current entry and another menu entry
  325. /// </summary>
  326. /// <param name="queryStringParamName">ex. itemid or itemname</param>
  327. /// <param name="queryStringParamValue">ex. 7 or 13 or cheese or apple</param>
  328. /// <param name="targetMenuId">id of target menu entry</param>
  329. /// <returns>the anchor herf attribute</returns>
  330. protected string GetLinkAddress(string queryStringParamName, string queryStringParamValue, int targetMenuId)
  331. {
  332. string res = "javascript:void(0);";
  333. if (menuTarget == null)
  334. {
  335. menuTarget = new MenuManager().GetByKey(targetMenuId);
  336. }
  337. if (!string.IsNullOrEmpty(menuTarget.RoutePattern))
  338. {
  339. res = Utility.GetRoutedUrl(menuTarget, queryStringParamName + "=" + queryStringParamValue, true);
  340. }
  341. //else
  342. //{
  343. // if (!string.IsNullOrEmpty(this.DetailHandlerPath))
  344. // {
  345. // res = VirtualPathUtility.ToAbsolute(this.DetailHandlerPath) + "?" + queryStringParamName + "=" + queryStringParamValue;
  346. // }
  347. //}
  348. return res;
  349. }
  350. /// <summary>
  351. /// Registers the user control web methods tagged with the UserControlWebMethodAttribute
  352. /// </summary>
  353. private void registerUserControlWebMethods()
  354. {
  355. foreach (MethodInfo method in this.GetType().GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod))
  356. if (method.GetCustomAttributes(typeof(UserControlScriptMethodAttribute), true).Length > 0)
  357. registerUserControlWebMethod(method);
  358. Type baseType = this.GetType().BaseType;
  359. if (baseType != null && (baseType.Namespace == null || !baseType.Namespace.StartsWith("System")))
  360. foreach (MethodInfo method in baseType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod))
  361. if (method.GetCustomAttributes(typeof(UserControlScriptMethodAttribute), true).Length > 0)
  362. registerUserControlWebMethod(method);
  363. }
  364. /// <summary>
  365. /// Registers a user control web method based on the methodInfo signature through reflection.
  366. /// </summary>
  367. /// <param name="method">The method.</param>
  368. /// <remarks>AJAX Voodoo!</remarks>
  369. private void registerUserControlWebMethod(MethodInfo method)
  370. {
  371. string blockName = string.Concat(method.Name, "_webMethod_uc");
  372. StringBuilder funcBuilder = new StringBuilder();
  373. funcBuilder.Append("function ");
  374. funcBuilder.Append(method.Name);
  375. funcBuilder.Append("(successCallback,failureCallback");
  376. foreach (var par in method.GetParameters())
  377. funcBuilder.AppendFormat(",{0}", par.Name);
  378. funcBuilder.Append("){if(PageMethods.PageServiceRequest){try{var parms=[];for(var i=2;i<arguments.length;i++){parms.push(arguments[i]);}PageMethods.PageServiceRequest(");
  379. funcBuilder.AppendFormat("'{0}','{1}'", method.DeclaringType.AssemblyQualifiedName, method.Name);
  380. funcBuilder.Append(",parms,successCallback,failureCallback);}catch(e){alert(e.toString());}}}");
  381. ScriptManager.RegisterClientScriptBlock(this, GetType(), blockName, funcBuilder.ToString(), true);
  382. }
  383. #endregion
  384. #region events
  385. /// <summary>
  386. /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
  387. /// </summary>
  388. /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
  389. protected override void OnPreRender(EventArgs e)
  390. {
  391. base.OnPreRender(e);
  392. registerUserControlWebMethods();
  393. }
  394. protected void Page_Init(object sender, EventArgs e)
  395. {
  396. string cssHref = "";
  397. //add css file
  398. if (BaseModule != null && !string.IsNullOrEmpty(BaseModule.CssFile))
  399. {
  400. cssHref = this.CurrViewPath + BaseModule.CssFile;
  401. Literal css1 = new Literal();
  402. css1.Text = "<link href='" + cssHref + "' rel='stylesheet' type='text/css' media='screen' />";
  403. Page.Header.Controls.Add(css1);
  404. }
  405. }
  406. #endregion
  407. }
  408. }