/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="output"></param>
		/// <param name="mode"></param>
		public static void ToJsonArray(UObj obj, TextWriter output, UObjSerializeMode mode)
		{
			output.Write("[");
			bool hasprop = false;
			foreach (var item in obj.Array)
			{
				if (item is UObj)
				{
					if (((UObj)item).UObjMode == UObjMode.Fake)
					{
						continue;
					}
				}
				if (hasprop)
				{
					output.Write(",");
				}
				else
				{
					hasprop = true;
				}
				ToJsonValue(output, mode, item);
			}
			output.Write("]");
		}
Example #2
0
        public Server()
        {
            obj = new UObj();


            //Создание канала
            BinaryServerFormatterSinkProvider srvPrvd = new BinaryServerFormatterSinkProvider();

            srvPrvd.TypeFilterLevel = TypeFilterLevel.Full;
            BinaryClientFormatterSinkProvider clntPrvd = new BinaryClientFormatterSinkProvider();
            Dictionary <string, string>       proprt   = new Dictionary <string, string>();

            proprt["port"] = "8086";
            TcpChannel channel = new TcpChannel(proprt, clntPrvd, srvPrvd);

            //Регистация канала
            ChannelServices.RegisterChannel(channel, false);

            RemotingConfiguration.Configure("C:\\Users\\Kirushka\\Desktop\\vaflin\\config.config", false);
            RemotingServices.Marshal(obj, "UdOb");  // задаем удаленный объект и слово через которое будет вестись связь


            Create();
            System.Threading.Timer timer = new System.Threading.Timer(tick, this, 0, 3600000);
        }
Example #3
0
        public void CanCreateAndUse()
        {
            dynamic uobj = new UObj();

            //one field
            uobj.a.b.c = 1;
            // second field (not alphabetic order)
            uobj.a.b.a = "tren\nd";
            //only GET will be treated as garbage
            var a = uobj.a.b.u.c.d.f;

            Assert.AreEqual(1, uobj.a.b.c);
            Console.WriteLine(uobj.ToJson());
            //test valid JSON in alphabet mode
            Assert.AreEqual(@"{""a"":{""b"":{""a"":""tren\nd"",""c"":1}}}", uobj.ToJson());
            uobj.a = new test {
                A = 3, B = 4
            };
            Console.WriteLine(uobj.ToJson());
            Assert.AreEqual(@"{""a"":{""A"":3,""B"":4}}", uobj.ToJson());
            Console.WriteLine(uobj.ToJson(UObjSerializeMode.KeepType));
            Assert.AreEqual(@"{""a"":{""_srctype"":""Qorpent.Serialization.Tests.Uson.UsonMainTest+test, Qorpent.Serialization.Tests"",""A"":3,""B"":4}}", uobj.ToJson(UObjSerializeMode.KeepType));
            uobj.a = new object[] { "x", 1, true, new DateTime(2002, 5, 2) };
            Console.WriteLine(uobj.ToJson());
            Assert.AreEqual(@"{""a"":[""x"",1,true,""2002-05-02T00:00:00""]}", uobj.ToJson());
            Assert.AreEqual(1, uobj.a[1]);
            Assert.AreEqual(null, uobj.a[10]);
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="output"></param>
		/// <param name="mode"></param>
		public static void ToJsonObject(UObj obj,TextWriter output, UObjSerializeMode mode)
		{
			output.Write("{");
			bool hasprop = false;
			if (mode.HasFlag(UObjSerializeMode.KeepType) && null != obj._srctype)
			{
				output.Write("\"{0}\":\"{1}, {2}\"", "_srctype", obj._srctype.FullName, obj._srctype.Assembly.GetName().Name);
				hasprop = true;
			}
			foreach (var property in obj.Properties.OrderBy(_ => _.Key))
			{
				if (property.Value is UObj)
				{
					if (((UObj) property.Value).UObjMode == UObjMode.Fake)
					{
						continue;
					}
				}
				if (hasprop)
				{
					output.Write(",");
				}
				else
				{
					hasprop = true;
				}
				output.Write("\"" + property.Key + "\"");
				output.Write(":");
				ToJsonValue(output,mode,property.Value);
			}
			output.Write("}");
		}
Example #5
0
        //不包含路径的预设体名,
        public UObj GetResource(string PrefabName)
        {
            UObj obj = null;

            string ABname = ResourceSetting.ConvertToAssetBundleName(PrefabName);

            if (dicAsset.TryGetValue(ABname, out obj) == false)
            {
                if (dicLoadingReq.ContainsKey(ABname))
                {
                    ConsoleEx.DebugLog("<GetResource Failed> Res is still loading, res.Name = " + ABname);
                }
                else
                {
                    // ConsoleEx.DebugLog("<GetResource Failed> Res not exist, res.Name = " + ABname);
                }
                obj = null;
            }
            else
            {
                // 添加引用
                RefAsset(ABname);
            }
            return(obj);
        }
Example #6
0
        public void ArrayByIndexTest()
        {
            dynamic uobj = new UObj();

            uobj.x[3] = 1;
            Console.WriteLine(uobj.ToJson());
            Assert.AreEqual(@"{""x"":[null,null,null,1]}", uobj.ToJson());
        }
Example #7
0
        public void ArrayByPushTest()
        {
            dynamic uobj = new UObj();

            uobj.x.push(1);
            uobj.x.push(2);
            uobj.x.push(3);
            Console.WriteLine(uobj.ToJson());
            Assert.AreEqual(@"{""x"":[1,2,3]}", uobj.ToJson());
        }
Example #8
0
        public void ArrayDefaults()
        {
            dynamic uobj  = new UObj();
            dynamic uobj2 = new UObj();

            uobj.push(null, 1, null, 2, null, 3);
            uobj2.push(-1, 2, -2, null, -3, 4);
            uobj.defaults(uobj2);
            Console.WriteLine(uobj.ToJson());
            Assert.AreEqual(@"[-1,1,-2,2,-3,3]", uobj.ToJson());
        }
Example #9
0
        public void DeepDefaults()
        {
            dynamic uobj  = new UObj();
            dynamic uobj2 = new UObj();

            uobj.a  = new { x = 1, y = 2 };
            uobj.b  = new { a = 3, b = 4 };
            uobj2.a = new { x = 2, z = 3 };
            uobj2.c = new { a = 4, c = 5 };
            uobj.deepdefaults(uobj2);
            Console.WriteLine(uobj.ToJson());
            Assert.AreEqual(@"{""a"":{""x"":1,""y"":2,""z"":3},""b"":{""a"":3,""b"":4},""c"":{""a"":4,""c"":5}}", uobj.ToJson());
        }
Example #10
0
        public void Defaults()
        {
            dynamic uobj  = new UObj();
            dynamic uobj2 = new UObj();

            uobj.a  = 1;
            uobj.b  = 2;
            uobj2.a = 3;
            uobj2.c = 4;
            uobj.defaults(uobj2);
            Console.WriteLine(uobj.ToJson());
            Assert.AreEqual(@"{""a"":1,""b"":2,""c"":4}", uobj.ToJson());
        }
Example #11
0
        private string GetErrorChartContent(IMvcContext context, IChartConfig config)
        {
            if (context.Get("format", context.Get("__format")) == "json")
            {
                dynamic result = new UObj();
                result.config       = config;
                result.error        = config.State.Message;
                context.ContentType = MimeHelper.JSON;
                return(result.ToJson());
            }
            var id     = "g" + Guid.NewGuid().ToString().Replace("-", "");
            var script = @"<div class='chart_Error chart_Error_'" + config.State.Level + "'>";

            if (!string.IsNullOrWhiteSpace(config.State.Title))
            {
                script += "<h3>" + config.State.Title + "</h3>";
            }
            else if (null != config.State.Exception)
            {
                script += "<p>Произошла ошибка " + config.State.Exception.GetType().Name + "</p>";
            }
            if (!string.IsNullOrWhiteSpace(config.State.Message))
            {
                script += "<p>" + config.State.Message.Replace("\r\n", "<br/>") + "</p>";
            }
            else if (null != config.State.Exception)
            {
                script += "<p>" + config.State.Exception.Message.Replace("\r\n", "<br/>") + "</p>";
            }
            if (null != config.State.Exception)
            {
                script += "<button onclick='$(\"#" + id + "\").toggle()'>Показать подробности ошибки</button>";
                script += "<BR /><textarea rows='30' cols='120' id='" + id + "' style='display:none'>" + config.State.Exception + "</textarea>";
            }
            script += "</div>";
            if (!string.IsNullOrWhiteSpace(context.Get("standalone")))
            {
                script = @"
<html>
<header>
</header>
<body>
<script type=""text/javascript"" src=""../scripts/jquery.min.js""></script>
" + script + @"
</body>
</html>";
            }
            return(script);
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="output"></param>
		/// <param name="mode"></param>
		public static void ToJson(UObj obj, TextWriter output, UObjSerializeMode mode = UObjSerializeMode.None)
		{
			if (obj.UObjMode == UObjMode.Default)
			{
				ToJsonObject(obj,output, mode);
			}
			else if (obj.UObjMode == UObjMode.Array)
			{
				ToJsonArray(obj,output, mode);
			}
			else
			{
				throw new NotImplementedException();
			}
		}
Example #13
0
        public void CanUseUObj()
        {
            dynamic g = new UObj();

            g.x = 1;
            g.y = 2;
            g.z = 3;
            var result = Compile(@"
class A a=z${x} b=${y} y=3", g, null);
            var a      = result.Get("A");
            var x      = a.Compiled.ToString().Replace("\"", "'");

            Console.WriteLine(x);
            Assert.AreEqual("<class code='A' a='z1' b='3' y='3' fullcode='A' />", x);
        }
Example #14
0
        private static UObj PrepareParameters(Uri uri)
        {
            UObj parameters = null;
            var  q          = "";

            if (uri.Query.Length > 1)
            {
                q = Uri.UnescapeDataString(uri.Query.Substring(1));
            }
            if (q.StartsWith("{") && q.EndsWith("}"))
            {
                parameters = q.ToUson();
            }
            RefineParameters(parameters);
            return(parameters);
        }
Example #15
0
	    private string GetErrorChartContent(IMvcContext context, IChartConfig config) {
			if (context.Get("format", context.Get("__format")) == "json")
			{
				dynamic result = new UObj();
				result.config = config;			
				result.error = config.State.Message;
				context.ContentType = MimeHelper.JSON;
				return result.ToJson();
			}
		    var id = "g"+Guid.NewGuid().ToString().Replace("-", "");
		    var script = @"<div class='chart_Error chart_Error_'"+config.State.Level+"'>";
			if (!string.IsNullOrWhiteSpace(config.State.Title)){
				script += "<h3>" + config.State.Title + "</h3>";
			} else if (null != config.State.Exception) {
				script += "<p>Произошла ошибка " + config.State.Exception.GetType().Name + "</p>"; 
			}
			if (!string.IsNullOrWhiteSpace(config.State.Message)) {
				script += "<p>" + config.State.Message.Replace("\r\n", "<br/>") + "</p>";
			} else if (null != config.State.Exception) {
				script += "<p>" + config.State.Exception.Message.Replace("\r\n", "<br/>") + "</p>";
			}
			if (null != config.State.Exception){
				script += "<button onclick='$(\"#" + id + "\").toggle()'>Показать подробности ошибки</button>";
				script += "<BR /><textarea rows='30' cols='120' id='" + id + "' style='display:none'>" + config.State.Exception + "</textarea>";
			}
		    script += "</div>";
			if (!string.IsNullOrWhiteSpace(context.Get("standalone")))
			{
				script = @"
<html>
<header>
</header>
<body>
<script type=""text/javascript"" src=""../scripts/jquery.min.js""></script>
" + script + @"
</body>
</html>";
			}
		    return script;
	    }
Example #16
0
        /// <summary>
        /// 同步加载位于本机的资源
        /// </summary>
        /// <returns>The load.</returns>
        /// <param name="task">Task.</param>
        public IEnumerator SyncLoad(AssetTask task)
        {
            string assetBundleName = task.AssetBundleName;

            // 添加引用
            RefAsset(assetBundleName);

            string fullPath = Path.Combine(DeviceInfo.PersistRootPath, GetPlatformName());

            fullPath = Path.Combine(fullPath, assetBundleName);

            WWW www = new WWW("file:///" + fullPath);

            www.threadPriority = ThreadPriority.High;
            yield return(www);

            if (www.error != null)
            {
                ConsoleEx.DebugLog("WWW download:" + www.error);
            }
            else
            {
                UObj obj = www.assetBundle.Load(task.PrefabName, task.UType);

                dicAsset.Add(assetBundleName, obj);
                task.Obj = obj;
                dicLoadingReq.Remove(assetBundleName);
                www.assetBundle.Unload(false);
                www.Dispose();
                www = null;

                //本地加载完成
                LoadEnd();
                if (task.LoadFinished != null)
                {
                    task.LoadFinished(task);
                }
            }
        }
Example #17
0
 private static void RefineParameters(UObj parameters)
 {
     foreach (var p in parameters.Properties.ToArray())
     {
         var str = p.Value as string;
         if (null != str)
         {
             var toint = str.ToInt();
             if ("0" == str || 0 != toint)
             {
                 parameters.Properties[p.Key] = toint;
             }
             else if ("true" == str)
             {
                 parameters.Properties[p.Key] = true;
             }
             else if ("false" == str)
             {
                 parameters.Properties[p.Key] = false;
             }
         }
         else if (p.Value is decimal)
         {
             var d = (decimal)p.Value;
             if (Math.Round(d, 0) == d)
             {
                 if (d > int.MaxValue)
                 {
                     parameters.Properties[p.Key] = (long)d;
                 }
                 else
                 {
                     parameters.Properties[p.Key] = (int)d;
                 }
             }
         }
     }
     parameters.IgnoreCase = true;
 }
Example #18
0
        private static UObj PrepareParameters(WebContext context)
        {
            var  uri        = context.Uri;
            UObj parameters = null;

            var q = "";

            if (uri.Query.Length > 1)
            {
                q = Uri.UnescapeDataString(uri.Query.Substring(1));
            }
            if (q.StartsWith("{") && q.EndsWith("}"))
            {
                parameters = q.ToUson();
            }
            else
            {
                var ps = RequestParameters.Create(context).GetParameters();
                if (ps.ContainsKey("__postdata"))
                {
                    var pd = ps["__postdata"].Trim();
                    if (pd.StartsWith("{") && pd.EndsWith("}"))
                    {
                        parameters = pd.ToUson();
                    }
                    ps.Remove("__postdata");
                }

                if (null == parameters)
                {
                    parameters = ps.ToUson();
                }
            }
            RefineParameters(parameters);
            return(parameters);
        }
		private static void RefineParameters(UObj parameters){
			foreach (var p in parameters.Properties.ToArray()){
				var str = p.Value as string;
				if (null != str){
					var toint = str.ToInt();
					if ("0" == str || 0 != toint){
						parameters.Properties[p.Key] = toint;
					}
					else if ("true" == str){
						parameters.Properties[p.Key] = true;
					}
					else if ("false" == str){
						parameters.Properties[p.Key] = false;
					}
				}
				else if (p.Value is decimal){
					var d = (decimal) p.Value;
					if (Math.Round(d, 0) == d){
						if (d > int.MaxValue){
							parameters.Properties[p.Key] = (long) d;
						}
						else{
							parameters.Properties[p.Key] = (int) d;
						}
					}
				}
			}
			parameters.IgnoreCase = true;
		}
Example #20
0
        public void CanSupplyDefaultParameters()
        {
            dynamic o = new UObj();

            t(o.first, o.second);
        }
Example #21
0
	    private string GetNormalChartContent(IMvcContext context, IChartConfig config) {
		    var comments = GetComments(context).Aggregate(string.Empty, (_, __) => _ + __);
		    var datascript = RenderDataScript(context, config);
			if (string.IsNullOrWhiteSpace(datascript)) {
				return GetErrorChartContent(context, config);
			}
		    var script = "";
		    var error = string.Empty;

		    if (string.IsNullOrWhiteSpace(datascript)) {
			    error = "Нет данных для отображения";
		    }

		    if (context.Get("format", context.Get("__format")) == "json") {
			    dynamic result = new UObj();
			    result.config = config;
			    result.data = datascript;
			    result.error = error;
			    context.ContentType = MimeHelper.JSON;
				return result.ToJson().Replace("\\\'", "'");
		    }

		    var id = config.Id;
		    var container = config.Container;

		    if (string.IsNullOrWhiteSpace(container)) {
			    container = "fc-container-" + id;
			    script += string.Format(@"
<div class=""assoiGraphContainer""><div class=""fusinchart-container{0}"" id=""{1}"">{2}</div>{3}</div>", string.IsNullOrEmpty(error) ? " fusionchart-error" : "", container, error, comments);
		    }


		    if (string.IsNullOrWhiteSpace(error)) {
			    script += string.Format(@"
<div style=""display:none"" id=""fc-data-{1}"">{5}</div>
<script type=""text/javascript""><!--
    FusionCharts.setCurrentRenderer('javascript');
    var myChart = new FusionCharts('../charts/{0}.swf', 'fc-chart-{1}', '{2}', '{3}', '{4}');
    myChart.set{7}Data($('#fc-data-{1}').text());
    myChart.render('{6}');
// -->
</script>", config.Type, id, config.Width, config.Height, config.Debug, datascript.Replace("<", "&lt;").Replace("&quot;","&amp;quot;"), container, config.DataType);
			    context.ContentType = "text/html";
		    }

		    if (!string.IsNullOrWhiteSpace(context.Get("standalone"))) {
			    script = @"
<html>
<header>
	<style type=""text/css"">
		.assoiGraphContainer { position: relative;}
		.assoiGraphComment {
			position: absolute;
			background: #FFFED6;
			border: 1px #006699 dotted;
			color: #000;
			padding: 5px 8px 5px 8px;
		}
	</style>
	<title>График АССОИ</title>
</header>
<body>
<script type=""text/javascript"" src=""../scripts/jquery.min.js""></script>
<script type=""text/javascript"" src=""../scripts/FusionCharts.js""></script>
<script type=""text/javascript"" src=""../scripts/FusionCharts.HC.js""></script>
<script type=""text/javascript"" src=""../scripts/FusionCharts.HC.PowerCharts.js""></script>
<script type=""text/javascript"" src=""../scripts/FusionCharts.HC.Widgets.js""></script>
" + script + @"
</body>
</html>";
		    }
		    return script;
	    }
	//	static  readonly  object  locker = new object();
		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="parent"></param>
		/// <param name="noParseJson"></param>
		/// <returns></returns>
		public static object ToUson(object obj,UObj parent = null, bool noParseJson = false)
		{
		//	lock (locker){
				if (obj is string && !noParseJson){
					var s = obj.ToString().Trim();
					if (0 != s.Length){
						if (s[0] == '{' && s[s.Length - 1] == '}'){
							return new JsonParser().Parse(s).ToUson();
						}
					}
				}

				if (obj is string){
					var s = obj as string;
					if (s == "0") return 0m;
					var dec = s.ToDecimal(true);
					if (dec != 0 && dec.ToString(CultureInfo.InvariantCulture) == s){
						return dec;
					}
					return s;
				}

				if (obj == null || obj.GetType().IsValueType){

					return obj;
				}
				var result = new UObj{Parent = parent, _srctype = obj.GetType()};
				if (obj is UObj){
					result.UObjMode = (obj as UObj).UObjMode;
					foreach (var p in ((UObj) obj).Properties){
						result.Properties[p.Key] = ToUson(p.Value, null, noParseJson);
					}
					foreach (var p in ((UObj) obj).Array){
						result.Array.Add(p);
					}
					return result;
				}
				if (obj is JsonItem){
					if (obj is JsonObject){
						foreach (var p in ((JsonObject) obj).Properties){
							result.Properties[p.Name.Value] = ToUson(p.Value, null, noParseJson);
						}
						return result;
					}
					else if (obj is JsonArray){
						foreach (var p in ((JsonArray) obj).Values){
							result.Array.Add(ToUson(p.Value, null, noParseJson));
						}
						return result;
					}
					else if (obj is JsonValue){
						var jv = (JsonValue) obj;
						if (jv.Type == JsonTokenType.String) return ToUson(jv.Value, null, noParseJson);
						if (jv.Type == JsonTokenType.Number) return decimal.Parse(jv.Value);
						if (jv.Type == JsonTokenType.Null) return null;
						if (jv.Type == JsonTokenType.Bool) return Boolean.Parse(jv.Value);
						return ToUson(jv.Value, null, noParseJson);
					}

				}
				if (obj is Array){
					result.UObjMode = UObjMode.Array;
					foreach (var item in ((IEnumerable) obj)){
						result.Array.Add(ToUson(item, null, noParseJson));
					}
				}
				else if (obj.GetType().Name.StartsWith("Dictionary")){
					result.UObjMode = UObjMode.Default;
					foreach (dynamic item in ((IEnumerable) obj)){
						result.Properties[item.Key.ToString()] = ToUson(item.Value);
					}

				}
				else if (obj.GetType().Name.StartsWith("List")){
					result.UObjMode = UObjMode.Array;
					foreach (var item in ((IEnumerable) obj)){
						result.Array.Add(ToUson(item, null, noParseJson));
					}
				}

				else{
					foreach (var p in SerializableItem.GetSerializableItems(obj)){
						result.Properties[p.Name] = ToUson(p.Value, null, noParseJson);
					}
				}

				return result;
	//		}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="writer"></param>
		/// <param name="mode"></param>
		public static void WriteXml(UObj obj, XmlWriter writer, UObjSerializeMode mode)
		{
			WriteXml(obj, "result",null, writer, mode);
		}
Example #24
0
        private string GetNormalChartContent(IMvcContext context, IChartConfig config)
        {
            var comments   = GetComments(context).Aggregate(string.Empty, (_, __) => _ + __);
            var datascript = RenderDataScript(context, config);

            if (string.IsNullOrWhiteSpace(datascript))
            {
                return(GetErrorChartContent(context, config));
            }
            var script = "";
            var error  = string.Empty;

            if (string.IsNullOrWhiteSpace(datascript))
            {
                error = "Нет данных для отображения";
            }

            if (context.Get("format", context.Get("__format")) == "json")
            {
                dynamic result = new UObj();
                result.config       = config;
                result.data         = datascript;
                result.error        = error;
                context.ContentType = MimeHelper.JSON;
                return(result.ToJson().Replace("\\\'", "'"));
            }

            var id        = config.Id;
            var container = config.Container;

            if (string.IsNullOrWhiteSpace(container))
            {
                container = "fc-container-" + id;
                script   += string.Format(@"
<div class=""assoiGraphContainer""><div class=""fusinchart-container{0}"" id=""{1}"">{2}</div>{3}</div>", string.IsNullOrEmpty(error) ? " fusionchart-error" : "", container, error, comments);
            }


            if (string.IsNullOrWhiteSpace(error))
            {
                script += string.Format(@"
<div style=""display:none"" id=""fc-data-{1}"">{5}</div>
<script type=""text/javascript""><!--
    FusionCharts.setCurrentRenderer('javascript');
    var myChart = new FusionCharts('../charts/{0}.swf', 'fc-chart-{1}', '{2}', '{3}', '{4}');
    myChart.set{7}Data($('#fc-data-{1}').text());
    myChart.render('{6}');
// -->
</script>", config.Type, id, config.Width, config.Height, config.Debug, datascript.Replace("<", "&lt;").Replace("&quot;", "&amp;quot;"), container, config.DataType);
                context.ContentType = "text/html";
            }

            if (!string.IsNullOrWhiteSpace(context.Get("standalone")))
            {
                script = @"
<html>
<header>
	<style type=""text/css"">
		.assoiGraphContainer { position: relative;}
		.assoiGraphComment {
			position: absolute;
			background: #FFFED6;
			border: 1px #006699 dotted;
			color: #000;
			padding: 5px 8px 5px 8px;
		}
	</style>
	<title>График АССОИ</title>
</header>
<body>
<script type=""text/javascript"" src=""../scripts/jquery.min.js""></script>
<script type=""text/javascript"" src=""../scripts/FusionCharts.js""></script>
<script type=""text/javascript"" src=""../scripts/FusionCharts.HC.js""></script>
<script type=""text/javascript"" src=""../scripts/FusionCharts.HC.PowerCharts.js""></script>
<script type=""text/javascript"" src=""../scripts/FusionCharts.HC.Widgets.js""></script>
" + script + @"
</body>
</html>";
            }
            return(script);
        }
        private string GenerateSingleController(IBSharpClass targetclass)
        {
            var xml      = targetclass.Compiled;
            var code     = xml.Attr("fullcode").Split('.').Last();
            var sb       = new StringBuilder();
            var deps     = new Dictionary <string, XElement>();
            var advanced = new StringBuilder();

            if (xml.Elements().Any(_ => _.GetSmartValue("persistent", "persistentCode").ToBool()) && deps.All(_ => _.Value.Attr("type") != "settings"))
            {
                deps["settings"] = new XElement("service", new XAttribute("type", "settings"), new XAttribute("before", "true"));
            }
            foreach (var s in xml.Elements("service"))
            {
                var scode = s.Attr("code");
                deps[scode] = s;
            }
            var deplist = string.Join("','", deps.Values.Select(_ => _.ChooseAttr("type", "code")).Distinct().OrderBy(_ => _));

            if (!string.IsNullOrWhiteSpace(deplist))
            {
                deplist = ", '" + deplist + "'";
            }
            var calllist = string.Join(",", deps.Values.Select(_ => _.ChooseAttr("type", "code")).Distinct().OrderBy(_ => _));

            if (!string.IsNullOrWhiteSpace(calllist))
            {
                calllist = ", " + calllist;
            }
            sb.Append(string.Format(@"
        .controller('{3}_{0}', ['$scope','$http','$rootScope'{1},'$element', function ($scope, $http, $rootScope{2},$element) {{ 
                $scope.api = Api($http, $rootScope);
				$scope.$services = {{}};
				$scope.$services.$element = $element;
				$scope.$services.$http = $http;
				$scope.$services.$rootScope = $rootScope;
", code, deplist, calllist, Project.ProjectName));
            foreach (var dep in deps)
            {
                sb.Append("\t\t\t\t$scope.$services." + dep.Key + "=" + dep.Key + ";");
                sb.AppendLine();
            }
            sb.AppendFormat(
                @"				$scope.{2} = '{0}.html';
				$scope.title= '{1}';
",
                targetclass.Compiled.ChooseAttr("view", "code"),
                targetclass.Compiled.ChooseAttr("name", "code"),
                (targetclass.Compiled.Element("menu") == null)?"view":"_view"
                );



            var items = xml.Elements("item");

            foreach (var e in deps.Where(_ => _.Value.Attr("before").ToBool()).OrderBy(_ => _.Key))
            {
                var type = e.Value.ChooseAttr("type", "code");
                UnifyPersistentCode(targetclass, e);
                if (type == "refresh")
                {
                    SetupRefresh(targetclass, e, advanced);
                }
                sb.AppendLine("\t\t\t\t" + type + "($scope," + e.Value.ToJson() + ");");
            }
            foreach (var item in items.OrderBy(_ => _.Attr("code")))
            {
                var type    = item.Attr("type");
                var typestr = "{}";
                var watcher = "";
                if (!string.IsNullOrWhiteSpace(type))
                {
                    var persistent = item.GetSmartValue("persistent", "persistentCode");
                    if (persistent == "1")
                    {
                        persistent = Project.ProjectName + "-" + xml.Attr("code") + "-" + item.Attr("code");
                    }

                    dynamic ext        = new UObj();
                    var     parameters = item.Element("parameters");
                    if (null != parameters)
                    {
                        foreach (var a in parameters.Attributes())
                        {
                            ext[a.Name.LocalName] = a.Value;
                        }
                    }
                    string ctor = ext.ToJson(UObjSerializeMode.Javascript);
                    if (!string.IsNullOrWhiteSpace(persistent))
                    {
                        ctor = "$.extend(" + ctor + ",$scope.settings.get('" + persistent + "'))";
                    }
                    typestr = "new Types." + type.Split('.').Last() + "(" + ctor + ")";
                    watcher = "\t\t\t\t$scope.$watch('" + item.Attr("code") + "',function(n,o){$scope.settings.set('" + persistent +
                              "',n)},true);";
                }
                else if (item.HasElements)
                {
                    var uson = new UObj();
                    foreach (var e in item.Elements())
                    {
                        var u = e.XmlToUson();
                        u.Properties["itemtype"] = e.Name.LocalName;
                        uson.push(u);
                    }

                    typestr = uson.ToJson(UObjSerializeMode.Javascript);
                }


                sb.AppendLine("\t\t\t\t$scope." + item.Attr("code") + " = " + typestr + ";");
                if (!string.IsNullOrWhiteSpace(watcher))
                {
                    sb.AppendLine(watcher);
                }
            }

            foreach (var e in deps.Where(_ => !_.Value.Attr("before").ToBool()).OrderBy(_ => _.Key))
            {
                var type = e.Value.ChooseAttr("type", "code");
                UnifyPersistentCode(targetclass, e);
                if (type == "refresh")
                {
                    SetupRefresh(targetclass, e, advanced);
                }
                sb.AppendLine("\t\t\t\t" + type + "($scope," + e.Value.ToJson() + ");");
            }
            sb.AppendLine(advanced.ToString());

            sb.AppendLine("\t\t}])");


            //sb.AppendLine();
            return(sb.ToString());
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <param name="elementName"></param>
		/// <param name="advAttributes"></param>
		/// <param name="writer"></param>
		/// <param name="mode"></param>
		private static void WriteXml(UObj obj, string elementName, string advAttributes, XmlWriter writer, UObjSerializeMode mode)
		{
			if(obj.UObjMode==UObjMode.Fake)return;			
			writer.WriteStartElement(elementName);
			if (!string.IsNullOrWhiteSpace(advAttributes))
			{
				writer.WriteRaw(" "+advAttributes+" ");
			}
			if (mode.HasFlag(UObjSerializeMode.KeepType) && null != obj._srctype)
			{
				writer.WriteAttributeString("_srctype",string.Format("{0}, {1}",obj._srctype.FullName,obj._srctype.Assembly.GetName().Name));
			}
			if (obj.UObjMode == UObjMode.Default)
			{
				foreach (var property in obj.Properties)
				{
					if (property.Value == null) continue;
					if (property.Value is string || property.Value.GetType().IsValueType)
					{
						writer.WriteAttributeString(property.Key, ToXmlValue(property.Value));
					}
				}
				foreach (var property in obj.Properties)
				{
					if (property.Value == null) continue;
					if (!(property.Value is string || property.Value.GetType().IsValueType))
					{
						WriteXml((UObj) property.Value, property.Key, null, writer, mode);
					}
				}
			}
			else
			{
				writer.WriteAttributeString("_array","true");
				foreach (var p in obj.Array)
				{
					if (null == p)
					{
						writer.WriteElementString("item", "");
					}else if (p is string || p.GetType().IsValueType)
					{
						writer.WriteElementString("item", ToXmlValue(p));
					}
					else
					{
						WriteXml(p as UObj,"item",null,writer,mode);
					}
				}
			}
			writer.WriteEndElement();
		}