PageRenderTime 62ms CodeModel.GetById 39ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 0ms

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