Example #1
0
        public static void CallFunctionsWithFurniture(IEnumerable <string> functionNames, Furniture furn, float deltaTime)
        {
            foreach (var fname in functionNames)
            {
                var func = _instance.myLuaScript.Globals[fname];

                if (func == null)
                {
                    Debug.LogErrorFormat("Function {0} is not a LUA function.", fname);
                    return;
                }

                var result = _instance.myLuaScript.Call(func, new object[] { furn, deltaTime });
                if (result.Type != DataType.Void)
                {
                    if (result.Type == DataType.Number)
                    {
                        Debug.LogFormat("{0} {1}", fname, result.Number);
                    }

                    if (result.Type == DataType.String)
                    {
                        Debug.LogFormat("{0} {1}", fname, result.String);
                    }

                    if (result.Type == DataType.UserData)
                    {
                        Debug.LogFormat("{0} {1}", fname, result.UserData.Object.ToString());
                    }
                }
            }
        }
        /// <summary>
        /// Gets a NugetPackage from the NuGet server that matches (or is in range of) the <see cref="NugetPackageIdentifier"/> given.
        /// </summary>
        /// <param name="package">The <see cref="NugetPackageIdentifier"/> containing the ID and Version of the package to get.</param>
        /// <returns>The retrieved package, if there is one.  Null if no matching package was found.</returns>
        public NugetPackage GetSpecificPackage(NugetPackageIdentifier package)
        {
            if (package.HasVersionRange)
            {
                return(FindPackagesById(package).FirstOrDefault());
            }

            if (IsLocalPath)
            {
                string localPackagePath = Path.Combine(ExpandedPath, string.Format("./{0}.{1}.nupkg", package.Id, package.Version));
                if (File.Exists(localPackagePath))
                {
                    NugetPackage localPackage = NugetPackage.FromNupkgFile(localPackagePath);
                    return(localPackage);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                string url = string.Format("{0}Packages(Id='{1}',Version='{2}')", ExpandedPath, package.Id, package.Version);
                try
                {
                    return(GetPackagesFromUrl(url, UserName, ExpandedPassword).First());
                }
                catch (Exception e)
                {
                    Debug.LogErrorFormat("Unable to retrieve package from {0}\n{1}", url, e.ToString());
                    return(null);
                }
            }
        }
Example #3
0
        private void LogResponse()
        {
            if (WebRequest == null || !WebRequest.isDone)
            {
                return;
            }
            double size  = WebRequest.downloadedBytes;
            var    order = 0;

            while (size >= 1024.0f && order + 1 < sizes.Length)
            {
                ++order;
                size /= 1024.0f;
            }
            var sizeString = String.Format("{0:0.##}{1}", size, sizes[order]);
            var status     = WebRequest.responseCode;
            var message    = string.IsNullOrEmpty(WebRequest.error) && status == 200 ? "OK" : WebRequest.error;

            if (WebRequest.isError || status != 200)
            {
                Debug.LogErrorFormat(logFormat, WebRequest.url, WebRequest.method, status, message, sizeString,
                                     responseTime, "HTTPResponse");
            }
            else
            {
                Debug.LogFormat(logFormat, WebRequest.url, WebRequest.method, status, message, sizeString, responseTime, "HTTPResponse");
            }
        }
Example #4
0
        public Note(float genTime, string type, string noteName, float beat)
        {
            _isHit     = false;
            _isSucceed = false;
            _genTime   = genTime;
            _beat      = beat;
            _type      = NoteType.None;
            _noteName  = noteName;
            switch (type)
            {
            case "Notice":
                _type = NoteType.Notice;
                break;

            case "Touch":
                _type = NoteType.Touch;
                break;

            case "Swipe":
                _type = NoteType.Swipe;
                break;

            case "None":
                _type = NoteType.None;
                break;

            default:
                Debug.LogErrorFormat("Undefined Note Type!! {0}", type);
                break;
            }
        }
        /// <summary>
        /// Gets a list of all available packages from a local source (not a web server) that match the given filters.
        /// </summary>
        /// <param name="searchTerm">The search term to use to filter packages. Defaults to the empty string.</param>
        /// <param name="includeAllVersions">True to include older versions that are not the latest version.</param>
        /// <param name="includePrerelease">True to include prerelease packages (alpha, beta, etc).</param>
        /// <param name="numberToGet">The number of packages to fetch.</param>
        /// <param name="numberToSkip">The number of packages to skip before fetching.</param>
        /// <returns>The list of available packages.</returns>
        private List <NugetPackage> GetLocalPackages(string searchTerm = "", bool includeAllVersions = false, bool includePrerelease = false, int numberToGet = 15, int numberToSkip = 0)
        {
            List <NugetPackage> localPackages = new List <NugetPackage>();

            if (numberToSkip != 0)
            {
                // we return the entire list the first time, so no more to add
                return(localPackages);
            }

            string path = ExpandedPath;

            if (Directory.Exists(path))
            {
                string[] packagePaths = Directory.GetFiles(path, string.Format("*{0}*.nupkg", searchTerm));

                foreach (var packagePath in packagePaths)
                {
                    var package = NugetPackage.FromNupkgFile(packagePath);
                    package.PackageSource = this;

                    if (package.IsPrerelease && !includePrerelease)
                    {
                        // if it's a prerelease package and we aren't supposed to return prerelease packages, just skip it
                        continue;
                    }

                    if (includeAllVersions)
                    {
                        // if all versions are being included, simply add it and move on
                        localPackages.Add(package);
                        //LogVerbose("Adding {0} {1}", package.Id, package.Version);
                        continue;
                    }

                    var existingPackage = localPackages.FirstOrDefault(x => x.Id == package.Id);
                    if (existingPackage != null)
                    {
                        // there is already a package with the same ID in the list
                        if (existingPackage < package)
                        {
                            // if the current package is newer than the existing package, swap them
                            localPackages.Remove(existingPackage);
                            localPackages.Add(package);
                        }
                    }
                    else
                    {
                        // there is no package with the same ID in the list yet
                        localPackages.Add(package);
                    }
                }
            }
            else
            {
                Debug.LogErrorFormat("Local folder not found: {0}", path);
            }

            return(localPackages);
        }
Example #6
0
        private static void GatherDependencies()
        {
            if (EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }

            dependenciesList = new List <Dependency>();

            foreach (Type dependencyType in ReflectionUtils.GetConcreteImplementationsOf <Dependency>())
            {
                try
                {
                    if (ReflectionUtils.CreateInstanceOfType(dependencyType) is Dependency dependencyInstance && string.IsNullOrEmpty(dependencyInstance.Package) == false)
                    {
                        dependenciesList.Add(dependencyInstance);
                    }
                }
                catch (Exception exception)
                {
                    Debug.LogErrorFormat("{0} while retrieving Dependency object of type {1}.\n{2}", exception.GetType().Name, dependencyType.Name, exception.StackTrace);
                }
            }

            if (dependenciesList.Any())
            {
                dependenciesList = dependenciesList.OrderBy(setup => setup.Priority).ToList();
                ProcessDependencies();
            }
        }
        private bool ExtracNativeAssets(string packagePath, string targetDirectory)
        {
            var process = new Process {
                StartInfo =
                {
                    FileName               = "tar",
                    Arguments              = string.Format("xzf \"{0}\" -C \"{1}\"", packagePath, targetDirectory),
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true
                }
            };

            try {
                process.Start();
                process.WaitForExit();
                process.Close();
            }
            catch (Exception e) {
                Debug.LogErrorFormat("{0}->ExtractPackage: extract package {1} failed: {2}", GetType().Name, packagePath, e.Message);
                return(false);
            }

            return(true);
        }
Example #8
0
        /// <summary>
        /// Builds a list of NugetPackages from the XML returned from the HTTP GET request issued at the given URL.
        /// Note that NuGet uses an Atom-feed (XML Syndicaton) superset called OData.
        /// See here http://www.odata.org/documentation/odata-version-2-0/uri-conventions/
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private List <NugetPackage> GetPackagesFromUrl(string url)
        {
            NugetHelper.LogVerbose("Getting packages from: {0}", url);

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            List <NugetPackage> packages = new List <NugetPackage>();

            try
            {
                HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(url);
                getRequest.Timeout          = 5000;
                getRequest.ReadWriteTimeout = 5000;
                Stream       responseStream = getRequest.GetResponse().GetResponseStream();
                StreamReader streamReader   = new StreamReader(responseStream);

                packages = NugetODataResponse.Parse(XDocument.Load(streamReader));

                foreach (var package in packages)
                {
                    package.PackageSource = this;
                }
            }
            catch (System.Exception e)
            {
                Debug.LogErrorFormat(e.ToString());
            }

            stopwatch.Stop();
            NugetHelper.LogVerbose("Retreived {0} packages in {1} ms", packages.Count, stopwatch.ElapsedMilliseconds);

            return(packages);
        }
Example #9
0
 public void ErrorFormat(IFormatProvider provider, string format, params object[] args)
 {
     if (!IsErrorEnabled)
     {
         return;
     }
     Debugger.LogErrorFormat(format, args);
 }
Example #10
0
 public static void Error(string tag, string format, params object[] args)
 {
     if (!string.IsNullOrEmpty(tag) && !enabledTags.Contains(tag))
     {
         return;
     }
     Debug.LogErrorFormat(format, args);
 }
Example #11
0
 public void ErrorFormat(string format, object arg0, object arg1, object arg2)
 {
     if (!IsErrorEnabled)
     {
         return;
     }
     Debugger.LogErrorFormat(format, arg0, arg1, arg2);
 }
Example #12
0
        /// <summary>
        /// Gets a list of NuGetPackages from this package source.
        /// This allows searching for partial IDs or even the empty string (the default) to list ALL packages.
        ///
        /// NOTE: See the functions and parameters defined here: https://www.nuget.org/api/v2/$metadata
        /// </summary>
        /// <param name="searchTerm">The search term to use to filter packages. Defaults to the empty string.</param>
        /// <param name="includeAllVersions">True to include older versions that are not the latest version.</param>
        /// <param name="includePrerelease">True to include prerelease packages (alpha, beta, etc).</param>
        /// <param name="numberToGet">The number of packages to fetch.</param>
        /// <param name="numberToSkip">The number of packages to skip before fetching.</param>
        /// <returns>The list of available packages.</returns>
        public List <NugetPackage> Search(string searchTerm = "", bool includeAllVersions = false, bool includePrerelease = false, int numberToGet = 15, int numberToSkip = 0)
        {
            if (IsLocalPath)
            {
                return(GetLocalPackages(searchTerm, includeAllVersions, includePrerelease, numberToGet, numberToSkip));
            }

            //Example URL: "http://www.nuget.org/api/v2/Search()?$filter=IsLatestVersion&$orderby=Id&$skip=0&$top=30&searchTerm='newtonsoft'&targetFramework=''&includePrerelease=false";

            string url = ExpandedPath;

            // call the search method
            url += "Search()?";

            // filter results
            if (!includeAllVersions)
            {
                if (!includePrerelease)
                {
                    url += "$filter=IsLatestVersion&";
                }
                else
                {
                    url += "$filter=IsAbsoluteLatestVersion&";
                }
            }

            // order results
            //url += "$orderby=Id&";
            //url += "$orderby=LastUpdated&";
            url += "$orderby=DownloadCount desc&";

            // skip a certain number of entries
            url += string.Format("$skip={0}&", numberToSkip);

            // show a certain number of entries
            url += string.Format("$top={0}&", numberToGet);

            // apply the search term
            url += string.Format("searchTerm='{0}'&", searchTerm);

            // apply the target framework filters
            url += "targetFramework=''&";

            // should we include prerelease packages?
            url += string.Format("includePrerelease={0}", includePrerelease.ToString().ToLower());

            //    TODO: This might have to be looked at, removed some code and removed warning for not running on separate thread.
            try
            {
                return(GetPackagesFromUrl(url, UserName, ExpandedPassword));
            }
            catch (System.Exception e)
            {
                Debug.LogErrorFormat("Unable to retrieve package list from {0}\n{1}", url, e.ToString());
                return(new List <NugetPackage>());
            }
        }
Example #13
0
        public static void Assert(bool that, string format, params object[] args)
        {
            if (that)
            {
                return;
            }
            Debug.LogErrorFormat(format, args);
            string msg = string.Format(format, args);

            throw new AssertionException(msg, msg);
        }
Example #14
0
        public static DynValue CallFunction(string fname, params object[] args)
        {
            var func = _instance.myLuaScript.Globals[fname];

            if (func == null)
            {
                Debug.LogErrorFormat("Function {0} is not a Lua function.", fname);
                return(DynValue.Nil);
            }

            return(_instance.myLuaScript.Call(func, args));
        }
Example #15
0
        private static void PushSameAssetToABUnit(IAssetDataQuerier varQuerier, List <string> varRepeatAssets,
                                                  Dictionary <string, List <string> > varAssetBeDep)
        {
            for (int iR = 0; iR < varRepeatAssets.Count;)
            {
                var tempAssetPath = varRepeatAssets[iR];

                var tempAssetBeDeps = varAssetBeDep[tempAssetPath];
                if (tempAssetBeDeps.Count < 2)
                {
                    UDebug.LogErrorFormat("Repeat analysis error.[{0}]", tempAssetPath);
                    iR++;
                    continue;
                }

                var tempSameDeps = new List <int>()
                {
                    iR
                };
                for (int iR2 = iR + 1; iR2 < varRepeatAssets.Count; ++iR2)
                {
                    var tempAsetBenDeps2 = varAssetBeDep[varRepeatAssets[iR2]];
                    if (tempAsetBenDeps2.Count != tempAssetBeDeps.Count)
                    {
                        continue;
                    }

                    bool tempSameDep = true;
                    for (int iC = 0; iC < tempAssetBeDeps.Count; ++iC)
                    {
                        if (tempAssetBeDeps[iC] == tempAsetBenDeps2[iC])
                        {
                            continue;
                        }
                        tempSameDep = false;
                        break;
                    }
                    if (tempSameDep)
                    {
                        tempSameDeps.Add(iR2);
                    }
                }

                var tempNewUnitName = string.Format(AutoGenABFormat, HashABUnitName(tempAssetBeDeps));
                for (int iSD = tempSameDeps.Count - 1; iSD >= 0; --iSD)
                {
                    var tempIdx  = tempSameDeps[iSD];
                    var tempPath = varRepeatAssets[tempIdx];
                    varQuerier.SetAssetBundleName(tempPath, tempNewUnitName);
                    varRepeatAssets.RemoveAt(tempIdx);
                }
            }
        }
        /// <summary>Update current time, and try to trigger event.</summary>
        /// <param name="newCurrent"></param>
        private void TriggerEventIfCrossSession(DateTime newCurrent)
        {
            if (newCurrent == m_Current)
            {
                return;
            }

            DateTime oldCurrent = m_Current;

            m_Current = newCurrent;
            if (lastSession < newCurrent && newCurrent < nextSession)
            {
                // Debug.Log("Within session");
            }
            else if (newCurrent >= nextSession)
            {
                // Debug.Log("Pass session detected.");
                int      diff           = 0;
                DateTime oldNextSession = nextSession;
                CalculateSession();
                while (m_Current > oldNextSession && diff < int.MaxValue)
                {
                    oldNextSession = oldNextSession.Add(oneSession);
                    diff++;
                }

                Debug.LogFormat("Session updated: <color=green>Diff {0}</color>\n\rLast Current {1:G}\n\rCurrent {2:G}, \n\n\rLast Session {3:G}\n\rNext Session {4:G}\n\n\rOne Session {5:c}\n", diff, oldCurrent, m_Current, lastSession, nextSession, oneSession);
                if (EVENT_SessionChanged != null)
                {
                    EVENT_SessionChanged(oldCurrent, m_Current, diff);
                }
            }
            // The latest time(newCurrent) are smaller than the record that we had, back to the future.
            else             // if (newCurrent < oldCurrent)
            {
                CalculateSession();
                if (newCurrent < lastSession)
                {
                    Debug.LogErrorFormat("Time traveler detected := Session Jumpped.\ncurrent : {0:G} -> {1:G},\nLast session : {2:G}\nNext Session : {3:G}\nOne session : {4:c}", m_Current, newCurrent, lastSession, nextSession, oneSession);
                }
                else
                {
                    Debug.LogWarningFormat("Time traveler detected := within session.\ncurrent : {0:G} -> {1:G},\nLast session : {2:G}\nNext Session : {3:G}\nOne session : {4:c}", m_Current, newCurrent, lastSession, nextSession, oneSession);
                }

                if (EVENT_SessionChanged != null)
                {
                    EVENT_SessionChanged(oldCurrent, m_Current, -1);
                }
            }
        }
Example #17
0
        unsafe static PdbSymbolImporter()
        {
            var module = Process.GetCurrentProcess().MainModule;
            var scope  = PdbSession.Current.globalScope;

            foreach (var field in GetFieldsWithAttribute <PdbSymbolAttribute>())
            {
                if (!field.IsStatic)
                {
                    Debug.LogErrorFormat("{0} must be static.", field.Name);
                    continue;
                }

                scope.findChildren(
                    SymTagEnum.SymTagPublicSymbol,
                    GetCustomAttribute <PdbSymbolAttribute>(field).SymbolName,
                    (uint)NameSearchOptions.None,
                    out var symbols
                    );

                foreach (IDiaSymbol symbol in symbols)
                {
                    var address = new IntPtr(module.BaseAddress.ToInt64() + symbol.relativeVirtualAddress);

                    if (field.FieldType == typeof(IntPtr))
                    {
                        field.SetValue(null, address);
                    }
                    else if (field.FieldType == typeof(UIntPtr))
                    {
                        field.SetValue(null, new UIntPtr(address.ToPointer()));
                    }
                    else if (field.FieldType.IsPointer)
                    {
                        CreateStaticSetter <IntPtr>(field).Invoke(address);
                    }
                    else if (field.FieldType.IsSubclassOf(typeof(Delegate)))
                    {
                        field.SetValue(null, Marshal.GetDelegateForFunctionPointer(address, field.FieldType));
                    }
                    else
                    {
                        Debug.LogErrorFormat("{0} must be of IntPtr, UIntPtr or delegate type.", field.Name);
                    }

                    break;
                }
            }
        }
        public static void LogErrorFormat(string format, params object[] message)
        {
#if NOLOG
            return;
#endif
            if (Debug.isDebugBuild)
            {
                Debug.LogErrorFormat(format, message);
#if !UNITY_EDITOR
                if (MDNManager.Instance != null)
                {
                    MDNManager.Instance.ShowXcodeLog(string.Format(format, message));
                }
#endif
            }
        }
Example #19
0
 public static void SaveOptions()
 {
     try
     {
         var xmlSerializer = new XmlSerializer(typeof(Options));
         using (var streamWriter = new StreamWriter(FileName))
         {
             xmlSerializer.Serialize(streamWriter, OptionsHolder.Options);
         }
     }
     catch (Exception e)
     {
         Debug.LogErrorFormat("Unexpected {0} while saving options: {1}\n{2}",
                              e.GetType().Name, e.Message, e.StackTrace);
     }
 }
Example #20
0
        /// <summary>
        /// Builds a list of NugetPackages from the XML returned from the HTTP GET request issued at the given URL.
        /// Note that NuGet uses an Atom-feed (XML Syndicaton) superset called OData.
        /// See here http://www.odata.org/documentation/odata-version-2-0/uri-conventions/
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private List <NugetPackage> GetPackagesFromUrl(string url)
        {
            NugetHelper.LogVerbose("Getting packages from: {0}", url);

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            List <NugetPackage> packages = new List <NugetPackage>();

            try
            {
                // Mono doesn't have a Certificate Authority, so we have to provide all validation manually.  Currently just accept anything.
                // See here: http://stackoverflow.com/questions/4926676/mono-webrequest-fails-with-https

                // remove all handlers
                ServicePointManager.ServerCertificateValidationCallback = null;

                // add anonymous handler
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, policyErrors) => true;

                HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(url);
                getRequest.Timeout          = 5000;
                getRequest.ReadWriteTimeout = 5000;
                Stream       responseStream = getRequest.GetResponse().GetResponseStream();
                StreamReader streamReader   = new StreamReader(responseStream);

                packages = NugetODataResponse.Parse(XDocument.Load(streamReader));

                foreach (var package in packages)
                {
                    package.PackageSource = this;
                }
            }
            catch (System.Exception e)
            {
                Debug.LogErrorFormat(e.ToString());
            }

            stopwatch.Stop();
            NugetHelper.LogVerbose("Retreived {0} packages in {1} ms", packages.Count, stopwatch.ElapsedMilliseconds);

            return(packages);
        }
Example #21
0
        static AssetStoreToolsCallbacks()
        {
            var AssetStorePackageController = FindClass("AssetStorePackageController");

            var methods = new [] {
                "OnAssetsUploaded",
                // "OnUploadAssetBundlesFinished",
                "Export",
                "Upload",
                // "UploadAssetBundles",
                "OnAssetsUploading",
                "OnUploadSuccessfull",
                "OnSubmitionFail",
            };

            foreach (var method in methods)
            {
                var source = FindMethod(AssetStorePackageController, method);
                var target = FindMethod(typeof(AssetStoreToolsCallbacks), method);

                if (source == null)
                {
                    Debug.LogErrorFormat("Source method not found in {1}: {0}", method, AssetStorePackageController.Name);
                }
                if (target == null)
                {
                    Debug.LogErrorFormat("Target method not found in {1}: {0}", method, typeof(AssetStoreToolsCallbacks).Name);
                }

                try {
                    patchers[method] = new Patcher(source, target);
                    patchers[method].SwapMethods();
                } catch (Exception ex) {
                    Debug.LogException(ex);
                    Debug.LogError("Failed to patch method " + method);
                }
            }
        }
Example #22
0
        /// <summary>Wait for a condition to become true, then executes the callback.</summary>
        /// <param name="condition">Function that will be called every frame that returns whether to invoke the callback or not.</param>
        /// <param name="callback">The callback to be called when the condition becomes true.</param>
        /// <param name="timeoutMs">Maximum time to wait in milliseconds before cancelling the callback.</param>
        public static void Condition(Func <bool> condition, Action callback, double timeoutMs = 0d)
        {
            var update     = new EditorApplication.CallbackFunction(() => { });
            var timeoutsAt = EditorApplication.timeSinceStartup + (timeoutMs / 1000d);
            var stack      = new StackFrame(1, true);

            update = () => {
                if (timeoutMs > 0d && EditorApplication.timeSinceStartup >= timeoutsAt)
                {
                    EditorApplication.update -= update;
                    Debug.LogErrorFormat("Condition timedout at {0}:{1}", stack.GetFileName(), stack.GetFileLineNumber());
                    return;
                }

                if (condition())
                {
                    EditorApplication.update -= update;
                    callback();
                }
            };

            EditorApplication.update += update;
        }
Example #23
0
 public static void LoadOptions()
 {
     try
     {
         try
         {
             var xmlSerializer = new XmlSerializer(typeof(Options));
             using (var streamReader = new StreamReader(FileName))
             {
                 OptionsHolder.Options = (Options)xmlSerializer.Deserialize(streamReader);
             }
         }
         catch (FileNotFoundException)
         {
             // No options file yet
         }
     }
     catch (Exception e)
     {
         Debug.LogErrorFormat("Unexpected {0} while loading options: {1}\n{2}",
                              e.GetType().Name, e.Message, e.StackTrace);
     }
 }
Example #24
0
        public AppVersion(string versionStr)
        {
            var strs = versionStr.Trim().Split('.');

            if (strs.Length != 3)
            {
                Log.LogErrorFormat("Invalid version {0}", versionStr);
            }
            Main = int.Parse(strs[0]);
            Sub  = int.Parse(strs[1]);

            var index = strs[2].IndexOf('-');

            if (index == -1)
            {
                Fix = int.Parse(strs[2]);
                Pre = null;
            }
            else
            {
                Fix = int.Parse(strs[2].Substring(0, index));
                Pre = strs[2].Substring(index);
            }
        }
Example #25
0
        /// <summary>
        /// Queries the source with the given list of installed packages to get any updates that are available.
        /// </summary>
        /// <param name="installedPackages">The list of currently installed packages.</param>
        /// <param name="includePrerelease">True to include prerelease packages (alpha, beta, etc).</param>
        /// <param name="includeAllVersions">True to include older versions that are not the latest version.</param>
        /// <param name="targetFrameworks">The specific frameworks to target?</param>
        /// <param name="versionContraints">The version constraints?</param>
        /// <returns>A list of all updates available.</returns>
        public List <NugetPackage> GetUpdates(IEnumerable <NugetPackage> installedPackages, bool includePrerelease = false, bool includeAllVersions = false, string targetFrameworks = "", string versionContraints = "")
        {
            if (IsLocalPath)
            {
                return(GetLocalUpdates(installedPackages, includePrerelease, includeAllVersions));
            }

            List <NugetPackage> updates = new List <NugetPackage>();

            // check for updates in groups of 10 instead of all of them, since that causes servers to throw errors for queries that are too long
            for (int i = 0; i < installedPackages.Count(); i += 10)
            {
                var packageGroup = installedPackages.Skip(i).Take(10);

                string packageIds = string.Empty;
                string versions   = string.Empty;

                foreach (var package in packageGroup)
                {
                    if (string.IsNullOrEmpty(packageIds))
                    {
                        packageIds += package.Id;
                    }
                    else
                    {
                        packageIds += "|" + package.Id;
                    }

                    if (string.IsNullOrEmpty(versions))
                    {
                        versions += package.Version;
                    }
                    else
                    {
                        versions += "|" + package.Version;
                    }
                }

                string url = string.Format("{0}GetUpdates()?packageIds='{1}'&versions='{2}'&includePrerelease={3}&includeAllVersions={4}&targetFrameworks='{5}'&versionConstraints='{6}'", ExpandedPath, packageIds, versions, includePrerelease.ToString().ToLower(), includeAllVersions.ToString().ToLower(), targetFrameworks, versionContraints);

                try
                {
                    var newPackages = GetPackagesFromUrl(url, ExpandedPassword);
                    updates.AddRange(newPackages);
                }
                catch (System.Exception e)
                {
                    WebException    webException = e as WebException;
                    HttpWebResponse webResponse  = webException != null ? webException.Response as HttpWebResponse : null;
                    if (webResponse != null && webResponse.StatusCode == HttpStatusCode.NotFound)
                    {
                        // Some web services, such as VSTS don't support the GetUpdates API. Attempt to retrieve updates via FindPackagesById.
                        NugetHelper.LogVerbose("{0} not found. Falling back to FindPackagesById.", url);
                        return(GetUpdatesFallback(installedPackages, includePrerelease, includeAllVersions, targetFrameworks, versionContraints));
                    }

                    Debug.LogErrorFormat("Unable to retrieve package list from {0}\n{1}", url, e.ToString());
                }
            }

            // sort alphabetically
            updates.Sort(delegate(NugetPackage x, NugetPackage y)
            {
                if (x.Id == null && y.Id == null)
                {
                    return(0);
                }
                else if (x.Id == null)
                {
                    return(-1);
                }
                else if (y.Id == null)
                {
                    return(1);
                }
                else if (x.Id == y.Id)
                {
                    return(x.Version.CompareTo(y.Version));
                }
                else
                {
                    return(x.Id.CompareTo(y.Id));
                }
            });

#if TEST_GET_UPDATES_FALLBACK
            // Enable this define in order to test that GetUpdatesFallback is working as intended. This tests that it returns the same set of packages
            // that are returned by the GetUpdates API. Since GetUpdates isn't available when using a Visual Studio Team Services feed, the intention
            // is that this test would be conducted by using nuget.org's feed where both paths can be compared.
            List <NugetPackage> updatesReplacement = GetUpdatesFallback(installedPackages, includePrerelease, includeAllVersions, targetFrameworks, versionContraints);
            ComparePackageLists(updates, updatesReplacement, "GetUpdatesFallback doesn't match GetUpdates API");
#endif

            return(updates);
        }
Example #26
0
        /// <summary>
        /// Gets a list of all available packages from a local source (not a web server) that match the given filters.
        /// </summary>
        /// <param name="searchTerm">The search term to use to filter packages. Defaults to the empty string.</param>
        /// <param name="includeAllVersions">True to include older versions that are not the latest version.</param>
        /// <param name="includePrerelease">True to include prerelease packages (alpha, beta, etc).</param>
        /// <param name="numberToGet">The number of packages to fetch.</param>
        /// <param name="numberToSkip">The number of packages to skip before fetching.</param>
        /// <returns>The list of available packages.</returns>
        private List <NugetPackage> GetLocalPackages(string searchTerm = "", bool includeAllVersions = false, bool includePrerelease = false, int numberToGet = 15, int numberToSkip = 0)
        {
            NugetHelper.LogVerbose("{0}: Getting local packages {1}", typeof(NugetPackageSource).Name, ExpandedPath);

            List <NugetPackage> localPackages = new List <NugetPackage>();

            if (numberToSkip != 0)
            {
                // we return the entire list the first time, so no more to add
                return(localPackages);
            }

            string path = ExpandedPath;

            if (Directory.Exists(path))
            {
                List <string> packagePaths = new List <string>();

                if (!IsLocalPathAndVersion33)                                                                  // 3.3-
                {
                    packagePaths.AddRange(Directory.GetFiles(path, string.Format("*{0}*.nupkg", searchTerm))); // adding loose packages
                }
                else // 3.3+
                {
                    // https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds

                    // hierarchy of local feed
                    // 0.\\myserver\packages
                    // 1. └─<packageID>
                    // 2. └─<version>
                    // 3.   ├─<packageID>.<version>.nupkg
                    // 4.   └─<other files>

                    string aPackage = "";

                    // nuget v3 support
                    foreach (DirectoryInfo aDirPackageID in new DirectoryInfo(path).GetDirectories(string.Format("*{0}*", searchTerm))) // 0; for each package directory which matches the terms
                    {
                        NugetHelper.LogVerbose("{0}: Found a matching directory {1}", typeof(NugetPackageSource).Name, aDirPackageID);

                        aPackage = aDirPackageID.Name; // example: sinedustries.collections

                        //~ could optimize version checks while iterating?

                        foreach (DirectoryInfo aDirVersion in aDirPackageID.GetDirectories()) // 1; for each version directory for a package directory
                        {
                            NugetHelper.LogVerbose("{0}: Found a version directory {1}", typeof(NugetPackageSource).Name, aDirVersion);

                            aPackage = NugetPackage.PathLocal33Get(path, aDirPackageID.Name, aDirVersion.Name); // 2; path for package;

                            if (File.Exists(aPackage))                                                          // expected package exists
                            {
                                packagePaths.Add(aPackage);                                                     // add the package to paths
                                NugetHelper.LogVerbose("{0}: Added package {1}", typeof(NugetPackageSource).Name, aPackage);
                            }
                            else // no find path
                            {
                                throw new FileNotFoundException("Could not find NuGet package: {0};", aPackage);
                            }
                        }
                    }
                }

                foreach (var packagePath in packagePaths)
                {
                    var package = NugetPackage.FromNupkgFile(packagePath);
                    package.PackageSource = this;

                    if (package.IsPrerelease && !includePrerelease)
                    {
                        // if it's a prerelease package and we aren't supposed to return prerelease packages, just skip it
                        continue;
                    }

                    if (includeAllVersions)
                    {
                        // if all versions are being included, simply add it and move on
                        localPackages.Add(package);
                        NugetHelper.LogVerbose("Adding {0} {1}", package.Id, package.Version);
                        continue;
                    }

                    var existingPackage = localPackages.FirstOrDefault(x => x.Id == package.Id);
                    if (existingPackage != null)
                    {
                        // there is already a package with the same ID in the list
                        if (existingPackage < package)
                        {
                            // if the current package is newer than the existing package, swap them
                            localPackages.Remove(existingPackage);
                            localPackages.Add(package);
                        }
                    }
                    else
                    {
                        // there is no package with the same ID in the list yet
                        localPackages.Add(package);
                    }
                }
            }
            else
            {
                Debug.LogErrorFormat("Local folder not found: {0}", path);
            }

            return(localPackages);
        }
Example #27
0
        /// <summary>
        /// Gets a NugetPackage from the NuGet server that matches (or is in range of) the <see cref="NugetPackageIdentifier"/> given.
        /// If an exact match isn't found, it selects the next closest version available.
        /// </summary>
        /// <param name="package">The <see cref="NugetPackageIdentifier"/> containing the ID and Version of the package to get.</param>
        /// <returns>The retrieved package, if there is one.  Null if no matching package was found.</returns>
        public List <NugetPackage> FindPackagesById(NugetPackageIdentifier package)
        {
            List <NugetPackage> foundPackages = null;

            if (IsLocalPath)
            {
                // determine local path
                string localPackagePath;
                if (IsLocalPathAndVersion33)
                {
                    localPackagePath = NugetPackage.PathLocal33Get(ExpandedPath, package.Id, package.Version);
                }
                else
                {
                    localPackagePath = NugetPackage.PathLocalGet(ExpandedPath, package.Id, package.Version);
                }

                if (File.Exists(localPackagePath))
                {
                    NugetPackage localPackage = NugetPackage.FromNupkgFile(localPackagePath);
                    foundPackages = new List <NugetPackage> {
                        localPackage
                    };
                }
                else
                {
                    // TODO: Sort the local packages?  Currently assuming they are in alphabetical order due to the filesystem.
                    // TODO: Optimize to no longer use GetLocalPackages, since that loads the .nupkg itself

                    // Try to find later versions of the same package
                    var packages = GetLocalPackages(package.Id, true, true);
                    foundPackages = new List <NugetPackage>(packages.SkipWhile(x => !package.InRange(x)));
                }
            }
            else
            {
                // See here: http://www.odata.org/documentation/odata-version-2-0/uri-conventions/
                string url = string.Empty;

                // We used to rely on expressions such as &$filter=Version ge '9.0.1' to find versions in a range, but the results were sorted alphabetically. This
                // caused version 10.0.0 to be less than version 9.0.0. In order to work around this issue, we'll request all versions and perform filtering ourselves.

                url = string.Format("{0}FindPackagesById()?$orderby=Version asc&id='{1}'", ExpandedPath, package.Id);

                try
                {
                    foundPackages = GetPackagesFromUrl(url, ExpandedPassword);
                }
                catch (System.Exception e)
                {
                    foundPackages = new List <NugetPackage>();
                    Debug.LogErrorFormat("Unable to retrieve package list from {0}\n{1}", url, e.ToString());
                }

                foundPackages.Sort();
                if (foundPackages.Exists(p => package.InRange(p)))
                {
                    // Return all the packages in the range of versions specified by 'package'.
                    foundPackages.RemoveAll(p => !package.InRange(p));
                }
                else
                {
                    // There are no packages in the range of versions specified by 'package'.
                    // Return the most recent version after the version specified by 'package'.
                    foundPackages.RemoveAll(p => package.CompareVersion(p.Version) < 0);
                    if (foundPackages.Count > 0)
                    {
                        foundPackages.RemoveRange(1, foundPackages.Count - 1);
                    }
                }
            }

            if (foundPackages != null)
            {
                foreach (NugetPackage foundPackage in foundPackages)
                {
                    foundPackage.PackageSource = this;
                }
            }

            return(foundPackages);
        }
        /// <summary>
        /// Gets a NugetPackage from the NuGet server that matches (or is in range of) the <see cref="NugetPackageIdentifier"/> given.
        /// </summary>
        /// <param name="package">The <see cref="NugetPackageIdentifier"/> containing the ID and Version of the package to get.</param>
        /// <returns>The retrieved package, if there is one.  Null if no matching package was found.</returns>
        public List <NugetPackage> FindPackagesById(NugetPackageIdentifier package)
        {
            List <NugetPackage> foundPackages = null;

            if (IsLocalPath)
            {
                if (!package.HasVersionRange)
                {
                    string localPackagePath = Path.Combine(ExpandedPath, string.Format("./{0}.{1}.nupkg", package.Id, package.Version));
                    if (File.Exists(localPackagePath))
                    {
                        NugetPackage localPackage = NugetPackage.FromNupkgFile(localPackagePath);
                        foundPackages = new List <NugetPackage> {
                            localPackage
                        };
                    }
                    else
                    {
                        foundPackages = new List <NugetPackage>();
                    }
                }
                else
                {
                    // TODO: Optimize to no longer use GetLocalPackages, since that loads the .nupkg itself
                    foundPackages = GetLocalPackages(package.Id, true, true);
                }
            }
            else
            {
                // See here: http://www.odata.org/documentation/odata-version-2-0/uri-conventions/
                string url = string.Format("{0}FindPackagesById()?id='{1}'", ExpandedPath, package.Id);

                // Are we looking for a specific package?
                if (!package.HasVersionRange)
                {
                    url = string.Format("{0}&$filter=Version eq '{1}'", url, package.Version);
                }

                try
                {
                    foundPackages = GetPackagesFromUrl(url, UserName, ExpandedPassword);
                }
                catch (Exception e)
                {
                    foundPackages = new List <NugetPackage>();
                    Debug.LogErrorFormat("Unable to retrieve package list from {0}\n{1}", url, e.ToString());
                }
            }

            if (foundPackages != null)
            {
                // Return all the packages in the range of versions specified by 'package'.
                foundPackages.RemoveAll(p => !package.InRange(p));
                foundPackages.Sort();

                foreach (NugetPackage foundPackage in foundPackages)
                {
                    foundPackage.PackageSource = this;
                }
            }

            return(foundPackages);
        }
        static ConditionalCompilationUtility()
        {
            var buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
            var defines          = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup).Split(';').ToList();

            if (!defines.Contains(k_EnableCCU, StringComparer.OrdinalIgnoreCase))
            {
                defines.Add(k_EnableCCU);
                PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, string.Join(";", defines.ToArray()));

                // This will trigger another re-compile, which needs to happen, so all the custom attributes will be visible
                return;
            }

            var ccuDefines = new List <string> {
                k_EnableCCU
            };

            var conditionalAttributeType = typeof(ConditionalAttribute);

            const string kDependentClass = "dependentClass";
            const string kDefine         = "define";

            var attributeTypes = GetAssignableTypes(typeof(Attribute), type =>
            {
                var conditionals = (ConditionalAttribute[])type.GetCustomAttributes(conditionalAttributeType, true);

                foreach (var conditional in conditionals)
                {
                    if (string.Equals(conditional.ConditionString, k_EnableCCU, StringComparison.OrdinalIgnoreCase))
                    {
                        var dependentClassField = type.GetField(kDependentClass);
                        if (dependentClassField == null)
                        {
                            Debug.LogErrorFormat("[CCU] Attribute type {0} missing field: {1}", type.Name, kDependentClass);
                            return(false);
                        }

                        var defineField = type.GetField(kDefine);
                        if (defineField == null)
                        {
                            Debug.LogErrorFormat("[CCU] Attribute type {0} missing field: {1}", type.Name, kDefine);
                            return(false);
                        }
                    }
                    return(true);
                }

                return(false);
            });

            var dependencies = new Dictionary <string, string>();

            ForEachAssembly(assembly =>
            {
                var typeAttributes = assembly.GetCustomAttributes(false).Cast <Attribute>();
                foreach (var typeAttribute in typeAttributes)
                {
                    if (attributeTypes.Contains(typeAttribute.GetType()))
                    {
                        var t = typeAttribute.GetType();

                        // These fields were already validated in a previous step
                        var dependentClass = t.GetField(kDependentClass).GetValue(typeAttribute) as string;
                        var define         = t.GetField(kDefine).GetValue(typeAttribute) as string;

                        if (!string.IsNullOrEmpty(dependentClass) && !string.IsNullOrEmpty(define) && !dependencies.ContainsKey(dependentClass))
                        {
                            dependencies.Add(dependentClass, define);
                        }
                    }
                }
            });

            ForEachAssembly(assembly =>
            {
                foreach (var dependency in dependencies)
                {
                    var type = assembly.GetType(dependency.Key);
                    if (type != null)
                    {
                        var define = dependency.Value;
                        if (!defines.Contains(define, StringComparer.OrdinalIgnoreCase))
                        {
                            defines.Add(define);
                        }

                        ccuDefines.Add(define);
                    }
                }
            });

            ConditionalCompilationUtility.defines = ccuDefines.ToArray();

            PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, string.Join(";", defines.ToArray()));
        }
Example #30
0
        /// <summary>
        /// Gets a NugetPackage from the NuGet server that matches (or is in range of) the <see cref="NugetPackageIdentifier"/> given.
        /// </summary>
        /// <param name="package">The <see cref="NugetPackageIdentifier"/> containing the ID and Version of the package to get.</param>
        /// <returns>The retrieved package, if there is one.  Null if no matching package was found.</returns>
        public List <NugetPackage> FindPackagesById(NugetPackageIdentifier package)
        {
            List <NugetPackage> foundPackages = null;

            if (IsLocalPath)
            {
                // determine local path
                string localPackagePath;
                if (IsLocalPathAndVersion33)
                {
                    localPackagePath = NugetPackage.PathLocal33Get(ExpandedPath, package.Id, package.Version);
                }
                else
                {
                    localPackagePath = NugetPackage.PathLocalGet(ExpandedPath, package.Id, package.Version);
                }

                if (File.Exists(localPackagePath))
                {
                    string localPackagePath = Path.Combine(ExpandedPath, string.Format("./{0}.{1}.nupkg", package.Id, package.Version));
                    if (File.Exists(localPackagePath))
                    {
                        NugetPackage localPackage = NugetPackage.FromNupkgFile(localPackagePath);
                        foundPackages = new List <NugetPackage> {
                            localPackage
                        };
                    }
                    else
                    {
                        foundPackages = new List <NugetPackage>();
                    }
                }
                else
                {
                    // Try to find later versions of the same package
                    var packages = GetLocalPackages(package.Id, true, true);
                    foundPackages = new List <NugetPackage>(packages.SkipWhile(x => !package.InRange(x)));
                }
            }
            else
            {
                // See here: http://www.odata.org/documentation/odata-version-2-0/uri-conventions/
                // Note: without $orderby=Version, the Version filter below will not work
                string url = string.Format("{0}FindPackagesById()?id='{1}'&$orderby=Version asc", ExpandedPath, package.Id);

                // Are we looking for a specific package?
                if (!package.HasVersionRange)
                {
                    url = string.Format("{0}&$filter=Version eq '{1}'", url, package.Version);
                }

                try
                {
                    foundPackages = GetPackagesFromUrl(url, UserName, ExpandedPassword);
                }
                catch (Exception e)
                {
                    foundPackages = new List <NugetPackage>();
                    Debug.LogErrorFormat("Unable to retrieve package list from {0}\n{1}", url, e.ToString());
                }
            }

            if (foundPackages != null)
            {
                // Return all the packages in the range of versions specified by 'package'.
                foundPackages.RemoveAll(p => !package.InRange(p));
                foundPackages.Sort();

                foreach (NugetPackage foundPackage in foundPackages)
                {
                    foundPackage.PackageSource = this;
                }
            }

            return(foundPackages);
        }