internal sealed override bool OnTryRead(ref BinaryReader reader, Type typeToConvert, BinarySerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out T value)
        {
            object        obj;
            ArgumentState argumentState = state.Current.CtorArgumentState !;


            if (state.Current.ObjectState == StackFrameObjectState.None)
            {
                if (!reader.ReadStartToken())
                {
                    value = default;
                    return(false);
                }
                RefState refState = BinarySerializer.ReadReferenceForObject(this, ref state, ref reader, out object refValue);
                if (refState == RefState.None)
                {
                    state.Current.ObjectState = StackFrameObjectState.StartToken;
                    BeginRead(ref state, ref reader, options);
                    // 初始化中可能会修改状态对象
                    argumentState = state.Current.CtorArgumentState !;
                }
                else
                {
                    state.Current.ObjectState = StackFrameObjectState.CreatedObject;
                    state.Current.ReturnValue = refValue;
                    state.Current.RefState    = refState;
                }
            }

            // 读取构造参数
            if (!ReadConstructorArgumentsWithContinuation(ref state, ref reader, options))
            {
                value = default;
                return(false);
            }
            if (state.Current.ObjectState < StackFrameObjectState.CreatedObject)
            {
                obj = CreateObject(ref state.Current);
                state.ReferenceResolver.AddReferenceObject(state.Current.RefId, obj);
            }
            else
            {
                obj = state.Current.ReturnValue;
            }

            if (argumentState.FoundPropertyCount > 0)
            {
                for (int i = 0; i < argumentState.FoundPropertyCount; i++)
                {
                    BinaryPropertyInfo binaryPropertyInfo = argumentState.FoundPropertiesAsync ![i].Item1;
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Program"/> class.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        private Program(string[] args)
        {
            this.InputFilePath   = string.Empty;
            this.TargetNamespace = "DefaultNamespace";

            // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has been parsed, the command line
            // parser assumes that it's reading the file name from the command line.
            ArgumentState argumentState = ArgumentState.InputFileName;

            // Parse the command line for arguments.
            foreach (string argument in args)
            {
                // Use the dictionary to transition from one state to the next based on the input parameters.
                ArgumentState nextArgumentState;
                if (Program.argumentStates.TryGetValue(argument, out nextArgumentState))
                {
                    argumentState = nextArgumentState;
                    continue;
                }

                // The parsing state will determine which variable is read next.
                switch (argumentState)
                {
                case ArgumentState.InputFileName:

                    // Expand the environment variables so that paths don't need to be absolute.
                    this.InputFilePath = Environment.ExpandEnvironmentVariables(argument);

                    // The output name defaults to the input file name with a new extension.
                    this.OutputFilePath = string.Format("{0}.cs", Path.GetFileNameWithoutExtension(this.InputFilePath));

                    break;

                case ArgumentState.OutputFileName:

                    // Expand the environment variables so that paths don't need to be absolute.
                    this.OutputFilePath = Environment.ExpandEnvironmentVariables(argument);
                    break;

                case ArgumentState.TargetNamespace:

                    // This is the namespace that is used to create the target data model.
                    this.TargetNamespace = argument;
                    break;
                }

                // The default state is to look for the input file name on the command line.
                argumentState = ArgumentState.InputFileName;
            }
        }
Example #3
0
        static int Main(string[] args)
        {
            // If this flag is set during the processing of the file, the program will exit with an error code.
            bool hasErrors = false;

            try
            {
                // Defaults
                batchSize     = 100;
                assemblyName  = "External Service";
                nameSpaceName = "MarkThree.Quasar.External";

                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has been
                // read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.FileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    if (argument == "-a")
                    {
                        argumentState = ArgumentState.Assembly; continue;
                    }
                    if (argument == "-b")
                    {
                        argumentState = ArgumentState.BatchSize; continue;
                    }
                    if (argument == "-n")
                    {
                        argumentState = ArgumentState.NameSpace; continue;
                    }
                    if (argument == "-i")
                    {
                        argumentState = ArgumentState.FileName; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.Assembly:
                        assemblyName = argument;
                        break;

                    case ArgumentState.BatchSize:
                        batchSize = Convert.ToInt32(argument);
                        break;

                    case ArgumentState.FileName:
                        fileName = argument;
                        break;

                    case ArgumentState.NameSpace:
                        nameSpaceName = argument;
                        break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.FileName;
                }

                // Throw a usage message back at the user if no file name was given.
                if (fileName == null)
                {
                    throw new Exception("Usage: Loader.Algorithm -i <FileName>");
                }

                // Open up the file containing all the broker.
                BrokerReader brokerReader = new BrokerReader(fileName);

                // Loading the database involves creating a batch of commands and sending them off as a transaction.  This gives
                // the server a chance to pipeline a large chunk of processing, without completely locking up the server for the
                // entire set of data.  This will construct a header for the command batch which gives information about which
                // assembly contains the class that is used to load the data.
                Batch           batch           = new Batch();
                TransactionPlan transactionPlan = batch.Transactions.Add();
                AssemblyPlan    assemblyPlan    = batch.Assemblies.Add(assemblyName);
                TypePlan        typePlan        = assemblyPlan.Types.Add(string.Format("{0}.{1}", nameSpaceName, "Broker"));

                // Read the file until an EOF is reached.
                while (true)
                {
                    // This counter keeps track of the number of records sent.  When the batch is full, it's sent to the server to be
                    // executed as a single transaction.
                    int batchCounter = 0;

                    // Read the next broker from the input stream.  A 'null' is returned when we've read past the end of file.
                    Broker broker = brokerReader.ReadBroker();
                    if (broker != null)
                    {
                        // Create a new method from the type information and the name found in the XML file.
                        MethodPlan methodPlan = new MethodPlan("Load");

                        // Construct a call to the 'Load' method to populate the broker record.
                        methodPlan.Parameters.Add(new InputParameter("brokerId", broker.Symbol));
                        methodPlan.Parameters.Add(new InputParameter("name", broker.Name));
                        methodPlan.Parameters.Add(new InputParameter("symbol", broker.Symbol));

                        // Create a method from the XML data and add it to the transaction.
                        transactionPlan.Methods.Add(typePlan, methodPlan);
                    }

                    // This will check to see if it's time to send the batch.  A batch is sent when the 'batchSize' has been
                    // reached, or if the last record has just been converted into a command.
                    if (++batchCounter % batchSize == 0 || broker == null)
                    {
                        WebTransactionProtocol.Execute(batch);

                        batch           = new Batch();
                        transactionPlan = batch.Transactions.Add();
                        assemblyPlan    = batch.Assemblies.Add(assemblyName);
                        typePlan        = assemblyPlan.Types.Add(string.Format("{0}.{1}", nameSpaceName, "Broker"));
                    }

                    // If the end of file was reached, break out of the loop and exit the application.
                    if (broker == null)
                    {
                        break;
                    }
                }
            }
            catch (BatchException batchException)
            {
                foreach (Exception exception in batchException.Exceptions)
                {
                    Console.WriteLine(exception.Message);
                }
                hasErrors = true;
            }
            catch (Exception exception)
            {
                // Show the system error and exit with an error.
                Console.WriteLine(exception.Message);
                hasErrors = true;
            }

            // Any errors will cause an abnormal exit.
            if (hasErrors)
            {
                return(1);
            }

            // Write a status message when a the file is loaded successfully.
            Console.WriteLine(String.Format("{0} Data: Brokers, Loaded", DateTime.Now.ToString("u")));

            // If we reached here, the file was imported without issue.
            return(0);
        }
        internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out T value)
        {
            JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo;

            if (jsonTypeInfo.CreateObject != null)
            {
                // Contract customization: fall back to default object converter if user has set a default constructor delegate.
                return(base.OnTryRead(ref reader, typeToConvert, options, ref state, out value));
            }

            object        obj;
            ArgumentState argumentState = state.Current.CtorArgumentState !;

            if (!state.SupportContinuation && !state.Current.CanContainMetadata)
            {
                // Fast path that avoids maintaining state variables.

                if (reader.TokenType != JsonTokenType.StartObject)
                {
                    ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert);
                }

                ReadOnlySpan <byte> originalSpan = reader.OriginalSpan;

                ReadConstructorArguments(ref state, ref reader, options);

                obj = (T)CreateObject(ref state.Current);

                jsonTypeInfo.OnDeserializing?.Invoke(obj);

                if (argumentState.FoundPropertyCount > 0)
                {
                    Utf8JsonReader tempReader;

                    FoundProperty[]? properties = argumentState.FoundProperties;
                    Debug.Assert(properties != null);

                    for (int i = 0; i < argumentState.FoundPropertyCount; i++)
                    {
                        JsonPropertyInfo jsonPropertyInfo    = properties[i].Item1;
                        long             resumptionByteIndex = properties[i].Item3;
                        byte[]? propertyNameArray = properties[i].Item4;
                        string?dataExtKey = properties[i].Item5;

                        tempReader = new Utf8JsonReader(
                            originalSpan.Slice(checked ((int)resumptionByteIndex)),
                            isFinalBlock: true,
                            state: properties[i].Item2);

                        Debug.Assert(tempReader.TokenType == JsonTokenType.PropertyName);

                        state.Current.JsonPropertyName = propertyNameArray;
                        state.Current.JsonPropertyInfo = jsonPropertyInfo;
                        state.Current.NumberHandling   = jsonPropertyInfo.EffectiveNumberHandling;

                        bool useExtensionProperty = dataExtKey != null;

                        if (useExtensionProperty)
                        {
                            Debug.Assert(jsonPropertyInfo == state.Current.JsonTypeInfo.ExtensionDataProperty);
                            state.Current.JsonPropertyNameAsString = dataExtKey;
                            JsonSerializer.CreateExtensionDataProperty(obj, jsonPropertyInfo, options);
                        }

                        ReadPropertyValue(obj, ref state, ref tempReader, jsonPropertyInfo, useExtensionProperty);
                    }

                    FoundProperty[] toReturn = argumentState.FoundProperties !;
                    argumentState.FoundProperties = null;
                    ArrayPool <FoundProperty> .Shared.Return(toReturn, clearArray: true);
                }
            }
            else
            {
                // Slower path that supports continuation and metadata reads.

                if (state.Current.ObjectState == StackFrameObjectState.None)
                {
                    if (reader.TokenType != JsonTokenType.StartObject)
                    {
                        ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert);
                    }

                    state.Current.ObjectState = StackFrameObjectState.StartToken;
                }

                // Read any metadata properties.
                if (state.Current.CanContainMetadata && state.Current.ObjectState < StackFrameObjectState.ReadMetadata)
                {
                    if (!JsonSerializer.TryReadMetadata(this, jsonTypeInfo, ref reader, ref state))
                    {
                        value = default;
                        return(false);
                    }

                    if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref)
                    {
                        value = JsonSerializer.ResolveReferenceId <T>(ref state);
                        return(true);
                    }

                    state.Current.ObjectState = StackFrameObjectState.ReadMetadata;
                }

                // Dispatch to any polymorphic converters: should always be entered regardless of ObjectState progress
                if (state.Current.MetadataPropertyNames.HasFlag(MetadataPropertyName.Type) &&
                    state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted &&
                    ResolvePolymorphicConverter(jsonTypeInfo, options, ref state) is JsonConverter polymorphicConverter)
                {
                    Debug.Assert(!IsValueType);
                    bool success = polymorphicConverter.OnTryReadAsObject(ref reader, options, ref state, out object?objectResult);
                    value = (T)objectResult !;
                    state.ExitPolymorphicConverter(success);
                    return(success);
                }

                // Handle metadata post polymorphic dispatch
                if (state.Current.ObjectState < StackFrameObjectState.ConstructorArguments)
                {
                    if (state.Current.CanContainMetadata)
                    {
                        JsonSerializer.ValidateMetadataForObjectConverter(this, ref reader, ref state);
                    }

                    if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref)
                    {
                        value = JsonSerializer.ResolveReferenceId <T>(ref state);
                        return(true);
                    }

                    BeginRead(ref state, ref reader, options);

                    state.Current.ObjectState = StackFrameObjectState.ConstructorArguments;
                }

                if (!ReadConstructorArgumentsWithContinuation(ref state, ref reader, options))
                {
                    value = default;
                    return(false);
                }

                obj = (T)CreateObject(ref state.Current);

                if (state.Current.MetadataPropertyNames.HasFlag(MetadataPropertyName.Id))
                {
                    Debug.Assert(state.ReferenceId != null);
                    Debug.Assert(options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve);
                    state.ReferenceResolver.AddReference(state.ReferenceId, obj);
                    state.ReferenceId = null;
                }

                jsonTypeInfo.OnDeserializing?.Invoke(obj);

                if (argumentState.FoundPropertyCount > 0)
                {
                    for (int i = 0; i < argumentState.FoundPropertyCount; i++)
                    {
                        JsonPropertyInfo jsonPropertyInfo = argumentState.FoundPropertiesAsync ![i].Item1;
Example #5
0
        static int Main(string[] args)
        {
            try
            {
                // Defaults
                batchSize = 100;

                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has
                // been read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.FileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    if (argument == "-a")
                    {
                        argumentState = ArgumentState.Assembly; continue;
                    }
                    if (argument == "-b")
                    {
                        argumentState = ArgumentState.BatchSize; continue;
                    }
                    if (argument == "-n")
                    {
                        argumentState = ArgumentState.NameSpace; continue;
                    }
                    if (argument == "-i")
                    {
                        argumentState = ArgumentState.FileName; continue;
                    }
                    if (argument == "-t")
                    {
                        argumentState = ArgumentState.Timeout; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.BatchSize: batchSize = Convert.ToInt32(argument); break;

                    case ArgumentState.FileName: fileName = argument; break;

                    case ArgumentState.Timeout: timeout = Convert.ToInt32(argument) * 1000; break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.FileName;
                }

                // Throw a usage message back at the user if no file name was given.
                if (fileName == null)
                {
                    throw new Exception("Usage: Loader.Table -i <FileName>");
                }

                // Read the XML data from the specified file.
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(fileName);

                // Sending records to the server is state driven.  This loop will collect a batch of commands until a new table is
                // found in the XML stream, or until the limit of a batch is reached, or until the end of the file is read.  The
                // idea is to allow several tables of data to exist in a single file.
                XmlNode rootNode = xmlDocument.DocumentElement;
                switch (rootNode.Name)
                {
                case "batch":

                    LoadCommand(rootNode);
                    break;
                }

                // If we reached here, the file was imported without issue.
                if (!hasErrors)
                {
                    Console.WriteLine(String.Format("{0} {1}: {2} Commands Executed", DateTime.Now.ToString("u"),
                                                    rootNode.Attributes["name"] == null ? "Unnamed Batch" : rootNode.Attributes["name"].Value, recordCounter));
                }
            }
            catch (Exception exception)
            {
                // Show the system error and exit with an error.
                Console.WriteLine(exception.Message);
                hasErrors = true;
            }

            // Any errors will cause an abnormal exit.
            return(hasErrors ? 1 : 0);
        }
        static int Main(string[] args)
        {
            try
            {
                // Defaults
                targetNamespace = "DefaultNamespace";

                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has
                // been read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.InputFileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    if (argument == "-i")
                    {
                        argumentState = ArgumentState.InputFileName; continue;
                    }
                    if (argument == "-ns")
                    {
                        argumentState = ArgumentState.TargetNamespace; continue;
                    }
                    if (argument == "-out")
                    {
                        argumentState = ArgumentState.OutputFileName; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.InputFileName:
                        inputFilePath = argument;
                        break;

                    case ArgumentState.OutputFileName:
                        outputFileName = argument;
                        break;

                    case ArgumentState.TargetNamespace:
                        targetNamespace = argument;
                        break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.InputFileName;
                }

                // Expand the environment variables for the input file path.
                if (inputFilePath == null)
                {
                    throw new Exception("Usage: DataSetGenerator -i <InputFileName>");
                }
                inputFilePath = Environment.ExpandEnvironmentVariables(inputFilePath);

                // Expand the environment variables for the outpt file path.
                if (outputFileName == null)
                {
                    outputFileName = string.Format("{0}.cs", Path.GetFileNameWithoutExtension(inputFilePath));
                }
                outputFileName = Environment.ExpandEnvironmentVariables(outputFileName);

                // The main idea here is to emulate the interface that Visual Studio uses to generate a file.  The first step is to
                // read the schema from the input file into a string.  This emulates the way that the IDE would normally call a
                // code generator.  Then create a 'ClientGenerator' to compile the schema.
                StreamReader streamReader = new StreamReader(inputFilePath);
                string       fileContents = streamReader.ReadToEnd();
                streamReader.Close();
                IntPtr[]        buffer = new IntPtr[1];
                uint            bufferSize;
                ClientGenerator clientGenerator = new ClientGenerator();
                clientGenerator.Generate(inputFilePath, fileContents, targetNamespace, buffer, out bufferSize, new ProgressIndicator());

                // Once the buffer of source code is generated, it is copied back out of the unmanaged buffers and written to the
                // output file.
                byte[] outputBuffer = new byte[bufferSize];
                Marshal.Copy(buffer[0], outputBuffer, 0, Convert.ToInt32(bufferSize));
                StreamWriter streamWriter = new StreamWriter(outputFileName);
                streamWriter.Write(Encoding.UTF8.GetString(outputBuffer));
                streamWriter.Close();
            }
            catch (Exception exception)
            {
                // Dump any exceptions to the console.
                Console.WriteLine(exception.Message);
            }

            // At this point the code generated created the code-behind for the source schema successfully.
            return(0);
        }
Example #7
0
        static int Main(string[] args)
        {
            try
            {
                // Defaults
                ExternalInterfaceCompiler.targetNamespace   = string.Empty;
                ExternalInterfaceCompiler.internalNamespace = string.Empty;
                ExternalInterfaceCompiler.persistentStore   = string.Empty;
                ExternalInterfaceCompiler.dataSetName       = string.Empty;
                ExternalInterfaceCompiler.references        = new ArrayList();

                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has
                // been read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.InputFileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    switch (argument)
                    {
                    case "-ds": argumentState = ArgumentState.DataSetName; continue;

                    case "-i": argumentState = ArgumentState.InputFileName; continue;

                    case "-is": argumentState = ArgumentState.InternalNamespace; continue;

                    case "-ns": argumentState = ArgumentState.TargetNamespace; continue;

                    case "-out": argumentState = ArgumentState.OutputFileName; continue;

                    case "-ps": argumentState = ArgumentState.PersistentStore; continue;

                    case "-ref": argumentState = ArgumentState.Reference; continue;

                    case "-t": argumentState = ArgumentState.TargetTable; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.DataSetName: ExternalInterfaceCompiler.dataSetName = argument; break;

                    case ArgumentState.InputFileName: ExternalInterfaceCompiler.inputFileName = argument; break;

                    case ArgumentState.InternalNamespace: ExternalInterfaceCompiler.internalNamespace = argument; break;

                    case ArgumentState.OutputFileName: ExternalInterfaceCompiler.outputFileName = argument; break;

                    case ArgumentState.PersistentStore: ExternalInterfaceCompiler.persistentStore = argument; break;

                    case ArgumentState.Reference: ExternalInterfaceCompiler.references.Add(argument); break;

                    case ArgumentState.TargetNamespace: ExternalInterfaceCompiler.targetNamespace = argument; break;

                    case ArgumentState.TargetTable: ExternalInterfaceCompiler.targetTableName = argument; break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.InputFileName;
                }

                // Throw a usage message back at the user if no file name was given.
                if (inputFileName == null || targetNamespace == string.Empty)
                {
                    throw new Exception("Usage: Generator -i <input file name> -t <target table name>");
                }

                // If the name of the internal namespace MarkThree.MiddleTier to find the commands that use only internal identifiers) was
                // not specified on the command line, then try to infer it from the target namespace.
                if (internalNamespace == string.Empty)
                {
                    internalNamespace = targetNamespace.Replace(".External", string.Empty);
                }

                // If no output file name was specified, create one from the input file specification.
                if (outputFileName == null)
                {
                    outputFileName = string.Format("{0}.cs", Path.GetFileNameWithoutExtension(inputFileName));
                }

                StreamReader            streamReader            = new StreamReader(inputFileName);
                string                  inputContents           = streamReader.ReadToEnd();
                ExternalInterfaceSchema externalInterfaceSchema = new ExternalInterfaceSchema(inputContents);
                MiddleTierTable         middleTierTable         = new MiddleTierTable(externalInterfaceSchema, ExternalInterfaceCompiler.targetTableName);

                externalInterfaceSchema.InternalNamespace = ExternalInterfaceCompiler.internalNamespace;
                externalInterfaceSchema.TargetNamespace   = ExternalInterfaceCompiler.targetNamespace;
                externalInterfaceSchema.PersistentStore   = ExternalInterfaceCompiler.persistentStore;
                externalInterfaceSchema.DataSetName       = ExternalInterfaceCompiler.dataSetName;
                externalInterfaceSchema.References        = ExternalInterfaceCompiler.references;

                byte[] buffer = GenerateCode(externalInterfaceSchema, middleTierTable);

                FileStream outputStream = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.Write);
                outputStream.Write(buffer, 0, buffer.Length);
                outputStream.Close();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }

            return(0);
        }
Example #8
0
        static int Main(string[] args)
        {
            // This is the object that will do the work of loading the scripts.
            ScriptLoader scriptLoader = new ScriptLoader();

            try
            {
                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has
                // been read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.FileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    if (argument == "-f")
                    {
                        scriptLoader.ForceLogin = true; continue;
                    }
                    if (argument == "-i")
                    {
                        argumentState = ArgumentState.FileName; continue;
                    }
                    if (argument == "-b")
                    {
                        argumentState = ArgumentState.TransactionSize; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.FileName:
                        scriptLoader.FileName = argument;
                        break;

                    case ArgumentState.TransactionSize:
                        scriptLoader.TransactionSize = Convert.ToInt32(argument);
                        break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.FileName;
                }

                // Throw a usage message back at the user if no file name was given.
                if (scriptLoader.FileName == null)
                {
                    throw new Exception("Usage: \"Script Loader\" [-b <Batch Size>] [-f] -i <FileName>");
                }

                // Now that the command line arguments have been parsed into the loader, send the data to the server.
                scriptLoader.Load();
            }
            catch (BatchException batchException)
            {
                foreach (Exception exception in batchException.Exceptions)
                {
                    Console.WriteLine(exception.Message);
                }
            }
            catch (Exception exception)
            {
                // Display the error.
                Console.WriteLine(exception.Message);

                // This will force an abnormal exit from the program.
                scriptLoader.HasErrors = true;
            }

            // If an error happened anywhere, don't exit normally.
            if (scriptLoader.HasErrors)
            {
                return(1);
            }

            // If we reached here, the file was imported without issue.
            if (!scriptLoader.HasErrors)
            {
                Console.WriteLine(String.Format("{0} {1}: {2} Commands Executed", DateTime.Now.ToString("u"),
                                                scriptLoader.ScriptName, scriptLoader.MethodCount));
            }

            // The Script Loader has components that must be disposed of explicitly.
            scriptLoader.Dispose();

            // If we reached here, the file was imported without issue.
            return(0);
        }
Example #9
0
        static int Main(string[] args)
        {
            try
            {
                bool streamFileContentsBackToClient = false;
                bool logLocks     = false;
                bool cleanMatches = false;
                bool matchAll     = false;
                bool resetConfig  = false;
                waitForEndResetEvent = new ManualResetEvent(false);
                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has
                // been read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.FileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    if (argument == "-f")
                    {
                        continue;
                    }
                    if (argument == "-s")
                    {
                        streamFileContentsBackToClient = true; continue;
                    }
                    if (argument == "-l")
                    {
                        logLocks = true; continue;
                    }
                    if (argument == "-m")
                    {
                        cleanMatches = true; continue;
                    }
                    if (argument == "-ma")
                    {
                        matchAll = true; continue;
                    }
                    if (argument == "-rc")
                    {
                        resetConfig = true; continue;
                    }
                    if (argument == "-i")
                    {
                        argumentState = ArgumentState.FileName; continue;
                    }
                    if (argument == "-p")
                    {
                        argumentState = ArgumentState.Password; continue;
                    }
                    if (argument == "-u")
                    {
                        argumentState = ArgumentState.UserName; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.FileName:
                        fileName = Environment.ExpandEnvironmentVariables(argument);
                        break;

                    case ArgumentState.Password:
                        password = Environment.ExpandEnvironmentVariables(argument);
                        break;

                    case ArgumentState.UserName:
                        username = Environment.ExpandEnvironmentVariables(argument);
                        break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.FileName;
                }

                // Throw a usage message back at the user if no file name was given.
                if (logLocks == false && cleanMatches == false && matchAll == false && resetConfig == false)
                {
                    if (fileName == null)
                    {
                        throw new Exception("Usage: \"Script Loader\" [-u username] [-p password] [-f] -i <FileName>");
                    }

                    if (Path.IsPathRooted(fileName) == false)
                    {
                        fileName = Path.Combine(Environment.CurrentDirectory, fileName);
                    }
                }
                // Now that the command line arguments have been parsed into the loader, send the data to the server.

                Console.Write("Connecting to: ");

                ChannelStatus.LoginEvent.Set();

                bool hasException = true;
                ServerAdminMessageListner listener = new ServerAdminMessageListner(username, password);
                try
                {
                    listener.Open();

                    ServerAdminMessageSender sender = new ServerAdminMessageSender(listener.ClientId, username, password);
                    try
                    {
                        if (logLocks == true)
                        {
                            sender.OutputLocksToLog();
                        }
                        else if (cleanMatches == true)
                        {
                            sender.CleanUnpairedMatches();
                        }
                        else if (matchAll == true)
                        {
                            sender.RematchAllWorkingOrders();
                        }
                        else if (resetConfig == true)
                        {
                            sender.ResetServerConfigs();
                        }
                        else
                        {
                            if (sender.SendLoadScriptFile(fileName, streamFileContentsBackToClient) == false)
                            {
                                hasException = false;
                                //error SendLoadScriptFile will write error to console
                                return(-1);
                            }

                            waitForEndResetEvent.WaitOne();

                            if (listener.StreamDataId == null)
                            {
                                AsyncMethodResponse retVal = listener.GetAsyncResponseData(listener.PayloadTicket);
                                Console.WriteLine(retVal.AsyncResponseData);
                            }
                            else
                            {
                                FluidTrade.Guardian.ServerAdminStreamRef.ServerAdminStreamManagerClient streamClient =
                                    new FluidTrade.Guardian.ServerAdminStreamRef.ServerAdminStreamManagerClient("TcpServerAdminStreamMgrEndpoint");
                                streamClient.ClientCredentials.UserName.UserName = username;
                                streamClient.ClientCredentials.UserName.Password = password;

                                Stream serverStream = streamClient.GetAsyncResponseStreamData(listener.StreamDataId);

                                StreamReader streamReader = new StreamReader(serverStream);
                                string       tmp          = streamReader.ReadToEnd();
                                Console.WriteLine(tmp);
                            }
                            //Console.WriteLine(message);
                            //if(response.IsSuccessful == false)
                            //{
                            //    Console.WriteLine("FAILED");
                            //}
                            //Console.WriteLine(retVal.AsyncResponseData);
                        }
                        hasException = false;
                    }
                    finally
                    {
                        try
                        {
                            if (hasException == false)
                            {
                                sender.Dispose();
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                finally
                {
                    try
                    {
                        if (hasException == false)
                        {
                            listener.Dispose();
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                Exception exOut = ex;
                while (exOut != null)
                {
                    //// Display the error.
                    Console.WriteLine("{0}: {1}", exOut.Message, ex.ToString());
                    Console.WriteLine("");

                    exOut = exOut.InnerException;
                }
                return(-1);
            }

            return(0);
        }
Example #10
0
        static int Main(string[] args)
        {
            try
            {
                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has
                // been read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.InputFileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    if (argument == "-i")
                    {
                        argumentState = ArgumentState.InputFileName; continue;
                    }
                    if (argument == "-out")
                    {
                        argumentState = ArgumentState.OutputFileName; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.InputFileName:
                        inputFilePath = argument;
                        break;

                    case ArgumentState.OutputFileName:
                        outputFileName = argument;
                        break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.InputFileName;
                }

                // Expand the environment variables for the input file path.
                if (inputFilePath == null)
                {
                    throw new Exception("Usage: SchemaScrubber -i <InputFileName>");
                }
                inputFilePath = Environment.ExpandEnvironmentVariables(inputFilePath);

                // Expand the environment variables for the outpt file path.
                if (outputFileName == null)
                {
                    outputFileName = String.Format("{0}.cs", Path.GetFileNameWithoutExtension(inputFilePath));
                }
                outputFileName = Environment.ExpandEnvironmentVariables(outputFileName);

                // The main idea here is to emulate the interface that Visual Studio uses to generate a file.  The first step is to read the schema from the input
                // file into a string.  This emulates the way that the IDE would normally call a code generator.
                StreamReader    streamReader    = new StreamReader(inputFilePath);
                DataModelSchema dataModelSchema = new DataModelSchema(streamReader.ReadToEnd());

                // Regurgitate the schema as an XDocument
                XDocument xDocument     = new XDocument();
                XElement  schemaElement = new XElement(
                    SchemaScrubber.xs + "schema",
                    new XAttribute("id", dataModelSchema.Name),
                    new XAttribute("targetNamespace", dataModelSchema.TargetNamespace),
                    new XAttribute(XNamespace.Xmlns + "mstns", "http://tempuri.org/DataModel.xsd"),
                    new XAttribute("xmlns", "http://tempuri.org/DataModel.xsd"),
                    new XAttribute(XNamespace.Xmlns + "xs", "http://www.w3.org/2001/XMLSchema"),
                    new XAttribute(XNamespace.Xmlns + "msdata", "urn:schemas-microsoft-com:xml-msdata"),
                    new XAttribute(XNamespace.Xmlns + "msprop", "urn:schemas-microsoft-com:xml-msprop"),
                    new XAttribute("attributeFormDefault", "qualified"),
                    new XAttribute("elementFormDefault", "qualified")
                    );


                // Emit Annotations
                foreach (ObjectSchema itemSchema0 in dataModelSchema.Items)
                {
                    if (itemSchema0 is AnnotationSchema)
                    {
                        AnnotationSchema annotationSchema  = itemSchema0 as AnnotationSchema;
                        XElement         annotationElement = new XElement(SchemaScrubber.xs + "annotation");
                        foreach (ObjectSchema itemSchema1 in annotationSchema.Items)
                        {
                            if (itemSchema1 is AppInfoSchema)
                            {
                                AppInfoSchema appInfoSchema  = itemSchema1 as AppInfoSchema;
                                XElement      appInfoElement = new XElement(SchemaScrubber.xs + "appinfo");
                                if (appInfoSchema.Source != String.Empty)
                                {
                                    appInfoElement.Add(new XAttribute("source", appInfoSchema.Source));
                                }
                                foreach (XmlNode xmlNode in appInfoSchema.Markup)
                                {
                                    appInfoElement.Add(XElement.Parse(xmlNode.OuterXml));
                                }
                                annotationElement.Add(appInfoElement);
                            }
                        }
                        schemaElement.Add(annotationElement);
                    }
                }

                // Data Model
                //   <xs:element name="DataModel" msdata:IsDataSet="true" msdata:UseCurrentLocale="true" msprop:Generator_UserDSName="DataModel"
                //		msprop:Generator_DataSetName="DataModel" msprop:EnableTableAdapterManager="true">
                XElement dataModelElement = new XElement(
                    SchemaScrubber.xs + "element",
                    new XAttribute("name", dataModelSchema.Name),
                    new XAttribute(msdata + "IsDataSet", true),
                    new XAttribute(msdata + "UseCurrentLocale", true),
                    new XAttribute(SchemaScrubber.msprop + "Generator_UserDSName", dataModelSchema.Name),
                    new XAttribute(SchemaScrubber.msprop + "Generator_DataSetName", dataModelSchema.Name),
                    new XAttribute(SchemaScrubber.msprop + "EnableTableAdapterManager", true));

                //    <xs:complexType>
                XElement dataModelComlexTypeElement = new XElement(SchemaScrubber.xs + "complexType");

                //      <xs:choice minOccurs="0" maxOccurs="unbounded">
                XElement dataModelChoices = new XElement(
                    SchemaScrubber.xs + "choice",
                    new XAttribute("minOccurs", 0),
                    new XAttribute("maxOccurs", "unbounded"));

                // This will scrub and add each of the tables to the schema in alphabetical order.
                foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables)
                {
                    dataModelChoices.Add(CreateTable(keyValuePair.Value));
                }

                // The complex types that define the tables.
                dataModelComlexTypeElement.Add(dataModelChoices);
                dataModelElement.Add(dataModelComlexTypeElement);

                // This will order the primary keys.
                List <UniqueConstraintSchema> primaryKeyList = new List <UniqueConstraintSchema>();
                foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables)
                {
                    primaryKeyList.AddRange(keyValuePair.Value.UniqueConstraintSchemas);
                }
                primaryKeyList.Sort((first, second) => { return(first.Name.CompareTo(second.Name)); });
                foreach (UniqueConstraintSchema uniqueConstraintSchema in primaryKeyList)
                {
                    dataModelElement.Add(CreateUniqueKey(uniqueConstraintSchema));
                }

                // This will order the foreign primary keys.
                List <ForeignKeyConstraintSchema> foreignKeyList = new List <ForeignKeyConstraintSchema>();
                foreach (KeyValuePair <String, TableSchema> keyValuePair in dataModelSchema.Tables)
                {
                    foreignKeyList.AddRange(keyValuePair.Value.ForeignKeyConstraintSchemas);
                }
                foreignKeyList.Sort((first, second) => { return(first.Name.CompareTo(second.Name)); });
                foreach (ForeignKeyConstraintSchema foreignConstraintSchema in foreignKeyList)
                {
                    dataModelElement.Add(CreateForeignKey(foreignConstraintSchema));
                }

                // Add the data model element to the document.
                schemaElement.Add(dataModelElement);

                // Create the document from the root.
                xDocument.Add(schemaElement);

                // Save the regurgitated output.

                xDocument.Save(outputFileName);
            }
            catch (Exception exception)
            {
                // Dump any exceptions to the console.
                Console.WriteLine(exception.Message);
            }

            // At this point the code generated created the code-behind for the source schema successfully.
            return(0);
        }
        static int Main(string[] args)
        {
            try
            {
                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has
                // been read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.InputFileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    switch (argument)
                    {
                    case "-i":
                        argumentState = ArgumentState.InputFileName;
                        continue;

                    case "-out":
                        argumentState = ArgumentState.OutputFileName;
                        continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.InputFileName:
                        DatabaseGenerator.inputFileName = argument;
                        break;

                    case ArgumentState.OutputFileName:
                        DatabaseGenerator.outputFileName = argument;
                        break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.InputFileName;
                }

                // Throw a usage message back at the user if no file name was given.
                if (inputFileName == null)
                {
                    throw new Exception("Usage: \"Database Generator\" -i <input file name> -out <DDL file>");
                }
                inputFileName = Environment.ExpandEnvironmentVariables(inputFileName);

                // If no output file name was specified, create one from the input file specification.
                if (outputFileName == null)
                {
                    outputFileName = String.Format("{0}.sql", Path.GetFileNameWithoutExtension(inputFileName));
                }
                outputFileName = Environment.ExpandEnvironmentVariables(outputFileName);

                // Read the schema into a string.  This emulates the way that the IDE would normally call a code generator.  Create
                // the MiddleTierSchema (like a Schema, but with extra helping functions and relations for this type of code generation).
                StreamReader streamReader = new StreamReader(inputFileName);
                // This will generate a buffer of source code from the input schema.
                DataModelSchema dataModelSchema = new DataModelSchema(streamReader.ReadToEnd());
                byte[]          buffer          = GenerateDdl(dataModelSchema);

                // Write the buffer to the specified output file.
                FileStream outputStream = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.Write);
                outputStream.Write(buffer, 0, buffer.Length);
                outputStream.SetLength(buffer.Length);
                outputStream.Close();
            }
            catch (Exception exception)
            {
                // Write the error to the console.
                Console.WriteLine(exception.Message);
            }

            return(0);
        }
Example #12
0
        static int Main(string[] args)
        {
            // If this flag is set during the processing of the file, the program will exit with an error code.
            bool hasErrors = false;

            try
            {
                // Defaults
                batchSize     = 100;
                assemblyName  = "Service.External";
                nameSpaceName = "Shadows.WebService.External";

                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has been
                // read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.FileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state change (or some other action).
                    if (argument == "-a")
                    {
                        argumentState = ArgumentState.Assembly; continue;
                    }
                    if (argument == "-b")
                    {
                        argumentState = ArgumentState.BatchSize; continue;
                    }
                    if (argument == "-n")
                    {
                        argumentState = ArgumentState.NameSpace; continue;
                    }
                    if (argument == "-i")
                    {
                        argumentState = ArgumentState.FileName; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.Assembly: assemblyName = argument; break;

                    case ArgumentState.BatchSize: batchSize = Convert.ToInt32(argument); break;

                    case ArgumentState.FileName: fileName = argument; break;

                    case ArgumentState.NameSpace: nameSpaceName = argument; break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.FileName;
                }

                // Throw a usage message back at the user if no file name was given.
                if (fileName == null)
                {
                    throw new Exception("Usage: Loader.Algorithm -i <FileName>");
                }

                // Open up the file containing all the broker.
                BrokerReader brokerReader = new BrokerReader(fileName);

                // Create a new web client that will serve as the connection point to the server.
                WebClient webClient = new WebClient();

                // Loading the database involves creating a batch of commands and sending them off as a transaction.  This gives
                // the server a chance to pipeline a large chunk of processing, without completely locking up the server for the
                // entire set of data.  This will construct a header for the command batch which gives information about which
                // assembly contains the class that is used to load the data.
                RemoteBatch       remoteBatch       = new RemoteBatch();
                RemoteTransaction remoteTransaction = remoteBatch.Transactions.Add();
                RemoteAssembly    remoteAssembly    = remoteBatch.Assemblies.Add(assemblyName);
                RemoteType        remoteType        = remoteAssembly.Types.Add(string.Format("{0}.{1}", nameSpaceName, "Broker"));

                // Read the file until an EOF is reached.
                while (true)
                {
                    // This counter keeps track of the number of records sent.  When the batch is full, it's sent to the server to be
                    // executed as a single transaction.
                    int batchCounter = 0;

                    // Read the next broker from the input stream.  A 'null' is returned when we've read past the end of file.
                    Broker broker = brokerReader.ReadBroker();
                    if (broker != null)
                    {
                        // Construct a call to the 'Load' method to populate the broker record.
                        RemoteMethod remoteMethod = remoteType.Methods.Add("Load");
                        remoteMethod.Transaction = remoteTransaction;
                        remoteMethod.Parameters.Add("brokerId", broker.Symbol);
                        remoteMethod.Parameters.Add("name", broker.Name);
                        remoteMethod.Parameters.Add("symbol", broker.Symbol);
                    }

                    // This will check to see if it's time to send the batch.  A batch is sent when the 'batchSize' has been
                    // reached, or if the last record has just been converted into a command.
                    if (++batchCounter % batchSize == 0 || broker == null)
                    {
                        // Call the web services to execute the command batch.
                        remoteBatch.Merge(webClient.Execute(remoteBatch));

                        // Any error during the batch will terminate the execution of the remaining records in the data file.
                        if (remoteBatch.HasExceptions)
                        {
                            // Display each error on the console.
                            foreach (RemoteMethod remoteMethod in remoteBatch.Methods)
                            {
                                foreach (RemoteException remoteException in remoteMethod.Exceptions)
                                {
                                    Console.WriteLine(String.Format("{0}: {1}", remoteMethod.Parameters["brokerId"].Value,
                                                                    remoteException.Message));
                                }
                            }

                            // This will signal the error exit from this loader.
                            hasErrors = true;
                        }

                        // If the end of file was reached, break out of the loop and exit the application.
                        if (broker == null)
                        {
                            break;
                        }

                        // After each batch has been send, check to see if there are additional records to be send.  If so,
                        // regenerate the remote batch and set up the header.
                        remoteBatch       = new RemoteBatch();
                        remoteTransaction = remoteBatch.Transactions.Add();
                        remoteAssembly    = remoteBatch.Assemblies.Add(assemblyName);
                        remoteType        = remoteAssembly.Types.Add(string.Format("{0}.{1}", nameSpaceName, "Broker"));
                    }
                }
            }
            catch (Exception exception)
            {
                // Show the system error and exit with an error.
                Console.WriteLine(exception.Message);
                hasErrors = true;
            }

            // Any errors will cause an abnormal exit.
            if (hasErrors)
            {
                return(1);
            }

            // Write a status message when a the file is loaded successfully.
            Console.WriteLine(String.Format("{0} Data: Brokers, Loaded", DateTime.Now.ToString("u")));

            // If we reached here, the file was imported without issue.
            return(0);
        }
Example #13
0
        static Int32 Main(String[] args)
        {
            // These are the parameters that are parsed out of the command line.
            String inputFilePath  = String.Empty;
            String outputFilePath = String.Empty;

            try
            {
                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has been parsed, the command line
                // parser assumes that it's reading the file name from the command line.
                ArgumentState argumentState = ArgumentState.InputFileName;

                // Parse the command line for arguments.
                foreach (String argument in args)
                {
                    // Use the dictionary to transition from one state to the next based on the input parameters.
                    ArgumentState nextArgumentState;
                    if (Program.argumentStates.TryGetValue(argument, out nextArgumentState))
                    {
                        argumentState = nextArgumentState;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.InputFileParam:

                        // The next command line argument will be the input file name.
                        argumentState = ArgumentState.InputFileName;
                        break;

                    case ArgumentState.InputFileName:

                        // Expand the environment variables so that paths don't need to be absolute.
                        inputFilePath = Environment.ExpandEnvironmentVariables(argument);
                        argumentState = ArgumentState.InputFileParam;
                        break;

                    case ArgumentState.OutputFileParam:

                        // The next command line argument will be the input file name.
                        argumentState = ArgumentState.OutputFileName;
                        break;

                    case ArgumentState.OutputFileName:

                        // Expand the environment variables so that paths don't need to be absolute.
                        outputFilePath = Environment.ExpandEnvironmentVariables(argument);
                        break;

                    default:

                        // The parser will revert back to looking for an input file when it doesn't recognized the switch.
                        argumentState = ArgumentState.InputFileName;
                        break;
                    }
                }

                // Throw a usage message back at the user if no file name was given.
                if (inputFilePath == null)
                {
                    throw new Exception("Usage: \"Organization Builder\" [-b <Batch Size>] [-f] -i <FileName>");
                }

                // This will convert the organization description into a script that can be loaded via the Script Loader.
                XDocument organizationScript = Organization.Create(XDocument.Load(inputFilePath));
                organizationScript.Save(outputFilePath);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }

            // If we reached here, the file was imported without issue.
            return(0);
        }
Example #14
0
        static Int32 Main(String[] args)
        {
            // This object is used to load the script and keeps track of loading statistics.
            ScriptLoader scriptLoader = new ScriptLoader();

            // The endpoint is pulled from the application settings first.  It can be overridden with the command line.
            scriptLoader.Endpoint = Properties.Settings.Default.DataModelEndpoint;

            // These are the parameters that are parsed out of the command line.
            Boolean   forceLogin    = false;
            String    inputFilePath = String.Empty;
            Verbosity verbosity     = Verbosity.Minimal;

            try
            {
                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has been parsed, the command line
                // parser assumes that it's reading the file name from the command line.
                ArgumentState argumentState = ArgumentState.InputFileName;

                // Parse the command line for arguments.
                foreach (String argument in args)
                {
                    // Use the dictionary to transition from one state to the next based on the input parameters.
                    ArgumentState nextArgumentState;
                    if (Program.argumentStates.TryGetValue(argument, out nextArgumentState))
                    {
                        argumentState = nextArgumentState;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.EndpointParam:

                        // The next command line argument will be endpoint.
                        argumentState = ArgumentState.Endpoint;
                        break;

                    case ArgumentState.Endpoint:

                        // This will set the endpoint to use when communicating with the service.
                        scriptLoader.Endpoint = argument;
                        break;

                    case ArgumentState.ForceLoginParam:

                        // This will cause the script loader to prompt for login credentials.
                        forceLogin    = true;
                        argumentState = ArgumentState.InputFileName;
                        break;

                    case ArgumentState.InputFileParam:

                        // The next command line argument will be the input file name.
                        argumentState = ArgumentState.InputFileName;
                        break;

                    case ArgumentState.InputFileName:

                        // Expand the environment variables so that paths don't need to be absolute.
                        inputFilePath = Environment.ExpandEnvironmentVariables(argument);
                        break;

                    case ArgumentState.VerbosityParam:

                        // Verbose output.
                        argumentState = ArgumentState.Verbosity;
                        break;

                    case ArgumentState.Verbosity:

                        try
                        {
                            // Make sure any parsing errors are ignored.
                            verbosity = (Verbosity)Enum.Parse(typeof(Verbosity), argument);
                        }
                        catch { }

                        break;

                    default:

                        // The parser will revert back to looking for an input file when it doesn't recognized the switch.
                        argumentState = ArgumentState.InputFileName;
                        break;
                    }
                }

                // Throw a usage message back at the user if no file name was given.
                if (inputFilePath == null)
                {
                    throw new Exception("Usage: \"Script Loader\" [-b <Batch Size>] [-f] -i <FileName>");
                }

                // Expand the environment variables and load the resulting file.
                scriptLoader.ForceLogin = forceLogin;
                scriptLoader.FileName   = inputFilePath;
                scriptLoader.Verbosity  = verbosity;
                scriptLoader.Load();
            }
            catch (Exception exception)
            {
                // Dump the error.
                Console.WriteLine(exception.Message);

                // This will force an abnormal exit from the program.
                scriptLoader.HasErrors = true;
            }

            // Print the final status of the load.
            Console.WriteLine(String.Format("{0} {1}: {2} Methods Executed", DateTime.Now.ToString("u"), scriptLoader.ScriptName, scriptLoader.MethodCount));

            // If an error happened anywhere, don't exit normally.
            if (scriptLoader.HasErrors)
            {
                return(1);
            }

            // After a successful load, the properties (specifically user name and password) can be saved for the next invocation of this application.
            Properties.Settings.Default.Save();

            // If we reached here, the file was imported without issue.
            return(0);
        }
Example #15
0
        static int Main(string[] args)
        {
            // This is the object that will do the work of loading the stylesheets.
            LogoPacker logoLoader = new LogoPacker();

            try
            {
                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has
                // been read, the command line parser assumes that it's reading the file name from the command line.
                argumentState = ArgumentState.Path;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state.
                    if (argument == "-f")
                    {
                        logoLoader.ForceLogin = true; continue;
                    }
                    if (argument == "-p")
                    {
                        argumentState = ArgumentState.Path; continue;
                    }
                    if (argument == "-o")
                    {
                        argumentState = ArgumentState.OutputFile; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    // Read the command line argument into the proper variable based on the parsing state.
                    case ArgumentState.Path:
                        logoLoader.Path = argument;
                        break;

                    case ArgumentState.OutputFile:
                        logoLoader.OutputFile = argument;
                        break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.Path;
                }

                // Throw a usage message back at the user if no file name was given.
                if (logoLoader.Path == null)
                {
                    throw new Exception("Usage: \"Stylesheet Loader\" [-f] -i <Path>");
                }

                // Now that the command line arguments have been parsed into the loader, send the data to the server.
                logoLoader.Load();
            }
            catch (Exception exception)
            {
                // Display the error.
                Console.WriteLine(exception.Message);

                // This will force an abnormal exit from the program.
                logoLoader.HasErrors = true;
            }

            // If an error happened anywhere, don't exit normally.
            if (logoLoader.HasErrors)
            {
                return(1);
            }

            // If we reached here, the file was imported without issue.
            if (!logoLoader.HasErrors)
            {
                Console.WriteLine("{0} {1}: Company Logos Loaded", DateTime.Now.ToString("u"), logoLoader.LogoCount);
            }

            // If we reached here, the file was imported without issue.
            return(0);
        }
        public static int Main(string[] args)
        {
            // Validate the argument.
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            // These are the parameters that are parsed out of the command line.
            string inputFilePath   = string.Empty;
            string outputFileName  = string.Empty;
            string targetNamespace = "DefaultNamespace";

            try
            {
                // The command line parser is driven by different states that are triggered by the flags read.  Unless a flag has been parsed, the command line
                // parser assumes that it's reading the file name from the command line.
                ArgumentState argumentState = ArgumentState.InputFileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Use the dictionary to transition from one state to the next based on the input parameters.
                    ArgumentState nextArgumentState;
                    if (Program.ArgumentStates.TryGetValue(argument, out nextArgumentState))
                    {
                        argumentState = nextArgumentState;
                        continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    case ArgumentState.InputFileName:

                        // Expand the environment variables so that paths don't need to be absolute.
                        inputFilePath = Environment.ExpandEnvironmentVariables(argument);

                        // The output name defaults to the input file name with a new extension.
                        outputFileName = $"{Path.GetFileNameWithoutExtension(inputFilePath)}.cs";

                        break;

                    case ArgumentState.OutputFileName:

                        // Expand the environment variables so that paths don't need to be absolute.
                        outputFileName = Environment.ExpandEnvironmentVariables(argument);
                        break;

                    case ArgumentState.TargetNamespace:

                        // This is the namespace that is used to create the target data model.
                        targetNamespace = argument;
                        break;
                    }

                    // The default state is to look for the input file name on the command line.
                    argumentState = ArgumentState.InputFileName;
                }

                // This will read the input XML schema into a large buffer.
                string fileContents;
                using (StreamReader streamReader = new StreamReader(inputFilePath))
                {
                    fileContents = streamReader.ReadToEnd();
                }

                // This next step simulates the calling convention used by a custom tool, which is to say it uses unmanaged code.  The progress indicator is used
                // to provide feedback, to either the IDE or the command line, about how far along the compilation is.  Note that the calling interface is from
                // unmanaged-code to managed code, the way you would expect the IDE to call the generator, so we create an unmanaged buffer pointer for the results.
                IntPtr[]  buffer = new IntPtr[1];
                uint      bufferSize;
                Generator generator = new Generator();
                IVsSingleFileGenerator ivsSingleFileGenerator = generator as IVsSingleFileGenerator;
                ivsSingleFileGenerator.Generate(inputFilePath, fileContents, targetNamespace, buffer, out bufferSize, null);

                // Once the buffer of source code is generated, it is copied back out of the unmanaged buffers and written to the output file.
                byte[] outputBuffer = new byte[bufferSize];
                Marshal.Copy(buffer[0], outputBuffer, 0, Convert.ToInt32(bufferSize));
                using (StreamWriter streamWriter = new StreamWriter(outputFileName))
                {
                    streamWriter.Write(Encoding.UTF8.GetString(outputBuffer));
                }
            }
            catch (ArgumentException argumentException)
            {
                // This will catch any generic errors and dump them to the console.
                Console.WriteLine(argumentException.Message);
            }

            // The execution at this point was a success.
            return(0);
        }
Example #17
0
        static int Main(string[] args)
        {
            // If this flag is set during the processing of the file, the program will exit with an error code.
            bool hasErrors = false;

            try
            {
                // Defaults
                assemblyName              = "Service.External";
                namespaceName             = "Shadows.WebService.External";
                externalConfigurationCode = "DEFAULT";
                argumentState             = ArgumentState.FileName;

                // Parse the command line for arguments.
                foreach (string argument in args)
                {
                    // Decode the current argument into a state.
                    if (argument == "-c")
                    {
                        argumentState = ArgumentState.ConfigurationCode; continue;
                    }
                    if (argument == "-i")
                    {
                        argumentState = ArgumentState.FileName; continue;
                    }
                    if (argument == "-id")
                    {
                        argumentState = ArgumentState.StylesheetId; continue;
                    }
                    if (argument == "-t")
                    {
                        argumentState = ArgumentState.StylesheetTypeCode; continue;
                    }

                    // The parsing state will determine which variable is read next.
                    switch (argumentState)
                    {
                    // Read the command line argument into the proper variable based on the parsing state.
                    case ArgumentState.ConfigurationCode: externalConfigurationCode = argument; break;

                    case ArgumentState.StylesheetTypeCode: stylesheetTypeCode = argument; break;

                    case ArgumentState.FileName: fileName = argument; break;

                    case ArgumentState.Name: name = argument; break;

                    case ArgumentState.StylesheetId: StylesheetId = argument; break;
                    }

                    // The default state for the parser is to look for a file name.
                    argumentState = ArgumentState.FileName;
                }

                // If no file name was specified, we return an error.
                if (fileName == null)
                {
                    throw new Exception("Usage: Loader.Stylesheet -i <FileName>");
                }

                // Load up an XML document with the contents of the file specified on the command line.
                XmlDocument stylesheet = new XmlDocument();
                stylesheet.Load(fileName);

                // The XML document has several nodes that need to be read -- and then removed -- that contain attributes of the
                // stylesheet.  These nodes can be found easily using the XSL Path functions which need a namespace manager to sort
                // out the tag prefixes.
                XmlNamespaceManager namespaceManager = new XmlNamespaceManager(stylesheet.NameTable);
                namespaceManager.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
                namespaceManager.AddNamespace("sss", "urn:schemas-shadows-com:shadows:stylesheet");

                // The spreadhseet source has several nodes which contain information about how the data in the XML document should
                // be loaded into the server, such as the stylesheet identifier, the name and the stylesheet style.  They are found
                // at this node.  After these information nodes have been read, they are removed from the stylesheet source.
                XmlNode stylesheetNode = stylesheet.SelectSingleNode("xsl:stylesheet", namespaceManager);
                if (stylesheetNode == null)
                {
                    throw new Exception("Syntax Error: missing stylesheet declaration.");
                }

                // Find the StylesheetId node.
                XmlNode StylesheetIdNode = stylesheetNode.SelectSingleNode("sss:stylesheetId", namespaceManager);
                if (StylesheetIdNode == null)
                {
                    throw new Exception("Syntax Error: missing StylesheetId declaration.");
                }

                // Find the StylesheetStyle node.
                XmlNode stylesheetTypeCodeNode = stylesheetNode.SelectSingleNode("sss:stylesheetTypeCode", namespaceManager);
                if (stylesheetTypeCodeNode == null)
                {
                    throw new Exception("Syntax Error: missing StylesheetStyle declaration.");
                }

                // Find the name node.
                XmlNode nameNode = stylesheetNode.SelectSingleNode("sss:name", namespaceManager);
                if (nameNode == null)
                {
                    throw new Exception("Syntax Error: missing name declaration.");
                }

                // Extract the data from the XML nodes.
                StylesheetId       = StylesheetIdNode.InnerText;
                stylesheetTypeCode = stylesheetTypeCodeNode.InnerText;
                name = nameNode.InnerText;

                // Remove the stylesheet nodes from the XSL spreadsheet before loading it into the server.
                stylesheetNode.RemoveChild(StylesheetIdNode);
                stylesheetNode.RemoveChild(stylesheetTypeCodeNode);
                stylesheetNode.RemoveChild(nameNode);

                // Create a command to load the stylesheet from the data loaded from the file.
                RemoteBatch    remoteBatch    = new RemoteBatch();
                RemoteAssembly remoteAssembly = remoteBatch.Assemblies.Add(assemblyName);
                RemoteType     remoteType     = remoteAssembly.Types.Add(string.Format("{0}.{1}", namespaceName, "Stylesheet"));
                RemoteMethod   remoteMethod   = remoteType.Methods.Add("Load");
                remoteMethod.Parameters.Add("StylesheetId", StylesheetId);
                remoteMethod.Parameters.Add("stylesheetTypeCode", stylesheetTypeCode);
                remoteMethod.Parameters.Add("name", name);
                remoteMethod.Parameters.Add("text", stylesheet.InnerXml);

                // Create a new web client that will serve as the connection point to the server and call the web services to
                // execute the command batch.
                WebClient webClient = new WebClient();
                remoteBatch.Merge(webClient.Execute(remoteBatch));

                // Display the each of the exceptions and set a global flag that shows that there was an exception to the normal
                // execution.
                if (remoteBatch.HasExceptions)
                {
                    foreach (RemoteException exception in remoteBatch.Exceptions)
                    {
                        Console.WriteLine(String.Format("{0}: {1}", remoteMethod.Parameters["StylesheetId"].Value, exception.Message));
                    }
                    hasErrors = true;
                }
            }
            catch (Exception exception)
            {
                // Show the system error and exit with an error.
                Console.WriteLine(exception.Message);
                hasErrors = true;
            }

            // Any errors will cause an abnormal exit.
            if (hasErrors)
            {
                return(1);
            }

            // Display the template that was loaded and exit with a successful code.
            Console.WriteLine(String.Format("{0} Stylesheet: {1}, Loaded", DateTime.Now.ToString("u"), name));
            return(0);
        }
Example #18
0
        internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out T value)
        {
            object        obj;
            ArgumentState argumentState = state.Current.CtorArgumentState !;

            if (state.UseFastPath)
            {
                // Fast path that avoids maintaining state variables.

                ReadOnlySpan <byte> originalSpan = reader.OriginalSpan;

                ReadConstructorArguments(ref state, ref reader, options);

                obj = (T)CreateObject(ref state.Current);

                if (obj is IJsonOnDeserializing onDeserializing)
                {
                    onDeserializing.OnDeserializing();
                }

                if (argumentState.FoundPropertyCount > 0)
                {
                    Utf8JsonReader tempReader;

                    FoundProperty[]? properties = argumentState.FoundProperties;
                    Debug.Assert(properties != null);

                    for (int i = 0; i < argumentState.FoundPropertyCount; i++)
                    {
                        JsonPropertyInfo jsonPropertyInfo    = properties[i].Item1;
                        long             resumptionByteIndex = properties[i].Item3;
                        byte[]? propertyNameArray = properties[i].Item4;
                        string?dataExtKey = properties[i].Item5;

                        tempReader = new Utf8JsonReader(
                            originalSpan.Slice(checked ((int)resumptionByteIndex)),
                            isFinalBlock: true,
                            state: properties[i].Item2);

                        Debug.Assert(tempReader.TokenType == JsonTokenType.PropertyName);

                        state.Current.JsonPropertyName = propertyNameArray;
                        state.Current.JsonPropertyInfo = jsonPropertyInfo;
                        state.Current.NumberHandling   = jsonPropertyInfo.NumberHandling;

                        bool useExtensionProperty = dataExtKey != null;

                        if (useExtensionProperty)
                        {
                            Debug.Assert(jsonPropertyInfo == state.Current.JsonTypeInfo.DataExtensionProperty);
                            state.Current.JsonPropertyNameAsString = dataExtKey;
                            JsonSerializer.CreateDataExtensionProperty(obj, jsonPropertyInfo, options);
                        }

                        ReadPropertyValue(obj, ref state, ref tempReader, jsonPropertyInfo, useExtensionProperty);
                    }

                    FoundProperty[] toReturn = argumentState.FoundProperties !;
                    argumentState.FoundProperties = null;
                    ArrayPool <FoundProperty> .Shared.Return(toReturn, clearArray: true);
                }
            }
            else
            {
                // Slower path that supports continuation.

                if (state.Current.ObjectState == StackFrameObjectState.None)
                {
                    state.Current.ObjectState = StackFrameObjectState.StartToken;
                    BeginRead(ref state, ref reader, options);
                }

                if (!ReadConstructorArgumentsWithContinuation(ref state, ref reader, options))
                {
                    value = default;
                    return(false);
                }

                obj = (T)CreateObject(ref state.Current);

                if (obj is IJsonOnDeserializing onDeserializing)
                {
                    onDeserializing.OnDeserializing();
                }

                if (argumentState.FoundPropertyCount > 0)
                {
                    for (int i = 0; i < argumentState.FoundPropertyCount; i++)
                    {
                        JsonPropertyInfo jsonPropertyInfo = argumentState.FoundPropertiesAsync ![i].Item1;
        internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, [MaybeNullWhen(false)] out T value)
        {
            object        obj;
            ArgumentState argumentState = state.Current.CtorArgumentState !;

            if (state.UseFastPath)
            {
                // Fast path that avoids maintaining state variables.

                if (reader.TokenType != JsonTokenType.StartObject)
                {
                    ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert);
                }

                ReadOnlySpan <byte> originalSpan = reader.OriginalSpan;

                ReadConstructorArguments(ref state, ref reader, options);

                obj = (T)CreateObject(ref state.Current);

                if (obj is IJsonOnDeserializing onDeserializing)
                {
                    onDeserializing.OnDeserializing();
                }

                if (argumentState.FoundPropertyCount > 0)
                {
                    Utf8JsonReader tempReader;

                    FoundProperty[]? properties = argumentState.FoundProperties;
                    Debug.Assert(properties != null);

                    for (int i = 0; i < argumentState.FoundPropertyCount; i++)
                    {
                        JsonPropertyInfo jsonPropertyInfo    = properties[i].Item1;
                        long             resumptionByteIndex = properties[i].Item3;
                        byte[]? propertyNameArray = properties[i].Item4;
                        string?dataExtKey = properties[i].Item5;

                        tempReader = new Utf8JsonReader(
                            originalSpan.Slice(checked ((int)resumptionByteIndex)),
                            isFinalBlock: true,
                            state: properties[i].Item2);

                        Debug.Assert(tempReader.TokenType == JsonTokenType.PropertyName);

                        state.Current.JsonPropertyName = propertyNameArray;
                        state.Current.JsonPropertyInfo = jsonPropertyInfo;
                        state.Current.NumberHandling   = jsonPropertyInfo.NumberHandling;

                        bool useExtensionProperty = dataExtKey != null;

                        if (useExtensionProperty)
                        {
                            Debug.Assert(jsonPropertyInfo == state.Current.JsonTypeInfo.DataExtensionProperty);
                            state.Current.JsonPropertyNameAsString = dataExtKey;
                            JsonSerializer.CreateDataExtensionProperty(obj, jsonPropertyInfo, options);
                        }

                        ReadPropertyValue(obj, ref state, ref tempReader, jsonPropertyInfo, useExtensionProperty);
                    }

                    FoundProperty[] toReturn = argumentState.FoundProperties !;
                    argumentState.FoundProperties = null;
                    ArrayPool <FoundProperty> .Shared.Return(toReturn, clearArray: true);
                }
            }
            else
            {
                // Slower path that supports continuation and metadata reads.

                if (state.Current.ObjectState == StackFrameObjectState.None)
                {
                    if (reader.TokenType != JsonTokenType.StartObject)
                    {
                        ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert);
                    }

                    state.Current.ObjectState = StackFrameObjectState.StartToken;
                }

                // Read any metadata properties.
                if (state.CanContainMetadata && state.Current.ObjectState < StackFrameObjectState.ReadMetadata)
                {
                    if (!JsonSerializer.TryReadMetadata(this, ref reader, ref state))
                    {
                        value = default;
                        return(false);
                    }

                    state.Current.ObjectState = StackFrameObjectState.ReadMetadata;
                }

                if (state.Current.ObjectState < StackFrameObjectState.ConstructorArguments)
                {
                    if (state.CanContainMetadata)
                    {
                        JsonSerializer.ValidateMetadataForObjectConverter(this, ref reader, ref state);
                    }

                    if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref)
                    {
                        value = JsonSerializer.ResolveReferenceId <T>(ref state);
                        return(true);
                    }

                    BeginRead(ref state, ref reader, options);

                    state.Current.ObjectState = StackFrameObjectState.ConstructorArguments;
                }

                if (!ReadConstructorArgumentsWithContinuation(ref state, ref reader, options))
                {
                    value = default;
                    return(false);
                }

                obj = (T)CreateObject(ref state.Current);

                if (state.Current.MetadataPropertyNames.HasFlag(MetadataPropertyName.Id))
                {
                    Debug.Assert(state.ReferenceId != null);
                    Debug.Assert(options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve);
                    state.ReferenceResolver.AddReference(state.ReferenceId, obj);
                    state.ReferenceId = null;
                }

                if (obj is IJsonOnDeserializing onDeserializing)
                {
                    onDeserializing.OnDeserializing();
                }

                if (argumentState.FoundPropertyCount > 0)
                {
                    for (int i = 0; i < argumentState.FoundPropertyCount; i++)
                    {
                        JsonPropertyInfo jsonPropertyInfo = argumentState.FoundPropertiesAsync ![i].Item1;