PixelDragons.MVC

Struct的流程为
找到对应页面的control,分别调用其中BeforeAction;CallAction(defaultAction/customAction);AfterAction;操作完毕后显示到对应的view.

1. 针对NHibernate进行包装

PixelDragons.MVC.Persistence.SessionManager 根据配置文件提供了ISession的维护
PixelDragons.MVC.Persistence.GenericDao<T> 提供Get,Delete,ListPaged等
  public   void  Delete(Guid itemUid)
        
{
            ISession session 
= ActiveSession;

            
bool disconnect = false;
            
if (!session.IsConnected)
            
{
                session.Reconnect();
                disconnect 
= true;
            }

            
try
            
{
                T item 
= (T)session.Load(typeof(T), itemUid);
                session.Delete(item);
            }

            
catch (Exception ex)
            
{
                
throw ex;
            }

            
finally
            
{
                
if (session.IsConnected && disconnect)
                
{
                    session.Disconnect();
                }

            }

        }

{
   
public List<T> ListAll()
        
{
            List
<T> list = null;
            ISession session 
= ActiveSession;
            
bool disconnect = false;
            
if (!session.IsConnected)
            
{
                session.Reconnect();
                disconnect 
= true;
            }

            
try
            
{
                list 
= (List<T>)session.CreateCriteria(typeof(T)).List<T>();
            }

            
catch (Exception ex)
            
{
                
throw ex;
            }

            
finally
            
{
                
if (session.IsConnected && disconnect)
                
{
                    session.Disconnect();
                }

            }


            
return list;
        }


        
public List<T> ListPaged(PageSettings pageSettings)
        
{
            List
<T> list = null;
            ISession session 
= ActiveSession;
            
bool disconnect = false;
            
if (!session.IsConnected)
            
{
                session.Reconnect();
                disconnect 
= true;
            }

            
try
            
{
                ICriteria criteria 
=  session.CreateCriteria(typeof(T));

                
foreach (SimpleExpression expression in pageSettings.FilterExpressions)
                
{
                    
if (expression != null)
                    
{
                        criteria.Add(expression 
as ICriterion);
                    }

                }


                
if (pageSettings.CalculateTotal)
                
{
                    
//Slow way to get the total count, refactor later to use supplied hql that uses count(*)
                    list = (List<T>)criteria.List<T>();
                    pageSettings.TotalItemCount 
= list.Count;
                }


                
foreach (string columnName in pageSettings.ColumnSorting.Keys)
                
{
                    SortDirection sort 
= pageSettings.ColumnSorting[columnName];
                    
                    
if (sort == SortDirection.Ascending)
                    
{
                        criteria.AddOrder(Order.Asc(columnName));
                    }

                    
else
                    
{
                        criteria.AddOrder(Order.Desc(columnName));
                    }

                }


                list 
= (List<T>)criteria.SetFirstResult(pageSettings.CurrentPageIndex * pageSettings.PageSize).SetMaxResults(pageSettings.PageSize).List();

                
return list;
            }

            
catch (Exception ex)
            
{
                
throw ex;
            }

            
finally
            
{
                
if (session.IsConnected && disconnect)
                
{
                    session.Disconnect();
                }

            }

        }


        
public List<T> ListUsingQuery(string hql, params object[] args)
        
{
            hql 
= String.Format(hql, args);

            List
<T> list = null;
            ISession session 
= ActiveSession;
            
bool disconnect = false;
            
if (!session.IsConnected)
            
{
                session.Reconnect();
                disconnect 
= true;
            }

            
try
            
{
                IQuery query 
= session.CreateQuery(hql);
                list 
= (List<T>)query.List<T>();
            }

            
catch (Exception ex)
            
{
                
throw ex;
            }

            
finally
            
{
                
if (session.IsConnected && disconnect)
                
{
                    session.Disconnect();
                }

            }


            
return list;
        }


        
public List<T> ListPagedUsingQuery(PageSettings pageSettings, string hql, params object[] args)
        
{
            hql 
= String.Format(hql, args);

            List
<T> list = null;
            ISession session 
= ActiveSession;
            
bool disconnect = false;
            
if (!session.IsConnected)
            
{
                session.Reconnect();
                disconnect 
= true;
            }

            
try
            
{
                IQuery query 
= session.CreateQuery(hql);

                
if (pageSettings.CalculateTotal)
                
{
                    
//Slow way to get the total count, refactor later to use supplied hql that uses count(*)
                    list = (List<T>)query.List<T>();
                    pageSettings.TotalItemCount 
= list.Count;
                }


                list 
= (List<T>)query.SetFirstResult(pageSettings.CurrentPageIndex * pageSettings.PageSize).SetMaxResults(pageSettings.PageSize).List<T>();
            }

            
catch (Exception ex)
            
{
                
throw ex;
            }

            
finally
            
{
                
if (session.IsConnected && disconnect)
                
{
                    session.Disconnect();
                }

            }


            
return list;
        }

}

2. View and Action


1.
使用自定义的句柄来捕捉*.ashx
<httpHandlers>
      <remove verb="*" path="*.ashx"/>
            <add verb="*" path="*.ashx" type="PixelDragons.MVC.MVCHandler, PixelDragons.MVC" />
        </httpHandlers>
       
2.
定义转发替换规则
<mvc mappingFile="mvc.config"
             controllerPattern="PixelDragons.MVCSample.Controllers.[ControllerName]Controller"
             viewWithActionPattern="UI/views/[ControllerName]/[ActionName].aspx"
             viewWithNoActionPattern="UI/views/[ControllerName].aspx"
             defaultController="PixelDragons.MVC.Controllers.BaseController">
3.
定义Control和VIEW
<views>
    <view id="viewPart-contactsList" path="UI/viewParts/contactsList.aspx" />

    <view id="ajaxAccessDenied" path="UI/views/blank.aspx" />
  </views>
<controllers>
    <controller name="users">
      <action name="login">
        <view name="loginSuccess" type="redirect" url="contacts-list.ashx" />
        <view name="invalidLogins" type="redirect" url="home.ashx?error=invalidLogins" />
      </action>
4.default.aspx
<%@ Page %>
<%Response.Redirect("home.ashx")%>
5.
MVCHandler 根据替换原则(先尝试controllerPattern,找不到尝试controllers节中的配置信息)找到 Controller: PixelDragons.MVCSample.Controllers.HomeController,(同时Cache类型到MVCHandler的成员中)

private  IController GetController(Command command)
        
{
            
//First try to get the controller type from the cache
            Type controllerType = null;
            
if (_controllerTypeCache.ContainsKey(command.CommandText))
            
{
                controllerType 
= _controllerTypeCache[command.CommandText];
            }

            
else
            
{
                   
//Otherwise, try to get the controller from the controller pattern
                string controllerClass = _settings.ControllerPattern.Replace("[ControllerName]", command.ControllerName);
                controllerType 
= BuildManager.GetType(controllerClass, falsefalse);
                
if (controllerType == null)
                
{
                    _logger.DebugFormat(
"Controller class '{0}' does not exist, trying to lookup in config", controllerClass);

                    
//Couldn't get the controller type from the controller pattern, so look up in the config
                    XmlElement controllerNode = (XmlElement)_settings.ConfigXml.DocumentElement.SelectSingleNode(String.Format("controllers/controller[@name='{0}']", command.ControllerName.ToLower()));
                    
if (controllerNode != null && controllerNode.HasAttribute("class"))
                    
{
                        controllerClass 
= controllerNode.GetAttribute("class");
                        controllerType 
= BuildManager.GetType(controllerClass, truefalse);
                    }

                }


                
if (controllerType == null)
                
{
                    _logger.DebugFormat(
"No controller available for '{0}', so using the default controller", command.CommandText);

                    
//No controller found so use the default controller. This means that a command 
                    
//doesn't need it's own controller if there it just needs to show the default
                    
//view.
                    controllerType = BuildManager.GetType(_settings.DefaultController, truefalse);
                }


                
//Cache this for next time
                _controllerTypeCache.Add(command.CommandText, controllerType);
            }


            _logger.DebugFormat(
"Creating controller: {0}", controllerType.ToString());

            
return (IController)Activator.CreateInstance(controllerType); //重新构造一个对象
        }


并依次调用 HomeController 的 BeforeAction;CallAction;AfterAction;
其中CallAction(controller, command, context);(controller.DefaultAction();
或若定义了ActionName则使用反射调用

{
Type controllerType 
= controller.GetType();
MethodInfo method 
= controllerType.GetMethod(command.ActionName);
 
if (method != null)
                
{
                    _logger.DebugFormat(
"Found action method '{0}' in controller: {1}, converting parameters...", command.ActionName, controller.GetType().ToString());

                    
//Make up the list of parameters
                    ParameterInfo[] methodParams = method.GetParameters();
                    List
<object> paramList = new List<object>();
                    
foreach (ParameterInfo param in methodParams)
                    
{
                        
//Convert request param to correct type
                        object convertedValue = null;

                        
if (param.ParameterType == typeof(HttpPostedFile))
                        
{
                            
//Get the posted file from the files collection
                            convertedValue = context.Request.Files[param.Name];
                        }

                        
else if (param.ParameterType == typeof(Guid))
                        
{
                            
//Get the posted file from the files collection
                            string valueAsString = context.Request[param.Name];
                            
if (valueAsString == null)
                            
{
                                convertedValue 
= Guid.Empty;
                            }

                            
else
                            
{
                                convertedValue 
= new Guid(valueAsString);
                            }

                        }

                        
else
                        
{
                            
//Convert value to correct type
                            string valueAsString = context.Request[param.Name];
                            
if (param.ParameterType.IsArray)
                            
{
                                
//This is an array
                                if (valueAsString.Length > 0)
                                
{
                                    
string[] array = valueAsString.Split(',');
                                    convertedValue 
= ArrayConverter.ConvertStringArray(array, param.ParameterType);
                                }

                            }

                            
else
                            
{
                                
//Normal type (not an array)
                                try
                                
{
                                    convertedValue 
= Convert.ChangeType(valueAsString, param.ParameterType);
                                }

                                
catch(Exception)
                                
{
                                    convertedValue 
= null;
                                }

                            }

                        }


                        
if (convertedValue == null)
                        
{
                            
//The converted value is null, create a new instance of this type
                            
//to ensure we are using the defaults for value types.
                            if (param.ParameterType.IsValueType)
                            
{
                                convertedValue 
= Activator.CreateInstance(param.ParameterType);
                            }

                        }


                        
//Add converted value to param list
                        paramList.Add(convertedValue);
                    }


                    
//Call the action with parameters
                    method.Invoke(controller, paramList.ToArray());
}

6.
没有定义ViewName的话,则根据配置的替换(viewWithNoActionPattern or viewWithNoActionPattern)规则,获取相应的view
最后根据View的类型,进行执行或者重转
i
f (command.View.ViewType  ==  ViewType.Render)
                    
{
                        _logger.DebugFormat(
"Rendering view: {0}", command.View.ViewPath);
                        context.Server.Execute(command.View.ViewPath);
                    }

                    
else
                    
{
                        _logger.DebugFormat(
"Redirecting to url: {0}", command.View.ViewUrl);
                        context.Response.Redirect(command.View.ViewUrl);
                    }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值