Esempio n. 1
0
        protected virtual CodeTypeDeclaration GetStateClass(
            GrainInterfaceData grainInterfaceData,
            Action <Type> referred,
            string stateClassBaseName,
            string stateClassName,
            out bool hasStateClass)
        {
            var sourceType = grainInterfaceData.Type;

            stateClassName = FixupTypeName(stateClassName);
            CodeTypeParameterCollection genericTypeParams = grainInterfaceData.GenericTypeParams;

            Func <Type, bool> nonamespace = t => CurrentNamespace == t.Namespace || ReferencedNamespaces.Contains(t.Namespace);

            Type persistentInterface = GetPersistentInterface(sourceType);

            if (persistentInterface != null)
            {
                if (!persistentInterface.IsInterface)
                {
                    hasStateClass = false;
                    return(null);
                }
                else
                {
                    ConsoleText.WriteError(String.Format("Warning: Usage of grain state interfaces as type arguments for Grain<T> has been deprecated. " +
                                                         "Define an equivalent class with automatic properties instead of the state interface for {0}.", sourceType.FullName));
                }
            }

            Dictionary <string, PropertyInfo> asyncProperties = GrainInterfaceData.GetPersistentProperties(persistentInterface)
                                                                .ToDictionary(p => p.Name.Substring(p.Name.LastIndexOf('.') + 1), p => p);

            Dictionary <string, string> properties = asyncProperties.ToDictionary(p => p.Key,
                                                                                  p => GetGenericTypeName(GrainInterfaceData.GetPromptType(p.Value.PropertyType), referred, nonamespace));

            var stateClass = new CodeTypeDeclaration(stateClassBaseName);

            if (genericTypeParams != null)
            {
                stateClass.TypeParameters.AddRange(genericTypeParams);
            }
            stateClass.IsClass = true;

            if (persistentInterface != null)
            {
                stateClass.TypeAttributes = persistentInterface.IsPublic ? TypeAttributes.Public : TypeAttributes.NotPublic;
            }
            else
            {
                stateClass.TypeAttributes = TypeAttributes.Public;
            }

            stateClass.BaseTypes.Add(new CodeTypeReference(typeof(GrainState), CodeTypeReferenceOptions.GlobalReference));
            MarkAsGeneratedCode(stateClass);
            referred(typeof(GrainState));

            if (persistentInterface != null)
            {
                stateClass.BaseTypes.Add(new CodeTypeReference(GetGenericTypeName(persistentInterface, referred, nonamespace)));
            }

            stateClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(SerializableAttribute).Name));
            stateClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(GrainStateAttribute), CodeTypeReferenceOptions.GlobalReference),
                                                                         new CodeAttributeArgument(new CodePrimitiveExpression(grainInterfaceData.Type.Namespace + "." + TypeUtils.GetParameterizedTemplateName(grainInterfaceData.Type, language: language)))));

            referred(typeof(SerializableAttribute));
            referred(typeof(OnDeserializedAttribute));

            var initStateFields = new CodeMemberMethod {
                Name = "InitStateFields"
            };

            initStateFields.Attributes = (initStateFields.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
            foreach (var peoperty in asyncProperties)
            {
                Type propertyType = peoperty.Value.PropertyType;

                bool noCreateNew = propertyType.IsPrimitive || typeof(string).IsAssignableFrom(propertyType) || // Primative types
                                   propertyType.IsAbstract || propertyType.IsInterface || propertyType.IsGenericParameter || // No concrete implementation
                                   propertyType.GetConstructor(Type.EmptyTypes) == null; // No default constructor

                var initExpression = noCreateNew                                         // Pre-initialize this type to default value
                    ? (CodeExpression) new CodeDefaultValueExpression(new CodeTypeReference(GetGenericTypeName(propertyType, referred, nonamespace)))
                    : new CodeObjectCreateExpression(new CodeTypeReference(GetGenericTypeName(propertyType, referred, nonamespace)));

                initStateFields.Statements.Add(new CodeAssignStatement(
                                                   new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), peoperty.Key),
                                                   initExpression));
            }

            hasStateClass = properties.Count > 0;

            if (hasStateClass)
            {
                foreach (var pair in properties)
                {
                    GenerateStateClassProperty(stateClass, asyncProperties[pair.Key], pair.Key, pair.Value);
                }

                var returnType = new CodeTypeReference("System.Collections.Generic.IDictionary",
                                                       new CodeTypeReference(typeof(string)), new CodeTypeReference(typeof(object)));
                var concreteType = new CodeTypeReference("System.Collections.Generic.Dictionary",
                                                         new CodeTypeReference(typeof(string)), new CodeTypeReference(typeof(object)));

                var asDictionary = new CodeMemberMethod
                {
                    Name       = "AsDictionary",
                    Attributes = MemberAttributes.Public | MemberAttributes.Override,
                    ReturnType = returnType
                };

                asDictionary.Statements.Add(new CodeVariableDeclarationStatement(concreteType, "result", new CodeObjectCreateExpression(concreteType)));
                foreach (var pair in properties)
                {
                    asDictionary.Statements.Add(new CodeAssignStatement(
                                                    new CodeIndexerExpression(new CodeVariableReferenceExpression("result"), new CodePrimitiveExpression(pair.Key)),
                                                    new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), pair.Key)));
                }

                asDictionary.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("result")));
                stateClass.Members.Add(asDictionary);

                GenerateSetAll(stateClass, properties);
                GenerateToString(stateClass, stateClassName, properties);
            }

            // Copier, serializer, and deserializer for the state class
            var copier       = SerializerGenerationUtilities.GenerateCopier("_Copier", stateClassName, genericTypeParams);
            var serializer   = SerializerGenerationUtilities.GenerateSerializer("_Serializer", stateClassName, genericTypeParams);
            var deserializer = SerializerGenerationUtilities.GenerateDeserializer("_Deserializer", stateClassName, genericTypeParams);

            var ctor = new CodeConstructor {
                Attributes = (copier.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public
            };

            ctor.BaseConstructorArgs.Add(new CodePrimitiveExpression(TypeUtils.GetFullName(grainInterfaceData.Type, language)));
            ctor.Statements.Add(new CodeMethodInvokeExpression(
                                    new CodeThisReferenceExpression(),
                                    "InitStateFields"));

            copier.Statements.Add(new CodeMethodReturnStatement(
                                      new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("input"), "DeepCopy")));

            serializer.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("input"),
                    "SerializeTo", new CodeArgumentReferenceExpression("stream")));

            deserializer.Statements.Add(new CodeVariableDeclarationStatement(stateClassName, "result",
                                                                             new CodeObjectCreateExpression(stateClassName)));
            deserializer.Statements.Add(new CodeMethodInvokeExpression(
                                            new CodeVariableReferenceExpression("result"),
                                            "DeserializeFrom",
                                            new CodeArgumentReferenceExpression("stream")));
            deserializer.Statements.Add(new CodeMethodReturnStatement(
                                            new CodeVariableReferenceExpression("result")));

            stateClass.Members.Add(ctor);
            stateClass.Members.Add(initStateFields);
            stateClass.Members.Add(copier);
            stateClass.Members.Add(serializer);
            stateClass.Members.Add(deserializer);

            return(stateClass);
        }
Esempio n. 2
0
        internal bool OnKey(ConsoleKeyInfo arg, ConsoleText line, ref int cursorIndex)
        {
            bool resetMap        = true;
            bool resetCompletion = true;

            try
            {
                bool hasShift = (arg.Modifiers & ConsoleModifiers.Shift) != 0;

                // For now, we discard SHIFT entirely, as it is handled separately for range selection
                // TODO: we should handle them not differently from ctrl/alt, but it's complicated
                arg = new ConsoleKeyInfo(arg.KeyChar, arg.Key, false, (arg.Modifiers & ConsoleModifiers.Alt) != 0, (arg.Modifiers & ConsoleModifiers.Control) != 0);

                KalkConsoleKey kalkKey = arg;
                if (cursorIndex >= 0 && cursorIndex <= line.Count)
                {
                    if (_currentShortcutKeyMap.TryGetValue(kalkKey, out var value))
                    {
                        if (value is KalkShortcutKeyMap map)
                        {
                            _currentShortcutKeyMap = map;
                            resetMap = false; // we don't reset if
                        }
                        else
                        {
                            var expression = (ScriptExpression)value;
                            var result     = EvaluateExpression(expression);
                            if (result is KalkActionObject command)
                            {
                                // Particular case the completion action, we handle it here
                                if (command.Action == "completion")
                                {
                                    // In case of shift we go backward
                                    if (OnCompletionRequested(hasShift, line, ref cursorIndex))
                                    {
                                        resetCompletion = false;
                                        return(true);
                                    }
                                }
                                else if (OnAction != null)
                                {
                                    command.Call(OnAction);
                                }
                            }
                            else if (result != null)
                            {
                                var resultStr = ObjectToString(result);
                                line.Insert(cursorIndex, resultStr);
                                cursorIndex += resultStr.Length;
                            }
                        }

                        return(true);
                    }
                }
            }
            finally
            {
                if (resetMap)
                {
                    // Restore the root key map in case of an error.
                    _currentShortcutKeyMap = Shortcuts.ShortcutKeyMap;
                }

                if (resetCompletion)
                {
                    ResetCompletion();
                }
            }

            return(false);
        }
Esempio n. 3
0
 public void SetCheckpoint(Vector3 position)
 {
     currentCheckpointPosition = position;
     ConsoleText.getInstance().ShowMessage("Checkpoint Reached!");
     player.ResetEnergy();
 }
Esempio n. 4
0
        /// <summary>
        /// Generate all the necessary logic for serialization of payload types used by grain interfaces.
        /// </summary>
        internal static void GenerateSerializationForClass(Assembly grainAssembly, Type t, CodeNamespace container, HashSet <string> referencedNamespaces, Language language)
        {
            var generateSerializers = !CheckForCustomSerialization(t);
            var generateCopier      = !CheckForCustomCopier(t);

            if (!generateSerializers && !generateCopier)
            {
                return; // If the class declares all custom implementations, then we don't need to do anything...
            }
            bool notVB         = (language != Language.VisualBasic);
            var  openGenerics  = notVB ? "<" : "(Of ";
            var  closeGenerics = notVB ? ">" : ")";

            // Add the class's namespace to this namespace's imports, as well as some other imports we use
            container.Imports.Add(new CodeNamespaceImport("System"));
            container.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            container.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            container.Imports.Add(new CodeNamespaceImport("Orleans.Serialization"));
            if (!string.IsNullOrEmpty(t.Namespace))
            {
                container.Imports.Add(new CodeNamespaceImport(t.Namespace));
            }

            // Create the class declaration, including any required generic parameters
            // At one time this was a struct, not a class, so all the variable names are "structFoo". Too bad.
            // Note that we need to replace any periods in the type name with _ to properly handle nested classes
            var className = TypeUtils.GetSimpleTypeName(TypeUtils.GetFullName(t));
            var serializationClassName     = className.Replace('.', '_') + SERIALIZER_CLASS_NAME_SUFFIX;
            var serializationClassOpenName = serializationClassName;
            var classDecl = new CodeTypeDeclaration(serializationClassName)
            {
                IsClass = true
            };

            classDecl.Attributes     = (classDecl.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
            classDecl.TypeAttributes = TypeAttributes.NotPublic;
            CodeGeneratorBase.MarkAsGeneratedCode(classDecl);

            if (!t.IsGenericType)
            {
                classDecl.CustomAttributes.Add(
                    new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegisterSerializerAttribute),
                                                                       CodeTypeReferenceOptions.GlobalReference)));
            }

            if (t.IsGenericType)
            {
                className += openGenerics;
                serializationClassOpenName += openGenerics;
                bool first = true;
                foreach (var genericParameter in t.GetGenericTypeDefinition().GetGenericArguments())
                {
                    var param = new CodeTypeParameter(genericParameter.Name);
                    if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != GenericParameterAttributes.None)
                    {
                        param.Constraints.Add(" class");
                    }
                    if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != GenericParameterAttributes.None)
                    {
                        param.Constraints.Add(" struct");
                    }

                    var constraints = genericParameter.GetGenericParameterConstraints();
                    foreach (var constraintType in constraints)
                    {
                        param.Constraints.Add(new CodeTypeReference(TypeUtils.GetParameterizedTemplateName(constraintType)));
                    }

                    if ((genericParameter.GenericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != GenericParameterAttributes.None)
                    {
                        param.HasConstructorConstraint = true;
                    }

                    classDecl.TypeParameters.Add(param);
                    if (!first)
                    {
                        className += ", ";
                        serializationClassOpenName += ",";
                    }
                    className += genericParameter.Name;
                    first      = false;
                }
                className += closeGenerics;
                serializationClassOpenName += closeGenerics;
            }

            // A couple of repeatedly-used CodeDom snippets
            var classType                  = new CodeTypeOfExpression(className);
            var classTypeReference         = new CodeTypeReference(className);
            var objectTypeReference        = new CodeTypeReference(typeof(object));
            var serMgrRefExp               = new CodeTypeReferenceExpression(typeof(SerializationManager));
            var currentSerialzationContext = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(SerializationContext)), "Current");

            // Static DeepCopyInner method:
            var copier = new CodeMemberMethod();

            if (generateCopier)
            {
                classDecl.Members.Add(copier);
            }

            copier.Attributes = (copier.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            copier.Attributes = (copier.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
            copier.Name       = "DeepCopier";
            copier.Parameters.Add(new CodeParameterDeclarationExpression(objectTypeReference, "original"));
            bool shallowCopyable = t.IsOrleansShallowCopyable();

            if (shallowCopyable)
            {
                copier.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("original")));
            }
            else
            {
                copier.Statements.Add(new CodeVariableDeclarationStatement(classTypeReference, "input",
                                                                           new CodeCastExpression(classTypeReference, new CodeArgumentReferenceExpression("original"))));
            }

            copier.ReturnType = objectTypeReference;

            // Static serializer method:
            var serializer = new CodeMemberMethod();

            if (generateSerializers)
            {
                classDecl.Members.Add(serializer);
            }

            serializer.Attributes = (serializer.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            serializer.Attributes = (serializer.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
            serializer.Name       = "Serializer";
            serializer.Parameters.Add(new CodeParameterDeclarationExpression(objectTypeReference, "untypedInput"));
            serializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamWriter), "stream"));
            serializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected"));
            serializer.ReturnType = new CodeTypeReference(typeof(void));
            serializer.Statements.Add(new CodeVariableDeclarationStatement(classTypeReference, "input",
                                                                           new CodeCastExpression(classTypeReference, new CodeArgumentReferenceExpression("untypedInput"))));

            // Static deserializer method; note that this will never get called for null values or back references
            var deserializer = new CodeMemberMethod();

            if (generateSerializers)
            {
                classDecl.Members.Add(deserializer);
            }

            deserializer.Attributes = (deserializer.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            deserializer.Attributes = (deserializer.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
            deserializer.Name       = "Deserializer";
            deserializer.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected"));
            deserializer.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(BinaryTokenStreamReader), CodeTypeReferenceOptions.GlobalReference), "stream"));
            deserializer.ReturnType = objectTypeReference;

            // Static constructor, which just calls the Init method
            var staticConstructor = new CodeTypeConstructor();

            classDecl.Members.Add(staticConstructor);
            staticConstructor.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(null, "Register")));

            // Init method, which registers the type with the serialization manager, and later may get some static FieldInfo initializers
            var init = new CodeMemberMethod();

            classDecl.Members.Add(init);
            init.Name       = "Register";
            init.Attributes = (init.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            init.Attributes = (init.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;

            if (generateCopier && generateSerializers)
            {
                init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType,
                                                                   new CodeMethodReferenceExpression(null, notVB ? "DeepCopier" : "AddressOf DeepCopier"),
                                                                   new CodeMethodReferenceExpression(null, notVB ? "Serializer" : "AddressOf Serializer"),
                                                                   new CodeMethodReferenceExpression(null, notVB ? "Deserializer" : "AddressOf Deserializer")));
            }
            else if (generateCopier)
            {
                init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType,
                                                                   new CodeMethodReferenceExpression(null, notVB ? "DeepCopier" : "AddressOf DeepCopier"),
                                                                   null,
                                                                   null));
            }
            else
            {
                init.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register", classType,
                                                                   null,
                                                                   new CodeMethodReferenceExpression(null, notVB ? "Serializer" : "AddressOf Serializer"),
                                                                   new CodeMethodReferenceExpression(null, notVB ? "Deserializer" : "AddressOf Deserializer")));
            }

            CodeStatement constructor;
            var           consInfo = t.GetConstructor(Type.EmptyTypes);

            if (consInfo != null)
            {
                if (!t.ContainsGenericParameters)
                {
                    constructor = new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeObjectCreateExpression(t));
                }
                else
                {
                    var typeName = TypeUtils.GetParameterizedTemplateName(t, tt => tt.Namespace != container.Name && !referencedNamespaces.Contains(tt.Namespace), true);
                    if (language == Language.VisualBasic)
                    {
                        typeName = typeName.Replace("<", "(Of ").Replace(">", ")");
                    }
                    constructor = new CodeVariableDeclarationStatement(classTypeReference, "result",
                                                                       new CodeObjectCreateExpression(typeName));
                }
            }
            else if (t.IsValueType)
            {
                constructor = !t.ContainsGenericParameters
                    ? new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeDefaultValueExpression(new CodeTypeReference(t)))
                    : new CodeVariableDeclarationStatement(classTypeReference, "result", new CodeDefaultValueExpression(new CodeTypeReference(TypeUtils.GetTemplatedName(t))));
            }
            else
            {
                if (!t.ContainsGenericParameters)
                {
                    constructor = new CodeVariableDeclarationStatement(classTypeReference, "result",
                                                                       new CodeCastExpression(className, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Runtime.Serialization.FormatterServices)),
                                                                                                                                        "GetUninitializedObject", new CodeTypeOfExpression(t))));
                }
                else
                {
                    constructor = new CodeVariableDeclarationStatement(classTypeReference, "result",
                                                                       new CodeCastExpression(className, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Runtime.Serialization.FormatterServices)),
                                                                                                                                        "GetUninitializedObject", new CodeTypeOfExpression(TypeUtils.GetTemplatedName(t)))));
                }
            }
            if (!shallowCopyable)
            {
                copier.Statements.Add(constructor);
                copier.Statements.Add(new CodeMethodInvokeExpression(currentSerialzationContext, "RecordObject",
                                                                     new CodeVariableReferenceExpression("original"),
                                                                     new CodeVariableReferenceExpression("result")));
            }
            deserializer.Statements.Add(constructor);

            // For structs, once we encounter a field that we have to use reflection to set, we need to switch to a boxed representation and reflection
            // for the rest of the fields in the struct while setting. This flag indicates that we're in that mode.
            bool usingBoxedReflection = false;

            // For every field in the class:
            int counter             = 0;
            List <FieldInfo> fields = GetAllFields(t).ToList();

            fields.Sort(new FieldNameComparer());
            foreach (var fld in fields)
            {
                if (fld.IsNotSerialized || fld.IsLiteral)
                {
                    continue;
                }

                var fldType = fld.FieldType;
                if (TypeUtilities.IsTypeIsInaccessibleForSerialization(fldType, t.Module, grainAssembly))
                {
                    ConsoleText.WriteStatus("Skipping generation of serializer for {0} because one of it's field {1} is of a private/internal type {2}.", t.FullName, fld.Name, fldType);
                    return; // We cannot deserialize a class with a field of non-public type. Need to add a proper reporting here.
                }

                // Import the namespace for the field's type (and any of its parameters), just in case it's not already added
                ImportFieldNamespaces(fld.FieldType, container.Imports);
                SerializerGenerationManager.RecordTypeToGenerate(fld.FieldType);
                counter++;

                // Add the statements moving to and from a class instance, to the instance creation method and the non-default constructor
                // Getter and setter for this field's value from a class object
                CodeExpression  getter = null;
                SetterGenerator setter = null;

                var name = fld.Name;
                // Normalize the field name -- strip trailing @ (F#) and look for automatic properties
                var normalizedName = name.TrimEnd('@');
                if (name.StartsWith("<"))
                {
                    // Backing field for an automatic property; see if it's public so we can use it
                    var propertyName = name.Substring(1, name.IndexOf('>') - 1).TrimEnd('@');
                    var property     = t.GetProperty(propertyName);
                    // If the property is public and not hidden...
                    if ((property != null) && property.DeclaringType == fld.DeclaringType)
                    {
                        if (property.GetGetMethod() != null)
                        {
                            getter = new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("input"),
                                                                         propertyName);
                        }
                        if (!usingBoxedReflection && (property.GetSetMethod() != null))
                        {
                            setter = value =>
                            {
                                var s = new CodeAssignStatement
                                {
                                    Left  = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("result"), propertyName),
                                    Right = value
                                };
                                return(new CodeStatementCollection(new CodeStatement[] { s }));
                            };
                        }
                    }
                }

                var typeName = TypeUtils.GetTemplatedName(fld.FieldType, _ => !_.IsGenericParameter, language);

                // See if it's a public field
                if ((getter == null) || (setter == null))
                {
                    if (fld.Attributes.HasFlag(FieldAttributes.Public))
                    {
                        if (getter == null)
                        {
                            getter = new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("input"), normalizedName);
                        }

                        if (!usingBoxedReflection && (setter == null) && !fld.IsInitOnly)
                        {
                            setter = value =>
                            {
                                var s = new CodeAssignStatement
                                {
                                    Left  = new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("result"), normalizedName),
                                    Right = value
                                };
                                return(new CodeStatementCollection(new CodeStatement[] { s }));
                            };
                        }
                    }
                }

                // Have to use reflection
                if ((getter == null) || (setter == null))
                {
                    // Add a static field for the FieldInfo, and a static constructor
                    string infoName = "fieldInfo" + counter;
                    var    info     = new CodeMemberField(typeof(FieldInfo), infoName);
                    info.Attributes |= MemberAttributes.Private | MemberAttributes.Static;
                    classDecl.Members.Add(info);
                    CodeTypeOfExpression fieldAccessType;
                    if (fld.DeclaringType == t)
                    {
                        fieldAccessType = classType;
                    }
                    else
                    {
                        FieldInfo fld2 = t.GetField(fld.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        if ((fld2 != null) && fld2.DeclaringType == fld.DeclaringType)
                        {
                            fieldAccessType = classType;
                        }
                        else
                        {
                            fieldAccessType = fld.DeclaringType.IsGenericType
                                ? new CodeTypeOfExpression(TypeUtils.GetTemplatedName(fld.DeclaringType))
                                : new CodeTypeOfExpression(fld.DeclaringType);
                        }
                    }

                    init.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(null, infoName),
                                                                new CodeMethodInvokeExpression(fieldAccessType, "GetField", new CodePrimitiveExpression(name),
                                                                                               new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Instance"),
                                                                                                                                CodeBinaryOperatorType.BitwiseOr,
                                                                                                                                new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "Public"),
                                                                                                                                                                 CodeBinaryOperatorType.BitwiseOr,
                                                                                                                                                                 new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(BindingFlags)), "NonPublic"))))));

                    // Build the getter and setter
                    if (getter == null)
                    {
                        getter = new CodeMethodInvokeExpression(
                            new CodeMethodReferenceExpression(
                                new CodeFieldReferenceExpression(null, infoName), "GetValue"),
                            new CodeArgumentReferenceExpression("input"));
                    }

                    if (setter == null)
                    {
                        // If the type is a struct, then the setter becomes somewhat more complicated, so first treat non-structs
                        if (t.IsByRef)
                        {
                            setter = value =>
                            {
                                var s = new CodeExpressionStatement
                                {
                                    Expression =
                                        new CodeMethodInvokeExpression(
                                            new CodeMethodReferenceExpression(
                                                new CodeFieldReferenceExpression(null, infoName), "SetValue"),
                                            new CodeVariableReferenceExpression("result"), value)
                                };
                                return(new CodeStatementCollection(new CodeStatement[] { s }));
                            };
                        }
                        else
                        {
                            // If this is the first field to use setting by reflection in a struct, we need to box the struct before we can continue
                            if (!usingBoxedReflection)
                            {
                                usingBoxedReflection = true;
                                // NOTE: object objResult = (object)result;
                                if (!shallowCopyable)
                                {
                                    copier.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "objResult",
                                                                                               new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("result"))));
                                }

                                deserializer.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "objResult",
                                                                                                 new CodeCastExpression(typeof(object), new CodeVariableReferenceExpression("result"))));
                            }
                            var temp = "temp" + counter;
                            setter = value =>
                            {
                                var s1 = new CodeVariableDeclarationStatement(typeof(object), temp, value);
                                var s2 = new CodeExpressionStatement
                                {
                                    Expression = new CodeMethodInvokeExpression(
                                        new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(null, infoName), "SetValue"),
                                        new CodeVariableReferenceExpression("objResult"),
                                        new CodeVariableReferenceExpression(temp))
                                };
                                return(new CodeStatementCollection(new CodeStatement[] { s1, s2 }));
                            };
                        }
                    }
                }

                // Copy this field, if needed
                if (!shallowCopyable)
                {
                    if (fld.FieldType.IsOrleansShallowCopyable())
                    {
                        copier.Statements.AddRange(setter(getter));
                    }
                    else
                    {
                        copier.Statements.AddRange(fld.FieldType == typeof(object)
                            ? setter(new CodeMethodInvokeExpression(serMgrRefExp, "DeepCopyInner", getter))
                            : setter(new CodeCastExpression(typeName,
                                                            new CodeMethodInvokeExpression(serMgrRefExp, "DeepCopyInner", getter))));
                    }
                }

                // Serialize this field
                serializer.Statements.Add(new CodeMethodInvokeExpression(serMgrRefExp, "SerializeInner", getter, new CodeArgumentReferenceExpression("stream"),
                                                                         new CodeTypeOfExpression(typeName)));

                // Deserialize this field
                deserializer.Statements.AddRange(setter(new CodeCastExpression(typeName,
                                                                               new CodeMethodInvokeExpression(serMgrRefExp, "DeserializeInner",
                                                                                                              new CodeTypeOfExpression(typeName), new CodeArgumentReferenceExpression("stream")))));
            }

            // Add return statements, as needed
            if (!shallowCopyable)
            {
                copier.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(usingBoxedReflection ? "objResult" : "result")));
            }

            deserializer.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(usingBoxedReflection ? "objResult" : "result")));

            // Special processing for generic types, necessary so that the appropriate closed types will get generated at run-time
            if (t.IsGenericType)
            {
                var masterClassName = TypeUtils.GetSimpleTypeName(t) + "GenericMaster";

                var masterClass = new CodeTypeDeclaration(masterClassName);
                container.Types.Add(masterClass);
                masterClass.IsClass        = true;
                masterClass.Attributes    |= MemberAttributes.Static | MemberAttributes.Assembly | MemberAttributes.Final;
                masterClass.TypeAttributes = TypeAttributes.NotPublic;
                masterClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegisterSerializerAttribute), CodeTypeReferenceOptions.GlobalReference)));

                var masterInit = AddInitMethod(masterClass);
                masterInit.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(SerializationManager), CodeTypeReferenceOptions.GlobalReference)), "Register",
                                                                         new CodeTypeOfExpression(t),
                                                                         new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericCopier"),
                                                                         new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericSerializer"),
                                                                         new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(notVB ? masterClassName : "AddressOf " + masterClassName), "GenericDeserializer")));

                var initClosed = new CodeMethodInvokeExpression
                {
                    Method = new CodeMethodReferenceExpression
                    {
                        MethodName   = "Invoke",
                        TargetObject =
                            new CodeMethodInvokeExpression(
                                new CodeVariableReferenceExpression
                                    ("closed"), "GetMethod",
                                new CodePrimitiveExpression(
                                    "Register"))
                    }
                };
                initClosed.Parameters.Add(new CodePrimitiveExpression(null));
                initClosed.Parameters.Add(new CodeArrayCreateExpression(typeof(object), 0));

                var create = new CodeMemberMethod();
                masterClass.Members.Add(create);
                create.Attributes = (create.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                create.Attributes = (create.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
                create.Name       = "CreateConcreteType";
                create.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type[]), "typeParams"));
                create.ReturnType = new CodeTypeReference(typeof(Type));
                create.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeTypeOfExpression(serializationClassOpenName),
                                                                                                   "MakeGenericType", new CodeArgumentReferenceExpression("typeParams"))));

                var cop = new CodeMemberMethod();
                masterClass.Members.Add(cop);
                cop.Attributes = (cop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                cop.Attributes = (cop.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
                cop.Name       = "GenericCopier";
                cop.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "obj"));
                cop.ReturnType = new CodeTypeReference(typeof(object));
                cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t",
                                                                        new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType",
                                                                                                       new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("obj"), "GetType"), "GetGenericArguments"))));
                cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f",
                                                                        new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("DeepCopier"))));
                cop.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args",
                                                                        new CodeArrayCreateExpression(typeof(object), new CodeExpression[] { new CodeArgumentReferenceExpression("obj") })));
                cop.Statements.Add(new CodeMethodReturnStatement(
                                       new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(),
                                                                      new CodeVariableReferenceExpression("args"))));

                var ser = new CodeMemberMethod();
                masterClass.Members.Add(ser);
                ser.Attributes = (ser.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                ser.Attributes = (ser.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
                ser.Name       = "GenericSerializer";
                ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "input"));
                ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamWriter), "stream"));
                ser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected"));
                ser.ReturnType = new CodeTypeReference(typeof(void));
                ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t",
                                                                        new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType",
                                                                                                       new CodeMethodInvokeExpression(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("input"), "GetType"), "GetGenericArguments"))));
                ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f",
                                                                        new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("Serializer"))));
                ser.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args",
                                                                        new CodeArrayCreateExpression(typeof(object), new CodeArgumentReferenceExpression("input"), new CodeArgumentReferenceExpression("stream"), new CodeArgumentReferenceExpression("expected"))));
                ser.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(),
                                                                  new CodeVariableReferenceExpression("args")));

                var deser = new CodeMemberMethod();
                masterClass.Members.Add(deser);
                deser.Attributes = (deser.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
                deser.Attributes = (deser.Attributes & ~MemberAttributes.ScopeMask) | MemberAttributes.Static;
                deser.Name       = "GenericDeserializer";
                deser.ReturnType = new CodeTypeReference(typeof(object));
                deser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Type), "expected"));
                deser.Parameters.Add(new CodeParameterDeclarationExpression(typeof(BinaryTokenStreamReader), "stream"));
                deser.ReturnType = new CodeTypeReference(typeof(object));
                deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(Type), "t",
                                                                          new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(masterClassName), "CreateConcreteType",
                                                                                                         new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("expected"), "GetGenericArguments"))));
                deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(MethodInfo), "f",
                                                                          new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"), "GetMethod", new CodePrimitiveExpression("Deserializer"))));
                deser.Statements.Add(new CodeVariableDeclarationStatement(typeof(object[]), "args",
                                                                          new CodeArrayCreateExpression(typeof(object), new CodeArgumentReferenceExpression("expected"), new CodeArgumentReferenceExpression("stream"))));
                deser.Statements.Add(new CodeMethodReturnStatement(
                                         new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "Invoke", new CodePrimitiveExpression(),
                                                                        new CodeVariableReferenceExpression("args"))));
            }
            container.Types.Add(classDecl);
        }
Esempio n. 5
0
        /// <summary>
        /// Updates the source file in the project if required.
        /// </summary>
        /// <param name="sourceFileToBeUpdated">Path to file to be updated.</param>
        /// <param name="outputFileGenerated">File that was updated.</param>
        private static void UpdateIntellisenseFile(string sourceFileToBeUpdated, string outputFileGenerated)
        {
            if (string.IsNullOrEmpty(sourceFileToBeUpdated))
            {
                throw new ArgumentNullException("sourceFileToBeUpdated", "Output file must not be blank");
            }
            if (string.IsNullOrEmpty(outputFileGenerated))
            {
                throw new ArgumentNullException("outputFileGenerated", "Generated file must already exist");
            }

            var sourceToUpdateFileInfo = new FileInfo(sourceFileToBeUpdated);
            var generatedFileInfo      = new FileInfo(outputFileGenerated);

            if (!generatedFileInfo.Exists)
            {
                throw new Exception("Generated file must already exist");
            }

            if (File.Exists(sourceFileToBeUpdated))
            {
                bool filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo);
                if (filesMatch)
                {
                    ConsoleText.WriteStatus(
                        "Orleans-CodeGen - No changes to the generated file {0}",
                        sourceFileToBeUpdated);
                    return;
                }

                // we come here only if files don't match
                sourceToUpdateFileInfo.Attributes = sourceToUpdateFileInfo.Attributes & (~FileAttributes.ReadOnly);
                // remove read only attribute
                ConsoleText.WriteStatus(
                    "Orleans-CodeGen - copying file {0} to {1}",
                    outputFileGenerated,
                    sourceFileToBeUpdated);
                File.Copy(outputFileGenerated, sourceFileToBeUpdated, true);
                filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo);
                ConsoleText.WriteStatus(
                    "Orleans-CodeGen - After copying file {0} to {1} Matchs={2}",
                    outputFileGenerated,
                    sourceFileToBeUpdated,
                    filesMatch);
            }
            else
            {
                var dir = Path.GetDirectoryName(sourceFileToBeUpdated);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                ConsoleText.WriteStatus(
                    "Orleans-CodeGen - copying file {0} to {1}",
                    outputFileGenerated,
                    sourceFileToBeUpdated);
                File.Copy(outputFileGenerated, sourceFileToBeUpdated, true);
                bool filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo);
                ConsoleText.WriteStatus(
                    "Orleans-CodeGen - After copying file {0} to {1} Matchs={2}",
                    outputFileGenerated,
                    sourceFileToBeUpdated,
                    filesMatch);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Generates a syntax tree for the provided assemblies.
        /// </summary>
        /// <param name="assemblies">The assemblies to generate code for.</param>
        /// <param name="runtime">Whether or not runtime code generation is being performed.</param>
        /// <returns>The generated syntax tree.</returns>
        private static GeneratedSyntax GenerateForAssemblies(List <Assembly> assemblies, bool runtime)
        {
            if (Logger.IsVerbose)
            {
                Logger.Verbose(
                    "Generating code for assemblies: {0}",
                    string.Join(", ", assemblies.Select(_ => _.FullName)));
            }

            Assembly       targetAssembly;
            HashSet <Type> ignoredTypes;

            if (runtime)
            {
                // Ignore types which have already been accounted for.
                ignoredTypes = CodeGeneratorCommon.GetTypesWithImplementations(
                    typeof(MethodInvokerAttribute),
                    typeof(GrainReferenceAttribute),
                    typeof(GrainStateAttribute),
                    typeof(SerializerAttribute));
                targetAssembly = null;
            }
            else
            {
                ignoredTypes   = new HashSet <Type>();
                targetAssembly = assemblies.FirstOrDefault();
            }

            var members = new List <MemberDeclarationSyntax>();

            // Get types from assemblies which reference Orleans and are not generated assemblies.
            var includedTypes = new HashSet <Type>();

            foreach (var type in assemblies.SelectMany(_ => _.GetTypes()))
            {
                // The module containing the serializer.
                var module = runtime ? null : type.Module;

                // Every type which is encountered must be considered for serialization.
                if (!type.IsNested && !type.IsGenericParameter && type.IsSerializable)
                {
                    // If a type was encountered which can be accessed, process it for serialization.
                    var isAccessibleForSerialization =
                        !TypeUtilities.IsTypeIsInaccessibleForSerialization(type, module, targetAssembly);
                    if (isAccessibleForSerialization)
                    {
                        includedTypes.Add(type);
                        SerializerGenerationManager.RecordTypeToGenerate(type);
                    }
                }

                // Collect the types which require code generation.
                if (GrainInterfaceData.IsGrainInterface(type))
                {
                    if (Logger.IsVerbose2)
                    {
                        Logger.Verbose2("Will generate code for: {0}", type.GetParseableName());
                    }

                    includedTypes.Add(type);
                }
            }

            includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_));

            // Group the types by namespace and generate the required code in each namespace.
            foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
            {
                var namespaceMembers = new List <MemberDeclarationSyntax>();
                foreach (var type in group)
                {
                    // The module containing the serializer.
                    var module = runtime ? null : type.Module;

                    // Every type which is encountered must be considered for serialization.
                    Action <Type> onEncounteredType = encounteredType =>
                    {
                        // If a type was encountered which can be accessed, process it for serialization.
                        var isAccessibleForSerialization =
                            !TypeUtilities.IsTypeIsInaccessibleForSerialization(encounteredType, module, targetAssembly);
                        if (isAccessibleForSerialization)
                        {
                            SerializerGenerationManager.RecordTypeToGenerate(encounteredType);
                        }
                    };

                    if (Logger.IsVerbose2)
                    {
                        Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
                    }

                    if (GrainInterfaceData.IsGrainInterface(type))
                    {
                        if (Logger.IsVerbose2)
                        {
                            Logger.Verbose2(
                                "Generating GrainReference and MethodInvoker for {0}",
                                type.GetParseableName());
                        }

                        namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, onEncounteredType));
                        namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type));
                    }

                    // Generate serializers.
                    var  first = true;
                    Type toGen;
                    while (SerializerGenerationManager.GetNextTypeToProcess(out toGen))
                    {
                        // Filter types which are inaccessible by the serialzation module/assembly.
                        var skipSerialzerGeneration =
                            toGen.GetAllFields()
                            .Any(
                                field =>
                                TypeUtilities.IsTypeIsInaccessibleForSerialization(
                                    field.FieldType,
                                    module,
                                    targetAssembly));
                        if (skipSerialzerGeneration)
                        {
                            continue;
                        }

                        if (!runtime)
                        {
                            if (first)
                            {
                                ConsoleText.WriteStatus("ClientGenerator - Generating serializer classes for types:");
                                first = false;
                            }

                            ConsoleText.WriteStatus(
                                "\ttype " + toGen.FullName + " in namespace " + toGen.Namespace
                                + " defined in Assembly " + toGen.Assembly.GetName());
                        }

                        if (Logger.IsVerbose2)
                        {
                            Logger.Verbose2(
                                "Generating & Registering Serializer for Type {0}",
                                toGen.GetParseableName());
                        }

                        namespaceMembers.AddRange(SerializerGenerator.GenerateClass(toGen, onEncounteredType));
                    }
                }

                if (namespaceMembers.Count == 0)
                {
                    if (Logger.IsVerbose)
                    {
                        Logger.Verbose2("Skipping namespace: {0}", group.Key);
                    }

                    continue;
                }

                members.Add(
                    SF.NamespaceDeclaration(SF.ParseName(group.Key))
                    .AddUsings(
                        TypeUtils.GetNamespaces(typeof(TaskUtility), typeof(GrainExtensions))
                        .Select(_ => SF.UsingDirective(SF.ParseName(_)))
                        .ToArray())
                    .AddMembers(namespaceMembers.ToArray()));
            }

            return(new GeneratedSyntax
            {
                SourceAssemblies = assemblies,
                Syntax = members.Count > 0 ? SF.CompilationUnit().AddMembers(members.ToArray()) : null
            });
        }
Esempio n. 7
0
 /// <summary>
 /// Makes warnings visible in VS and MSBuild by prefixing error message with "Warning"
 /// </summary>
 /// <param name="warning">Warning message</param>
 internal static void ReportWarning(string warning)
 {
     ConsoleText.WriteWarning("Warning: " + warning);
 }
Esempio n. 8
0
        public KalkEngine() : base(new KalkObjectWithAlias())
        {
            FileService = new DefaultFileService();
            KalkSettings.Initialize();
            KalkEngineFolder = AppContext.BaseDirectory;

            // Enforce UTF8 encoding
            Console.OutputEncoding = Encoding.UTF8;
            EnableEngineOutput     = true;
            EchoEnabled            = true;
            DisplayVersion         = true;
            CurrentDisplay         = KalkDisplayMode.Standard;
            KalkUserFolder         = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.DoNotVerify), ".kalk");

            HighlightOutput             = new ConsoleText();
            InputReader                 = Console.In;
            OutputWriter                = Console.Out;
            ErrorWriter                 = Console.Error;
            IsOutputSupportHighlighting = ConsoleHelper.SupportEscapeSequences;

            // Fetch version
            var assemblyInfoVersion = (AssemblyInformationalVersionAttribute)typeof(KalkEngine).Assembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute));

            Version = assemblyInfoVersion.InformationalVersion;

            Builtins = BuiltinObject;
            ((KalkObjectWithAlias)Builtins).Engine = this;

            Units     = new KalkUnits(this);
            Shortcuts = new KalkShortcuts();
            Aliases   = new KalkAliases();
            _currentShortcutKeyMap  = Shortcuts.ShortcutKeyMap;
            _completionMatchingList = new List <string>();
            Config      = new KalkConfig();
            Variables   = new ScriptVariables(this);
            Descriptors = new Dictionary <string, KalkDescriptor>();
            EnableRelaxedMemberAccess = false;
            _modules      = new Dictionary <Type, KalkModule>();
            TryConverters = new List <TryToObjectDelegate>();
            ErrorForStatementFunctionAsExpression = true;
            StrictVariables = true;
            UseScientific   = true;
            LoopLimit       = int.MaxValue; // no limits for loops
            RecursiveLimit  = int.MaxValue; // no limits (still guarded by Scriban)

            // Setup default clipboard methods
            _localClipboard  = string.Empty;
            GetClipboardText = GetClipboardTextImpl;
            SetClipboardText = SetClipboardTextImpl;

            _cancellationTokenSource = new CancellationTokenSource();

            PushGlobal(Units);
            PushGlobal(Variables);

            _parserOptions = new ParserOptions();

            _lexerOptions = new LexerOptions()
            {
                KeepTrivia = true,
                Mode       = ScriptMode.ScriptOnly,
                Lang       = ScriptLang.Scientific
            };
            _lexerInterpolatedOptions = new LexerOptions()
            {
                KeepTrivia = true,
                Mode       = ScriptMode.Default,
                Lang       = ScriptLang.Scientific
            };
            _tempOutputHighlight = new ConsoleText();

            // Init last result with 0
            _lastResult = 0;

            HistoryList = new List <string>();

            _isInitializing = true;
            RegisterFunctions();
            _isInitializing = false;
        }
Esempio n. 9
0
        /// <summary>
        /// </summary>
        /// <param name="args">
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        private static void Main(string[] args)
        {
            LogUtil.SetupConsoleLogging(LogLevel.Debug);
            LogUtil.SetupFileLogging("${basedir}/LoginEngineLog.txt", LogLevel.Trace);



            SettingsOverride.LoadCustomSettings("NBug.LoginEngine.Config");
            Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;



            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            var ct = new ConsoleText();

            ct.TextRead("main.txt");
            Console.Write("Loading ");
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.Write(AssemblyInfoclass.Title + " ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(AssemblyInfoclass.Description);
            Console.ResetColor();
            Console.WriteLine("...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[OK]");
            Console.ResetColor();

            // Sying helped figure all this code out, about 5 yearts ago! :P
            bool processedargs = false;

            loginServer = Container.GetInstance <LoginServer>();
            bool TCPEnable = true;
            bool UDPEnable = false;
            int  Port      = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort);

            try
            {
                if (Config.Instance.CurrentConfig.ListenIP == "0.0.0.0")
                {
                    loginServer.TcpEndPoint = new IPEndPoint(IPAddress.Any, Port);
                }
                else
                {
                    loginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
                }
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            // TODO: ADD More Handlers.
            loginServer.MaximumPendingConnections = 100;

            #region Console Commands

            // Andyzweb: Added checks for start and stop
            // also added a running command to return status of the server
            // and added Console.Write("\nServer Command >>"); to login server
            string consoleCommand;
            ct.TextRead("login_consolecommands.txt");
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            loginServer.Start(TCPEnable, UDPEnable);
                        }
                    }

                    processedargs = true;
                }

                Console.Write("\nServer Command >>");

                consoleCommand = Console.ReadLine();
                string temp = string.Empty;
                while (temp != consoleCommand)
                {
                    temp           = consoleCommand;
                    consoleCommand = consoleCommand.Replace("  ", " ");
                }

                consoleCommand = consoleCommand.Trim();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (loginServer.IsRunning)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisrunning.txt");
                        Console.ResetColor();
                        break;
                    }

                    loginServer.Start(TCPEnable, UDPEnable);
                    break;

                case "stop":
                    if (!loginServer.IsRunning)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisnotrunning.txt");
                        Console.ResetColor();
                        break;
                    }

                    loginServer.Stop();
                    break;

                case "exit":
                    Process.GetCurrentProcess().Kill();
                    break;

                case "running":
                    if (loginServer.IsRunning)
                    {
                        // Console.WriteLine("Login Server is running");
                        ct.TextRead("loginisrunning.txt");
                        break;
                    }

                    // Console.WriteLine("Login Server not running");
                    ct.TextRead("loginisnotrunning.txt");
                    break;

                    #region Help Commands....

                case "help":
                    ct.TextRead("logincmdhelp.txt");
                    break;

                case "help start":
                    ct.TextRead("helpstart.txt");
                    break;

                case "help exit":
                    ct.TextRead("helpstop.txt");
                    break;

                case "help running":
                    ct.TextRead("loginhelpcmdrunning.txt");
                    break;

                case "help Adduser":
                    ct.TextRead("logincmdadduserhelp.txt");
                    break;

                case "help setpass":
                    ct.TextRead("logincmdhelpsetpass.txt");
                    break;

                    #endregion

                default:

                    #region Adduser

                    // This section handles the command for adding a user to the database
                    if (consoleCommand.ToLower().StartsWith("adduser"))
                    {
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length < 9)
                        {
                            Console.WriteLine(
                                "Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>");
                            break;
                        }

                        string username = parts[1];
                        string password = parts[2];
                        int    numChars = 0;
                        try
                        {
                            numChars = int.Parse(parts[3]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <number of characters> must be a number (duh!)");
                            break;
                        }

                        int expansions = 0;
                        try
                        {
                            expansions = int.Parse(parts[4]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        if (expansions < 0 || expansions > 2047)
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        int gm = 0;
                        try
                        {
                            gm = int.Parse(parts[5]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <GM Level> must be number (duh!)");
                            break;
                        }

                        string email = parts[6];
                        if (email == null)
                        {
                            email = string.Empty;
                        }

                        if (!TestEmailRegex(email))
                        {
                            Console.WriteLine("Error: <Email> You must supply an email address for this account");
                            break;
                        }

                        string firstname = parts[7];
                        try
                        {
                            if (firstname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <FirstName> You must supply a first name for this accout");
                            break;
                        }

                        string lastname = parts[8];
                        try
                        {
                            if (lastname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <LastName> You must supply a last name for this account");
                            break;
                        }

                        DBLoginData login = new DBLoginData
                        {
                            Username           = username,
                            AccountFlags       = 0,
                            Allowed_Characters = numChars,
                            CreationDate       = DateTime.Now,
                            Email      = email,
                            Expansions = expansions,
                            FirstName  = firstname,
                            LastName   = lastname,
                            GM         = gm,
                            Flags      = 0,
                            Password   = new LoginEncryption().GeneratePasswordHash(password)
                        };
                        try
                        {
                            LoginDataDao.WriteLoginData(login);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(
                                "An error occured while trying to add a new user account:\n{0}", ex.Message);
                            break;
                        }

                        Console.WriteLine("User added successfully.");
                        break;
                    }

                    #endregion

                    #region Hashpass

                    // This function just hashes the string you enter using the loginencryption method
                    if (consoleCommand.ToLower().StartsWith("hash"))
                    {
                        string Syntax =
                            "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 2)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }

                        string pass   = parts[1];
                        var    le     = new LoginEncryption();
                        string hashed = le.GeneratePasswordHash(pass);
                        Console.WriteLine(hashed);
                        break;
                    }

                    #endregion

                    #region setpass

                    // sets the password for the given username
                    // Added by Andyzweb
                    // Still TODO add exception and error handling
                    if (consoleCommand.ToLower().StartsWith("setpass"))
                    {
                        string Syntax =
                            "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 3)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }

                        string username = parts[1];
                        string newpass  = parts[2];
                        var    le       = new LoginEncryption();
                        string hashed   = le.GeneratePasswordHash(newpass);

                        try
                        {
                            LoginDataDao.WriteNewPassword(
                                new DBLoginData {
                                Username = username, Password = hashed
                            });
                        }
                        // yeah this part here, some kind of exception handling for mysql errors
                        catch (Exception ex)
                        {
                            Console.WriteLine("Could not set new Password\r\n" + ex.Message);
                            LogUtil.ErrorException(ex);
                        }
                    }

                    #endregion

                    ct.TextRead("login_consolecmdsdefault.txt");
                    break;
                }
            }

            #endregion
        }
Esempio n. 10
0
        /// <summary>
        /// Generates a syntax tree for the provided assemblies.
        /// </summary>
        /// <param name="assemblies">The assemblies to generate code for.</param>
        /// <param name="runtime">Whether or not runtime code generation is being performed.</param>
        /// <returns>The generated syntax tree.</returns>
        private GeneratedSyntax GenerateForAssemblies(List <Assembly> assemblies, bool runtime)
        {
            if (Logger.IsVerbose)
            {
                Logger.Verbose(
                    "Generating code for assemblies: {0}",
                    string.Join(", ", assemblies.Select(_ => _.FullName)));
            }

            Assembly       targetAssembly;
            HashSet <Type> ignoredTypes;

            if (runtime)
            {
                // Ignore types which have already been accounted for.
                ignoredTypes   = GetTypesWithGeneratedSupportClasses();
                targetAssembly = null;
            }
            else
            {
                ignoredTypes   = new HashSet <Type>();
                targetAssembly = assemblies.FirstOrDefault();
            }

            var members = new List <MemberDeclarationSyntax>();

            // Include assemblies which are marked as included.
            var knownAssemblyAttributes = new Dictionary <Assembly, KnownAssemblyAttribute>();
            var knownAssemblies         = new HashSet <Assembly>();

            foreach (var attribute in assemblies.SelectMany(asm => asm.GetCustomAttributes <KnownAssemblyAttribute>()))
            {
                knownAssemblyAttributes[attribute.Assembly] = attribute;
                knownAssemblies.Add(attribute.Assembly);
            }

            if (knownAssemblies.Count > 0)
            {
                knownAssemblies.UnionWith(assemblies);
                assemblies = knownAssemblies.ToList();
            }

            // Get types from assemblies which reference Orleans and are not generated assemblies.
            var includedTypes = new HashSet <Type>();

            for (var i = 0; i < assemblies.Count; i++)
            {
                var assembly = assemblies[i];
                foreach (var attribute in assembly.GetCustomAttributes <ConsiderForCodeGenerationAttribute>())
                {
                    ConsiderType(attribute.Type, runtime, targetAssembly, includedTypes, considerForSerialization: true);
                    if (attribute.ThrowOnFailure && !serializerGenerationManager.IsTypeRecorded(attribute.Type))
                    {
                        throw new CodeGenerationException(
                                  $"Found {attribute.GetType().Name} for type {attribute.Type.GetParseableName()}, but code"
                                  + " could not be generated. Ensure that the type is accessible.");
                    }
                }

                KnownAssemblyAttribute knownAssemblyAttribute;
                var considerAllTypesForSerialization = knownAssemblyAttributes.TryGetValue(assembly, out knownAssemblyAttribute) &&
                                                       knownAssemblyAttribute.TreatTypesAsSerializable;
                foreach (var type in TypeUtils.GetDefinedTypes(assembly, Logger))
                {
                    var considerForSerialization = considerAllTypesForSerialization || type.IsSerializable;
                    ConsiderType(type.AsType(), runtime, targetAssembly, includedTypes, considerForSerialization);
                }
            }

            includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_));

            // Group the types by namespace and generate the required code in each namespace.
            foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
            {
                var namespaceMembers = new List <MemberDeclarationSyntax>();
                foreach (var type in group)
                {
                    // The module containing the serializer.
                    var module = runtime ? null : type.GetTypeInfo().Module;

                    // Every type which is encountered must be considered for serialization.
                    Action <Type> onEncounteredType = encounteredType =>
                    {
                        // If a type was encountered which can be accessed, process it for serialization.
                        serializerGenerationManager.RecordTypeToGenerate(encounteredType, module, targetAssembly);
                    };

                    if (Logger.IsVerbose2)
                    {
                        Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
                    }

                    if (GrainInterfaceUtils.IsGrainInterface(type))
                    {
                        if (Logger.IsVerbose2)
                        {
                            Logger.Verbose2(
                                "Generating GrainReference and MethodInvoker for {0}",
                                type.GetParseableName());
                        }

                        GrainInterfaceUtils.ValidateInterfaceRules(type);

                        namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, onEncounteredType));
                        namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type));
                    }

                    // Generate serializers.
                    var  first = true;
                    Type toGen;
                    while (serializerGenerationManager.GetNextTypeToProcess(out toGen))
                    {
                        if (!runtime)
                        {
                            if (first)
                            {
                                ConsoleText.WriteStatus("ClientGenerator - Generating serializer classes for types:");
                                first = false;
                            }

                            ConsoleText.WriteStatus(
                                "\ttype " + toGen.FullName + " in namespace " + toGen.Namespace
                                + " defined in Assembly " + toGen.GetTypeInfo().Assembly.GetName());
                        }

                        if (Logger.IsVerbose2)
                        {
                            Logger.Verbose2(
                                "Generating & Registering Serializer for Type {0}",
                                toGen.GetParseableName());
                        }

                        namespaceMembers.Add(SerializerGenerator.GenerateClass(toGen, onEncounteredType));
                    }
                }

                if (namespaceMembers.Count == 0)
                {
                    if (Logger.IsVerbose)
                    {
                        Logger.Verbose2("Skipping namespace: {0}", group.Key);
                    }

                    continue;
                }

                members.Add(
                    SF.NamespaceDeclaration(SF.ParseName(group.Key))
                    .AddUsings(
                        TypeUtils.GetNamespaces(typeof(TaskUtility), typeof(GrainExtensions), typeof(IntrospectionExtensions))
                        .Select(_ => SF.UsingDirective(SF.ParseName(_)))
                        .ToArray())
                    .AddMembers(namespaceMembers.ToArray()));
            }

            return(new GeneratedSyntax
            {
                SourceAssemblies = assemblies,
                Syntax = members.Count > 0 ? SF.CompilationUnit().AddMembers(members.ToArray()) : null
            });
        }
Esempio n. 11
0
        /// <summary>
        /// 선택지를 표시한 후 선택된 원소의 번호를 반환합니다.
        /// </summary>
        /// <returns>선택된 원소의 번호</returns>
        public int GetSelect(bool isKeep = false)
        {
            int         currentSelectedNumber = 0;
            ConsoleText item = UpdateElementColor(currentSelectedNumber, this.SelectedForegroundColor, this.SelectedBackgroundColor);

            textBox.Present();
            Console.SetCursorPosition(item.Left + item.asciiLength, item.Top);
            while (true)
            {
                inputMgr.KeyCheck();

                switch (inputMgr.KeyInfo.Key)
                {
                case ConsoleKey.UpArrow:
                    if (currentSelectedNumber > 0)
                    {
                        item = UpdateElementColor(currentSelectedNumber--, this.ForegroundColor, this.BackgroundColor);
                        item.Present();
                        item = UpdateElementColor(currentSelectedNumber, this.SelectedForegroundColor, this.SelectedBackgroundColor);
                        item.Present();
                        Console.SetCursorPosition(item.Left + item.asciiLength, item.Top);
                    }
                    break;

                case ConsoleKey.DownArrow:
                    if (currentSelectedNumber + 1 < textBox.Row)
                    {
                        item = UpdateElementColor(currentSelectedNumber++, this.ForegroundColor, this.BackgroundColor);
                        item.Present();
                        item = UpdateElementColor(currentSelectedNumber, this.SelectedForegroundColor, this.SelectedBackgroundColor);
                        item.Present();
                        Console.SetCursorPosition(item.Left + item.asciiLength, item.Top);
                    }
                    break;

                case ConsoleKey.Enter:
                    if (!isKeep)
                    {
                        textBox.ForegroundColor = this.ForegroundColor;
                        textBox.BackgroundColor = this.BackgroundColor;
                        textBox.Depresent();
                    }
                    Console.SetCursorPosition(0, textBox.Top + textBox.ConsoleTexts.Length);
                    return(currentSelectedNumber);

                case ConsoleKey.F1:
                case ConsoleKey.D1:
                    if (InputNumber(0, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F2:
                case ConsoleKey.D2:
                    if (InputNumber(1, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F3:
                case ConsoleKey.D3:
                    if (InputNumber(2, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F4:
                case ConsoleKey.D4:
                    if (InputNumber(3, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F5:
                case ConsoleKey.D5:
                    if (InputNumber(4, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F6:
                case ConsoleKey.D6:
                    if (InputNumber(5, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F7:
                case ConsoleKey.D7:
                    if (InputNumber(6, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F8:
                case ConsoleKey.D8:
                    if (InputNumber(7, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F9:
                case ConsoleKey.D9:
                    if (InputNumber(8, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F10:
                case ConsoleKey.D0:
                    if (InputNumber(9, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F11:
                    if (InputNumber(10, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }

                case ConsoleKey.F12:
                    if (InputNumber(11, ref currentSelectedNumber))
                    {
                        goto case ConsoleKey.Enter;
                    }
                    else
                    {
                        break;
                    }
                }
                Thread.Sleep(1);
            }
        }
Esempio n. 12
0
 void ConsoleAddString(string str)
 {
     ConsoleText.Add(str);
 }
Esempio n. 13
0
        private static void Main(string[] args)
        {
            bool processedargs = false;

            // Please dont kill the commented out lines below for the moment -NV
            //Misc.Playfields.Instance.playfields[0].districts.Add(new ZoneEngine.Misc.DistrictInfo());
            //Misc.Playfields.Instance.playfields[0].districts[0].districtName = "some district";
            //Misc.Playfields.Instance.playfields[0].districts.Add(new ZoneEngine.Misc.DistrictInfo());
            //Misc.Playfields.Instance.playfields[0].districts[1].districtName = "some other district";
            //Misc.DistrictInfo.DumpXML(@"C:\list.xml", Misc.Playfields.Instance.playfields[0]);

            #region Console Text...
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();
            ct.TextRead("main.txt");
            Console.WriteLine("Loading " + AssemblyInfoclass.Title + "...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Using ISComm v1.0");
            Console.WriteLine("[OK]");
            Console.ResetColor();
            #endregion

            #region Delete old SqlError.log, so it doesnt get too big
            if (File.Exists("sqlerror.log"))
            {
                File.Delete("sqlerror.log");
            }
            #endregion

            #region ISComm Code Area...
            Console.WriteLine("[ISComm] Waiting for Link...");
            ChatCom.StartLink(Config.Instance.CurrentConfig.CommPort);
            //System.Console.WriteLine("[ISComm] Linked Successfully! :D");
            #endregion

            zoneServer = new Server {
                EnableTCP = true, EnableUDP = false
            };

            #region Script Loading Code Area..
            csc = new ScriptCompiler();
            #endregion

            try
            {
                zoneServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }
            try
            {
                zoneServer.UdpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            zoneServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.ZonePort);

            #region NLog
            LoggingConfiguration config        = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            fileTarget.FileName = "${basedir}/ZoneEngineLog.txt";
            fileTarget.Layout   = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);
            LogManager.Configuration = config;
            #endregion

            #region NBug
            SettingsOverride.LoadCustomSettings("NBug.ZoneEngine.Config");
            NBug.Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;
            //TODO: ADD More Handlers.
            #endregion

            FunctionC.ReadFunctions();
            Console.WriteLine("Registered " + FunctionC.NumberofRegisteredFunctions().ToString() + " Functions");

            #region Console Commands...
            string consoleCommand;
            ct.TextRead("zone_consolecommands.txt");
            // removed CheckDBs here, added commands check and updatedb (updatedb will change to a versioning

            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            csc.Compile(false);
                            StartTheServer();
                        }
                    }
                    processedargs = true;
                }
                Console.Write("\nServer Command >>");
                consoleCommand = Console.ReadLine();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    //TODO: Add Sql Check.
                    csc.Compile(false);
                    StartTheServer();
                    break;

                case "startm":     // Multiple dll compile
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    //TODO: Add Sql Check.
                    csc.Compile(true);
                    StartTheServer();
                    break;

                case "stop":
                    if (!zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Zone Server is not running");
                        Console.ResetColor();
                        break;
                    }
                    zoneServer.Stop();
                    ThreadMgr.Stop();
                    break;

                case "check":
                case "updatedb":
                    using (SqlWrapper sqltester = new SqlWrapper())
                    {
                        sqltester.CheckDBs();
                        Console.ResetColor();
                    }
                    break;

                case "exit":
                case "quit":
                    if (zoneServer.Running)
                    {
                        zoneServer.Stop();
                        ThreadMgr.Stop();
                    }
                    Process.GetCurrentProcess().Kill();
                    break;

                case "ls":     //list all available scripts, dont remove it since it does what it should
                    Console.WriteLine("Available scripts");

                    /* Old Lua way
                     * string[] files = Directory.GetFiles("Scripts");*/
                    string[] files = Directory.GetFiles("Scripts\\", "*.cs", SearchOption.AllDirectories);
                    if (files.Length == 0)
                    {
                        Console.WriteLine("No scripts were found.");
                        break;
                    }
                    Console.ForegroundColor = ConsoleColor.Green;
                    foreach (string s in files)
                    {
                        Console.WriteLine(s);

                        /* Old Lua way
                         * if (s.EndsWith(".lua"))
                         * {
                         *  Console.WriteLine(s.Split('\\')[1].Split('.')[0]);
                         * }*/
                    }
                    Console.ResetColor();
                    break;

                case "ping":
                    // ChatCom.Server.Ping();
                    Console.WriteLine("Ping is disabled till we can fix it");
                    break;

                case "running":
                    if (zoneServer.Running)
                    {
                        Console.WriteLine("Zone Server is Running");
                        break;
                    }
                    Console.WriteLine("Zone Server not Running");
                    break;

                case "online":
                    if (zoneServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        lock (zoneServer.Clients)
                        {
                            foreach (Client c in zoneServer.Clients)
                            {
                                Console.WriteLine("Character " + c.Character.Name + " online");
                            }
                        }
                        Console.ResetColor();
                    }
                    break;

                default:
                    ct.TextRead("zone_consolecmdsdefault.txt");
                    break;
                }
            }
        }
Esempio n. 14
0
		public static void Main (string[] args)
		{
			const int WIDTH = 80;
			const int HEIGHT = 30;
			var defaultSize = new Size (WIDTH, HEIGHT);
			var win = new ConsoleArea (defaultSize);
			//var driver = new ConsoleDriver ();
			var driver = new AnsiDriver ();
			var screen = new ConsoleUpdater (driver, defaultSize);
			var scrolly = new ConsoleScrollWindow (new Size (WIDTH - 2, 10));

			scrolly.Window.Background = ConsoleColor.DarkRed;

			win.Foreground = ConsoleColor.White;
			var input = new ConsoleInputField ();
			const int diff = 40;
			bool hide = false;

			for (var anim = 0; anim < 1000; ++anim)
			{
				win.Background = ConsoleColor.Blue;
				win.Clear ();
				var x = (int)(Math.Sin (anim / 10.0f) * diff + diff);

				win.Background = ConsoleColor.DarkBlue;
				win.Foreground = ConsoleColor.Yellow;
				var xStart = x / 3;
				var yStart = x / 8;
				var borderWidth = x / 3;
				var borderHeight = x / 5 + 1;
				ConsoleBorder.Draw (win, xStart, yStart, borderWidth, borderHeight);
				win.Background = ConsoleColor.DarkGreen;
				var p = new Position (xStart, yStart);
				var s = new Size (borderWidth - 2, borderHeight - 2);
				var rect = new Rectangle (p, s);
				win.Fill (rect);
				win.Background = ConsoleColor.Black;
				win.Foreground = ConsoleColor.Yellow;

				if (x > 40)
				{
					win.Background = ConsoleColor.Cyan;
				}
				else
				{
					win.Background = ConsoleColor.Red;
				}
				scrolly.AddString ("This is a test", true);
				win.Move (new Position (x, 10));
				win.AddString ("Hello world!");
				win.Background = ConsoleColor.DarkMagenta;
				win.Copy (scrolly.Window, new Position (40 - x / 6, 10 - x / 3));
				// ConsoleText.Draw (win, "THis is a field", 25, ConsoleText.TextAlign.Center);
				var info = driver.ReadKey ();
				var result = input.DoChar (info);

				if (result == InputResult.Enter)
				{
					hide = true;
				}
				else if (result == InputResult.Escape)
				{
					break;
				}
				win.Move (new Position (0, 15));

				if (!hide)
				{
					var adjustedCursorX = ConsoleText.Draw (win, input.Value, input.CursorX, 25, ConsoleText.TextAlign.Left);
					win.Move (new Position (adjustedCursorX, 15));
				}
				screen.Update (win);

				Task.Delay (10).Wait ();
			}
		}
Esempio n. 15
0
        private static void Main(string[] args)
        {
            #region Console Texts...
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();
            ct.TextRead("main.txt");
            Console.WriteLine("Loading " + AssemblyInfoclass.Title + "...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[OK]");
            Console.ResetColor();
            #endregion

            //Sying helped figure all this code out, about 5 yearts ago! :P
            bool processedargs = false;
            loginLoginServer           = new LoginServer();
            loginLoginServer.EnableTCP = true;
            loginLoginServer.EnableUDP = false;
            try
            {
                loginLoginServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }
            loginLoginServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.LoginPort);

            #region NLog
            LoggingConfiguration config        = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            fileTarget.FileName = "${basedir}/LoginEngineLog.txt";
            fileTarget.Layout   = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);
            LogManager.Configuration = config;
            #endregion

            #region NBug
            SettingsOverride.LoadCustomSettings("NBug.LoginEngine.Config");
            NBug.Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;
            //TODO: ADD More Handlers.
            #endregion

            loginLoginServer.MaximumPendingConnections = 100;

            #region Console Commands
            //Andyzweb: Added checks for start and stop
            //also added a running command to return status of the server
            //and added Console.Write("\nServer Command >>"); to login server
            string consoleCommand;
            ct.TextRead("login_consolecommands.txt");
            while (true)
            {
                if (!processedargs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            ThreadMgr.Start();
                            loginLoginServer.Start();
                        }
                    }
                    processedargs = true;
                }
                Console.Write("\nServer Command >>");

                consoleCommand = Console.ReadLine();
                string temp = "";
                while (temp != consoleCommand)
                {
                    temp           = consoleCommand;
                    consoleCommand = consoleCommand.Replace("  ", " ");
                }
                consoleCommand = consoleCommand.Trim();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (loginLoginServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisrunning.txt");
                        Console.ResetColor();
                        break;
                    }
                    ThreadMgr.Start();
                    loginLoginServer.Start();
                    break;

                case "stop":
                    if (!loginLoginServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ct.TextRead("loginisnotrunning.txt");
                        Console.ResetColor();
                        break;
                    }
                    ThreadMgr.Stop();
                    loginLoginServer.Stop();
                    break;

                case "exit":
                    Process.GetCurrentProcess().Kill();
                    break;

                case "running":
                    if (loginLoginServer.Running)
                    {
                        //Console.WriteLine("Login Server is running");
                        ct.TextRead("loginisrunning.txt");
                        break;
                    }
                    //Console.WriteLine("Login Server not running");
                    ct.TextRead("loginisnotrunning.txt");
                    break;

                    #region Help Commands....
                case "help":
                    ct.TextRead("logincmdhelp.txt");
                    break;

                case "help start":
                    ct.TextRead("helpstart.txt");
                    break;

                case "help exit":
                    ct.TextRead("helpstop.txt");
                    break;

                case "help running":
                    ct.TextRead("loginhelpcmdrunning.txt");
                    break;

                case "help Adduser":
                    ct.TextRead("logincmdadduserhelp.txt");
                    break;

                case "help setpass":
                    ct.TextRead("logincmdhelpsetpass.txt");
                    break;
                    #endregion

                default:

                    #region Adduser
                    //This section handles the command for adding a user to the database
                    if (consoleCommand.ToLower().StartsWith("adduser"))
                    {
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length < 9)
                        {
                            Console.WriteLine(
                                "Invalid command syntax.\nPlease use:\nAdduser <username> <password> <number of characters> <expansion> <gm level> <email> <FirstName> <LastName>");
                            break;
                        }
                        string username = parts[1];
                        string password = parts[2];
                        int    numChars = 0;
                        try
                        {
                            numChars = int.Parse(parts[3]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <number of characters> must be a number (duh!)");
                            break;
                        }
                        int expansions = 0;
                        try
                        {
                            expansions = int.Parse(parts[4]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }
                        if (expansions < 0 || expansions > 2047)
                        {
                            Console.WriteLine("Error: <expansions> must be a number between 0 and 2047!");
                            break;
                        }

                        int gm = 0;
                        try
                        {
                            gm = int.Parse(parts[5]);
                        }
                        catch
                        {
                            Console.WriteLine("Error: <GM Level> must be number (duh!)");
                            break;
                        }

                        string email = parts[6];
                        if (email == null)
                        {
                            email = String.Empty;
                        }
                        if (!TestEmailRegex(email))
                        {
                            Console.WriteLine("Error: <Email> You must supply an email address for this account");
                            break;
                        }
                        string firstname = parts[7];
                        try
                        {
                            if (firstname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <FirstName> You must supply a first name for this accout");
                            break;
                        }
                        string lastname = parts[8];
                        try
                        {
                            if (lastname == null)
                            {
                                throw new ArgumentNullException();
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Error: <LastName> You must supply a last name for this account");
                            break;
                        }

                        const string FormatString =
                            "INSERT INTO `login` (`CreationDate`, `Flags`,`AccountFlags`,`Username`,`Password`,`Allowed_Characters`,`Expansions`, `GM`, `Email`, `FirstName`, `LastName`) VALUES "
                            + "(NOW(), '0', '0', '{0}', '{1}', {2}, {3}, {4}, '{5}', '{6}', '{7}');";

                        LoginEncryption le = new LoginEncryption();

                        string hashedPassword = le.GeneratePasswordHash(password);

                        string sql = String.Format(
                            FormatString,
                            username,
                            hashedPassword,
                            numChars,
                            expansions,
                            gm,
                            email,
                            firstname,
                            lastname);
                        SqlWrapper sqlWrapper = new SqlWrapper();
                        try
                        {
                            sqlWrapper.SqlInsert(sql);
                        }
                        catch (MySqlException ex)
                        {
                            switch (ex.Number)
                            {
                            case 1062:         //duplicate entry for key
                                Console.WriteLine("A user account with this username already exists.");
                                break;

                            default:
                                Console.WriteLine(
                                    "An error occured while trying to add a new user account:\n{0}", ex.Message);
                                break;
                            }
                            break;
                        }
                        Console.WriteLine("User added successfully.");
                        break;
                    }
                    #endregion

                    #region Hashpass
                    //This function just hashes the string you enter using the loginencryption method
                    if (consoleCommand.ToLower().StartsWith("hash"))
                    {
                        string Syntax =
                            "The Syntax for this command is \"hash <String to hash>\" alphanumeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 2)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }
                        string          pass   = parts[1];
                        LoginEncryption le     = new LoginEncryption();
                        string          hashed = le.GeneratePasswordHash(pass);
                        Console.WriteLine(hashed);
                        break;
                    }
                    #endregion

                    #region setpass
                    //sets the password for the given username
                    //Added by Andyzweb
                    //Still TODO add exception and error handling
                    if (consoleCommand.ToLower().StartsWith("setpass"))
                    {
                        string Syntax =
                            "The syntax for this command is \"setpass <account username> <newpass>\" where newpass is alpha numeric no spaces";
                        string[] parts = consoleCommand.Split(' ');
                        if (parts.Length != 3)
                        {
                            Console.WriteLine(Syntax);
                            break;
                        }
                        string          username = parts[1];
                        string          newpass  = parts[2];
                        LoginEncryption le       = new LoginEncryption();
                        string          hashed   = le.GeneratePasswordHash(newpass);
                        string          formatString;
                        formatString = "UPDATE `login` SET Password = '******' WHERE login.Username = '******'";

                        string sql = String.Format(formatString, hashed, username);

                        SqlWrapper updt = new SqlWrapper();
                        try
                        {
                            updt.SqlUpdate(sql);
                        }
                        //yeah this part here, some kind of exception handling for mysql errors
                        catch
                        {
                        }
                    }
                    #endregion

                    ct.TextRead("login_consolecmdsdefault.txt");
                    break;
                }
            }
            #endregion
        }
Esempio n. 16
0
        /// <summary>
        /// Parse command line arguments, to allow override of some silo runtime config settings.
        /// </summary>
        /// <param name="args">Command line arguments, as received by the Main program.</param>
        /// <returns></returns>
        public bool ParseArguments(string[] args)
        {
            string siloName = Dns.GetHostName(); // Default to machine name

            SiloHost = new SiloHost(siloName);

            int argPos = 1;

            for (int i = 0; i < args.Length; i++)
            {
                string a = args[i];
                if (a.StartsWith("-") || a.StartsWith("/"))
                {
                    switch (a.ToLowerInvariant())
                    {
                    case "/?":
                    case "/help":
                    case "-?":
                    case "-help":
                        // Query usage help
                        return(false);

                    case "/debug":
                        SiloHost.Debug = true;
                        break;

                    default:
                        ConsoleText.WriteError("Bad command line arguments supplied: " + a);
                        return(false);
                    }
                }
                else if (a.Contains("="))
                {
                    string[] split = a.Split('=');
                    if (String.IsNullOrEmpty(split[1]))
                    {
                        ConsoleText.WriteError("Bad command line arguments supplied: " + a);
                        return(false);
                    }
                    switch (split[0].ToLowerInvariant())
                    {
                    case "deploymentid":
                        SiloHost.DeploymentId = split[1];
                        break;

                    case "deploymentgroup":
                        ConsoleText.WriteError("Ignoring deprecated command line argument: " + a);
                        break;

                    default:
                        ConsoleText.WriteError("Bad command line arguments supplied: " + a);
                        return(false);
                    }
                }
                // unqualified arguments below
                else if (argPos == 1)
                {
                    SiloHost.Name = a;
                    argPos++;
                }
                else if (argPos == 2)
                {
                    SiloHost.ConfigFileName = a;
                    argPos++;
                }
                else
                {
                    // Too many command line arguments
                    ConsoleText.WriteError("Too many command line arguments supplied: " + a);
                    return(false);
                }
            }

            return(true);
        }
 public void ACText(string s)
 {
     ConsoleText.AppendText(s);
 }
Esempio n. 18
0
 private void OutputLine(string line)
 {
     ConsoleText.Text += line + "\n";
     ConsoleText.ScrollToEnd();
 }
Esempio n. 19
0
 /// <summary>
 /// Makes errors visible in VS and MSBuild by prefixing error message with "Error"
 /// </summary>
 /// <param name="errorMsg">Error message</param>
 /// <param name="exc">Exception associated with the error</param>
 internal static void ReportError(string errorMsg, Exception exc)
 {
     ConsoleText.WriteError("Error: Orleans code generator found error: " + errorMsg, exc);
 }
Esempio n. 20
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// Program arguments
        /// </param>
        private static void Main(string[] args)
        {
            Console.Title = "CellAO " + AssemblyInfoclass.Title + " Console. Version: " + AssemblyInfoclass.Description
                            + " " + AssemblyInfoclass.AssemblyVersion + " " + AssemblyInfoclass.Trademark;

            ConsoleText ct = new ConsoleText();

            ct.TextRead("main.txt");
            Console.WriteLine("Loading " + AssemblyInfoclass.Title + "...");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Using ISComm v1.0");
            Console.WriteLine("[OK]");
            Console.ResetColor();

            bool       processedArgs = false;
            ChatServer chatServer    = new ChatServer();

            Console.WriteLine("[ISComm] Waiting for link...");

            #region NLog
            LoggingConfiguration config        = new LoggingConfiguration();
            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            FileTarget fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);
            fileTarget.FileName = "${basedir}/ChatEngineLog.txt";
            fileTarget.Layout   = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
            config.LoggingRules.Add(rule1);
            LoggingRule rule2 = new LoggingRule("*", LogLevel.Trace, fileTarget);
            config.LoggingRules.Add(rule2);
            LogManager.Configuration = config;
            #endregion

            #region NBug

            SettingsOverride.LoadCustomSettings("NBug.ChatEngine.Config");
            Settings.WriteLogToDisk = true;
            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;

            // TODO: ADD More Handlers.
            #endregion

            IPAddress localISComm;

            try
            {
                // Local ISComm IP valid?
                localISComm = IPAddress.Parse(Config.Instance.CurrentConfig.ISCommLocalIP);
            }
            catch
            {
                // Fallback to ZoneIP
                localISComm = IPAddress.Parse(Config.Instance.CurrentConfig.ZoneIP);
            }

            if (!ZoneCom.Link(localISComm.ToString(), Config.Instance.CurrentConfig.CommPort, chatServer))
            {
                Console.WriteLine("[ISComm] Unable to link to ZoneEngine. :(");
                return;
            }

            Console.WriteLine("[ISComm] Linked with ZoneEngine! :D");

            chatServer.EnableTCP = true;
            chatServer.EnableUDP = false;

            try
            {
                chatServer.TcpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            try
            {
                chatServer.UdpIP = IPAddress.Parse(Config.Instance.CurrentConfig.ListenIP);
            }
            catch
            {
                ct.TextRead("ip_config_parse_error.txt");
                Console.ReadKey();
                return;
            }

            chatServer.TcpPort = Convert.ToInt32(Config.Instance.CurrentConfig.ChatPort);
            chatServer.MaximumPendingConnections = 100;

            AppDomain.CurrentDomain.UnhandledException += Handler.UnhandledException;
            TaskScheduler.UnobservedTaskException      += Handler.UnobservedTaskException;

            // TODO: ADD More Handlers.

            // Andyzweb: I added checks for if the server is running or not
            // also a command called running that returns the status of the server
            // and added the Console.Write("\nServer Command >>"); to chatserver
            string consoleCommand;
            ct.TextRead("chat_consolecommands.txt");
            while (true)
            {
                if (!processedArgs)
                {
                    if (args.Length == 1)
                    {
                        if (args[0].ToLower() == "/autostart")
                        {
                            ct.TextRead("autostart.txt");
                            ThreadMgr.Start();
                            chatServer.Start();
                        }
                    }

                    processedArgs = true;
                }

                Console.Write("\nServer Command >>");
                consoleCommand = Console.ReadLine();
                switch (consoleCommand.ToLower())
                {
                case "start":
                    if (chatServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Chat Server is already running");
                        Console.ResetColor();
                        break;
                    }

                    ThreadMgr.Start();
                    chatServer.Start();
                    break;

                case "stop":
                    if (!chatServer.Running)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Chat Server is not running");
                        Console.ResetColor();
                        break;
                    }

                    ThreadMgr.Stop();
                    chatServer.Stop();
                    break;

                case "exit":
                    Process.GetCurrentProcess().Kill();
                    break;

                case "running":
                    if (chatServer.Running)
                    {
                        Console.WriteLine("Chat Server is Running");
                        break;
                    }

                    Console.WriteLine("Chat Server not Running");
                    break;

                default:
                    ct.TextRead("chat_consolecmdsdefault.txt");
                    break;
                }
            }
        }
Esempio n. 21
0
        public int RunMain(string[] args)
        {
            ConsoleText.WriteStatus("Orleans-CodeGen - command-line = {0}", Environment.CommandLine);

            if (args.Length < 1)
            {
                PrintUsage();

                return(1);
            }

            try
            {
                var options = new CodeGenOptions();

                // STEP 1 : Parse parameters
                if (args.Length == 1 && args[0].StartsWith("@"))
                {
                    // Read command line args from file
                    string arg      = args[0];
                    string argsFile = arg.Trim('"').Substring(1).Trim('"');
                    Console.WriteLine("Orleans-CodeGen - Reading code-gen params from file={0}", argsFile);
                    AssertWellFormed(argsFile, true);
                    args = File.ReadAllLines(argsFile);
                }
                int i = 1;
                foreach (string a in args)
                {
                    string arg = a.Trim('"').Trim().Trim('"');
                    if (GrainClientGeneratorFlags.Verbose)
                    {
                        Console.WriteLine("Orleans-CodeGen - arg #{0}={1}", i++, arg);
                    }
                    if (string.IsNullOrEmpty(arg) || string.IsNullOrWhiteSpace(arg))
                    {
                        continue;
                    }

                    if (arg.StartsWith("/"))
                    {
                        if (arg.StartsWith("/reference:") || arg.StartsWith("/r:"))
                        {
                            // list of references passed from from project file. separator =';'
                            string   refstr     = arg.Substring(arg.IndexOf(':') + 1);
                            string[] references = refstr.Split(';');
                            foreach (string rp in references)
                            {
                                AssertWellFormed(rp, true);
                                options.ReferencedAssemblies.Add(rp);
                            }
                        }
                        else if (arg.StartsWith("/in:"))
                        {
                            var infile = arg.Substring(arg.IndexOf(':') + 1);
                            AssertWellFormed(infile);
                            options.InputAssembly = new FileInfo(infile);
                        }
                        else if (arg.StartsWith("/out:"))
                        {
                            var outfile = arg.Substring(arg.IndexOf(':') + 1);
                            AssertWellFormed(outfile, false);
                            options.OutputFileName = outfile;
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Invalid argument: {arg}.");

                        PrintUsage();

                        return(1);
                    }
                }

                // STEP 2 : Validate and calculate unspecified parameters
                if (options.InputAssembly == null)
                {
                    Console.WriteLine("ERROR: Orleans-CodeGen - no input file specified.");
                    return(2);
                }

                if (String.IsNullOrEmpty(options.OutputFileName))
                {
                    Console.WriteLine("ERROR: Orleans-Codegen - no output filename specified");
                    return(2);
                }

                // STEP 3 : Dump useful info for debugging
                Console.WriteLine($"Orleans-CodeGen - Options {Environment.NewLine}\tInputLib={options.InputAssembly.FullName}{Environment.NewLine}\tOutputFileName={options.OutputFileName}");

                if (options.ReferencedAssemblies != null)
                {
                    Console.WriteLine("Orleans-CodeGen - Using referenced libraries:");
                    foreach (string assembly in options.ReferencedAssemblies)
                    {
                        Console.WriteLine("\t{0} => {1}", Path.GetFileName(assembly), assembly);
                    }
                }

                // STEP 5 : Finally call code generation
                if (!CreateGrainClientAssembly(options))
                {
                    return(-1);
                }

                // DONE!
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("-- Code-gen FAILED -- \n{0}", LogFormatter.PrintException(ex));
                return(3);
            }
        }
Esempio n. 22
0
 internal static void Init()
 {
     ConsoleText.WriteStatus("Initializing serializer generation manager");
     typesToProcess = new HashSet <Type>();
     processedTypes = new HashSet <Type>();
 }
Esempio n. 23
0
 private static void ReportErrorAndThrow(string errorMsg)
 {
     ConsoleText.WriteError("Orleans code generator found error: " + errorMsg);
     throw new OrleansException(errorMsg);
 }
Esempio n. 24
0
        internal static void RecordTypeToGenerate(Type t)
        {
            if (t.IsGenericParameter || processedTypes.Contains(t) || typesToProcess.Contains(t) ||
                typeof(Exception).IsAssignableFrom(t))
            {
                return;
            }

            if (t.IsArray)
            {
                RecordTypeToGenerate(t.GetElementType());
                return;
            }

            if (t.IsNestedPublic || t.IsNestedFamily || t.IsNestedPrivate)
            {
                Console.WriteLine("Skipping serializer generation for nested type {0}. If this type is used frequently, you may wish to consider making it non-nested.", t.Name);
            }

            if (t.IsGenericType)
            {
                var args = t.GetGenericArguments();
                foreach (var arg in args)
                {
                    if (!arg.IsGenericParameter)
                    {
                        RecordTypeToGenerate(arg);
                    }
                }
            }

            if (t.IsInterface || t.IsAbstract || t.IsEnum || t == typeof(object) || t == typeof(void) ||
                GrainInterfaceData.IsTaskType(t))
            {
                return;
            }

            if (t.IsGenericType)
            {
                var def = t.GetGenericTypeDefinition();
                if (def == typeof(Task <>) || (SerializationManager.GetSerializer(def) != null) ||
                    processedTypes.Contains(def) || typeof(IAddressable).IsAssignableFrom(def))
                {
                    return;
                }

                if (def.Namespace.Equals("System") || def.Namespace.StartsWith("System."))
                {
                    ConsoleText.WriteWarning("System type " + def.Name + " requires a serializer.");
                }
                else
                {
                    typesToProcess.Add(def);
                }

                return;
            }

            if (t.IsOrleansPrimitive() || (SerializationManager.GetSerializer(t) != null) ||
                typeof(IAddressable).IsAssignableFrom(t))
            {
                return;
            }

            bool isSystemType = t.Namespace != null && (t.Namespace.Equals("System") || t.Namespace.StartsWith("System."));

            if (isSystemType)
            {
                ConsoleText.WriteWarning("System type " + t.Name + " may require a custom serializer for optimal performance. " +
                                         "If you use arguments of this type a lot, consider asking the Orleans team to build a custom serializer for it.");
                return;
            }

            if (t.IsArray)
            {
                RecordTypeToGenerate(t.GetElementType());
                return;
            }

            bool hasCopier       = false;
            bool hasSerializer   = false;
            bool hasDeserializer = false;

            foreach (var method in t.GetMethods(BindingFlags.Static | BindingFlags.Public))
            {
                if (method.GetCustomAttributes(typeof(SerializerMethodAttribute), false).Length > 0)
                {
                    hasSerializer = true;
                }
                else if (method.GetCustomAttributes(typeof(DeserializerMethodAttribute), false).Length > 0)
                {
                    hasDeserializer = true;
                }

                if (method.GetCustomAttributes(typeof(CopierMethodAttribute), false).Length > 0)
                {
                    hasCopier = true;
                }
            }
            if (hasCopier && hasSerializer && hasDeserializer)
            {
                return;
            }

            typesToProcess.Add(t);
        }
Esempio n. 25
0
        public int RunMain(string[] args)
        {
            ConsoleText.WriteStatus("Orleans-CodeGen - command-line = {0}", Environment.CommandLine);

            if (args.Length < 1)
            {
                Console.WriteLine(
                    "Usage: ClientGenerator.exe <grain interface dll path> [<client dll path>] [<key file>] [<referenced assemblies>]");
                Console.WriteLine(
                    "       ClientGenerator.exe /server <grain dll path> [<factory dll path>] [<key file>] [<referenced assemblies>]");
                return(1);
            }

            try
            {
                var options = new CodeGenOptions();

                // STEP 1 : Parse parameters
                if (args.Length == 1 && args[0].StartsWith("@"))
                {
                    // Read command line args from file
                    string arg      = args[0];
                    string argsFile = arg.Trim('"').Substring(1).Trim('"');
                    Console.WriteLine("Orleans-CodeGen - Reading code-gen params from file={0}", argsFile);
                    AssertWellFormed(argsFile, true);
                    args = File.ReadAllLines(argsFile);
                }
                int i = 1;
                foreach (string a in args)
                {
                    string arg = a.Trim('"').Trim().Trim('"');
                    if (GrainClientGeneratorFlags.Verbose)
                    {
                        Console.WriteLine("Orleans-CodeGen - arg #{0}={1}", i++, arg);
                    }
                    if (string.IsNullOrEmpty(arg) || string.IsNullOrWhiteSpace(arg))
                    {
                        continue;
                    }

                    if (arg.StartsWith("/"))
                    {
                        if (arg.StartsWith("/reference:") || arg.StartsWith("/r:"))
                        {
                            // list of references passed from from project file. separator =';'
                            string   refstr     = arg.Substring(arg.IndexOf(':') + 1);
                            string[] references = refstr.Split(';');
                            foreach (string rp in references)
                            {
                                AssertWellFormed(rp, true);
                                options.ReferencedAssemblies.Add(rp);
                            }
                        }
                        else if (arg.StartsWith("/in:"))
                        {
                            var infile = arg.Substring(arg.IndexOf(':') + 1);
                            AssertWellFormed(infile);
                            options.InputLib = new FileInfo(infile);
                        }
                        else if (arg.StartsWith("/bootstrap") || arg.StartsWith("/boot"))
                        {
                            // special case for building circular dependecy in preprocessing:
                            // Do not build the input assembly, assume that some other build step
                            options.CodeGenFile = Path.GetFullPath(CodeGenFileRelativePathCSharp);
                            if (GrainClientGeneratorFlags.Verbose)
                            {
                                Console.WriteLine(
                                    "Orleans-CodeGen - Set CodeGenFile={0} from bootstrap",
                                    options.CodeGenFile);
                            }
                        }
                        else if (arg.StartsWith("/sources:") || arg.StartsWith("/src:"))
                        {
                            var sourcesStr = arg.Substring(arg.IndexOf(':') + 1);

                            string[] sources = sourcesStr.Split(';');
                            foreach (var source in sources)
                            {
                                HandleSourceFile(source, options);
                            }
                        }
                    }
                    else
                    {
                        HandleSourceFile(arg, options);
                    }
                }

                if (options.TargetLanguage != Language.CSharp)
                {
                    ConsoleText.WriteLine(
                        "ERROR: Compile-time code generation is supported for C# only. "
                        + "Remove code generation from your project in order to use run-time code generation.");
                    return(2);
                }

                // STEP 2 : Validate and calculate unspecified parameters
                if (options.InputLib == null)
                {
                    Console.WriteLine("ERROR: Orleans-CodeGen - no input file specified.");
                    return(2);
                }

                if (string.IsNullOrEmpty(options.CodeGenFile))
                {
                    Console.WriteLine(
                        "ERROR: No codegen file. Add a file '{0}' to your project",
                        Path.Combine("Properties", "orleans.codegen.cs"));
                    return(2);
                }

                options.SourcesDir = Path.Combine(options.InputLib.DirectoryName, "Generated");

                // STEP 3 : Dump useful info for debugging
                Console.WriteLine(
                    "Orleans-CodeGen - Options " + Environment.NewLine + "\tInputLib={0} " + Environment.NewLine
                    + "\tCodeGenFile={1}",
                    options.InputLib.FullName,
                    options.CodeGenFile);

                if (options.ReferencedAssemblies != null)
                {
                    Console.WriteLine("Orleans-CodeGen - Using referenced libraries:");
                    foreach (string assembly in options.ReferencedAssemblies)
                    {
                        Console.WriteLine("\t{0} => {1}", Path.GetFileName(assembly), assembly);
                    }
                }

                // STEP 5 : Finally call code generation
                if (!CreateGrainClientAssembly(options))
                {
                    return(-1);
                }

                // DONE!
                return(0);
            }
            catch (Exception ex)
            {
                File.WriteAllText("error.txt", ex.Message + Environment.NewLine + ex.StackTrace);
                Console.WriteLine("-- Code-gen FAILED -- \n{0}", LogFormatter.PrintException(ex));
                return(3);
            }
        }
Esempio n. 26
0
        public int RunMain(string[] args)
        {
            ConsoleText.WriteStatus("Orleans-CodeGen - command-line = {0}", Environment.CommandLine);

            if (args.Length < 1)
            {
                Console.WriteLine(
                    "Usage: ClientGenerator.exe <grain interface dll path> [<client dll path>] [<key file>] [<referenced assemblies>]");
                Console.WriteLine(
                    "       ClientGenerator.exe /server <grain dll path> [<factory dll path>] [<key file>] [<referenced assemblies>]");
                return(1);
            }

            try
            {
                var options = new CodeGenOptions();

                // STEP 1 : Parse parameters
                if (args.Length == 1 && args[0].StartsWith("@"))
                {
                    // Read command line args from file
                    string arg      = args[0];
                    string argsFile = arg.Trim('"').Substring(1).Trim('"');
                    Console.WriteLine("Orleans-CodeGen - Reading code-gen params from file={0}", argsFile);
                    AssertWellFormed(argsFile, true);
                    args = File.ReadAllLines(argsFile);
                }
                int i = 1;
                foreach (string a in args)
                {
                    string arg = a.Trim('"').Trim().Trim('"');
                    if (GrainClientGeneratorFlags.Verbose)
                    {
                        Console.WriteLine("Orleans-CodeGen - arg #{0}={1}", i++, arg);
                    }
                    if (string.IsNullOrEmpty(arg) || string.IsNullOrWhiteSpace(arg))
                    {
                        continue;
                    }

                    if (arg.StartsWith("/"))
                    {
                        if (arg.StartsWith("/reference:") || arg.StartsWith("/r:"))
                        {
                            // list of references passed from from project file. separator =';'
                            string   refstr     = arg.Substring(arg.IndexOf(':') + 1);
                            string[] references = refstr.Split(';');
                            foreach (string rp in references)
                            {
                                AssertWellFormed(rp, true);
                                options.ReferencedAssemblies.Add(rp);
                            }
                        }
                        else if (arg.StartsWith("/cwd:"))
                        {
                            options.WorkingDirectory = arg.Substring(arg.IndexOf(':') + 1);
                        }
                        else if (arg.StartsWith("/in:"))
                        {
                            var infile = arg.Substring(arg.IndexOf(':') + 1);
                            AssertWellFormed(infile);
                            options.InputLib = new FileInfo(infile);
                        }
                        else if (arg.StartsWith("/keyfile:") || arg.StartsWith("/key:"))
                        {
                            string keyFile = arg.Substring(arg.IndexOf(':') + 1);
                            if (!string.IsNullOrWhiteSpace(keyFile))
                            {
                                AssertWellFormed(keyFile, true);
                                options.SigningKey = new FileInfo(keyFile);
                            }
                        }
                        else if (arg.StartsWith("/config:"))
                        {
                            options.Config = arg.Substring(arg.IndexOf(':') + 1);
                        }
                        else if (arg.StartsWith("/fsharp:"))
                        {
                            var path = arg.Substring(arg.IndexOf(':') + 1);
                            if (!string.IsNullOrEmpty(path))
                            {
                                Console.WriteLine("F# compiler path = '{0}' ", path);
                                options.FSharpCompilerPath = path;
                            }
                            else
                            {
                                Console.WriteLine("F# compiler path not set.");
                            }
                        }
                        else if (arg.StartsWith("/rootns:") || arg.StartsWith("/rns:"))
                        {
                            options.RootNamespace = arg.Substring(arg.IndexOf(':') + 1);
                        }
                        else if (arg.StartsWith("/bootstrap") || arg.StartsWith("/boot"))
                        {
                            // special case for building circular dependecy in preprocessing:
                            // Do not build the input assembly, assume that some other build step
                            options.CodeGenFile = Path.GetFullPath(CodeGenFileRelativePathCSharp);
                            if (GrainClientGeneratorFlags.Verbose)
                            {
                                Console.WriteLine(
                                    "Orleans-CodeGen - Set CodeGenFile={0} from bootstrap",
                                    options.CodeGenFile);
                            }
                        }
                        else if (arg.StartsWith("/define:") || arg.StartsWith("/d:"))
                        {
                            // #define constants passed from project file. separator =';'
                            var definsStr = arg.Substring(arg.IndexOf(':') + 1);

                            if (!string.IsNullOrWhiteSpace(definsStr))
                            {
                                string[] defines = definsStr.Split(';');
                                foreach (var define in defines)
                                {
                                    options.Defines.Add(define);
                                }
                            }
                        }
                        else if (arg.StartsWith("/imports:") || arg.StartsWith("/i:"))
                        {
                            // Standard VB imports passed from project file. separator =';'
                            string importsStr = arg.Substring(arg.IndexOf(':') + 1);

                            if (!string.IsNullOrWhiteSpace(importsStr))
                            {
                                string[] imports = importsStr.Split(';');
                                foreach (var import in imports)
                                {
                                    options.Imports.Add(import);
                                }
                            }
                        }
                        else if (arg.StartsWith("/Option")) // VB-specific options
                        {
                            if (arg.StartsWith("/OptionExplicit:"))
                            {
                                options.OptionExplicit = arg.Substring(arg.IndexOf(':') + 1);
                            }
                            else if (arg.StartsWith("/OptionStrict:"))
                            {
                                options.OptionStrict = arg.Substring(arg.IndexOf(':') + 1);
                            }
                            else if (arg.StartsWith("/OptionInfer:"))
                            {
                                options.OptionInfer = arg.Substring(arg.IndexOf(':') + 1);
                            }
                            else if (arg.StartsWith("/OptionCompare:"))
                            {
                                options.OptionCompare = arg.Substring(arg.IndexOf(':') + 1);
                            }
                        }
                        else if (arg.StartsWith("/MyType:")) // VB-specific option
                        {
                            options.MyType = arg.Substring(arg.IndexOf(':') + 1);
                        }
                        else if (arg.StartsWith("/sources:") || arg.StartsWith("/src:"))
                        {
                            // C# sources passed from from project file. separator = ';'
                            //if (GrainClientGeneratorFlags.Verbose)
                            //    Console.WriteLine("Orleans-CodeGen - Unpacking source file list arg={0}", arg);

                            var sourcesStr = arg.Substring(arg.IndexOf(':') + 1);
                            //if (GrainClientGeneratorFlags.Verbose)
                            //    Console.WriteLine("Orleans-CodeGen - Splitting source file list={0}", sourcesStr);

                            string[] sources = sourcesStr.Split(';');
                            foreach (var source in sources)
                            {
                                AddSourceFile(
                                    options.SourceFiles,
                                    ref options.LanguageConflict,
                                    ref options.TargetLanguage,
                                    ref options.CodeGenFile,
                                    source);
                            }
                        }
                    }
                    else
                    {
                        // files passed in without associated flags , we'll make the best guess.
                        if (arg.ToLowerInvariant().EndsWith(".snk", StringComparison.InvariantCultureIgnoreCase))
                        {
                            options.SigningKey = new FileInfo(arg);
                        }
                        else
                        {
                            AddSourceFile(
                                options.SourceFiles,
                                ref options.LanguageConflict,
                                ref options.TargetLanguage,
                                ref options.CodeGenFile,
                                arg);
                        }
                    }
                }

                if (!options.TargetLanguage.HasValue)
                {
                    Console.WriteLine("ERROR: Unable to determine source code language to use for code generation.");
                    return(2);
                }

                // STEP 2 : Validate and calculate unspecified parameters
                if (options.InputLib == null)
                {
                    Console.WriteLine("ERROR: Orleans-CodeGen - no input file specified.");
                    return(2);
                }

                if (string.IsNullOrEmpty(options.CodeGenFile))
                {
                    Console.WriteLine(
                        "ERROR: No codegen file. Add a file '{0}' to your project",
                        Path.Combine("Properties", "orleans.codegen.cs"));
                    return(2);
                }

                // STEP 3 :  Check timestamps and skip if output is up-to-date wrt to all inputs

/*                if (!bootstrap && IsProjectUpToDate(options.InputLib, options.SourceFiles, options.ReferencedAssemblies)
 *                  && !Debugger.IsAttached)
 *              {
 *                  Console.WriteLine(
 *                      "Orleans-CodeGen - Skipping because all output files are up-to-date with respect to the input files.");
 *                  return 0;
 *              }*/

                options.SourcesDir = Path.Combine(options.InputLib.DirectoryName, "Generated");

                // STEP 4 : Dump useful info for debugging
                Console.WriteLine(
                    "Orleans-CodeGen - Options " + Environment.NewLine + "\tInputLib={0} " + Environment.NewLine
                    + "\tSigningKey={1} " + Environment.NewLine
                    + "\tCodeGenFile={2}",
                    options.InputLib.FullName,
                    options.SigningKey != null ? options.SigningKey.FullName : "",
                    options.CodeGenFile);

                if (options.ReferencedAssemblies != null)
                {
                    Console.WriteLine("Orleans-CodeGen - Using referenced libraries:");
                    foreach (string assembly in options.ReferencedAssemblies)
                    {
                        Console.WriteLine("\t{0} => {1}", Path.GetFileName(assembly), assembly);
                    }
                }

                // STEP 5 :
//                if (!bootstrap) BuildInputAssembly(options);

                // STEP 6 : Finally call code generation
                if (!CreateGrainClientAssembly(options))
                {
                    return(-1);
                }

                // DONE!
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("-- Code-gen FAILED -- \n{0}", TraceLogger.PrintException(ex));
                return(3);
            }
        }
Esempio n. 27
0
        private bool CollectCompletionList(ConsoleText line, int cursorIndex)
        {
            var text   = line.ToString();
            var lexer  = new Lexer(text, options: _lexerOptions);
            var tokens = lexer.ToList();

            // Find that we are in a correct place
            var index = FindTokenIndexFromColumnIndex(cursorIndex, text.Length, tokens);

            if (index >= 0)
            {
                // If we are in the middle of a comment/integer/float/string
                // we don't expect to make any completion
                var token = tokens[index];
                switch (token.Type)
                {
                case TokenType.Comment:
                case TokenType.CommentMulti:
                case TokenType.Identifier:
                case TokenType.IdentifierSpecial:
                case TokenType.Integer:
                case TokenType.HexaInteger:
                case TokenType.BinaryInteger:
                case TokenType.Float:
                case TokenType.String:
                case TokenType.ImplicitString:
                case TokenType.VerbatimString:
                    return(false);
                }
            }

            // Look for the start of the work to complete
            _startIndexForCompletion = cursorIndex - 1;
            while (_startIndexForCompletion >= 0)
            {
                var c = text[_startIndexForCompletion];
                if (!IsIdentifierLetter(c))
                {
                    break;
                }

                _startIndexForCompletion--;
            }
            _startIndexForCompletion++;

            if (!IsFirstIdentifierLetter(text[_startIndexForCompletion]))
            {
                return(false);
            }

            var startTextToFind = text.Substring(_startIndexForCompletion, cursorIndex - _startIndexForCompletion);

            Collect(startTextToFind, ScriptKeywords, _completionMatchingList);
            Collect(startTextToFind, ValueKeywords, _completionMatchingList);
            Collect(startTextToFind, Variables.Keys, _completionMatchingList);
            Collect(startTextToFind, Builtins.Keys, _completionMatchingList);

            // If we are not able to match anything from builtin and user variables/functions
            // continue on units
            if (_completionMatchingList.Count == 0)
            {
                Collect(startTextToFind, Units.Keys, _completionMatchingList);
            }
            return(true);
        }
Esempio n. 28
0
        /// <summary>
        /// Generates a syntax tree for the provided assemblies.
        /// </summary>
        /// <param name="assemblies">The assemblies to generate code for.</param>
        /// <param name="runtime">Whether or not runtime code generation is being performed.</param>
        /// <returns>The generated syntax tree.</returns>
        private static GeneratedSyntax GenerateForAssemblies(List <Assembly> assemblies, bool runtime)
        {
            if (Logger.IsVerbose)
            {
                Logger.Verbose(
                    "Generating code for assemblies: {0}",
                    string.Join(", ", assemblies.Select(_ => _.FullName)));
            }

            Assembly       targetAssembly;
            HashSet <Type> ignoredTypes;

            if (runtime)
            {
                // Ignore types which have already been accounted for.
                ignoredTypes   = GetTypesWithGeneratedSupportClasses();
                targetAssembly = null;
            }
            else
            {
                ignoredTypes   = new HashSet <Type>();
                targetAssembly = assemblies.FirstOrDefault();
            }

            var members = new List <MemberDeclarationSyntax>();

            // If any KnownAssemblies have been specified, include them during code generation.
            var knownAssemblies =
                assemblies.SelectMany(_ => _.GetCustomAttributes <KnownAssemblyAttribute>())
                .Select(_ => _.Assembly)
                .Distinct()
                .ToSet();

            if (knownAssemblies.Count > 0)
            {
                knownAssemblies.UnionWith(assemblies);
                assemblies = knownAssemblies.ToList();
            }

            // Get types from assemblies which reference Orleans and are not generated assemblies.
            var includedTypes = new HashSet <Type>();

            for (var i = 0; i < assemblies.Count; i++)
            {
                var assembly = assemblies[i];
                foreach (var attribute in assembly.GetCustomAttributes <KnownTypeAttribute>())
                {
                    ConsiderType(attribute.Type, runtime, targetAssembly, includedTypes);
                }

                foreach (var type in assembly.DefinedTypes)
                {
                    ConsiderType(type, runtime, targetAssembly, includedTypes);
                }
            }

            includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_));

            // Group the types by namespace and generate the required code in each namespace.
            foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_)))
            {
                var namespaceMembers = new List <MemberDeclarationSyntax>();
                foreach (var type in group)
                {
                    // The module containing the serializer.
                    var module = runtime ? null : type.Module;

                    // Every type which is encountered must be considered for serialization.
                    Action <Type> onEncounteredType = encounteredType =>
                    {
                        // If a type was encountered which can be accessed, process it for serialization.
                        SerializerGenerationManager.RecordTypeToGenerate(encounteredType, module, targetAssembly);
                    };

                    if (Logger.IsVerbose2)
                    {
                        Logger.Verbose2("Generating code for: {0}", type.GetParseableName());
                    }

                    if (GrainInterfaceData.IsGrainInterface(type))
                    {
                        if (Logger.IsVerbose2)
                        {
                            Logger.Verbose2(
                                "Generating GrainReference and MethodInvoker for {0}",
                                type.GetParseableName());
                        }

                        GrainInterfaceData.ValidateInterfaceRules(type);

                        namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, onEncounteredType));
                        namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type));
                    }

                    // Generate serializers.
                    var  first = true;
                    Type toGen;
                    while (SerializerGenerationManager.GetNextTypeToProcess(out toGen))
                    {
                        if (!runtime)
                        {
                            if (first)
                            {
                                ConsoleText.WriteStatus("ClientGenerator - Generating serializer classes for types:");
                                first = false;
                            }

                            ConsoleText.WriteStatus(
                                "\ttype " + toGen.FullName + " in namespace " + toGen.Namespace
                                + " defined in Assembly " + toGen.Assembly.GetName());
                        }

                        if (Logger.IsVerbose2)
                        {
                            Logger.Verbose2(
                                "Generating & Registering Serializer for Type {0}",
                                toGen.GetParseableName());
                        }

                        namespaceMembers.AddRange(SerializerGenerator.GenerateClass(toGen, onEncounteredType));
                    }
                }

                if (namespaceMembers.Count == 0)
                {
                    if (Logger.IsVerbose)
                    {
                        Logger.Verbose2("Skipping namespace: {0}", group.Key);
                    }

                    continue;
                }

                members.Add(
                    SF.NamespaceDeclaration(SF.ParseName(group.Key))
                    .AddUsings(
                        TypeUtils.GetNamespaces(typeof(TaskUtility), typeof(GrainExtensions))
                        .Select(_ => SF.UsingDirective(SF.ParseName(_)))
                        .ToArray())
                    .AddMembers(namespaceMembers.ToArray()));
            }

            return(new GeneratedSyntax
            {
                SourceAssemblies = assemblies,
                Syntax = members.Count > 0 ? SF.CompilationUnit().AddMembers(members.ToArray()) : null
            });
        }
Esempio n. 29
0
 public void addKey()
 {
     keys++;
     keyText.text = "x" + keys;
     ConsoleText.getInstance().ShowMessage("Single use keycard acquired");
 }
 private void MenuItem_ClearConsole_Click(object sender, RoutedEventArgs e)
 {
     ConsoleText.Clear();
 }