Example #1
0
        /// <summary>
        /// 获取资源
        /// </summary>
        /// <param name="resourceType">资源类型</param>
        /// <param name="userLanguage">用户语言</param>
        /// <param name="fileName">资源文件名</param>
        /// <param name="defaultOnly">只使用默认语言</param>
        /// <returns></returns>
        private static Hashtable GetResource(ResourceManagerType resourceType, string userLanguage, string fileName, bool defaultOnly)
        {
            string defaultLanguage = ResourceManager.defaultLanguage;
            string cacheKey        = resourceType.ToString() + defaultLanguage + userLanguage + fileName;

            // 如果用户没有定制语言,则使用默认
            //
            if (string.IsNullOrEmpty(userLanguage) || defaultOnly)
            {
                userLanguage = defaultLanguage;
            }

            // 从缓存中获取资源
            //
            Hashtable resources = CustomCache.Get(cacheKey) as Hashtable;

            if (resources == null)
            {
                resources = new Hashtable();

                resources = LoadResource(resourceType, resources, defaultLanguage, cacheKey, fileName);

                // 如果用户设置了语言则加载用户语言资源
                //
                if (defaultLanguage != userLanguage)
                {
                    resources = LoadResource(resourceType, resources, userLanguage, cacheKey, fileName);
                }
            }
            return(resources);
        }
Example #2
0
        //private static Hashtable GetResource(ResourceManagerType resourceType)
        //{
        //    return GetResource(resourceType, "fa");
        //}

        private static Hashtable GetResource(ResourceManagerType resourceType, string culture)
        {
            var resources = new Hashtable();

            resources = LoadResource(resourceType, resources, culture);
            return(resources);
        }
Example #3
0
        private static Hashtable LoadResource(ResourceManagerType resourceType, Hashtable target, string language, string cacheKey, string fileName)
        {
            string str = cacheKey;

            str = @"Languages\" + language + @"\" + fileName;
            string      baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string      newValue      = Path.DirectorySeparatorChar.ToString();
            string      filename      = baseDirectory.Replace("/", newValue).TrimEnd(new char[] { Path.DirectorySeparatorChar }) + Path.DirectorySeparatorChar.ToString() + str.TrimStart(new char[] { Path.DirectorySeparatorChar });
            HttpContext current       = HttpContext.Current;

            if (current != null)
            {
                filename = current.Server.MapPath("~/Languages/zh-CHS/" + fileName);
            }
            else
            {
                filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Languages/zh-CHS/" + fileName);
            }
            XmlDocument document = new XmlDocument();

            document.Load(filename);
            foreach (XmlNode node in document.SelectSingleNode("root").ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Comment)
                {
                    switch (resourceType)
                    {
                    case ResourceManagerType.String:
                    {
                        if (target[node.Attributes["name"].Value] != null)
                        {
                            goto Label_0188;
                        }
                        target.Add(node.Attributes["name"].Value, node.InnerText);
                        continue;
                    }

                    case ResourceManagerType.ErrorMessage:
                    {
                        ErrMessage message = new ErrMessage(node);
                        target[message.MessageId] = message;
                        continue;
                    }

                    case ResourceManagerType.Template:
                    {
                        continue;
                    }
                    }
                }
                continue;
Label_0188:
                target[node.Attributes["name"].Value] = node.InnerText;
            }
            return(target);
        }
Example #4
0
        /// <summary>
        /// 加载资源
        /// </summary>
        /// <param name="resourceType"></param>
        /// <param name="target"></param>
        /// <param name="language"></param>
        /// <param name="cacheKey"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static Hashtable LoadResource(ResourceManagerType resourceType, Hashtable target, string language, string cacheKey, string fileName)
        {
            HttpContext csContext = HttpContext.Current;

            string filePath = csContext.Server.MapPath("~/Languages/" + language + "/" + fileName);

            //switch (resourceType)
            //{
            //    case ResourceManagerType.ErrorMessage:
            //        filePath = string.Format(filePath, "Messages.xml");
            //        break;

            //    default:
            //        filePath = string.Format(filePath, "Resources.xml");
            //        break;
            //}

            CacheDependency dp = new CacheDependency(filePath);

            XmlDocument d = new XmlDocument();

            try
            {
                d.Load(filePath);
            }
            catch
            {
                return(target);
            }
            foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes)
            {
                if (n.NodeType != XmlNodeType.Comment)
                {
                    if (target[n.Attributes["name"].Value] == null)
                    {
                        target.Add(n.Attributes["name"].Value, n.InnerText);
                    }
                    else
                    {
                        target[n.Attributes["name"].Value] = n.InnerText;
                    }
                }
            }
            if (language == ResourceManager.defaultLanguage)
            {
                CustomCache.Max(cacheKey, target, dp);
            }
            else
            {
                CustomCache.Insert(cacheKey, target, dp, CustomCache.MinuteFactor * 5);
            }
            return(target);
        }
Example #5
0
        private static Hashtable LoadResource(ResourceManagerType resourceType, Hashtable target, string language, string cacheKey, string fileName)
        {
            string filePath = GlobalSettings.PhysicalPath("Languages\\" + language + "\\" + fileName);

            FileDependency dp;
            XmlDocument    d = new XmlDocument();

            try
            {
                dp = new FileDependency(filePath);
                d.Load(filePath);
            }
            catch
            {
                return(target);
            }
            foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes)
            {
                if (n.NodeType != XmlNodeType.Comment)
                {
                    switch (resourceType)
                    {
                    case ResourceManagerType.ErrorMessage:
                        Message m = new Message(n);
                        target[m.MessageID] = m;
                        break;

                    case ResourceManagerType.String:
                        if (target[n.Attributes["name"].Value] == null)
                        {
                            target.Add(n.Attributes["name"].Value, n.InnerText);
                        }
                        else
                        {
                            target[n.Attributes["name"].Value] = n.InnerText;
                        }
                        break;

                    case ResourceManagerType.UserLicence:
                        if (target["licence"] == null)
                        {
                            target.Add("licence", n.InnerText);
                        }
                        break;
                    }
                }
            }
            HHCache.Instance.Max(cacheKey, target, dp);
            return(target);
        }
Example #6
0
        private static Hashtable GetResource(ResourceManagerType resourceType, string userLanguage, string fileName, bool defaultOnly)
        {
            if (defaultOnly)
            {
                defaultOnly = false;
            }
            string    cacheKey = userLanguage + fileName;
            Hashtable target   = null;

            if (target == null)
            {
                target = new Hashtable();
                if ("en-US" != userLanguage)
                {
                    target = LoadResource(resourceType, target, userLanguage, cacheKey, fileName);
                }
            }
            return(target);
        }
Example #7
0
        private static Hashtable GetResource(ResourceManagerType resourceType, string userLanguage, string fileName, bool defaultOnly)
        {
            string defaultLanguage = HHConfiguration.GetConfig().DefaultLanguage;
            string cacheKey        = "HHOnline/Framework/" + resourceType.ToString() + defaultLanguage + userLanguage + fileName;

            if (GlobalSettings.IsNullOrEmpty(userLanguage) || defaultOnly)
            {
                userLanguage = defaultLanguage;
            }

            Hashtable resources = HHCache.Instance.Get(cacheKey) as Hashtable;

            if (resources == null)
            {
                resources = new Hashtable();
                resources = LoadResource(resourceType, resources, defaultLanguage, cacheKey, fileName);
                if (defaultLanguage != userLanguage)
                {
                    resources = LoadResource(resourceType, resources, userLanguage, cacheKey, fileName);
                }
            }
            return(resources);
        }
Example #8
0
    private static Hashtable GetResource(ResourceManagerType resourceType, string fileName, bool defaultOnly)
    {
        string cacheKey = resourceType.ToString() + fileName;
        Hashtable resources = new Hashtable();
        resources = LoadResource(resourceType, resources, cacheKey, fileName);

        return resources;
    }
Example #9
0
        static void OnToolsGUI(string rootNs, string viewNs, string constNs, string dataNs, string autoDir,
                               string scriptDir)
        {
            EditorGUILayout.Space();
            _resourceManagerType = (ResourceManagerType)EditorGUILayout.EnumPopup("资源加载类型", _resourceManagerType);

            switch (_resourceManagerType)
            {
                #region ResourceManagerType.Resource

            case ResourceManagerType.Resource:

                EditorGUILayout.LabelField("自动常量文件生成目录",
                                           Application.dataPath + "/" + rootNs + "/" + constNs + "/" + autoDir);
                EditorGUILayout.LabelField("常量工具类生成目录",
                                           Application.dataPath + "/" + rootNs + "/Utility/" + autoDir + "/ConstUtil.cs");
                EditorGUILayout.Space();

                createPathFile = EditorGUILayout.Toggle("是否生成资源路径文件", createPathFile);
                EditorGUILayout.Space();

                if (GUILayout.Button("生成常量"))
                {
                    #region 遍历Resources生成常量文件

                    var resourceDir = Application.dataPath + "/Resources";
                    var rootDir     = Application.dataPath + "/" + rootNs;

                    autoClassName.Clear();
                    otherResPathDic.Clear();
                    otherResFileNameDic.Clear();
                    allResPathDic.Clear();
                    allResFileNameDic.Clear();


                    foreach (var fullName in Directory.GetFileSystemEntries(resourceDir))
                    {
//                            Debug.Log(fullName);
                        if (Directory.Exists(fullName))
                        {
                            //如果是文件夹
                            OprateDir(new DirectoryInfo(fullName), rootNs, constNs, autoDir);
                        }
                        else
                        {
                            //是文件
                            OprateFile(new FileInfo(fullName));
                        }
                    }

                    //生成其他常量文件
                    if (otherResPathDic.Count > 0)
                    {
//                            Debug.Log("创建文件OtherResPath");
                        FileUtil.CreateConstClassByDictionary("OtherResPath",
                                                              rootDir + "/" + constNs + "/" + autoDir,
                                                              rootNs + "." + constNs, otherResPathDic);
                        FileUtil.CreateConstClassByDictionary("OtherResName",
                                                              rootDir + "/" + constNs + "/" + autoDir,
                                                              rootNs + "." + constNs, otherResFileNameDic);
                        autoClassName.Add("OtherRes");
                    }

                    //生成常量工具类
                    if (allResPathDic.Count > 0)
                    {
                        var content =
                            "\t\tprivate System.Collections.Generic.Dictionary<string,string> nameToPath \n" +
                            "\t\t\t= new System.Collections.Generic.Dictionary<string,string>{\n";

                        foreach (var kv in allResFileNameDic)
                        {
                            content += "\t\t\t\t\t{ @\"" + kv.Value + "\" , @\"" + allResPathDic[kv.Key] +
                                       "\" },\n";
                        }

                        content += "\t\t\t\t};\n";

                        content +=
                            "\t\tpublic override System.Collections.Generic.Dictionary<string,string> NameToPath => nameToPath;\n";

                        FileUtil.CreateClassFile("AssetConstUtil",
                                                 rootNs + ".Utility",
                                                 rootDir + "/Utility/" + autoDir,
                                                 parentClass: "ReadyGamerOne.MemorySystem.AssetConstUtil<AssetConstUtil>",
                                                 helpTips: "这个类提供了Resources下文件名和路径字典访问方式,同名资源可能引起bug",
                                                 fileContent: content,
                                                 autoOverwrite: true);
                    }


                    AssetDatabase.Refresh();
                    Debug.Log("生成结束");
                    #endregion
                }

                break;

                #endregion


                #region ResourceManagerType.AssetBundle

            case ResourceManagerType.AssetBundle:

                var newestVersion = PlayerPrefs.GetString(VersionDefine.PrefKey_LocalVersion, "0.0");

                if (GUILayout.Button("显示本地版本"))
                {
                    var versionData = PlayerPrefs.GetString(newestVersion);
                    Debug.Log("本地版本号:" + newestVersion + "\n版本信息:" + versionData);
                }

                EditorGUI.BeginChangeCheck();
                newestVersion = EditorGUILayout.DelayedTextField("本地版本", newestVersion);
                if (EditorGUI.EndChangeCheck())
                {
                    PlayerPrefs.SetString(VersionDefine.PrefKey_LocalVersion, newestVersion);
                }

                EditorGUILayout.Space();
                EditorGUILayout.LabelField("打包目录", assetToBundleDir);
                if (GUILayout.Button("设置要打包的目录"))
                {
                    assetToBundleDir = EditorUtility.OpenFolderPanel("选择需要打包的目录", Application.dataPath, "");
                }

                EditorGUILayout.Space();
                EditorGUILayout.LabelField("输出目录", outputDir);
                if (GUILayout.Button("设置输出目录"))
                {
                    outputDir = EditorUtility.OpenFolderPanel("选择输出目录", Application.dataPath, "");
                }

                EditorGUILayout.Space();
                assetBundleOptions =
                    (BuildAssetBundleOptions)EditorGUILayout.EnumFlagsField("打包选项", assetBundleOptions);

                buildTarget    = (BuildTarget)EditorGUILayout.EnumPopup("目标平台", buildTarget);
                clearOutputDir = EditorGUILayout.Toggle("清空生成目录", clearOutputDir);
                EditorGUILayout.Space();

                useForRuntime = EditorGUILayout.Foldout(useForRuntime, "使用用于生成运行时直接使用的AB包");
                if (useForRuntime)
                {
                    EditorGUILayout.LabelField("生成HotUpdatePath.cs路径",
                                               Application.dataPath + "/" + rootNs + "/" + constNs + "/" + autoDir + "/HotUpdatePath.cs");
                    useWeb = EditorGUILayout.Toggle("是否使用网络", useWeb);
                    EditorGUILayout.LabelField("游戏自身AB包名字", streamingAbName);

                    EditorGUILayout.Space();
                    if (GUILayout.Button("重新生成常量类【会覆盖】"))
                    {
                        if (!outputDir.Contains(Application.streamingAssetsPath))
                        {
                            Debug.LogError("运行时使用的AB包必须在StreamingAssets目录下");
                            return;
                        }

                        if (assetBundleNames.Count == 0)
                        {
                            Debug.LogError("AB包数组未空");
                            return;
                        }

                        CreatePathDataClass(rootNs, constNs, autoDir, assetBundleNames);
                        AssetDatabase.Refresh();
                        Debug.Log("生成完成");
                    }
                }


                if (GUILayout.Button("开始打包", GUILayout.Height(3 * EditorGUIUtility.singleLineHeight)))
                {
                    if (createPathDataClass)
                    {
                        if (!outputDir.Contains(Application.streamingAssetsPath))
                        {
                            Debug.LogError("运行时使用的AB包必须在StreamingAssets目录下");
                            return;
                        }
                    }

                    if (assetBundleNames.Count != 0)
                    {
                        assetBundleNames.Clear();
                    }
                    if (!Directory.Exists(assetToBundleDir))
                    {
                        Debug.LogError("打包目录设置异常");
                        return;
                    }

                    if (!Directory.Exists(outputDir))
                    {
                        Debug.LogError("输出目录设置异常");
                        return;
                    }

                    if (clearOutputDir)
                    {
                        if (Directory.Exists(outputDir))
                        {
                            //获取指定路径下所有文件夹
                            string[] folderPaths = Directory.GetDirectories(outputDir);

                            foreach (string folderPath in folderPaths)
                            {
                                Directory.Delete(folderPath, true);
                            }
                            //获取指定路径下所有文件
                            string[] filePaths = Directory.GetFiles(outputDir);

                            foreach (string filePath in filePaths)
                            {
                                File.Delete(filePath);
                            }
                        }
                    }

                    var builds = new List <AssetBundleBuild>();
                    foreach (var dirPath in System.IO.Directory.GetDirectories(assetToBundleDir))
                    {
                        var dirName    = new DirectoryInfo(dirPath).Name;
                        var paths      = new List <string>();
                        var assetNames = new List <string>();
                        FileUtil.SearchDirectory(dirPath,
                                                 fileInfo =>
                        {
                            if (fileInfo.Name.EndsWith(".meta"))
                            {
                                return;
                            }
                            var pureName = Path.GetFileNameWithoutExtension(fileInfo.FullName);
                            assetNames.Add(pureName);
                            var fileLoadPath = fileInfo.FullName.Replace("\\", "/")
                                               .Replace(Application.dataPath, "Assets");
                            var ai             = AssetImporter.GetAtPath(fileLoadPath);
                            ai.assetBundleName = dirName;
                            paths.Add(fileLoadPath);
                        }, true);

                        assetBundleNames.Add(dirName);
                        FileUtil.CreateConstClassByDictionary(
                            dirName + "Name",
                            Application.dataPath + "/" + rootNs + "/" + constNs,
                            rootNs + "." + constNs,
                            assetNames.ToDictionary(name => name));
                        builds.Add(new AssetBundleBuild
                        {
                            assetNames      = paths.ToArray(),
                            assetBundleName = dirName
                        });
                    }

                    if (createPathDataClass)
                    {
                        CreatePathDataClass(rootNs, constNs, autoDir, assetBundleNames);
                    }


                    BuildPipeline.BuildAssetBundles(outputDir, builds.ToArray(), assetBundleOptions, buildTarget);
                    AssetDatabase.Refresh();
                    Debug.Log("打包完成");
                }

                break;

                #endregion
            }
        }
        /// <summary>
        /// 获取xml语言包中的资源项
        /// </summary>
        /// <param name="resourceType"></param>
        /// <param name="target"></param>
        /// <param name="language"></param>
        /// <param name="cacheKey"></param>
        private static void LoadResource(ResourceManagerType resourceType,string resource, Hashtable target, string language, string cacheKey)
        {
            DateTime maxValue;
            //ForumContext current = ForumContext.Current;
            HttpContext current = HttpContext.Current;
            string format = current.Server.MapPath("Languages/" + language + "{0}");
            if (resourceType == ResourceManagerType.ErrorMessage)
            {
                format = string.Format(format, "Messages.xml");
            }
            else
            {
                format = string.Format(format, @".xml");
            }
            CacheDependency dependencies = new CacheDependency(format);

            string [] str = resource.Split('.');
            if (str.Length<1)
            {
                throw new Exception(resource + "not found!");
            }

            #region  XML写法
            XmlDocument document = new XmlDocument();
            try
            {
                document.Load(format);
            }
            catch
            {
                return;
            }
            foreach (XmlNode node in document.SelectSingleNode("Resources").ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Comment)
                {
                    switch (resourceType)
                    {
                        case ResourceManagerType.String:
                            {
                                if (node.Attributes["name"].Value == str[0])
                                {
                                    foreach (XmlNode chil in node)
                                    {
                                        if (chil.Attributes["tag"].Value.ToUpper()==str[1])
                                        {
                                            target[str[1]] = chil.InnerText;
                                        }
                                    }
                                    //xgoto Label_0142;
                                    //xtarget[node.Attributes["name"].Value] = node.InnerText;
                                }
                                //xtarget.Add(node.Attributes["name"].Value, node.InnerText);
                                continue;
                            }
                        case ResourceManagerType.ErrorMessage:
                            {
                                //ForumMessage message = new ForumMessage(node);
                                //target[message.MessageID] = message;
                                continue;
                            }
                    }
                }
                continue;
                //xLabel_0142:
                //xtarget[node.Attributes["name"].Value] = node.InnerText;
            }
            #endregion

            DateTime absoluteExpiration;
            if (language == "zh-CN")
            {
                absoluteExpiration = DateTime.MaxValue;
                current.Cache.Insert(cacheKey, target, dependencies, absoluteExpiration, TimeSpan.Zero);
            }
            absoluteExpiration = DateTime.Now.AddHours(1.0);
        }
        /// <summary>
        /// 获取特定语言的特定资源
        /// </summary>
        /// <param name="resourceType"></param>
        /// <param name="resource"></param>
        /// <param name="language"></param>
        /// <returns></returns>
        private static Hashtable GetResource(ResourceManagerType resourceType, string resource,string language)
        {
            HttpContext current = HttpContext.Current;
            string cacheKey = resourceType.ToString() + language;

            if (!string.IsNullOrEmpty(language))
            {
                throw new Exception(language+"not found!");
            }

            if (current.Cache[cacheKey] == null)
            {
                Hashtable target = new Hashtable();
                LoadResource(resourceType, resource, target, language, cacheKey);
            }
            return (Hashtable)current.Cache[cacheKey];
        }
        /// <summary>
        ///获取浏览器默认语言的相应资源
        /// </summary>
        /// <param name="resourceType"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        private static Hashtable GetResource(ResourceManagerType resourceType,string resource)
        {
            HttpContext current = HttpContext.Current;
            string language = "zh-CN";
            string defaultLanguage = current.Request.UserLanguages[0].ToString();
            //!容易重复
            string cacheKey = resourceType.ToString() + resource;

            if (string.IsNullOrEmpty(defaultLanguage))
            {
                defaultLanguage = language;
            }
            if (current.Cache[cacheKey] == null)
            {
                Hashtable target = new Hashtable();
                LoadResource(resourceType, resource, target, defaultLanguage, cacheKey);
                //if ("zh-CN" != language)
                //{
                //    LoadResource(resourceType,resource, target, language, cacheKey);
                //}
            }
            return (Hashtable)current.Cache[cacheKey];
        }
Example #13
0
        private static Hashtable LoadResource(ResourceManagerType resourceType, Hashtable target, string culture)
        {
            string filePath = AppPath.CorePath("Resource") + "{0}/{1}";

            switch (resourceType)
            {
            case ResourceManagerType.CustomMessage:
                filePath = string.Format(filePath, culture, "Messages.xml");
                break;

            case ResourceManagerType.String:
                filePath = string.Format(filePath, culture, "Resources.xml");
                break;

            case ResourceManagerType.Help:
                filePath = string.Format(filePath, culture, "Help.xml");
                break;

            default:
                filePath = string.Format(filePath, culture, "Resources.xml");
                break;
            }
            if (!System.IO.File.Exists(filePath))
            {
                throw new Exception(string.Format("File Doesn't Exists: {0}", filePath));
            }
            FileInfo  fileInfo = new FileInfo(filePath);
            long      fileSize = fileInfo.Length;
            long      prevSize = CustomCache.Get(string.Format("Core.Resource.Size.{0}", resourceType)).SafeLong(0);
            Hashtable resource = (Hashtable)CustomCache.Get(string.Format("Core.Resource.{0}", resourceType));


            //resource.Count
            if (resource == null || fileSize != prevSize)
            {
                XmlDocument d = new XmlDocument();
                try
                {
                    d.Load(filePath);
                }
                catch
                {
                    return(target);
                }
                var selectSingleNode = d.SelectSingleNode("root");
                if (selectSingleNode != null)
                {
                    foreach (XmlNode n in selectSingleNode.ChildNodes)
                    {
                        if (n.NodeType != XmlNodeType.Comment)
                        {
                            Message m;
                            switch (resourceType)
                            {
                            case ResourceManagerType.CustomMessage:
                                m = new Message(n);
                                target[m.Name] = m;
                                break;

                            case ResourceManagerType.Help:
                                m = new Message(n);
                                target[m.Name] = m;
                                break;

                            case ResourceManagerType.String:
                                if (target[n.Attributes["name"].Value.ToLower()] == null)
                                {
                                    target.Add(n.Attributes["name"].Value.ToLower(), n.InnerText.Replace("&gt;", ">").Replace("&lt;", "<"));
                                }
                                else
                                {
                                    target[n.Attributes["name"].Value.ToLower()] = n.InnerText.Replace("&gt;", ">").Replace("&lt;", "<");
                                }
                                break;
                                //m = new Message(n);
                                //target[m.Name] = m;

                                //break;
                            }
                        }
                    }
                }

                CustomCache.Insert(string.Format("Core.Resource.{0}", resourceType.ToString()), target);
                CustomCache.Insert(string.Format("Core.Resource.Size.{0}", resourceType.ToString()), fileSize);

                return(target);
            }
            return(resource);
        }
        /// <summary>
        /// Create or updates the subscription
        /// </summary>
        /// <param name='parameters'>
        /// Required. Subscription update parameters
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Result of the create or the update operation of the subscription
        /// </returns>
        public async Task <SubscriptionCreateOrUpdateAsAdminResult> CreateOrUpdateAsync(SubscriptionCreateOrUpdateAsAdminParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Subscription == null)
            {
                throw new ArgumentNullException("parameters.Subscription");
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/providers/Microsoft.Subscriptions.Admin/subscriptions/";
            if (parameters.Subscription.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(parameters.Subscription.SubscriptionId);
            }
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                JObject subscriptionCreateOrUpdateAsAdminParametersValue = new JObject();
                requestDoc = subscriptionCreateOrUpdateAsAdminParametersValue;

                if (parameters.Subscription.Id != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["id"] = parameters.Subscription.Id;
                }

                if (parameters.Subscription.SubscriptionId != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["subscriptionId"] = parameters.Subscription.SubscriptionId;
                }

                if (parameters.Subscription.DelegatedProviderSubscriptionId != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["delegatedProviderSubscriptionId"] = parameters.Subscription.DelegatedProviderSubscriptionId;
                }

                if (parameters.Subscription.DisplayName != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["displayName"] = parameters.Subscription.DisplayName;
                }

                if (parameters.Subscription.ExternalReferenceId != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["externalReferenceId"] = parameters.Subscription.ExternalReferenceId;
                }

                if (parameters.Subscription.Owner != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["owner"] = parameters.Subscription.Owner;
                }

                if (parameters.Subscription.TenantId != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["tenantId"] = parameters.Subscription.TenantId;
                }

                subscriptionCreateOrUpdateAsAdminParametersValue["routingResourceManagerType"] = parameters.Subscription.RoutingResourceManagerType.ToString();

                if (parameters.Subscription.OfferId != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["offerId"] = parameters.Subscription.OfferId;
                }

                if (parameters.Subscription.State != null)
                {
                    subscriptionCreateOrUpdateAsAdminParametersValue["state"] = parameters.Subscription.State.Value.ToString();
                }

                requestContent      = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    SubscriptionCreateOrUpdateAsAdminResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new SubscriptionCreateOrUpdateAsAdminResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            AdminSubscriptionDefinition subscriptionInstance = new AdminSubscriptionDefinition();
                            result.Subscription = subscriptionInstance;

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                subscriptionInstance.Id = idInstance;
                            }

                            JToken subscriptionIdValue = responseDoc["subscriptionId"];
                            if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
                            {
                                string subscriptionIdInstance = ((string)subscriptionIdValue);
                                subscriptionInstance.SubscriptionId = subscriptionIdInstance;
                            }

                            JToken delegatedProviderSubscriptionIdValue = responseDoc["delegatedProviderSubscriptionId"];
                            if (delegatedProviderSubscriptionIdValue != null && delegatedProviderSubscriptionIdValue.Type != JTokenType.Null)
                            {
                                string delegatedProviderSubscriptionIdInstance = ((string)delegatedProviderSubscriptionIdValue);
                                subscriptionInstance.DelegatedProviderSubscriptionId = delegatedProviderSubscriptionIdInstance;
                            }

                            JToken displayNameValue = responseDoc["displayName"];
                            if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
                            {
                                string displayNameInstance = ((string)displayNameValue);
                                subscriptionInstance.DisplayName = displayNameInstance;
                            }

                            JToken externalReferenceIdValue = responseDoc["externalReferenceId"];
                            if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null)
                            {
                                string externalReferenceIdInstance = ((string)externalReferenceIdValue);
                                subscriptionInstance.ExternalReferenceId = externalReferenceIdInstance;
                            }

                            JToken ownerValue = responseDoc["owner"];
                            if (ownerValue != null && ownerValue.Type != JTokenType.Null)
                            {
                                string ownerInstance = ((string)ownerValue);
                                subscriptionInstance.Owner = ownerInstance;
                            }

                            JToken tenantIdValue = responseDoc["tenantId"];
                            if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
                            {
                                string tenantIdInstance = ((string)tenantIdValue);
                                subscriptionInstance.TenantId = tenantIdInstance;
                            }

                            JToken routingResourceManagerTypeValue = responseDoc["routingResourceManagerType"];
                            if (routingResourceManagerTypeValue != null && routingResourceManagerTypeValue.Type != JTokenType.Null)
                            {
                                ResourceManagerType routingResourceManagerTypeInstance = ((ResourceManagerType)Enum.Parse(typeof(ResourceManagerType), ((string)routingResourceManagerTypeValue), true));
                                subscriptionInstance.RoutingResourceManagerType = routingResourceManagerTypeInstance;
                            }

                            JToken offerIdValue = responseDoc["offerId"];
                            if (offerIdValue != null && offerIdValue.Type != JTokenType.Null)
                            {
                                string offerIdInstance = ((string)offerIdValue);
                                subscriptionInstance.OfferId = offerIdInstance;
                            }

                            JToken stateValue = responseDoc["state"];
                            if (stateValue != null && stateValue.Type != JTokenType.Null)
                            {
                                SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true));
                                subscriptionInstance.State = stateInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Example #15
0
        static void OnToolsGUI(string rootNs, string viewNs, string constNs, string dataNs, string autoDir,
                               string scriptDir)
        {
            EditorGUILayout.Space();
            _resourceManagerType = (ResourceManagerType)EditorGUILayout.EnumPopup("资源加载类型", _resourceManagerType);

            switch (_resourceManagerType)
            {
                #region ResourceManagerType.Resource

            case ResourceManagerType.Resource:

                EditorGUILayout.LabelField("自动常量文件生成目录",
                                           Application.dataPath + "/" + rootNs + "/" + constNs + "/" + autoDir);
                EditorGUILayout.LabelField("常量工具类生成目录",
                                           Application.dataPath + "/" + rootNs + "/Utility/" + autoDir + "/ConstUtil.cs");
                EditorGUILayout.Space();

                createPathFile = EditorGUILayout.Toggle("是否生成资源路径文件", createPathFile);
                EditorGUILayout.Space();

                if (GUILayout.Button("生成常量"))
                {
                    GenerateResourcesConst(rootNs, constNs, autoDir);
                }

                break;

                #endregion


                #region ResourceManagerType.AssetBundle

            case ResourceManagerType.AssetBundle:

                var newestVersion = PlayerPrefs.GetString(VersionDefine.PrefKey_LocalVersion, "0.0");

                if (GUILayout.Button("显示本地版本"))
                {
                    var versionData = PlayerPrefs.GetString(newestVersion);
                    Debug.Log("本地版本号:" + newestVersion + "\n版本信息:" + versionData);
                }

                EditorGUI.BeginChangeCheck();
                newestVersion = EditorGUILayout.DelayedTextField("本地版本", newestVersion);
                if (EditorGUI.EndChangeCheck())
                {
                    PlayerPrefs.SetString(VersionDefine.PrefKey_LocalVersion, newestVersion);
                }

                EditorGUILayout.Space();
                EditorGUILayout.LabelField("打包目录", assetToBundleDir);
                if (GUILayout.Button("设置要打包的目录"))
                {
                    assetToBundleDir = EditorUtility.OpenFolderPanel("选择需要打包的目录", Application.dataPath, "");
                }

                EditorGUILayout.Space();
                EditorGUILayout.LabelField("输出目录", outputDir);
                if (GUILayout.Button("设置输出目录"))
                {
                    outputDir = EditorUtility.OpenFolderPanel("选择输出目录", Application.dataPath, "");
                }

                EditorGUILayout.Space();
                assetBundleOptions =
                    (BuildAssetBundleOptions)EditorGUILayout.EnumFlagsField("打包选项", assetBundleOptions);

                buildTarget    = (BuildTarget)EditorGUILayout.EnumPopup("目标平台", buildTarget);
                clearOutputDir = EditorGUILayout.Toggle("清空生成目录", clearOutputDir);
                EditorGUILayout.Space();

                useForRuntime = EditorGUILayout.Foldout(useForRuntime, "使用用于生成运行时直接使用的AB包");
                if (useForRuntime)
                {
                    EditorGUILayout.LabelField("生成HotUpdatePath.cs路径",
                                               Application.dataPath + "/" + rootNs + "/" + constNs + "/" + autoDir + "/HotUpdatePath.cs");
                    useWeb = EditorGUILayout.Toggle("是否使用网络", useWeb);
                    EditorGUILayout.LabelField("游戏自身AB包名字", streamingAbName);

                    EditorGUILayout.Space();
                    if (GUILayout.Button("重新生成常量类【会覆盖】"))
                    {
                        if (!outputDir.Contains(Application.streamingAssetsPath))
                        {
                            Debug.LogError("运行时使用的AB包必须在StreamingAssets目录下");
                            return;
                        }

                        if (assetBundleNames.Count == 0)
                        {
                            Debug.LogError("AB包数组未空");
                            return;
                        }

                        CreatePathDataClass(rootNs, constNs, autoDir, assetBundleNames);
                        AssetDatabase.Refresh();
                        Debug.Log("生成完成");
                    }
                }


                if (GUILayout.Button("开始打包", GUILayout.Height(3 * EditorGUIUtility.singleLineHeight)))
                {
                    if (createPathDataClass)
                    {
                        if (!outputDir.Contains(Application.streamingAssetsPath))
                        {
                            Debug.LogError("运行时使用的AB包必须在StreamingAssets目录下");
                            return;
                        }
                    }

                    if (assetBundleNames.Count != 0)
                    {
                        assetBundleNames.Clear();
                    }
                    if (!Directory.Exists(assetToBundleDir))
                    {
                        Debug.LogError("打包目录设置异常");
                        return;
                    }

                    if (!Directory.Exists(outputDir))
                    {
                        Debug.LogError("输出目录设置异常");
                        return;
                    }

                    if (clearOutputDir)
                    {
                        if (Directory.Exists(outputDir))
                        {
                            //获取指定路径下所有文件夹
                            string[] folderPaths = Directory.GetDirectories(outputDir);

                            foreach (string folderPath in folderPaths)
                            {
                                Directory.Delete(folderPath, true);
                            }
                            //获取指定路径下所有文件
                            string[] filePaths = Directory.GetFiles(outputDir);

                            foreach (string filePath in filePaths)
                            {
                                File.Delete(filePath);
                            }
                        }
                    }

                    var builds = new List <AssetBundleBuild>();
                    foreach (var dirPath in System.IO.Directory.GetDirectories(assetToBundleDir))
                    {
                        var dirName    = new DirectoryInfo(dirPath).Name;
                        var paths      = new List <string>();
                        var assetNames = new List <string>();
                        FileUtil.SearchDirectory(dirPath,
                                                 fileInfo =>
                        {
                            if (fileInfo.Name.EndsWith(".meta"))
                            {
                                return;
                            }
                            var pureName = Path.GetFileNameWithoutExtension(fileInfo.FullName);
                            assetNames.Add(pureName);
                            var fileLoadPath = fileInfo.FullName.Replace("\\", "/")
                                               .Replace(Application.dataPath, "Assets");
                            var ai             = AssetImporter.GetAtPath(fileLoadPath);
                            ai.assetBundleName = dirName;
                            paths.Add(fileLoadPath);
                        }, true);

                        assetBundleNames.Add(dirName);
                        FileUtil.CreateConstClassByDictionary(
                            dirName + "Name",
                            Application.dataPath + "/" + rootNs + "/" + constNs,
                            rootNs + "." + constNs,
                            assetNames.ToDictionary(name => name));
                        builds.Add(new AssetBundleBuild
                        {
                            assetNames      = paths.ToArray(),
                            assetBundleName = dirName
                        });
                    }

                    if (createPathDataClass)
                    {
                        CreatePathDataClass(rootNs, constNs, autoDir, assetBundleNames);
                    }


                    BuildPipeline.BuildAssetBundles(outputDir, builds.ToArray(), assetBundleOptions, buildTarget);
                    AssetDatabase.Refresh();
                    Debug.Log("打包完成");
                }

                break;

                #endregion
            }
        }
Example #16
0
    private static Hashtable LoadResource(ResourceManagerType resourceType, Hashtable target, string cacheKey, string fileName)
    {
        string filePath = fileName;//HttpContext.Current.Request.MapPath("~/Languages/fr.xml");

        //CacheDependency dp = new CacheDependency(filePath);

        XmlDocument d = new XmlDocument();
        try
        {
            d.Load(filePath);
        }
        catch
        {
            return target;
        }

        foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes)
        {
            if (n.NodeType == XmlNodeType.Element)
            {
                switch (resourceType)
                {
                    case ResourceManagerType.Text:
                        if (target[n.Attributes["name"].Value] == null)
                            target.Add(n.Attributes["name"].Value, n.InnerText);
                        else
                            target[n.Attributes["name"].Value] = n.InnerText;

                        break;
                }
            }
        }
        //TCache.Max(cacheKey, target, dp);

        return target;
    }
Example #17
0
        private static Hashtable LoadResource(ResourceManagerType resourceType, Hashtable target, string language, string cacheKey)
        {
            CSContext csContext = CSContext.Current;
            string filePath = csContext.PhysicalPath("Languages\\" + language + "\\{0}");// csContext.MapPath("~" + CSConfiguration.GetConfig().FilesPath + "/Languages/" + language + "/{0}");

            switch (resourceType) {
                case ResourceManagerType.ErrorMessage:
                    filePath = string.Format(filePath, "Messages.xml");
                    break;

                default:
                    filePath = string.Format(filePath, "Resources.xml");
                    break;
            }

            CacheDependency dp = new CacheDependency(filePath);

            XmlDocument d = new XmlDocument();
            try {
                d.Load( filePath );
            } catch {
                return target;
            }

            foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes) {
                if (n.NodeType != XmlNodeType.Comment) {
                    switch (resourceType) {
                        case ResourceManagerType.ErrorMessage:
                            Message m = new Message(n);
                            target[m.MessageID] = m;
                            break;

                        case ResourceManagerType.String:
                            if (target[n.Attributes["name"].Value] == null)
                                target.Add(n.Attributes["name"].Value, n.InnerText);
                            else
                                target[n.Attributes["name"].Value] = n.InnerText;

                            break;
                    }
                }
            }

            // Create a new cache dependency and set it to never expire
            // unless the underlying file changes
            //
            // 7/26/2004 Terry Denham
            // We should only keep the default language cached forever, not every language.
            //DateTime cacheUntil;
            if( language == CSConfiguration.GetConfig().DefaultLanguage ) {
                CSCache.Max(cacheKey,target,dp);
            }
            else {
                CSCache.Insert(cacheKey,target,dp,CSCache.HourFactor);
            }

            return target;
        }
Example #18
0
        private static Hashtable GetResource(ResourceManagerType resourceType, string userLanguage)
        {
            CSContext csContext = CSContext.Current;

            string defaultLanguage = CSConfiguration.GetConfig().DefaultLanguage;
            string cacheKey = resourceType.ToString() + defaultLanguage + userLanguage;

            // Ensure the user has a language set
            //
            if (userLanguage == "")
                userLanguage = defaultLanguage;

            // Attempt to get the resources from the Cache
            //
            Hashtable resources = CSCache.Get(cacheKey) as Hashtable;

            if (resources == null)
            {
                resources = new Hashtable();

                // First load the English resouce, changed from loading the default language
                // since the userLanguage is set to the defaultLanguage if the userLanguage
                // is unassigned. We load the english language always just to ensure we have
                // a resource loaded just incase the userLanguage doesn't have a translated
                // string for this English resource.
                //
                resources = LoadResource(resourceType, resources, "en-US", cacheKey);

                // If the user language is different load it
                //
                if ("en-US" != userLanguage)
                    resources= LoadResource(resourceType, resources, userLanguage, cacheKey);

            }

            return resources;
        }
Example #19
0
 private static Hashtable GetResource(ResourceManagerType resourceType)
 {
     return GetResource(resourceType, CSContext.Current.User.Profile.Language);
 }
        static void OnToolsGUI(string rootNs, string viewNs, string constNs, string dataNs, string autoDir,
                               string scriptNs)
        {
            EditorGUILayout.Space();
            EditorGUILayout.Space();

            createPanelClasses = EditorGUILayout.Toggle("是否自动生成Panel类型", createPanelClasses);
            if (createPanelClasses)
            {
                EditorGUILayout.LabelField("自动生成Panel文件路径", Application.dataPath + "/" + rootNs + "/" + viewNs);
            }
            EditorGUILayout.Space();


            createGameMgr = EditorGUILayout.Toggle("是否生成GameMgr", createGameMgr);
            if (createGameMgr)
            {
                _resourceManagerType = (ResourceManagerType)EditorGUILayout.EnumPopup("资源管理类型", _resourceManagerType);
                EditorGUILayout.LabelField("自动生成" + rootNs + "Mgr文件路径",
                                           Application.dataPath + "/" + rootNs + "/" + scriptNs);
            }
            EditorGUILayout.Space();


            createMessage = EditorGUILayout.Toggle("是否生成空Message常量类", createMessage);
            if (createMessage)
            {
                EditorGUILayout.LabelField("生成Message.cs路径",
                                           Application.dataPath + "/" + rootNs + "/" + constNs + "/Message.cs");
            }
            EditorGUILayout.Space();
            createGlobalVar = EditorGUILayout.Toggle("是否重写GlobalVar类", createGlobalVar);
            if (createGlobalVar)
            {
                EditorGUILayout.LabelField("生成GlobalVar.cs路径",
                                           Application.dataPath + "/" + rootNs + "/Global/GlobalVar.cs");
            }
            EditorGUILayout.Space();
            createSceneNameClass = EditorGUILayout.Toggle("是否生成SceneName类", createSceneNameClass);
            if (createSceneNameClass)
            {
                EditorGUILayout.LabelField("生成SceneName.cs路径",
                                           Application.dataPath + "/" + rootNs + "/" + constNs + "/" + autoDir + "/SceneName.cs");
            }
            EditorGUILayout.Space();



            if (GUILayout.Button("开启自动生成", GUILayout.Height(2 * EditorGUIUtility.singleLineHeight)))
            {
                #region 文件夹的创建

                var resourceDir = Application.dataPath + "/Resources";
                var rootDir     = Application.dataPath + "/" + rootNs;
                if (!Directory.Exists(resourceDir))
                {
                    Directory.CreateDirectory(resourceDir);
                    return;
                }

                FileUtil.CreateFolder(rootDir);
                FileUtil.CreateFolder(rootDir + "/" + constNs);
                FileUtil.CreateFolder(rootDir + "/" + constNs + "/" + autoDir);

                #endregion

                autoClassName.Clear();
                otherResPathDic.Clear();
                otherResFileNameDic.Clear();
                allResPathDic.Clear();
                allResFileNameDic.Clear();


                foreach (var fullName in Directory.GetFileSystemEntries(resourceDir))
                {
                    if (Directory.Exists(fullName))
                    {
                        //如果是文件夹
                        OprateDir(new DirectoryInfo(fullName));
                    }
                    else
                    {
                        //是文件
                        OprateFile(new FileInfo(fullName));
                    }
                }


                #region 特殊类的生成

                if (createPanelClasses && autoClassName.Contains("Panel"))
                {
                    CreatePanelFile(Application.dataPath + "/Resources/ClassPanel", viewNs, constNs, rootNs, autoDir);
                }

                #endregion


                #region 定向生成特殊小文件

                if (createGameMgr)
                {
                    CreateMgr(rootNs, constNs, scriptNs, autoDir);
                }

                if (createGlobalVar)
                {
                    FileUtil.CreateClassFile("GlobalVar", rootNs + ".Global", rootDir + "/Global",
                                             "ReadyGamerOne.Global.GlobalVar",
                                             "这里写当前项目需要的全局变量,调用GlobalVar时,最好调用当前这个类");
                }

                if (createMessage)
                {
                    FileUtil.CreateClassFile("Message", rootNs + "." + constNs, rootDir + "/" + constNs,
                                             helpTips: "自定义的消息写到这里");
                }

                if (createSceneNameClass)
                {
                    CreateSceneNameClass(rootNs, constNs, autoDir);
                }

                #endregion


                AssetDatabase.Refresh();
                Debug.Log("生成结束");
            }
        }
Example #21
0
        private static Hashtable GetResource(ResourceManagerType resourceType, string userLanguage, string fileName)
        {
            string cacheKey = resourceType.ToString()  + userLanguage + fileName;

            // Ensure the user has a language set
            //

            // Attempt to get the resources from the Cache

            Hashtable resources = Context.Cache.Get(cacheKey) as Hashtable;

            if (resources == null)
            {
                resources = new Hashtable();

                // First load the English resouce, changed from loading the default language
                // since the userLanguage is set to the defaultLanguage if the userLanguage
                // is unassigned. We load the english language always just to ensure we have
                // a resource loaded just incase the userLanguage doesn't have a translated
                // string for this English resource.
                //
                    resources = LoadResource(resourceType, resources, userLanguage, cacheKey, fileName);

            }

            return resources;
        }
Example #22
0
        private static Hashtable LoadResource(ResourceManagerType resourceType, Hashtable target, string language, string cacheKey, string fileName)
        {
            string filePath =Environment.CurrentDirectory +"\\Languages\\" + language + "\\" + fileName;

            //			switch (resourceType) {
            //				case ResourceManagerType.ErrorMessage:
            //					filePath = string.Format(filePath, "Messages.xml");
            //					break;
            //
            //				default:
            //					filePath = string.Format(filePath, "Resources.xml");
            //					break;
            //			}

            CacheDependency dp;
            XmlDocument d = new XmlDocument();

            try
            {
                dp = new CacheDependency(filePath);
                d.Load(filePath);
            }
            catch
            {
                return target;
            }

            foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes)
            {
                if (n.NodeType != XmlNodeType.Comment)
                {
                    switch (resourceType)
                    {
                        case ResourceManagerType.ErrorMessage:

                            break;

                        case ResourceManagerType.String:
                            if (target[n.Attributes["name"].Value] == null)
                                target.Add(n.Attributes["name"].Value, n.InnerText);
                            else
                                target[n.Attributes["name"].Value] = n.InnerText;
                            break;

                        case ResourceManagerType.Template:

                            break;
                    }
                }
            }

            // Create a new cache dependency and set it to never expire
            // unless the underlying file changes
            //
            // 7/26/2004 Terry Denham
            // We should only keep the default language cached forever, not every language.
            //DateTime cacheUntil;

               Context.Cache.Insert(cacheKey, target, dp);

            return target;
        }
        /// <summary>
        /// Lists the subscriptions
        /// </summary>
        /// <param name='includeDetails'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Result of the list operations
        /// </returns>
        public async Task <SubscriptionListAsAdminResult> ListAsync(bool includeDetails, CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("includeDetails", includeDetails);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/providers/Microsoft.Subscriptions.Admin/subscriptions";
            List <string> queryParameters = new List <string>();

            queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
            queryParameters.Add("includeDetails=" + Uri.EscapeDataString(includeDetails.ToString().ToLower()));
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    SubscriptionListAsAdminResult result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new SubscriptionListAsAdminResult();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    AdminSubscriptionDefinition adminSubscriptionDefinitionInstance = new AdminSubscriptionDefinition();
                                    result.Subscriptions.Add(adminSubscriptionDefinitionInstance);

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        adminSubscriptionDefinitionInstance.Id = idInstance;
                                    }

                                    JToken subscriptionIdValue = valueValue["subscriptionId"];
                                    if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null)
                                    {
                                        string subscriptionIdInstance = ((string)subscriptionIdValue);
                                        adminSubscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance;
                                    }

                                    JToken delegatedProviderSubscriptionIdValue = valueValue["delegatedProviderSubscriptionId"];
                                    if (delegatedProviderSubscriptionIdValue != null && delegatedProviderSubscriptionIdValue.Type != JTokenType.Null)
                                    {
                                        string delegatedProviderSubscriptionIdInstance = ((string)delegatedProviderSubscriptionIdValue);
                                        adminSubscriptionDefinitionInstance.DelegatedProviderSubscriptionId = delegatedProviderSubscriptionIdInstance;
                                    }

                                    JToken displayNameValue = valueValue["displayName"];
                                    if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
                                    {
                                        string displayNameInstance = ((string)displayNameValue);
                                        adminSubscriptionDefinitionInstance.DisplayName = displayNameInstance;
                                    }

                                    JToken externalReferenceIdValue = valueValue["externalReferenceId"];
                                    if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null)
                                    {
                                        string externalReferenceIdInstance = ((string)externalReferenceIdValue);
                                        adminSubscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance;
                                    }

                                    JToken ownerValue = valueValue["owner"];
                                    if (ownerValue != null && ownerValue.Type != JTokenType.Null)
                                    {
                                        string ownerInstance = ((string)ownerValue);
                                        adminSubscriptionDefinitionInstance.Owner = ownerInstance;
                                    }

                                    JToken tenantIdValue = valueValue["tenantId"];
                                    if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
                                    {
                                        string tenantIdInstance = ((string)tenantIdValue);
                                        adminSubscriptionDefinitionInstance.TenantId = tenantIdInstance;
                                    }

                                    JToken routingResourceManagerTypeValue = valueValue["routingResourceManagerType"];
                                    if (routingResourceManagerTypeValue != null && routingResourceManagerTypeValue.Type != JTokenType.Null)
                                    {
                                        ResourceManagerType routingResourceManagerTypeInstance = ((ResourceManagerType)Enum.Parse(typeof(ResourceManagerType), ((string)routingResourceManagerTypeValue), true));
                                        adminSubscriptionDefinitionInstance.RoutingResourceManagerType = routingResourceManagerTypeInstance;
                                    }

                                    JToken offerIdValue = valueValue["offerId"];
                                    if (offerIdValue != null && offerIdValue.Type != JTokenType.Null)
                                    {
                                        string offerIdInstance = ((string)offerIdValue);
                                        adminSubscriptionDefinitionInstance.OfferId = offerIdInstance;
                                    }

                                    JToken stateValue = valueValue["state"];
                                    if (stateValue != null && stateValue.Type != JTokenType.Null)
                                    {
                                        SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true));
                                        adminSubscriptionDefinitionInstance.State = stateInstance;
                                    }
                                }
                            }

                            JToken odatanextLinkValue = responseDoc["@odata.nextLink"];
                            if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
                            {
                                string odatanextLinkInstance = ((string)odatanextLinkValue);
                                result.NextLink = odatanextLinkInstance;
                            }
                        }
                    }
                    result.StatusCode = statusCode;

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }