예제 #1
0
 static void WriteApplePlist(Stream stream, AppleConfig config)
 {
     using (stream)
     {
         var plist = new NSDictionary();
         plist.Add("CFBundleDevelopmentRegion", "German");
         plist.Add("CFBundleExecutable", "MonoAppLauncher");
         plist.Add("CFBundleHelpBookFolder", $"{config.BundleName} Help");
         plist.Add("CFBundleHelpBookName", $"{config.BundleName} Help");
         plist.Add("CFBundleGetInfoString", $"{config.BundleName} {config.BundleVersion}");
         plist.Add("CFBundleIconFile", "app.icns");
         plist.Add("CFBundleIdentifier", config.BundleId);
         plist.Add("CFBundleInfoDictionaryVersion", "6.0");
         plist.Add("CFBundleName", config.BundleName);
         plist.Add("CFBundleShortVersionString", config.BundleVersion);
         var purl = new NSDictionary();
         purl.Add("CFBundleURLName", $"{config.BundleName} URL");
         var parray = new NSArray(new NSString(config.UrlPrefix));
         purl.Add("CFBundleURLSchemes", parray);
         var purls = new NSArray(purl);
         plist.Add("CFBundleURLTypes", purls);
         plist.Add("CFBundleVersion", config.BundleVersion);
         plist.Add("LSApplicationCategoryType", "public.app-category.business");
         plist.Add("LSMinimumSystemVersion", "10.7");
         var pMinVer = new NSDictionary();
         pMinVer.Add("i386", "10.7.0");
         pMinVer.Add("x86_64", "10.7.0");
         plist.Add("LSMinimumSystemVersionByArchitecture", pMinVer);
         plist.Add("NSHumanReadableCopyright", config.Copyright);
         PropertyListParser.SaveAsXml(plist, stream);
     }
 }
예제 #2
0
        /// <summary>
        /// Serializes this <see cref="NotificationProxyMessage"/> to a <see cref="NSDictionary"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="NSDictionary"/> which represents this <see cref="NotificationProxyMessage"/>.
        /// </returns>
        public NSDictionary ToPropertyList()
        {
            NSDictionary dict = new NSDictionary();

            dict.Add(nameof(this.Command), this.Command);
            dict.Add(nameof(this.Name), this.Name);
            return(dict);
        }
예제 #3
0
        /// <inheritdoc/>
        public NSDictionary ToDictionary()
        {
            var dict = new NSDictionary();

            dict.Add(nameof(this.Command), this.Command);
            dict.Add(nameof(this.ImageType), this.ImageType);
            return(dict);
        }
예제 #4
0
        /// <inheritdoc/>
        public virtual NSDictionary ToDictionary()
        {
            NSDictionary dictionary = new NSDictionary();

            dictionary.Add(nameof(this.Label), this.Label);
            dictionary.Add(nameof(this.ProtocolVersion), this.ProtocolVersion);
            dictionary.Add(nameof(this.Request), this.Request);
            return(dictionary);
        }
예제 #5
0
        /// <inheritdoc/>
        public override NSDictionary ToPropertyList()
        {
            NSDictionary dictionary = new NSDictionary();

            dictionary.Add(nameof(this.BundleID), new NSString(this.BundleID));
            dictionary.Add(nameof(this.ClientVersionString), new NSString(this.ClientVersionString));
            dictionary.Add(nameof(this.MessageType), new NSString(this.MessageType.ToString()));
            dictionary.Add(nameof(this.ProgName), new NSString(this.ProgName));
            return(dictionary);
        }
예제 #6
0
        /// <summary>
        /// Serializes this <see cref="PairingRecord"/> to a <see cref=" NSDictionary"/> object.
        /// </summary>
        /// <param name="includePrivateKeys">
        /// <see langword="true"/> if the root and host private keys should be serialized;
        /// otherwise, <see langword="false"/>.
        /// </param>
        /// <returns>
        /// A <see cref="NSDictionary"/> which represens this pairing record.
        /// </returns>
        public NSDictionary ToPropertyList(bool includePrivateKeys = true)
        {
            NSDictionary dict = new NSDictionary();

            dict.Add("DeviceCertificate", SerializeCertificate(this.DeviceCertificate));
            dict.Add("EscrowBag", this.EscrowBag);
            dict.Add("HostCertificate", SerializeCertificate(this.HostCertificate));
            dict.Add("HostID", this.HostId);

            if (includePrivateKeys)
            {
                dict.Add("HostPrivateKey", SerializePrivateKey(this.HostPrivateKey));
            }

            dict.Add("RootCertificate", SerializeCertificate(this.RootCertificate));

            if (includePrivateKeys)
            {
                dict.Add("RootPrivateKey", SerializePrivateKey(this.RootPrivateKey));
            }

            dict.Add("SystemBUID", this.SystemBUID);
            dict.Add("WiFiMACAddress", this.WiFiMacAddress);

            return(dict);
        }
예제 #7
0
파일: iOSOTA.cs 프로젝트: fbizuneh/Igor
        public virtual void GenerateAndSavePlist(string PlistFileName, string IPAName, string IconName, string BundleIdentifier, string BundleVersion, string BundleDisplayName)
        {
            string HTTPRoot = GetParamOrConfigString(OTAHTTPRootFlag, "iOS OTA HTTP root path is not set.  Can't generate the OTA manifest.");

            if (!HTTPRoot.EndsWith("/"))
            {
                HTTPRoot += "/";
            }

            if (HTTPRoot.StartsWith("http:"))
            {
                HTTPRoot = HTTPRoot.Replace("http:", "https:");
            }

            if (!HTTPRoot.StartsWith("https://"))
            {
                HTTPRoot = "https://" + HTTPRoot;
            }

            NSDictionary SoftwarePackageDict = new NSDictionary();

            SoftwarePackageDict.Add("kind", new NSString("software-package"));
            SoftwarePackageDict.Add("url", new NSString(HTTPRoot + IPAName));

            NSDictionary DisplayImageDict = new NSDictionary();

            DisplayImageDict.Add("kind", new NSString("display-image"));
            DisplayImageDict.Add("needs-shine", new NSNumber(false));
            DisplayImageDict.Add("url", new NSString(HTTPRoot + IconName));

            NSArray AssetsArray = new NSArray(new NSObject[] { SoftwarePackageDict, DisplayImageDict });

            NSDictionary MetadataDict = new NSDictionary();

            MetadataDict.Add("bundle-identifier", new NSString(BundleIdentifier));
            MetadataDict.Add("bundle-version", new NSString(BundleVersion));
            MetadataDict.Add("kind", new NSString("software"));
            MetadataDict.Add("title", new NSString(BundleDisplayName));

            NSDictionary Item0Dict = new NSDictionary();

            Item0Dict.Add("assets", AssetsArray);
            Item0Dict.Add("metadata", MetadataDict);

            NSArray ItemsArray = new NSArray(new NSObject[] { Item0Dict });

            NSDictionary RootDictionary = new NSDictionary();

            RootDictionary.Add("items", ItemsArray);

            FileInfo NewPlist = new FileInfo(PlistFileName);

            PropertyListParser.SaveAsXml(RootDictionary, NewPlist);
        }
예제 #8
0
        public void Read_Works()
        {
            var dict = new NSDictionary();

            dict.Add("Command", "RelayNotification");
            dict.Add("Name", "com.apple.mobile.application_installed");

            var value = NotificationProxyMessage.Read(dict);

            Assert.Equal("RelayNotification", value.Command);
            Assert.Equal("com.apple.mobile.application_installed", value.Name);
        }
예제 #9
0
        public void ReadGZipFormat()
        {
            var dict = new NSDictionary();

            dict.Add("Version", 1);
            dict.Add("UncompressedSize", 14);

            var metadata = new XipMetadata();

            metadata.ReadFrom(dict);
            Assert.Null(metadata.FileSystemCompressionFormat);
            Assert.Equal(1, metadata.Version);
            Assert.Equal(14, metadata.UncompressedSize);
        }
예제 #10
0
        public void FromDictionary_WithError_Works()
        {
            var dict = new NSDictionary();

            dict.Add("Request", "StartSession");
            dict.Add("Error", "SessionInactive");

            var response = new StartSessionResponse();

            response.FromDictionary(dict);

            Assert.Equal("StartSession", response.Request);
            Assert.Equal(LockdownError.SessionInactive, response.Error);
        }
예제 #11
0
        public void ReadBpxzFormat()
        {
            var dict = new NSDictionary();

            dict.Add("Version", 1);
            dict.Add("UncompressedSize", 0x00000007a33b8228);
            dict.Add("FileSystemCompressionFormat", "10.10");

            var metadata = new XipMetadata();

            metadata.ReadFrom(dict);
            Assert.Equal("10.10", metadata.FileSystemCompressionFormat);
            Assert.Equal(1, metadata.Version);
            Assert.Equal(0x00000007a33b8228, metadata.UncompressedSize);
        }
예제 #12
0
        /// <summary>
        /// Converts this <see cref="PairingOptions"/> object to a  <see cref="NSDictionary"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="NSDictionary"/> which represents this <see cref="PairingOptions"/> object.
        /// </returns>
        public NSDictionary ToPropertyList()
        {
            NSDictionary dict = new NSDictionary();

            dict.Add(nameof(this.ExtendedPairingErrors), new NSNumber(this.ExtendedPairingErrors));
            return(dict);
        }
예제 #13
0
        /// <inheritdoc/>
        public NSDictionary ToDictionary()
        {
            var dict = new NSDictionary();

            if (this.BuildID != Guid.Empty)
            {
                dict.Add(nameof(this.BuildID), this.BuildID.ToString().ToUpper());
            }

            dict.Add(nameof(this.ProductBuildVersion), this.ProductBuildVersion.ToString());
            dict.Add(nameof(this.ProductCopyright), this.ProductCopyright);
            dict.Add(nameof(this.ProductName), this.ProductName);
            dict.Add(nameof(this.ProductVersion), this.ProductVersion.ToString());

            return(dict);
        }
예제 #14
0
        public void ReadAny_ThrowsOnUnknownType()
        {
            var dictionary = new NSDictionary();

            dictionary.Add(nameof(MuxerMessage.MessageType), nameof(MuxerMessageType.None));
            Assert.Throws <ArgumentOutOfRangeException>(() => MuxerMessage.ReadAny(dictionary));
        }
예제 #15
0
        public void ReadAny_InvalidMessageType_ThrowsException()
        {
            var dict = new NSDictionary();

            dict.Add("MessageType", new NSString(nameof(MuxerMessageType.None)));
            Assert.Throws <ArgumentOutOfRangeException>("data", () => MuxerMessage.ReadAny(new NSDictionary()));
        }
예제 #16
0
        public NSDictionary ParseArchivedDictionary(NSDictionary archivedDictionary)
        {
            var keys    = archivedDictionary.GetAs <NSArray>("NS.keys");
            var objects = archivedDictionary.GetAs <NSArray>("NS.objects");

            if (keys == null || objects == null)
            {
                throw new NSKeyedArchiveException("Invalid archived NSDictionary");
            }

            if (keys.Count != objects.Count)
            {
                throw new NSKeyedArchiveException("NSDictionary: Different number of keys and values");
            }

            var dict = new NSDictionary();

            for (var i = 0; i < keys.Count; ++i)
            {
                var stringKey = ResolveObject(keys[i]) as NSString;
                if (stringKey == null)
                {
                    throw new NSKeyedArchiveException("Non-string keys in archived NSDictionaries are not supported");
                }

                var value = ResolveObject(objects[i]);

                dict.Add((string)stringKey, value);
            }

            return(dict);
        }
예제 #17
0
        // ReSharper disable once InconsistentNaming
        public static NSObject?ToNSObject(object?obj)
        {
            if (obj == null)
            {
                return(null);
            }

            var type = obj.GetType();

            if (type.IsPrimitive || type == typeof(string) || type == typeof(byte[]))
            {
                // NSObject can deal with this itself
                return(NSObject.Wrap(obj));
            }

            if (IsSet(type))
            {
                var nsSet = new NSSet();
                foreach (var value in (IEnumerable)obj)
                {
                    nsSet.AddObject(ToNSObject(value));
                }
                return(nsSet);
            }

            if (IsDictionary(type))
            {
                var nsDictionary = new NSDictionary();
                foreach (DictionaryEntry kvp in (IDictionary)obj)
                {
                    nsDictionary.Add((string)kvp.Key, ToNSObject(kvp.Value));
                }
                return(nsDictionary);
            }

            if (IsEnumerable(type))
            {
                var nsArray = new NSArray();
                foreach (var value in (IEnumerable)obj)
                {
                    nsArray.Add(ToNSObject(value));
                }
                return(nsArray);
            }

            var dict = new NSDictionary();

            foreach (var property in type.GetProperties(PropertyFlags))
            {
                var name           = property.Name;
                var dataMemberAttr = property.GetCustomAttribute <DataMemberAttribute>();
                if (dataMemberAttr?.Name != null)
                {
                    name = dataMemberAttr.Name;
                }

                dict.Add(name, ToNSObject(property.GetValue(obj)));
            }
            return(dict);
        }
예제 #18
0
        // Recursively links all `CF$UID` entries to corresponding elements in `objects` array.
        public static NSObject LinkUID(NSArray objects, NSObject current)
        {
            switch (current)
            {
            case NSArray currentArray:
                for (int i = 0; i < currentArray.Count; i++)
                {
                    currentArray[i] = LinkUID(objects, currentArray[i]);
                }
                return(currentArray);

            case NSDictionary currentDict:
                var newDict = new NSDictionary();
                foreach (var item in currentDict)
                {
                    var key   = item.Key;
                    var value = LinkUID(objects, item.Value);
                    newDict.Add(key, value);
                }
                return(newDict);

            case NSSet currentSet:
                var newArray = currentSet.AllObjects().Select(o => LinkUID(objects, o)).ToArray();
                return(new NSSet(NSSetSorted(currentSet), newArray));

            case UID currentUid:
                return(LinkUID(objects, objects[FromUID(currentUid)]));

            default:
                return(current);
            }
        }
예제 #19
0
 /// <summary>
 /// Adds a value to the dictionary, if the value is not <see langword="null"/>.
 /// </summary>
 /// <param name="dictionary">
 /// The dictionary to which to add the value.
 /// </param>
 /// <param name="key">
 /// The key with which to add the value.
 /// </param>
 /// <param name="value">
 /// The value to add.
 /// </param>
 public static void AddWhenNotNull(this NSDictionary dictionary, string key, object value)
 {
     if (value != null)
     {
         dictionary.Add(key, value);
     }
 }
예제 #20
0
        public void FromDictionary_Works()
        {
            var dict = new NSDictionary();

            dict.Add("Request", "StartSession");
            dict.Add("SessionID", "abc");

            var response = new StartSessionResponse();

            response.FromDictionary(dict);

            Assert.Equal("StartSession", response.Request);
            Assert.False(response.EnableSessionSSL);
            Assert.Equal("abc", response.SessionID);
            Assert.Null(response.Error);
        }
예제 #21
0
        /// <summary>
        /// Execute this instance.
        /// </summary>
        public void execute()
        {
            // Show the greatest summation of phone call durations, in seconds,
            // of the employees in the same department, together with the name of the department
            // (it can be assumed that there is only one department fulfilling that condition)

            var phonecallsAndPeople = _model.PhoneCalls.Join(
                _model.Employees,
                call => call.SourceNumber,
                emp => emp.TelephoneNumber,
                (call, freak) => new {
                Freak = freak,
                Call  = call
            }
                ).GroupBy(dep => dep.Freak.Department.Name);

            NSDictionary <string, int> calls = new NSDictionary <string, int>();

            foreach (var dep in phonecallsAndPeople)
            {
                calls.Add(dep.Key, dep.Sum(s => s.Call.Seconds));
            }

            var ordered = calls.OrderByDescending(c => c.Value);

            Console.WriteLine(ordered.First().Key + " : " + ordered.First().Value);
        }
예제 #22
0
        public void Read_Works()
        {
            var dict = new NSDictionary();

            dict.Add("Request", "QueryType");
            dict.Add("Result", "Success");
            dict.Add("Type", "com.apple.mobile.lockdown");

            var response = new GetValueResponse <string>();

            response.FromDictionary(dict);

            Assert.Equal("QueryType", response.Request);
            Assert.Equal("Success", response.Result);
            Assert.Equal("com.apple.mobile.lockdown", response.Type);
        }
예제 #23
0
        public void GetString_ReturnsValue()
        {
            var dict = new NSDictionary();

            dict.Add("key", new NSString("value"));

            Assert.Equal("value", dict.GetString("key"));
        }
예제 #24
0
        public void GetBoolean_ReturnsValue()
        {
            var dict = new NSDictionary();

            dict.Add("key", new NSNumber(true));

            Assert.True(dict.GetBoolean("key"));
        }
예제 #25
0
        public void GetStringArray_NSArrayOfInvalid_ReturnsValue()
        {
            var dict = new NSDictionary();

            dict.Add("foo", new NSNumber(1));

            Assert.Throws <ArgumentOutOfRangeException>(() => dict.GetStringArray("foo"));
        }
예제 #26
0
        public void GetNullabelInt32_ReturnsValue()
        {
            var dict = new NSDictionary();

            dict.Add("key", new NSNumber(42));

            Assert.Equal(42, dict.GetNullableInt32("key"));
        }
예제 #27
0
        public void GetDict_ReturnsValue()
        {
            var child = new NSDictionary();
            var dict  = new NSDictionary();

            dict.Add("key", child);

            Assert.Equal(child, dict.GetDict("key"));
        }
예제 #28
0
        public void Read_Works()
        {
            var dict = new NSDictionary();

            dict.Add("Status", "Success");

            var response = DiagnosticsRelayResponse.Read(dict);

            Assert.Equal(DiagnosticsRelayStatus.Success, response.Status);
        }
예제 #29
0
        public void Read_Works()
        {
            var dict = new NSDictionary();

            dict.Add("EnableServiceSSL", true);
            dict.Add("Port", 1234);
            dict.Add("Request", "StartService");
            dict.Add("Service", "my-service");

            var response = new StartServiceResponse();

            response.FromDictionary(dict);

            Assert.True(response.EnableServiceSSL);
            Assert.Null(response.Error);
            Assert.Equal(1234, response.Port);
            Assert.Equal("StartService", response.Request);
            Assert.Equal("my-service", response.Service);
        }
예제 #30
0
        /// <inheritdoc/>
        public NSDictionary ToDictionary()
        {
            var dict = new NSDictionary();

            dict.Add(nameof(this.Request), this.Request);
            dict.AddWhenNotNull(nameof(this.EntryName), this.EntryName);
            dict.AddWhenNotNull(nameof(this.EntryClass), this.EntryClass);
            dict.AddWhenNotNull(nameof(this.WaitForDisconnect), this.WaitForDisconnect);
            return(dict);
        }
예제 #31
0
        private MemoryStream GeneratePlist()
        {
            NSDictionary root = new NSDictionary();
            NSArray plCatalogs = GetCatalogs();
            NSArray plConditionals = GetConditionals();
            NSArray plIncludedManifests = GetIncludedManifests();
            NSArray plManagedInstalls = GetManagedInstalls();
            NSArray plManagedUninstalls = GetManagedUninstalls();
            NSArray plManagedUpdates = GetManagedUpdates();
            NSArray plOptionalInstalls = GetOptionlInstalls();

            if (plCatalogs.Count > 0) root.Add("catalogs", plCatalogs);
            if (plConditionals.Count > 0) root.Add("conditional_items", plConditionals);
            if (plIncludedManifests.Count > 0) root.Add("included_manifests", plIncludedManifests);
            if (plManagedInstalls.Count > 0) root.Add("managed_installs", plManagedInstalls);
            if (plManagedUninstalls.Count > 0) root.Add("managed_uninstalls", plManagedUninstalls);
            if (plManagedUpdates.Count > 0) root.Add("managed_updates", plManagedUpdates);
            if (plOptionalInstalls.Count > 0) root.Add("optional_installs", plOptionalInstalls);

            var rdr = new MemoryStream();
            try
            {

                PropertyListParser.SaveAsXml(root, rdr);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message);
            }

            return rdr;
        }
예제 #32
0
        private NSArray GetConditionals()
        {
            var uniqueConditions = GetAllUniqueConditions();
            NSArray conditionalItems = new NSArray(uniqueConditions.Count);
            var uniqueConditionsCounter = 0;
            foreach (var uniqueCondition in uniqueConditions)
            {
                NSDictionary condition = new NSDictionary();
                condition.Add("condition", uniqueCondition);
                conditionalItems.SetValue(uniqueConditionsCounter, condition);
                uniqueConditionsCounter++;

                NSArray plIncludedManifests = GetIncludedManifests(uniqueCondition);
                NSArray plManagedInstalls = GetManagedInstalls(uniqueCondition);
                NSArray plManagedUninstalls = GetManagedUninstalls(uniqueCondition);
                NSArray plManagedUpdates = GetManagedUpdates(uniqueCondition);
                NSArray plOptionalInstalls = GetOptionlInstalls(uniqueCondition);

                if (plIncludedManifests.Count > 0)
                    condition.Add("included_manifests", plIncludedManifests);
                if (plManagedInstalls.Count > 0)
                    condition.Add("managed_installs", plManagedInstalls);
                if (plManagedUninstalls.Count > 0)
                    condition.Add("managed_uninstalls", plManagedUninstalls);
                if (plManagedUpdates.Count > 0)
                    condition.Add("managed_updates", plManagedUpdates);
                if (plOptionalInstalls.Count > 0)
                    condition.Add("optional_installs", plOptionalInstalls);
            }

            return conditionalItems;
        }
예제 #33
0
        /// <summary>
        /// Parses a node in the XML structure and returns the corresponding NSObject
        /// </summary>
        /// <returns>The corresponding NSObject.</returns>
        /// <param name="n">The XML node.</param>
        static NSObject ParseObject(XmlNode n)
        {
            if (n.Name.Equals("dict"))
            {
                NSDictionary dict = new NSDictionary();
                List<XmlNode> children = FilterElementNodes(n.ChildNodes);
                for (int i = 0; i < children.Count; i += 2)
                {
                    XmlNode key = children[i];
                    XmlNode val = children[i + 1];

                    string keyString = GetNodeTextContents(key);

                    dict.Add(keyString, ParseObject(val));
                }
                return dict;
            }
            if (n.Name.Equals("array"))
            {
                List<XmlNode> children = FilterElementNodes(n.ChildNodes);
                NSArray array = new NSArray(children.Count);
                for (int i = 0; i < children.Count; i++)
                {
                    array.Add(ParseObject(children[i]));
                }
                return array;
            }
            if (n.Name.Equals("true"))
                return new NSNumber(true);
            if (n.Name.Equals("false"))
                return new NSNumber(false);
            if (n.Name.Equals("integer"))
                return new NSNumber(GetNodeTextContents(n), NSNumber.INTEGER);
            if (n.Name.Equals("real"))
                return new NSNumber(GetNodeTextContents(n), NSNumber.REAL);
            if (n.Name.Equals("string"))
                return new NSString(GetNodeTextContents(n));
            if (n.Name.Equals("data"))
                return new NSData(GetNodeTextContents(n));
            return n.Name.Equals("date") ? new NSDate(GetNodeTextContents(n)) : null;
        }
예제 #34
0
        /// <summary>
        /// Parses a dictionary from the current parsing position.
        /// The prerequisite for calling this method is, that a dictionary begin token has been read.
        /// </summary>
        /// <returns>The dictionary found at the parsing position.</returns>
        NSDictionary ParseDictionary()
        {
            //Skip begin token
            Skip();
            SkipWhitespacesAndComments();
            NSDictionary dict = new NSDictionary();
            while (!Accept(DICTIONARY_END_TOKEN))
            {
                //Parse key
                string keyString;
                if (Accept(QUOTEDSTRING_BEGIN_TOKEN))
                    keyString = ParseQuotedString();
                else
                    keyString = ParseString();
                SkipWhitespacesAndComments();

                //Parse assign token
                Read(DICTIONARY_ASSIGN_TOKEN);
                SkipWhitespacesAndComments();

                NSObject nso = ParseObject();
                dict.Add(keyString, nso);
                SkipWhitespacesAndComments();
                Read(DICTIONARY_ITEM_DELIMITER_TOKEN);
                SkipWhitespacesAndComments();
            }
            //skip end token
            Skip();
            return dict;
        }
예제 #35
0
        /// <summary>
        /// <para>
        /// Creates a NSObject representing the given .NET Object.
        /// </para><para>
        /// Numerics of type <see cref="bool"/>, <see cref="int"/>, <see cref="long"/>, <see cref="short"/>, <see cref="byte"/>, <see cref="float"/> or <see cref="double"/> are wrapped as NSNumber objects.
        /// </para><para>
        /// Strings are wrapped as <see cref="NSString"/> objects and byte arrays as <see cref="NSData"/> objects.
        /// </para><para>
        /// DateTime objects are wrapped as <see cref="NSDate"/> objects.
        /// </para><para>
        /// Serializable classes are serialized and their data is stored in <see cref="NSData"/> objects.
        /// </para><para>
        /// Arrays and Collection objects are converted to <see cref="NSArray"/> where each array member is wrapped into a <see cref="NSObject"/>.
        /// </para><para>
        /// Dictionaries are converted to <see cref="NSDictionary"/>. Each key is converted to a string and each value wrapped into a <see cref="NSObject"/>.
        /// </para>
        /// </summary>
        /// <param name="o">The object to represent.</param>
        ///<returns>A NSObject equivalent to the given object.</returns>
        public static NSObject Wrap(Object o)
        {
            if (o == null)
                throw new NullReferenceException("A null object cannot be wrapped as a NSObject");

            if (o is NSObject)
                return (NSObject)o;

            Type c = o.GetType();
            if (typeof(bool).Equals(c))
            {
                return Wrap((bool)o);
            }
            if (typeof(Byte).Equals(c))
            {
                return Wrap((int)(Byte)o);
            }
            if (typeof(short).Equals(c))
            {
                return Wrap((int)(short)o);
            }
            if (typeof(int).Equals(c))
            {
                return Wrap((int)(int)o);
            }
            if (typeof(long).IsAssignableFrom(c))
            {
                return Wrap((long)o);
            }
            if (typeof(float).Equals(c))
            {
                return Wrap((double)(float)o);
            }
            if (typeof(double).IsAssignableFrom(c))
            {
                return Wrap((double)o);
            }
            if (typeof(string).Equals(c))
            {
                return new NSString((string)o);
            }
            if (typeof(DateTime).Equals(c))
            {
                return new NSDate((DateTime)o);
            }
            if (c.IsArray)
            {
                Type cc = c.GetElementType();
                if (cc.Equals(typeof(byte)))
                {
                    return Wrap((byte[])o);
                }
                if (cc.Equals(typeof(bool)))
                {
                    bool[] array = (bool[])o;
                    NSArray nsa = new NSArray(array.Length);
                    for (int i = 0; i < array.Length; i++)
                        nsa.SetValue(i, Wrap(array[i]));
                    return nsa;
                }
                if (cc.Equals(typeof(float)))
                {
                    float[] array = (float[])o;
                    NSArray nsa = new NSArray(array.Length);
                    for (int i = 0; i < array.Length; i++)
                        nsa.SetValue(i, Wrap(array[i]));
                    return nsa;
                }
                if (cc.Equals(typeof(double)))
                {
                    double[] array = (double[])o;
                    NSArray nsa = new NSArray(array.Length);
                    for (int i = 0; i < array.Length; i++)
                        nsa.SetValue(i, Wrap(array[i]));
                    return nsa;
                }
                if (cc.Equals(typeof(short)))
                {
                    short[] array = (short[])o;
                    NSArray nsa = new NSArray(array.Length);
                    for (int i = 0; i < array.Length; i++)
                        nsa.SetValue(i, Wrap(array[i]));
                    return nsa;
                }
                if (cc.Equals(typeof(int)))
                {
                    int[] array = (int[])o;
                    NSArray nsa = new NSArray(array.Length);
                    for (int i = 0; i < array.Length; i++)
                        nsa.SetValue(i, Wrap(array[i]));
                    return nsa;
                }
                if (cc.Equals(typeof(long)))
                {
                    long[] array = (long[])o;
                    NSArray nsa = new NSArray(array.Length);
                    for (int i = 0; i < array.Length; i++)
                        nsa.SetValue(i, Wrap(array[i]));
                    return nsa;
                }
                    return Wrap((Object[])o);
            }
            if (typeof(Dictionary<string,Object>).IsAssignableFrom(c))
            {
                Dictionary<string,Object> netDict = (Dictionary<string,Object>)o;
                NSDictionary dict = new NSDictionary();
                foreach (KeyValuePair<string, Object> kvp in netDict)
                {
                    dict.Add(kvp.Key, Wrap(kvp.Value));
                }
                return dict;
            }
            if (typeof(List<Object>).IsAssignableFrom(c))
                return Wrap(((List<Object>)o).ToArray());
            return WrapSerialized(o);
        }
예제 #36
0
 /// <summary>
 /// Creates a NSDictionary with the contents of the given map.
 /// </summary>
 /// <param name="value">The value to represent as a NSObject.</param>
 /// <returns>A NSObject representing the given value.</returns>
 /// <exception cref="SystemException">When one of the values contained in the map cannot be represented by a NSObject.</exception>
 public static NSDictionary Wrap(Dictionary<string, Object> value)
 {
     NSDictionary dict = new NSDictionary();
     foreach (KeyValuePair<string, Object> kvp in value)
         dict.Add(kvp.Key, Wrap(kvp.Value));
     return dict;
 }
        /// <summary>
        /// Parses an object inside the currently parsed binary property list.
        /// For the format specification check
        /// <a href="http://www.opensource.apple.com/source/CF/CF-855.17/CFBinaryPList.c">
        /// Apple's binary property list parser implementation</a>.
        /// </summary>
        /// <returns>The parsed object.</returns>
        /// <param name="obj">The object ID.</param>
        /// <exception cref="PropertyListFormatException">When the property list's format could not be parsed.</exception>
        NSObject ParseObject(int obj)
        {
            int offset = offsetTable[obj];
            byte type = bytes[offset];
            int objType = (type & 0xF0) >> 4; //First  4 bits
            int objInfo = (type & 0x0F);      //Second 4 bits
            switch (objType)
            {
                case 0x0:
                    {
                        //Simple
                        switch (objInfo)
                        {
                            case 0x0:
                                {
                                    //null object (v1.0 and later)
                                    return null;
                                }
                            case 0x8:
                                {
                                    //false
                                    return new NSNumber(false);
                                }
                            case 0x9:
                                {
                                    //true
                                    return new NSNumber(true);
                                }
                            case 0xC:
                                {
                                    //URL with no base URL (v1.0 and later)
                                    //TODO Implement binary URL parsing (not yet even implemented in Core Foundation as of revision 855.17)
                                    break;
                                }
                            case 0xD:
                                {
                                    //URL with base URL (v1.0 and later)
                                    //TODO Implement binary URL parsing (not yet even implemented in Core Foundation as of revision 855.17)
                                    break;
                                }
                            case 0xE:
                                {
                                    //16-byte UUID (v1.0 and later)
                                    //TODO Implement binary UUID parsing (not yet even implemented in Core Foundation as of revision 855.17)
                                    break;
                                }
                            case 0xF:
                                {
                                    //filler byte
                                    return null;
                                }
                        }
                        break;
                    }
                case 0x1:
                    {
                        //integer
                        int length = (int)Math.Pow(2, objInfo);
                        return new NSNumber(CopyOfRange(bytes, offset + 1, offset + 1 + length), NSNumber.INTEGER);
                    }
                case 0x2:
                    {
                        //real
                        int length = (int)Math.Pow(2, objInfo);
                        return new NSNumber(CopyOfRange(bytes, offset + 1, offset + 1 + length), NSNumber.REAL);
                    }
                case 0x3:
                    {
                        //Date
                        if (objInfo != 0x3)
                        {
                            throw new PropertyListFormatException("The given binary property list contains a date object of an unknown type (" + objInfo + ")");
                        }
                        return new NSDate(CopyOfRange(bytes, offset + 1, offset + 9));
                    }
                case 0x4:
                    {
                        //Data
                        int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset);
                        int length = lengthAndOffset[0];
                        int dataoffset = lengthAndOffset[1];

                        return new NSData(CopyOfRange(bytes, offset + dataoffset, offset + dataoffset + length));
                    }
                case 0x5:
                    {
                        //ASCII String
                        int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset);
                        int length = lengthAndOffset[0]; //Each character is 1 byte
                        int stroffset = lengthAndOffset[1];

                        return new NSString(CopyOfRange(bytes, offset + stroffset, offset + stroffset + length), "ASCII");
                    }
                case 0x6:
                    {
                        //UTF-16-BE String
                        int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset);
                        int length = lengthAndOffset[0];
                        int stroffset = lengthAndOffset[1];

                        //UTF-16 characters can have variable length, but the Core Foundation reference implementation
                        //assumes 2 byte characters, thus only covering the Basic Multilingual Plane
                        length *= 2;
                        return new NSString(CopyOfRange(bytes, offset + stroffset, offset + stroffset + length), "UTF-16BE");
                    }
                case 0x7:
                    {
                        //UTF-8 string (v1.0 and later)
                        int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset);
                        int strOffset = lengthAndOffset[1];
                        int characters = lengthAndOffset[0];
                        //UTF-8 characters can have variable length, so we need to calculate the byte length dynamically
                        //by reading the UTF-8 characters one by one
                        int length = CalculateUtf8StringLength(bytes, offset + strOffset, characters);
                        return new NSString(CopyOfRange(bytes, offset + strOffset, offset + strOffset + length), "UTF-8");
                    }
                case 0x8:
                    {
                        //UID (v1.0 and later)
                        int length = objInfo + 1;
                        return new UID(obj.ToString(), CopyOfRange(bytes, offset + 1, offset + 1 + length));
                    }
                case 0xA:
                    {
                        //Array
                        int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset);
                        int length = lengthAndOffset[0];
                        int arrayOffset = lengthAndOffset[1];

                        NSArray array = new NSArray(length);
                        for (int i = 0; i < length; i++)
                        {
                            int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes,
                                             offset + arrayOffset + i * objectRefSize,
                                             offset + arrayOffset + (i + 1) * objectRefSize));
                            array.Add(ParseObject(objRef));
                        }
                        return array;

                    }
                case 0xB:
                    {
                        //Ordered set (v1.0 and later)
                        int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset);
                        int length = lengthAndOffset[0];
                        int contentOffset = lengthAndOffset[1];

                        NSSet set = new NSSet(true);
                        for (int i = 0; i < length; i++)
                        {
                            int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes,
                                             offset + contentOffset + i * objectRefSize,
                                             offset + contentOffset + (i + 1) * objectRefSize));
                            set.AddObject(ParseObject(objRef));
                        }
                        return set;
                    }
                case 0xC:
                    {
                        //Set (v1.0 and later)
                        int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset);
                        int length = lengthAndOffset[0];
                        int contentOffset = lengthAndOffset[1];

                        NSSet set = new NSSet();
                        for (int i = 0; i < length; i++)
                        {
                            int objRef = (int)ParseUnsignedInt(CopyOfRange(bytes,
                                             offset + contentOffset + i * objectRefSize,
                                             offset + contentOffset + (i + 1) * objectRefSize));
                            set.AddObject(ParseObject(objRef));
                        }
                        return set;
                    }
                case 0xD:
                    {
                        //Dictionary
                        int[] lengthAndOffset = ReadLengthAndOffset(objInfo, offset);
                        int length = lengthAndOffset[0];
                        int contentOffset = lengthAndOffset[1];

                        //System.out.println("Parsing dictionary #"+obj);
                        NSDictionary dict = new NSDictionary();
                        for (int i = 0; i < length; i++)
                        {
                            int keyRef = (int)ParseUnsignedInt(CopyOfRange(bytes,
                                             offset + contentOffset + i * objectRefSize,
                                             offset + contentOffset + (i + 1) * objectRefSize));
                            int valRef = (int)ParseUnsignedInt(CopyOfRange(bytes,
                                             offset + contentOffset + (length * objectRefSize) + i * objectRefSize,
                                             offset + contentOffset + (length * objectRefSize) + (i + 1) * objectRefSize));
                            NSObject key = ParseObject(keyRef);
                            NSObject val = ParseObject(valRef);
                            dict.Add(key.ToString(), val);
                        }
                        return dict;
                    }
                default:
                    {
                        Console.WriteLine("WARNING: The given binary property list contains an object of unknown type (" + objType + ")");
                        break;
                    }
            }
            return null;
        }
예제 #38
0
파일: iOSOTA.cs 프로젝트: RagtagShawn/Igor
        public virtual void GenerateAndSavePlist(string PlistFileName, string IPAName, string IconName, string BundleIdentifier, string BundleVersion, string BundleDisplayName)
        {
            string HTTPRoot = GetParamOrConfigString(OTAHTTPRootFlag, "iOS OTA HTTP root path is not set.  Can't generate the OTA manifest.");

            if(!HTTPRoot.EndsWith("/"))
            {
                HTTPRoot += "/";
            }

            if(HTTPRoot.StartsWith("http:"))
            {
                HTTPRoot = HTTPRoot.Replace("http:", "https:");
            }

            if(!HTTPRoot.StartsWith("https://"))
            {
                HTTPRoot = "https://" + HTTPRoot;
            }

            NSDictionary SoftwarePackageDict = new NSDictionary();

            SoftwarePackageDict.Add("kind", new NSString("software-package"));
            SoftwarePackageDict.Add("url", new NSString(HTTPRoot + IPAName));

            NSDictionary DisplayImageDict = new NSDictionary();

            DisplayImageDict.Add("kind", new NSString("display-image"));
            DisplayImageDict.Add("needs-shine", new NSNumber(false));
            DisplayImageDict.Add("url", new NSString(HTTPRoot + IconName));

            NSArray AssetsArray = new NSArray(new NSObject[] { SoftwarePackageDict, DisplayImageDict });

            NSDictionary MetadataDict = new NSDictionary();

            MetadataDict.Add("bundle-identifier", new NSString(BundleIdentifier));
            MetadataDict.Add("bundle-version", new NSString(BundleVersion));
            MetadataDict.Add("kind", new NSString("software"));
            MetadataDict.Add("title", new NSString(BundleDisplayName));

            NSDictionary Item0Dict = new NSDictionary();

            Item0Dict.Add("assets", AssetsArray);
            Item0Dict.Add("metadata", MetadataDict);

            NSArray ItemsArray = new NSArray(new NSObject[] { Item0Dict });

            NSDictionary RootDictionary = new NSDictionary();

            RootDictionary.Add("items", ItemsArray);

            FileInfo NewPlist = new FileInfo(PlistFileName);

            PropertyListParser.SaveAsXml(RootDictionary, NewPlist);
        }
예제 #39
0
        public static void AddBundleURLType(IIgorModule ModuleInst, string PlistPath, string NewURLScheme)
        {
            if(IgorAssert.EnsureTrue(ModuleInst, File.Exists(PlistPath), "Plist " + PlistPath + " doesn't exist!"))
            {
                FileInfo PlistFileInfo = new FileInfo(PlistPath);

                NSObject PlistRoot = PropertyListParser.Parse(PlistFileInfo);

                if(IgorAssert.EnsureTrue(ModuleInst, PlistRoot != null, "Plist " + PlistPath + " could not be parsed!"))
                {
                    if(IgorAssert.EnsureTrue(ModuleInst, typeof(NSDictionary).IsAssignableFrom(PlistRoot.GetType()), "Plist " + PlistPath + " root object is not a dictionary."))
                    {
                        NSDictionary RootDictionary = (NSDictionary)PlistRoot;

                        if(IgorAssert.EnsureTrue(ModuleInst, RootDictionary != null, "Plist root is not a dictionary."))
                        {
                            NSSet BundleURLTypes = null;

                            if(RootDictionary.ContainsKey("CFBundleURLTypes"))
                            {
                                NSObject BundleURLTypesObj = RootDictionary.Get("CFBundleURLTypes");

                                if(IgorAssert.EnsureTrue(ModuleInst, BundleURLTypesObj != null, "CFBundleURLTypes wasn't found in the root dictionary even though the key exists."))
                                {
                                    if(IgorAssert.EnsureTrue(ModuleInst, typeof(NSArray).IsAssignableFrom(BundleURLTypesObj.GetType()), "CFBundleURLTypes isn't an NSArray."))
                                    {
                                        BundleURLTypes = new NSSet(((NSArray)BundleURLTypesObj).GetArray());
                                    }
                                }
                            }

                            if(BundleURLTypes == null)
                            {
                                BundleURLTypes = new NSSet();
                            }

                            bool bAlreadyExists = false;

                            foreach(NSObject CurrentURLType in BundleURLTypes)
                            {
                                if(bAlreadyExists)
                                {
                                    break;
                                }

                                if(IgorAssert.EnsureTrue(ModuleInst, typeof(NSDictionary).IsAssignableFrom(CurrentURLType.GetType()), "One of the CFBundleURLTypes isn't an NSDictionary."))
                                {
                                    NSDictionary CurrentURLTypeDict = (NSDictionary)CurrentURLType;

                                    if(IgorAssert.EnsureTrue(ModuleInst, CurrentURLTypeDict != null, "One of the CFBundleURLTypes didn't cast to NSDictionary correctly."))
                                    {
                                        if(CurrentURLTypeDict.ContainsKey("CFBundleURLSchemes"))
                                        {
                                            NSObject CurrentURLSchemesArrayObj = CurrentURLTypeDict.Get("CFBundleURLSchemes");

                                            if(IgorAssert.EnsureTrue(ModuleInst, typeof(NSArray).IsAssignableFrom(CurrentURLSchemesArrayObj.GetType()), "A CFBundleURLSchemes key exists for a given CFBundleURLType, but it's not an NSArray type."))
                                            {
                                                NSArray CurrentURLSchemesArray = (NSArray)CurrentURLSchemesArrayObj;

                                                if(IgorAssert.EnsureTrue(ModuleInst, CurrentURLSchemesArray != null, "The CFBundleURLSchemes object didn't cast to NSDictionary correctly."))
                                                {
                                                    NSSet CurrentURLSchemesSet = new NSSet(CurrentURLSchemesArray.GetArray());

                                                    foreach(NSObject CurrentURLSchemeObj in CurrentURLSchemesSet)
                                                    {
                                                        if(IgorAssert.EnsureTrue(ModuleInst, typeof(NSString).IsAssignableFrom(CurrentURLSchemeObj.GetType()), "One of the CFBundleURLSchemes is not an NSString."))
                                                        {
                                                            NSString CurrentURLScheme = (NSString)CurrentURLSchemeObj;

                                                            if(IgorAssert.EnsureTrue(ModuleInst, CurrentURLScheme != null, "A CFBundleURLScheme entry didn't cast to NSString correctly."))
                                                            {
                                                                if(CurrentURLScheme.GetContent() == NewURLScheme)
                                                                {
                                                                    bAlreadyExists = true;

                                                                    IgorDebug.Log(ModuleInst, "URL scheme " + NewURLScheme + " is already in " + PlistPath);

                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if(!bAlreadyExists)
                            {
                                NSString NewSchemeString = new NSString(NewURLScheme);

                                NSArray NewSchemeArray = new NSArray(1);

                                NewSchemeArray.SetValue(0, NewSchemeString);

                                NSDictionary NewTypeDictionary = new NSDictionary();

                                NewTypeDictionary.Add("CFBundleURLSchemes", NewSchemeArray);

                                BundleURLTypes.AddObject(NewTypeDictionary);

                                NSArray BundleURLTypesArray = new NSArray(BundleURLTypes.AllObjects());

                                if(RootDictionary.ContainsKey("CFBundleURLTypes"))
                                {
                                    RootDictionary["CFBundleURLTypes"] = BundleURLTypesArray;

                                    IgorDebug.Log(ModuleInst, "Updated CFBundleURLTypes to add " + NewURLScheme + ".");
                                }
                                else
                                {
                                    RootDictionary.Add("CFBundleURLTypes", BundleURLTypesArray);

                                    IgorDebug.Log(ModuleInst, "Added CFBundleURLTypes to add " + NewURLScheme + ".");
                                }

                                IgorRuntimeUtils.DeleteFile(PlistPath);

                                PropertyListParser.SaveAsXml(RootDictionary, PlistFileInfo);
                            }
                        }
                    }
                }
            }
        }